Whether the memory allocated for this variable str?
If allocated, how many bytes will be allocated ?
if not memory allocated, How JVM will come to know that there is some variable called str is declared ?
If allocated and if there is null value inside the memory, then what exactly the representation of null in binary ?
When you declare String str = null; Java will allocate about 4 - 8 bytes of memory for the str variable. Here, it will store the memory address of the object you are pointing to. Null means the memory address will be 0. Java knows that if the memory address is 0, it points to nothing.
do you mean for all the variable which are assigned to null will be stored at 0th location ?
What if i declare some 5 string variables and assigned to null ? Whether all points to the same location ?
Basically as per my understanding memory will be allocated based on the type(datatype).
when above is true for eg : if one object is having many data members and its object is assigned to null, then how JVM will calculate the memory for the null objects ?
Thanks & Rergards
Stephan van Hulst
Joined: Sep 20, 2010
In Java, a variable holds either primitives (ints, booleans, chars, etc) or references. It's a mistake to think that a variable declared as String holds a String object. It doesn't. It holds the address to that String.
Let's make it easier to understand with a House class. Let's say we have a variable: House house = null; The variable "house" holds the address to a House. In this case, there is no address. It's just like a blank piece of paper. However, once we do house = new House(); Java will construct a new House somewhere in memory. The address of the House is then written to the house variable.
Now, houses take up a lot of space. Pieces of paper take up space as well. How much space an object of type House takes up, is not known. It depends on the House class. But the "house" variable itself will probably take up 4 or 8 bytes. Even if they are empty and you don't write an address to them.
When you do something like
house1 = house2;
it simply means we take the address written on one piece of paper, and write it down on the other piece of paper. We don't actually do anything with a House.