Question

Recently I have seen a code like this -

class Test{
        public static void main(String[] args){

                String s1 = "String1"; //1
                String s2 = new String("String2"); //2

                System.out.println(s1.equals("String1"));
                System.out.println(s1=="String1"); //3

                System.out.println(s2.equals("String2")); 
                System.out.println(s2=="String2"); //4
        }
}

and the out put is -

true
true
true
false

So far I know, at point 1 "String1" is placed in String pool and assigned with String type reference variable s1. Isn't there any String object created?

We know a new String object is created at point 2 and at point 4 the expression (s2=="String2") evaluated to false. If a new String object is created at point 1 then how the expression at point 3 (s1=="String1") evaluated to true. And if a new object is not created at point 1 how the expression at point 3 (s1=="String1") evaluated to true?

Thanks in Advance

Was it helpful?

Solution

== Compares the reference of the string and is unreliable to use for value comparison. Your s1=="String1" I would imagine is true because you're comparing two literals, compared to the s2 comparison of a new String object compared to a literal.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top