Sobes.tech
Junior

What happens when the '==' operator is used in Java?

sobes.tech AI

Answer from AI

The == operator in Java compares the following:

  • For primitive data types (boolean, byte, short, char, int, long, float, double): It compares the values of the variables themselves.
  • For reference data types (objects): It compares the references to the objects, i.e., it checks whether the variables point to the same object in memory. It does not compare the contents of the objects.
// Primitive types
int a = 10;
int b = 10;
System.out.println(a == b); // true

// Reference types
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2); // false (different objects in memory)

String s3 = s1;
System.out.println(s1 == s3); // true (pointing to the same object)

To compare the contents of objects, the equals() method should be used.