DEV Community

Cover image for Why is the new keyword used only for object creation and not for variables in Java?
Arul .A
Arul .A

Posted on

Why is the new keyword used only for object creation and not for variables in Java?

  • The new keyword in Java is used to create an object of a class in heap memory.
  • It allocates memory for all instance variables and initializes them using the constructor.
  • Static variables belong to the class and are created when the class is loaded, so they do not need new.
  • Variables like int, String, or class fields are not objects by themselves and cannot be created using new.
  • Therefore, new is required only to create objects, not to access or declare variables.

Example:

public class Supermarket
{
    static String shopName="arul";
    static int shopNo=3;
    String productName="eye";
    int productNo=1;
public static void main (String[] args)
{
    Supermarket product=new Supermarket();

    System.out.println(product.shopName);
    System.out.println(product.shopNo);
    System.out.println(product.productName);
    System.out.println(product.productNo);
}
}
Enter fullscreen mode Exit fullscreen mode

How to read this image :

Stack
Holds reference variables like product
→ Supermarket product

Heap
Holds the actual object created by
→ new Supermarket()

Static variables
(shopName, shopNo)
→ Stored once in class memory, NOT inside the object

Instance variables
(productName, productNo)
→ Stored inside the heap object

Top comments (0)