In Java, primitive (primitive data type) refers to the basic data type in the Java language, such as int, double, char, etc. In contrast, there are reference data types, such as String, Object, etc. Unlike reference data types, primitive types do not need to be compared using the .equals() method. This is because primitive type variables store actual values rather than object references. Therefore, when comparing two primitive type variables, you can directly use the == operator for comparison, because it compares whether the values themselves are equal. For reference data types, you need to use the .equals() method, because it compares whether the object references point to the same object. This is why in Java, primitive types do not need the .equals() method.
So in java if you compare strings you have to use .equals method because == only compares the memory address and not the content. That's okay, I can understand that. But what I don't understand is why the original doesn't have the same problem. How can we use == operator with primitives.
This comes down to the fact that primitives are not full Java objects, so they are "passed by value", whereas objects are "passed by reference".
Additionally, you cannot use the .equals()
function on a primitive because it is not a fully instantiated Java object from a class and requires the function to be defined in the class/object.
Most primitives have an equivalent object type, for example Integer
is a fully implemented object type of int
, in modern Java you would get the object type named autoboxing. So if instead of using int
, you use Integer
type, then you can call .equals()
String in Java is a bit special but it is basically an immutable object.
This is some random assortment of information, but I believe if you add it up you'll hopefully understand what's going on.
The above is the detailed content of Why does primitive not need the .equals method in java?. For more information, please follow other related articles on the PHP Chinese website!