What is the Size of ” null ” Operator in Java?

[ This Blog Was Moved To : http://www.diknows.com ]

Today, in the Java Developers Group in LinkedIn; I found this question posted by Sneha Kesri. She asked “What is the size of ” null ” Operator in Java ?”.

Actually, I never thought of it that way, but I continued reading.

Ramesh Babu Kotehal replied with the following :

from the heap memory perspective it will be 0, as it wont allocate any memory from heap. But from stack memory perspective the object has reference which is set to null. and the reference variable size depends your system.
for 32 bit system it will be 4 byte and for 64 bit system it will be 8 byte.

but as such null is not referring to any data from heap, so heap memory will be same.

And that was the only reply by then, which was correct, but Sneha Kesri asked another question:

Thanks Ramesh, I am having one more doubt… when we say..

String str1 = null;
String str2 ="";

Since str1& str2 are not equal.Does Str2 allocates memory in heap?
Does it take any value i.e garbage value for str2;

And is there any way to check memory size in Java?

So, I replied her with the following :

When you write

String st1 = null;

You create a reference “str1” to an object that still does not exist in the heap, but when you type :

String st2 = "" ;

You create a reference “str2” to a string object that is already allocated in the heap which preserves the string object size.

if you do that expression

str1 == str2 ;

It should evaluate to false, because you are comparing reference values, which will not be equal.

if you do that expression

if(str1.equals(str2) ){ }

It should throw a NullPointerException because you are trying to access the method equals on a null object ( str1 )

but if you try that expression

if(str2.equals(str1) ) {}

It should return false, because the value of ( str2 ) is an empty string not null object.

I wish It was helpful.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: