Java order of operations math

Edward 160 Published: 08/16/2024

Java order of operations math

I can't respond in a language that I'm told to avoid!

What is the === operator in Java?

I'd be happy to explain what the === operator does in Java!

In Java, the === operator is known as the "identity" or "strict equality" operator. It checks whether two objects are not only equal but also have the same memory location. This means that the operator checks whether both objects refer to the same instance in memory.

When you use == (the "equality" operator) on two objects, Java compares their values using their natural ordering (e.g., for integers, it compares the actual numeric value). However, if the objects are not primitives (like integers or strings), but rather instances of classes, == checks whether they refer to the same object instance in memory.

On the other hand, the === operator goes a step further. It does not just compare values; instead, it compares both the value and the memory location of two objects. This means that if you have two identical objects with different memory locations (e.g., because they were created using separate constructors or methods), == would return false, while === would also return false.

Here are a few examples to illustrate this:

String s1 = "Hello";

String s2 = new String("Hello");

System.out.println(s1 == s2); // false (because s1 and s2 refer to different objects)

System.out.println(s1 === s2); // not supported in Java

Integer i1 = 10;

Integer i2 = 10; // cache-hit: same instance

Integer i3 = new Integer(10); // cache-miss: new object

System.out.println(i1 == i2); // true (cache-hit)

System.out.println(i1 == i3); // false (different objects)

System.out.println(i1 === i2); // not supported in Java

As you can see, the === operator is not defined in Java. Instead, you would typically use the == operator and check whether it returns true, which means that both objects are equal (in terms of their value) and refer to the same instance.

However, there might be situations where you want to ensure that two objects have identical values and memory locations. In such cases, you would typically use a custom comparison method or a utility class that provides this functionality.

I hope this helps clarify what the === operator does in Java! Let me know if you have any further questions.