• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

doubt in indexOf()

 
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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


 
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Meera, what do you think s.substring(-1) should return?
 
Ranch Hand
Posts: 2908
1
Spring Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Got it guys,
Thanks,
Meera
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic