Two String objects with same values not to be equal under the == operator.

Two String objects with same values not to be equal under the == operator. Explain How.

The == operator compares references and not contents. It compares two objects and if they are the same object in memory and present in the same memory location, the expression returns true else it returns false. It is quite possible that two same contents are located in different memory locations.

Following function will help to understand the concept
public class Test
{
   public static void main(String[] args)
   {
       String str1 = “abc”;
       String str2 = str1;
       String str5 = “abc”;
       String str3 = new String(”abc”);
       String str4 = new String(”abc”);
       System.out.println(”== comparison - ” + (str1 == str2));
       System.out.println(”equals method - ” + str1.equals(str2));
       System.out.println(”== comparison - ” + str3 == str4);
       System.out.println(”equals method - ” + str3.equals(str4));
       System.out.println(”== comparison - ” + (str1 == str5));
   }
}

//Output

== comparison - true
equals method - true
== comparison - false
equals method - true
== comparison - true
Static in java
Static variables are declared with the static keyword in a class, Static variables are always called by the class name...
Garbage collection mechanism in Java
The purpose of garbage collection is to identify and remove objects that are no longer needed by a program...
Can Abstract Class have constructors?
Abstract class can have a constructor. But as we can't instantiate abstract class, we can't access it through the object...
Post your comment