The new operator in Java is used to create new instances of objects. The process of creating an object involves allocating memory, initializing fields, and invoking a constructor.
In classical programming languages, memory allocation and object initialization could happen separately. In Java, they are combined and managed by the Java Virtual Machine (JVM), which reduces the number of errors and memory leaks.
Misunderstanding the processes occurring during object creation can lead to incorrect initialization, memory leaks, or unexpected behavior.
When using the new operator:
Example code:
Person p = new Person("Ivan", 20);
After this, a separate Person object appears in memory that can be used.
Key features:
Can we avoid using the new operator when creating objects?
Yes. For example, when cloning (clone()), deserializing, using reflection (Class.newInstance()), but they have their own nuances and limitations.
Does new create a new object in the string pool?
No. If you create a string like this — new String("abc"), a new object will be created on the heap, even if such a string already exists in the String pool. It’s better to use string literals.
Is the behavior of new different for arrays?
Yes. For arrays, the new operator allocates memory for all elements of the array and initializes them with default values, but does not call constructors for elements unless they are primitives.
String[] arr = new String[5]; // All elements will be null
A developer writes:
String s1 = new String("hi"); String s2 = new String("hi"); System.out.println(s1 == s2); // false
Pros:
Cons:
A developer writes:
String s1 = "hi"; String s2 = "hi"; System.out.println(s1 == s2); // true
Pros:
Cons: