-2

I was expecting output true but i am getting output as a false Can any one explain me this?

String st = "mah";
        String st1 = "mah";
        String test = st + st1;
        String test1 = st + st1;
        System.out.println(test == test1);
Mahesh Kshirsagar
  • 390
  • 1
  • 3
  • 12
  • 1
    Please [edit] your question to add a tag for the language you're using. That's the most important tag. – Mat Sep 05 '18 at 07:22
  • 1
    Possible duplicate of [String comparison in Java](https://stackoverflow.com/questions/5286310/string-comparison-in-java) – jonrsharpe Sep 05 '18 at 07:26
  • You haven't specified the language. Assuming you're using java: 1. st + st1 returns a new object containing the "mahmah" 2. since st + st1 is called twice, it returns two different objects (maybe interning can sometimes make this statement invalid?) 3. you are using == which means (for objects) that unless both variables are "pointing" at the same object, you will get false. (for example, if String test1 = test, the result becomes true) But as mentioned in https://stackoverflow.com/questions/5286310/string-comparison-in-java you should use the equals method to compare strings – Roy Shahaf Sep 05 '18 at 07:26

1 Answers1

0

If the strings you're joining aren't compile time constants, you can't avoid creating a new string, because of String's immutability. try below-You will get true.

    final String st = "mah";
            final String st1 = "mah";
            String test = st + st1;
            String test1 = st + st1;
            System.out.println(test == test1);
tripleee
  • 175,061
  • 34
  • 275
  • 318
Geet San
  • 98
  • 8