Junior — Middle
Is it possible to initialize a reference type without using the new operator?
sobes.tech AI
Answer from AI
In Java, reference types are usually initialized using the new operator, which allocates memory for the object. However, there are exceptions:
- String literals can be used without
new:
String s = "Hello"; // without new
- Arrays must be initialized using
newor an array initializer:
int[] arr = {1, 2, 3}; // initialized without new, but an array is created under the hood
- Wrapper classes for primitive types (e.g.,
Integer) can be used with autoboxing:
Integer i = 10; // without explicit new
Thus, strings can be initialized directly with literals, and autoboxing can be used for wrappers, but for most objects, new is necessary.