0

When I put "I " into str, "It is I" is not printed, But I put "I" into str, "It is I" is printed.

Can anyone explain about this behaviour. Below is my code.

Code:

String str = "I "; // in = "I"

StringTokenizer st = new StringTokenizer(str, " ", false);
String typeCharater="";

if( st.hasMoreTokens() ) {
    typeCharater = st.nextToken();
}
} else if( typeCharater == "I" ) { 
    System.out.println("It is I"); 
}
sTg
  • 4,313
  • 16
  • 68
  • 115
arubirate
  • 87
  • 6

1 Answers1

0

I haven't really used stringtokenizer, but looking at the Java Doc (http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html) and the examples they have, I think the issue is that your string parameter you are trying to tokenize only has one letter in it, and thus it will always be "I"

Edit: Also, if memory serves me right, when comparing strings you want to use .equalsIgnoreCase or any of the other .equal methods as == may not return equality, even if they are equal, due to separate memory pointers.

Edit 2: Also, as for "I " vs "I" I think the reason may be that the first option already has a space, so the code skipped it over due to that fact as your delimiter is " ".

SomeStudent
  • 2,856
  • 1
  • 22
  • 36