import java.util.Date;

public class ReferenceDemo {
    public static void main(String [] args) {
        File f1 = new File("mydata.txt");
        File f2 = new File("mydata.txt");

        if (f1 != f2) 
            System.out.println("f1 != f2");

        Date today = new Date();
        Date now = today;

        if (today == now)
            System.out.println("today == now");

        String s1 = "Hello";
        String s2 = "Hello";

        if (s1 == s2)
            System.out.println("s1 == s2");

        String x1 = new String("Goodbye");
        String x2 = new String("Goodbye");

        if (x1 == x2)
            System.out.println("x1 == x2");
What will be printed out?
About the comparison s1 == s2.
The JVM creates a pool of String objects that can be referenced by multiple variables across the JVM. The next time you use the same literal value it's copy from the pool will be used. But if you use new then a separate object in the heap (not in the pool) will be created.
This behaviour is described in language specification section 3.10.5. ( )

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Продовжуйте вивчати
тести з Java
Зареєструйся Зараз
або Підпишись на майбутні тести