This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes indexOf Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "indexOf" Watch "indexOf" New topic
Author

indexOf

Smith
Greenhorn

Joined: Oct 18, 2000
Posts: 2
String str = "Java Jives, Java Jives Java";
int i4 = str.indexOf("Jives", 4);
int i5 = str.lastIndexOf("Jives", 5);
System.out.println(i4);
System.out.println(i5);
The output is 5 and 5.Can anynody explain the output?
Sudhir Bangera
Ranch Hand

Joined: Oct 10, 2000
Posts: 50
indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
"Jives" is found at index 5 so the output is 5.
If you set the fromIndex as 5 above, it still returns 5.

lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward
starting at the specified index.
Begins to search backward from index 5 but since "Jives" is found at index 5, it returns 5.
If you set the fromIndex as 4, "Jives" is not found hence returns -1.
I was confused by looking at the code too, but after running the code with different index values, I arrived at this conclusion.
Smith
Greenhorn

Joined: Oct 18, 2000
Posts: 2
still iam not clear of lastIndexOf
michael huang
Ranch Hand

Joined: Jul 30, 2000
Posts: 63
hi, Smith
this kind of problem you can take a look of API doc.
i try to explain:
first, indexOf() is search from start and lastIndexOf() is search from end.
second, indexOf() is find the lowest value as str.startWith("Jives", 4) && k>=4(according to doc ), so find String str is "Jives, Java Jives Java" and result is 5;
lastIndexOf() is find the largest value as str.startWith("Jives", 5) && k<=5, so find String str is "Java J", it can find at positoin 5->J, so result is 5;
hop this can help
michael
Ajith Kallambella
Sheriff

Joined: Mar 17, 2000
Posts: 5782
'Smith'
PROPER NAMES ARE NOW REQUIRED!!
Read this post for more details.
Ajith


Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
 
wood burning stoves
 
subject: indexOf
 
Similar Threads
why does this return false?
Creation of Ineger Wrapper Object
Arrays
== , equals() method problem
Integer unboxing and == operator question