Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about == operator in java

public class Demo {  

    public static void main(String[] args) {

        String s1 = "Hello";
        String s2 = "Hello";
        System.out.println("s1 == s2 " + (s1 == s2));

        String s5 = "Hel" + "lo";
        String s6 = "He" + "llo";
        System.out.println("s5 == s6 " + (s5 == s6));

        String s7 = "He";
        String s8 = "Hello";
        s7 = s7.concat("llo");
        System.out.println("s7 == s8 " + (s7 == s8));

        String s10 = "He";
        s10 = s10 + "llo";
        System.out.println("s1 == s10 "+(s1 == s10));
    }
}

In the preceding code s7 == s8 and s1 == s10 give false. Can someone please explain me, what is actually happened here in s7 = s7.concat ("llo"); and s10 = s10 + "llo"; I understand == operator checks reference and equal() checks content of object. But I need to know why s7 and s10 reference variables bit patterns are different from s8 and s1. If these things are related with compile time generated strings and run time generated strings then how can I identify whether it is compile time or run time string?

like image 276
ddfnfal Avatar asked Dec 02 '22 04:12

ddfnfal


1 Answers

The reason this is happening is because Java is optimizing in the compiler. When it sees that you're assigning the literal string "Hello" to s1, it uses the same "Hello" for s2, since all Java String operations are non-destructive (eg they return a clone rather than modify the original), so that's a safe thing to do.

Same thing goes for "Hel" + "lo" vs "He" + "llo"; it's clever enough to figure out that they're the same thing.

The others are complex enough that it can't optimize them, and thus you end up with separate objects.

like image 149
issa marie tseng Avatar answered Dec 28 '22 01:12

issa marie tseng