简体   繁体   中英

Java string pool test doesn't work

After reading about Java String Pool I've decided to run a little test. I've written the following test program that it's result doesn't match the Java String Pool behavior according to the JDK specification.

public class Temp_20141220 {

    private String b1 = "hello";

    public static void main(String[] args) {
        Temp_20141220 t = new Temp_20141220();
        String b = "hello";
        System.out.println("b==b1 =" + t.b1 == b);
    }
}

I've been expecting to get in output: b==b1 =true but I got: b==b1 =false

Why so? Does Ubuntu's JVM not support this Java String Pool feature?

This

System.out.println("b==b1 =" + t.b1 == b);

is equivalent to

System.out.println( ("b==b1 =" + t.b1) == b);

You're applying reference equality between b and the concatenation of "b==b1 =" and t.b1 .

you're comparing 2 different strings:

  1. string is "b==b1 =" + t.b1
  2. string is b

if you change your code to:

System.out.println("b==b1 =" + (t.b1 == b));

you will get true in output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM