0

I am a beginner in Java, so I don't know about the heap concept when I googled. In an OOP tutorial, I learnt that when we create an object using 'new' keyword, memory is allocated to the object. What if I don't provide values to the attributes of the instance of the class, so will that instance variables also take up memory but they are without any values.

class Employee{
    int age;
    String name;
}

public class Main {
    public static void main(String[] args) {
        Employee emp = new Employee();
        // I didn't provide any values to age and name
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Aryaman
  • 55
  • 5
  • 1
    "*... OOPs...*" - the right abbreviation is OOP. --- The two types in `Employee` are different in nature. `int age` is a primitive, so even without an intialization, it will hold the value `0` (alll primitives do). For `String name`, memory for a reference is created (since all objects addressed by references). The reference itself will reference `null` since we did not explicitly assign a value to it, signaling that there is currently no reference stored. – Turing85 Aug 28 '21 at 10:45
  • 1
    It is important to realise that the space of the variable itself and the space for the value of the variable (for a reference type) are two separate things. – Mark Rotteveel Aug 28 '21 at 10:45

2 Answers2

-1

Yes these get default values. For all primitives (int float etc.) that is 0 or false for booleans. For objects like strings it is null. It takes the same space as when initializing with null for objects. So it has the 4/8 bytes (32/64 bit) but no object is created yet for the String.

DownloadPizza
  • 3,307
  • 1
  • 12
  • 27
-1

Yes.Once you create an Object using the 'new' keyword , relevant heap space will be allocated because of there are default values for each variable.

Shan.M
  • 139
  • 3
  • 11