0

How String concatenation works in java?. This question is not for comparing Strings. Its for comparing objects and while concatenation i am getting only false. Why this is happen? I have written a code for comparing the String references

public class StringClass {
    public static void main(String[] args) {    
        String s1 = new String("hello");
        String s2 = new String("hello");
        String s3 = "hello";
        String s4 = "hello";
        String s5 = "java";
        String s6 = "developer";
        String s7 = s5 + s6;
        String s8 = "java" + s6;
        String s9 = "javadeveloper";
        String s10 = "java" + "developer";

        System.out.println("s1 == s2 " + s1==s2);
        System.out.println("s3 == s4 " + s3 == s4);
        System.out.println("s7 == s9" + s7 == s9);
        System.out.println("s9 == s10" + s9==s10);
    }

}

In console i am getting like this

false
false
false
false

Why concatenation doesnt work in this code?. I am expecting the output like this

s1 == s2 false
s3 == s4 true
s7 = s9 false
s9 == s10 true
Jinu P C
  • 3,146
  • 1
  • 20
  • 29
  • What's more likely, string concatenation is erroneous in Java or you are incorrectly comparing strings? – ChiefTwoPencils Aug 18 '16 at 07:38
  • 2
    This is a mixture of misunderstanding about string comparison and operator precedence (`"s3 == s4 " + s3 == s4` is the same as `("s3 == s4 " + s3) == s4`). – Andy Turner Aug 18 '16 at 07:38
  • I am not comparing strings i am comparing objects. My question is why concatenation is not working and i am new to java@ChiefTwoPencils – Jinu P C Aug 18 '16 at 07:39
  • Thank you @AndyTurner so plus operator having higher priority than comparison operator – Jinu P C Aug 18 '16 at 07:42
  • 1
    @JinuPC https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html – Andy Turner Aug 18 '16 at 07:43
  • Apologies for coming across rudely. I was poorly suggesting that it's highly unlikely that the language is broken compared to it being a user error. – ChiefTwoPencils Aug 18 '16 at 07:50
  • @JinuPC on a point of terminology, if you are really intending to compare *references* using `==`, "comparing the String *references*" would convey this better than "comparing the String *objects*". – Andy Turner Aug 18 '16 at 07:59

0 Answers0