javaobjectheap-memoryequals-operator

why is jvm returning false when comparing two objects of same type?


public class Test
    {
        public static void main(String[] args)
       {
        String s = new String("test");// *** 
        String s1 = s.toUpperCase();

        String s2 = s.toLowerCase();

        String s3 = s1.toLowerCase();

        System.out.println(s==s1);//first case

        System.out.println(s==s2);//second case

        System.out.println(s==s3);//third case
       }
    }

1) Why does it return false for the third case(commented). Both s3 and s are pointing test yeah? But it seems JVM creates another object named test for s3 in the heap memory. But it is not the same for the second case(commented). It uses the object which was previously created as s(commented as *** in the code). Why is that?

2) And what happens to s1 object TEST because s3 is created from s1. Will s1 be destroyed or will it be in heap?


Solution

  • Here String s = new String("test"); object will be created in heap area (not inside String pooled area) but any other string returned after any operation will be created in String pooled area. To answer your question:

    1. s==s3 returned false as they are two different objects.
    2. s1 won't be collected by garbage collector until it is being referenced.