Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

At String s1 = "str" + s.length(); the value of s1=str4 but it turns out to be false at next sysout statement during equality check

Tags:

java

string

public class Foo {

    public static void main(String[] args) {
        foo();
        bar();
    }

    public static void foo() {
        String s = "str4";
        String s1 = "str" + s.length();
        System.out.println("(s==s1)" + (s1 == s));
     }

    public static void bar() {
        String s = "str4";
        String s1 = "str" + "4";
        System.out.println("(s==s1)" + (s1 == s));
    }
}

OUTPUT

(s==s1)false

(s==s1)true

At String s1 = "str" + s.length(); the value of s1=str4 but it turns out to be false at next sysout statement during double equal (==) check

*/

like image 757
mohan4Spark Avatar asked May 02 '14 14:05

mohan4Spark


1 Answers

That's because "str" + "4" is compiled as "str4".

String s = "str4";
String s1 = "str" + "4";

For the compiler, it will be:

String s = "str4";
String s1 = "str4";

Note that "str4" is a literal String and it will be stored in String pool.

like image 118
Luiggi Mendoza Avatar answered Oct 03 '22 08:10

Luiggi Mendoza