Java中包装类无需构造方法调用?为何无需new关键字实例化?
new or Constructor Calls in Java? Great question—this is one of those Java "syntactic sugar" features that makes code cleaner, but it's easy to miss what's happening under the hood. Let's break it down step by step:
1. It's All About Autoboxing (Java 5+)
Starting with Java 5, the compiler introduced autoboxing—a feature that automatically converts primitive types to their corresponding wrapper class objects (and vice versa, with unboxing). When you write code like:
Integer myInt = 10;
You aren't skipping object creation entirely—instead, the compiler secretly rewrites your code to call a factory method for you:
Integer myInt = Integer.valueOf(10);
This is why you don't need to type new Integer(10) explicitly; the compiler handles the conversion behind the scenes.
2. Factory Methods + Object Caching = Performance Wins
The valueOf() method (available for all wrapper classes like Integer, Long, Byte, etc.) doesn't always create a new object. For commonly used values, Java maintains a cache pool of pre-created wrapper objects to avoid unnecessary memory allocation.
For example:
Integercaches values from-128to127(this range can be extended with a JVM flag).Byte,Short,Longcache all their possible values (since their ranges are small).Charactercaches values from\u0000to\u007F(ASCII characters).
So when you write Integer x = 5;, you're actually reusing an existing object from the cache instead of creating a new one—this is way more efficient than using new Integer(5) every time.
3. The Difference Between valueOf() and new
To make this concrete, compare these two lines:
Integer cachedInt = Integer.valueOf(5); // Reuses cached object Integer newInt = new Integer(5); // Always creates a new object
If you check cachedInt == newInt, it will return false because they're different objects. But cachedInt.equals(newInt) returns true since their values are the same.
Wrapping Up
The ability to create wrapper objects without new is just Java making your code more readable via autoboxing. Underneath, it's using factory methods that leverage caching to boost performance. It's a nice convenience that saves you from writing repetitive boilerplate code!
内容的提问来源于stack exchange,提问作者Akshat

