0

I am very wondering after executing the below java code.

public class HelloWorld {
    public static void main(String...strings) {
  String s3="abc";
  String s4="abc";
  System.out.println("Result::"+s3==s4);//1
  
  String s1 = "abc";
  String s2 = "abc";
  
  System.out.println(s1 == s2);//2
  
 }
 
 public static void main(String args) {
  System.out.println("From Static Method");
  HelloWorld.main("");
 }

}

Output:

The output is

Result:: false
true

If statement 1 is identical to statement 2, then why statement 1 is false, whereas statement 2 is true

Federico klez Culloca
  • 24,336
  • 15
  • 57
  • 93
jack
  • 11
  • 2
  • In your first println you concatenate first the left part of your expression. The correct way could be System.out.println("Result::"+(s3==s4)); – geoandri May 06 '22 at 11:30
  • Hint: `"a"+"b"=="ab"` is `true`. – Pshemo May 06 '22 at 11:30
  • System.out.println("Result::"+s3==s4); here you are actually comparing "Result::abc"=="abc" which evaluates false. put bracket around s3 and s4 comparison you will get true. And about comparison of string link already posted while closing question – MORÈ May 06 '22 at 11:31
  • BTW mostly not a good idea to compare `String` using `==`, use `equals()` for that (e.g. `"abc" == new String("abc")` is `false`, while `"abc".equals(new String("abc"))` is `true`) – user16320675 May 06 '22 at 12:50
  • Hint 2: There is no `Result::` part in your output (see again [image you ware trying to include](https://i.stack.imgur.com/5PuxF.png)) – Pshemo May 06 '22 at 13:01

0 Answers0