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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "indexof" Watch "indexof" New topic


Roopa Bagur
Ranch Hand

Joined: Nov 03, 2000
Posts: 267
Can somebody explain the output of 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") );
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Hi Roopa,
I am not sure what you are having problems with but the first three indexOf method are looking for the empty string character. The indexOf method will never fail to find a match for an empty string. It will always be the first index of any string!
The last indexOf method call is looking for a capital J which is found in the first index position.
Therefore, the output is four zeroes with a single space between them.
I agree. Here's the link:
subject: indexof
It's not a secret anymore!