Let’s look at a piece of code first:
public class Main{ public static void main(String[] args){ Integer num1 = 100; Integer num2 = 100; Integer num3 = 200; Integer num4 = 200; '''//输出结果''' System.out.println(num1==num2); System.out.println(num3==num4); } }
Guess what the result is?
Many people will think that the results are all true, but the results are not like this
true
false
Why is this the result? If you use memory to interpret the results, num1 and num2 point to the same object, while num3 and num4 point to different objects. Next, I will tell you why. Take a look at the source code of the valueof method of the Integer type:
public static Integer valueOf(int i) { assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + 128]; return new Integer(i); }
The implementation of IntegerCache:
'''// IntegerCache,一个内部类,注意它的属性都是定义为static final''' private static class IntegerCache { static final int high; '''//缓存上界,暂为null''' static final Integer cache[]; '''//缓存的整型数组''' '''// 块,为什么定义为块''' static { final int low = -128; '''// 缓存下界,不可变了。只有上界可以改变''' '''// high value may be configured by property''' '''// h值,可以通过设置jdk的AutoBoxCacheMax参数调整(以下有解释),自动缓存区间设置为[-128,N]。注意区间的下界是固定''' int h = 127; if (integerCacheHighPropValue != null) { '''// Use Long.decode here to avoid invoking methods that''' '''// require Integer's autoboxing cache to be initialized''' // 通过解码integerCacheHighPropValue,而得到一个候选的上界值''' int i = Long.decode(integerCacheHighPropValue).intValue(); '''// 取较大的作为上界,但又不能大于Integer的边界MAX_VALUE''' i = Math.max(i, 127); '''// Maximum array size is Integer.MAX_VALUE''' h = Math.min(i, Integer.MAX_VALUE - -low); } high = h; '''//上界确定''' '''// 就可以创建缓存块,注意缓存数组大小''' cache = new Integer[(high - low) + 1]; // int j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); '''// -128到high值逐一分配到缓存数组''' } private IntegerCache() {} }
It can be seen from these two pieces of code that when creating an Integer type object through the valueof method, the value range is [-128,127], and the value is in this range , the pointer points to an object reference that already exists in IntegerCache.cache. When the value exceeds this range, a new object will be created.
One thing to note is that not all types are in this range. Look at the Double type:
public class Main{ public static void main(String[] args){ Double i1 = 100.0; Double i2 = 100.0; Double i3 = 200.0; Double i4 = 200.0; System.out.println(i1==i2); System.out.println(i3==i4); } }
Finally The output result:
false
false
Specific reason for this result, you can take a look at the implementation of the Double valueof method in the source code, which is different from the Integer valueof method. This is because the number of integer values within a certain range is limited, but floating point numbers are not.
Note that the implementation of the valueOf method of Integer, Short, Byte, Character, and Long classes is similar.
The implementation of the valueOf method of Double and Float is similar.
Pulled down one, the Boolean type result has two True or False. Look directly at the source code:
public static Boolean valueOf(boolean b) { return (b ? TRUE : FALSE); }
and TRUE and FALSE are defined like this:
public static final Boolean TRUE = new Boolean(true); '''/** ''' '''* The <code>Boolean</code> object corresponding to the primitive ''' '''* value <code>false</code>. ''' '''*/''' public static final Boolean FALSE = new Boolean(false);
The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.
For more articles related to in-depth analysis of Java unboxing, please pay attention to the PHP Chinese website!

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
