0

Why do I get different values when I do System.out.println(s[0] == "java"); and System.out.println(args[0] == "java");

public class StringDemo {
    static void print(String[] s) {
        System.out.println(s[0] == "java");
    }

    public static void main(String[] args)
    {
        // java is passed as command line argument
        System.out.println(args[0] == "java");
        String s[] = new String[3];
        s[0] = "java";
        print(s);
    }
}
Dan
  • 7,286
  • 6
  • 49
  • 114
  • 1
    here is the complete code – vishal jagdale Dec 17 '16 at 09:18
  • i am using == in both statements this is not duplicate – vishal jagdale Dec 17 '16 at 09:20
  • Which one is `true` and which one is `false`? – RaminS Dec 17 '16 at 09:27
  • 3
    Possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) See [this one too](https://stackoverflow.com/questions/9698260/what-makes-reference-comparison-work-for-some-strings-in-java) – David Rawson Dec 17 '16 at 09:28
  • @DavidRawson I've tried to wrap my head around this with those "duplicates" too, but I don't seem to get it. Why does `args[0] == "foo"` evaluate to false when you give `"foo"` as argument? Is it stored in some hidden VM-variable with `new String()`? – RaminS Dec 17 '16 at 09:38
  • 2
    while both `args[0]` and `s[0]` contain references to strings with the characters `java` in it they do not contain references to the same string object. `s[0]` contains a reference to the interned string `java` which is the same string object you reference by writing the string literal "java". The command line parser of the JVM however does not pass a reference to this string literal in `args[0]`, it creates a new string objects for all the arguments you pass. – Thomas Kläger Dec 17 '16 at 09:38
  • @ThomasKläger If the string literal exists, why create a new one? And if it doesn't exist, why doesn't it exist? If the string exists, then the literal must exist as well, no? `args[0] == "foo"` is false in any code - not just this example. – RaminS Dec 17 '16 at 09:40
  • 1
    @Gendarme the command line parser doesn't know which string literals exist, so it just creates new string objects. And: no, not every string object has to be a string literal too. – Thomas Kläger Dec 17 '16 at 09:44
  • output of above code is false true – vishal jagdale Dec 17 '16 at 11:13
  • @DavidRawson I never understood how they are a problem other than wasting people's time at the time of posting. Right now it's buried cause it has no upvotes, no? – RaminS Dec 19 '16 at 10:01

1 Answers1

-1

The problem is because you compare of address, and not the value.

If you want compare of value you need use .equals method:

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

and

 System.out.println(s[0].equals("java"));
Tony
  • 9,672
  • 3
  • 47
  • 75
ruba ahmad
  • 24
  • 2