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?
It is not spelled out for
indexOf(String, int)
, butindexOf(int, int)
behaves the same way (emphasis mine):(Note that your text talks about
lastIndexOf
, but the code isindexOf
. The logic forlastIndexOf
is reversed: whereas the whole string is found after any negative index, none of the string is in front of a negative index, solastIndexOf
with a negative starting point will never find anything.)