-1

When I run the following code

public class Test {
    public static void main(String[] args) {
        System.out.println(args[0]);
        System.out.println("testing");
        System.out.println(args[0] == "testing");
    }
}

using

java Test testing

at the command line, it prints the following:

testing
testing
false

Why is the third printed line not 'true' when printed lines 1 and 2 seem to be the same?

Edit: Thanks for your replies - that's answered my query. I have a follow up query, which is: if == compares the String references, how can I find out what those references are?

danger mouse
  • 1,457
  • 1
  • 18
  • 31
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Jens Apr 16 '15 at 13:33

3 Answers3

0

Always use .equals() when comparing strings in Java.

System.out.println(args[0].equals("testing"));

Curtis
  • 681
  • 4
  • 9
0

== tests for reference equality.

.equals() tests for value equality.

You want to do this instead:

System.out.println(args[0].equals("testing"));
Justin L
  • 375
  • 2
  • 10
0

Use this instead

args[0].compareToIgnoreCase("testing")==0

Xain Malik
  • 11
  • 2