1
    System.out.println(args[0] == "x");
    System.out.println(args[0].equals("x"));

    String[] name = {"x"};
    System.out.println(name[0] == "x");
    System.out.println(name[0].equals("x"));

    String[] hello = new String[1];
    hello[0] = "x";
    System.out.println(hello[0] == "x");
    System.out.println(hello[0].equals("x"));

results in

false
true
true
true
true
true

Why does the first test result in 'false' when I invoke "java classname x"?

5
  • 1
    Your code shows that x argument from java YourClass x is not placed in String pool. You can get same effect with String[] name = {new String("x")}; Commented Apr 27, 2013 at 0:51
  • The operator == compares object addresses. The first two Strings you're comparing are different objects with the same contents, therefore == reports them as being different. String literals (that is, characters between pairs of " symbols), on the other hand, are always the same object if they have the same value, so comparing "x" == "x" will always report true. Commented Apr 27, 2013 at 1:01
  • 1
    Gotta give you +1 for composing a coherent question, even if it was poorly researched. Commented Apr 27, 2013 at 1:03
  • which means that java does a new String("x") before passing it to the main method as oppose to using literal. I however don't think that 'x' is not placed in the string pool. My understanding is that, it is placed in the string pool, except there is a String object in the heap too. Commented Apr 27, 2013 at 1:32
  • This question has been asked thousands of times on StackExchange. Please read one of the existing Answers. Commented Apr 27, 2013 at 1:43

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.