I know that fields stick to the objects as long as they exist, so they have some memory allocated, but what if I don’t initialize some fields and don’t use them? For example:
public class TEST {
public static void main(String[] args) {
Foo C = new Foo(5, 7);
Foo D = new Foo(5);
...
}
public class Foo{
private int A;
private float B;
public Foo (int A, float B){
this.A = A;
this.B = B;
}
public Foo (int A){
this.A = A;
}
...
}
Will C consume more memory than D?
Fields in Java are always initialized. Primitives are initialized to 0 or
false, and references (and arrays) are initialized tonull.Furthermore, once you declare a field, that field will always take up the same space in every instance. References take up only as much space as a pointer, but the referred-to object might take extra memory.