• 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

indexOf and lastIndexOf question

 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Concerning Q35 of Mock Exam 2 in Jiris:
What is the output of trying to compile and run the following code?
public class Test035
{
public static void main(String args[])
{
System.out.print(" ".indexOf("") + " " );
System.out.print("".indexOf("") + " " );
System.out.print("Java".indexOf("") + " ");
System.out.println("Java".indexOf("J") );
}
}
A: 0 0 0 0
B: 0 0 0 1
C: 0 0 1 1
D: 0 1 1 1
E: 1 1 1 1
Answer is: A
Does someone have an explanation for the first 3 zeros? What if it was lastIndexOf instead of indexOf?
 
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
String.indexOf returns zero if the argument is an empty String.
 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Regarding the searches, consider the strings as starting and ending with "".
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the case of lastIndexOf the null string is considered to be just after the last character of the string to be searched. So you get "1 0 4 0" printed as I have verified with BlueJ.
-Barry
 
reply
    Bookmark Topic Watch Topic
  • New Topic