4

There seems to be a difference between main(String[] args) and other string arrays that i can not figure out, my example.

public class TestArgs 
{
public static void main(String[] args) {
    String[] x = {"1","2","3"};
    System.out.print( x[2] == "3" );
    System.out.print( args[2] == "3" );
}}

I run this program as:

java TestArgs 1 2 3

I would expect the output to be "truetrue" but instead I get "truefalse"

Could someone please tell me what the difference is, or am I just doing something really stupid...

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
MrDetail
  • 230
  • 3
  • 12

3 Answers3

9

in java, you have to use "test".equals("test") to test for string-equality ;)

strings are objects and the objects are not the SAME, they just have the same VALUE

TheHe
  • 2,933
  • 18
  • 22
  • But if that is the case, why would the String I created work with the == operator but not the one created by main(String[] args)? – MrDetail Sep 04 '12 at 03:05
  • 4
    @MrDetail Because of the way Java internalises Strings. Rather then creating two instances of "3", Java has created one, hence the reference location is actually the same, as far as Java is concerned. This is why TheHe's solution is so important – MadProgrammer Sep 04 '12 at 03:07
5

That is because you're comparing the reference of the objects when you use ==. When you're comparing String, use .equals() instead of ==. This SO answer better explains why.

So your code would become something like this:

public class TestArgs {
    public static void main(String[] args) {
        String[] x = {"1","2","3"};
        System.out.print("3".equals(x[2]);
        System.out.print("3".equals(args[2]));
    }
}

Also, and this is not related directly to this answer, it is always a good idea to check the length of your args before doing any operation using that. The reason is that the end user might not have provided any value for args[2]

Community
  • 1
  • 1
Sujay
  • 6,753
  • 2
  • 30
  • 49
2

The == operator compares objects by reference.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964