1

1. -->

String s1 = "Rishi";

String s2 = "Ri" + "shi";
System.out.println(s1==s2);  // true

String s3 = "Ri".concat("shi");
System.out.println(s1==s3);  // false

Why while using '+' operator its coming as true but not in case of concatenation?

2. -->

String s1 = "Rishi";

String s2 = "Ri" + "shi";
System.out.println(s1==s2);  // true

String s3 = "Ri";
String s4 = s3 + "shi";
System.out.println(s1==s4);  // false  

Why the output varies even if using the same literal value?

trincot
  • 317,000
  • 35
  • 244
  • 286
Rishi
  • 55
  • 6
  • 2
    See http://stackoverflow.com/questions/34509566/in-case-of-string-concatenation-in-java/34509659 – Alexis C. Jan 17 '16 at 18:07
  • 1
    `"Ri" + "shi"` is concatenated at compilation time so it really is just `"Rishi"` literal, `"Ri".concat("shi")` is executed at runtime (it is hard to tell why it is not optimized like `+`, maybe compiler authors believe that since you explicitly are using `concat` you want to avoid this optimization). Also `s3 + "shi";` is not replaced by `"Rishi"` since compiler is not that advanced yet to be sure that `s3` represents only `"Ri"`. It would change if you declare `s3` to be `final`. – Pshemo Jan 17 '16 at 18:33

0 Answers0