0
Why i am getting both Output false and false? Someone explain to me this plz
public class Strings { public static void main(String[] args) { String S1 = "Wellcome to Java"; String S2 =new String("Wellcome to Java"); String S3 = "Wellcome to Java"; System.out.println("S1 ==S2"+S1 == S2); System.out.println("S1 ==S3"+S1 == S3); } }
8 Respuestas
+ 3
When left-hand operand is a string + operator acts as string concatenation operator.
"S1 == S2" + S1 == S2 ↓
"S1 == S2Wellcome to Java" == "Wellcome to Java"
+ Here acts as string concatenation, which concatenated "S1 == S2" with <S1> which contains "Wellcome to Java".
The combined string is not equal to "Wellcome to Java". That's what happens I guess.
+ 3
Put both of them in brackets like (S1==S3)
+ 2
When a string constant is created in the pool then as you know a similar constant cannot be created and if you try to create, it just returns the reference and the new instance is also pointing to the same constant. In this way both have same reference and return true. Remember you compare reference so it returns true.
But inside System.out.println() it consider everything as strings unless you use a bracket because () has more precedence and will execute before the actual printing of the output.
+ 2
Ipang nice one 👍
Edit: The target was hit right in the center.
0
Yeah i find this but what is logic behind this? Avinesh
0
Why i get true.with bracket and false without bracket
0
Operator == used to compare premative types, but with objects like String you should use ".equals()" method
so if you tried S1.equals(S2), it should print True