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); } }

21st Nov 2019, 2:06 PM
Abdul Wahab
Abdul Wahab - avatar
8 Réponses
+ 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.
21st Nov 2019, 2:26 PM
Ipang
+ 3
Put both of them in brackets like (S1==S3)
21st Nov 2019, 2:14 PM
Avinesh
Avinesh - avatar
+ 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.
21st Nov 2019, 2:27 PM
Avinesh
Avinesh - avatar
+ 2
Ipang nice one 👍 Edit: The target was hit right in the center.
21st Nov 2019, 2:30 PM
Avinesh
Avinesh - avatar
+ 2
Bundle of Thankssssss Avinesh and Ipang
21st Nov 2019, 2:31 PM
Abdul Wahab
Abdul Wahab - avatar
0
Yeah i find this but what is logic behind this? Avinesh
21st Nov 2019, 2:18 PM
Abdul Wahab
Abdul Wahab - avatar
0
Why i get true.with bracket and false without bracket
21st Nov 2019, 2:19 PM
Abdul Wahab
Abdul Wahab - avatar
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
22nd Nov 2019, 10:44 PM
Fr. Ibrahim Royshdy
Fr. Ibrahim Royshdy - avatar