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"?

Andy
  • 1,023
  • 1
  • 9
  • 17
  • 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")};` – Pshemo Apr 27 '13 at 00: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`. – Hot Licks Apr 27 '13 at 01:01
  • 1
    Gotta give you +1 for composing a coherent question, even if it was poorly researched. – Hot Licks Apr 27 '13 at 01: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. – Andy Apr 27 '13 at 01:32
  • This question has been asked thousands of times on StackExchange. Please read one of the existing Answers. – Stephen C Apr 27 '13 at 01:43

0 Answers0