I thought "==" operator checks to see if the objects being compared are the same object reference till I tried the foll: Sting s1="Hello"; Sting s2="Hello"; I tested with System.out.println(s1==s2?"same":"no"); I expected the answer to be "no" but I got "same"; But when I modified the code as under String s1="hello"; String s2="he"; Stirng s3=s2+"llo"; and tested s1==s3? I got the answer "no". Am I missing out on some concept here?
For efficiency, the compiler creates a single String object to represent each String literal. In your example, "Hello" is a string literal. Sting s1="Hello"; Sting s2="Hello"; Since the compiler only creates ONE object that contains the character sequence "Hello", both s1 and s2 are assigned a reference to this same object. That's why s1 == s2 is true. In your second case: String s1="hello"; String s2="he"; Stirng s3=s2+"llo"; and tested s1==s3? I got the answer "no". There are 3 String literals created ("hello", "he", and "llo".) s1 and s2 clearly will contain a reference to a different object. s3's value has to be determined at run time. At run time, s3 is assigned a reference to a NEW String object that gets created by concatenating s2 and the literal "llo". Remember that since Strings are immutable, you cannot actually change their character sequence. That's why concatenation results in a brand NEW String object being created, and its character sequence is "hello". But since it's a new String, it can't possibly be the same String object currently assigned to s1, can it? They are different String objects that contain the same character sequence.
Hi, 1) Format a = x ? b : c ; The ternary operator has left to right associativity and x should be a boolean expression. s2 is checked if it returns true or false, then based on that, the value "same" or "no" is assigned to s1.
2) String s1="hello"; String s2="he"; String s3=s2+"llo"; s1==s3? All string operations (concat, trim, replace, substring etc) construct and return new strings. s3 is a new string and thus is not == to s1. Clement