Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

last IndexOf method

 
Basanti Mathad
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
can anyone tell me what wud be the result of this method and why? I thought the answer is
-1.Is that right?
String banner = "One man, One vote";
int subInd1 = banner.lastIndexOf("One", 10);
System.out.println(subInd1);
Thank you
 
Sridhar Srikanthan
Ranch Hand
Posts: 366
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Basanti Mathad:
Hi,
can anyone tell me what wud be the result of this method and why? I thought the answer is
-1.Is that right?
String banner = "One man, One vote";
int subInd1 = banner.lastIndexOf("One", 10);
System.out.println(subInd1);
Thank you

According to java lang API,
public int lastIndexOf(String str,
int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index. The integer returned is the largest value k such that:

So it starts at index 10 which happens to be n in the second one in the string and searches backwords to find out the match for string "One". As there is a One starting at index 9, it returns 9. If you were to call banner.lastIndexOf("One",8 ), then the value is 0
Hope this helps
Sri
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic