aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt in indexOf() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


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

doubt in indexOf()

meera kanekal
Ranch Hand

Joined: Feb 13, 2005
Posts: 75
I got this from Enthuware
Which line will print the string "MUM"?



For line 3 the explanation given is "It will print IMUM. as s.indexOf('I', 3) will return 3."
For line 4 the explanation says "It will throw an exception as s.indexOf('I', 4) will return -1."


For line 3 the search for I starts at index 3. So it will return 3. For line 4 the search for I starts at index 4 and of course there is nothing. But why will it give an exception when the search returns -1 when no 'I' is found.
Thanks,
Meera


Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
Meera, what do you think s.substring(-1) should return?


All code in my posts, unless a source is explicitly mentioned, is my own.
Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2902
    
    1

meera kanekal wrote: But why will it give an exception when the search returns -1 when no 'I' is found.
Thanks,
Meera




Have you looked at API for String#substring(index);.

It says that
Throws:
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.


[LEARNING bLOG] | [Freelance Web Designer] | [and "Rohan" is part of my surname]
meera kanekal
Ranch Hand

Joined: Feb 13, 2005
Posts: 75
Got it guys,
Thanks,
Meera
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: doubt in indexOf()