Consider the following block of code:
class CheckStore {
private String displayText;
private boolean state;
private String meaningfulText;
private URL url;
public CheckStore(String text, boolean state) {
this.displayText = text;
this.state = state;
}
:
:
}
When I initialize two variables (displayText and state) in the constructor, do the other two variables (meaningfulText and url) require space in the memory to store null value?
Q1. If they do require space, how much memory does a null value take in the memory?
(ex. int takes 4 bytes).
Q2. How much space does a string take in memory? How much memory space does a string take? Does it depend on the length of the string?
In Java,
nullis just a value that a reference (which is basically a restricted pointer) can have. It means that the reference refers to nothing. In this case you still consume the space for the reference. This is 4 bytes on 32-bit systems or 8 bytes on 64-bit systems. However, you’re not consuming any space for the class that the reference points to until you actually allocate an instance of that class to point the reference at.Edit: As far as the String, a
Stringin Java takes 16 bits (2 bytes) for each character, plus a small amount of book-keeping overhead, which is probably undocumented and implementation specific.