Okay this is how datatypes work in Java. (You have to excuse my English, I am prob. not using the right vocab.
You have to differentiate between two of them. The base datatypes and the normal datatypes. Base data types pretty much make up everything that exists.
For example, there are all numbers, char, boolean etc.
The normal data types or complex data types is everything else.
A String is an array of chars, therefore a complex data type.
Every variable that you create is actually a pointer on the value in your memory.
For example:
String s = new String("This is just a test");
the variable "s" does NOT contain a String. It is a pointer. This pointer points on the variable in your memory.
When you call System.out.println(anyObject)
, the toString()
method of that object is called. If it did not override toString
from Object, it will print the pointer.
For example:
public class Foo{
public static void main(String[] args) {
Foo f = new Foo();
System.out.println(f);
}
}
>>>>
>>>>
>>>>Foo@330bedb4
Everything behind the "@" is the pointer. This only works for complex data types. Primitive datatypes are DIRECTLY saved in their pointer. So actually there is no pointer and the values are stored directly.
For example:
int i = 123;
i does NOT store a pointer in this case. i will store the integer value 123 (in byte ofc).
Okay so lets come back to the ==
operator.
It always compares the pointer and not the content saved at the pointer's position in the memory.
Example:
String s1 = new String("Hallo");
String s2 = new String("Hallo");
System.out.println(s1 == s2);
>>>>> false
This both String have a different pointer. String.equals(String other) however compares the content. You can compare primitive data types with the '==' operator because the pointer of two different objects with the same content is equal.
Null would mean that the pointer is empty. An empty primitive data type by default is 0 (for numbers). Null for any complex object however means, that object does not exist.
Greetings