import java.io.File;
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?
Explanation
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. ( https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.5 )
Java
Java Quiz
Start Quiz

or Read more about Java Quiz

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback