Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt in indexOf()

 
meera kanekal
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Meera, what do you think s.substring(-1) should return?
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
meera kanekal
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it guys,
Thanks,
Meera
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic