Reputation: 31
package ex;
class Item{
String text = "hello";
}
class A {
Item item;
private A() {}
private static class LazyHolder {
public static final A INSTANCE = new A();
}
public static A getInstance() {
return LazyHolder.INSTANCE;
}
}
public class Main {
public static void main(String[] args) {
A a = A.getInstance();
Item n0 = a.item;
a.item = new Item();
Item n1 = a.item;
a.item.text = "world";
Item n2 = a.item;
if(n0 != null)
{System.out.println(n0.text);}
else{System.out.println("null");};
// This print "null"
System.out.println(n1.text);
// This print "world"
System.out.println(n2.text);
// This print "world"
}
}
Hello I'm a student studying java alone. And i have a question.
As you see, n1 & n2 are not null, n0 is null. And n1.text and n2.text both has "world".
So when I saw this result, i got a conclusion, but i don't know what i think is true.
This is my question: If some field have null, Does it mean that the filed has no pointer?
re-question:
Can i understand that n0 "has" pointer to null, n1 and n2 has pointer to Item type Instance?
Upvotes: 0
Views: 308
Reputation: 12181
If some field have null, Does it mean that the filed has no pointer?
No it doesn't because a null pointer is still a pointer - it's just a pointer that's assigned null
.
Keep in mind that being assigned a null pointer is quite different than being completely uninitialized. For example, the following won't even compile:
public static void main(String []args){
String s;
System.out.println(s);
}
The following will compile, and it'll literally print null
:
public static void main(String []args){
String s = null;
System.out.println(s);
}
Some similar examples of trying to use something assigned null
may throw a NullPointerException
, which is actually one of the most discussed exceptions on Stack Overflow.
Upvotes: 2
Reputation: 1783
there is not pointer feature in JAVA, so if any object is not initialized with any value then reference to NULL
Upvotes: 0