I cant understand this lastindexof method in Java 11

218 Views Asked by At
    int a="abcd".indexOf("d",0);
    int b="abcd".indexOf("d",1);
    int c="abcd".indexOf("d",2);
    int d="abcd".indexOf("d",3);
    int e="abcd".indexOf("d",4);
    int f="abcd".indexOf("d",5);




    int b1="abcd".indexOf("d",-1);
    int c1="abcd".indexOf("d",-2);
    int d1="abcd".indexOf("d",-3);
    int e1="abcd".indexOf("d",-4);
    int f1="abcd".indexOf("d",-5);


    System.out.println("Last index of from index 0 "+a);
    System.out.println("Last index of from index 1 "+b);
    System.out.println("Last index of from index 2 "+c);
    System.out.println("Last index of from index 3 "+d);
    System.out.println("Last index of from index 4 "+a);
    System.out.println("Last index of from index 5 "+f);


    System.out.println("Last index of from index -1 "+b1);
    System.out.println("Last index of from index -2 "+c1);
    System.out.println("Last index of from index -3 "+d1);
    System.out.println("Last index of from index -4 "+e1);
    System.out.println("Last index of from index -5 "+f1);

Results

Last index of from index 0 3
Last index of from index 1 3
Last index of from index 2 3
Last index of from index 3 3
Last index of from index 4 3
Last index of from index 5 -1
Last index of from index -1 3
Last index of from index -2 3
Last index of from index -3 3
Last index of from index -4 3
Last index of from index -5 3

Can someone explain how positive and negative index work?

1

There are 1 best solutions below

8
On

It is not spelled out for indexOf(String, int), but indexOf(int, int) behaves the same way (emphasis mine):

There is no restriction on the value of fromIndex. If it is negative, it has the same effect as if it were zero: this entire string may be searched. If it is greater than the length of this string, it has the same effect as if it were equal to the length of this string: -1 is returned.

(Note that your text talks about lastIndexOf, but the code is indexOf. The logic for lastIndexOf is reversed: whereas the whole string is found after any negative index, none of the string is in front of a negative index, so lastIndexOf with a negative starting point will never find anything.)