Java packing and unpacking details and example code

Java packing and unpacking details

preface:

To understand the concepts of boxing and unpacking, you need to understand java data types

Boxing: wrap basic types with their corresponding reference types to make them have the nature of objects. Int packaged as integer, float packaged as float

Unpacking: instead of boxing, objects of reference type are simplified into data of value type

Look at the following code

m1

What is the print result?

"= =" compares addresses, but the addresses of a and B objects are different, that is, they are two objects, so they are both false

Parse bytecode through javap, as follows

m2

The print result is

A and B are still two objects

Javap parsing content

m3

Print results

Why is the first true and the second false? Observe the data parsed by javap

Javap parsing content

m4

Print results

Javap parsing content

analysis

Javap is a built-in tool for Java. You can decompile or view the bytecode generated by the java compiler (the above code only uses javap - C datatype). It is a good tool for analyzing code. Please Google how to use it

Let's take a look M4. Why does "true" appear in the running result? True indicates that a and B are the same object.  

But the a object calls integer Valueof (), B is an object generated by auto boxing. Why is it the same object? Take another look at bytecode. After all, Java programs rely on bytecode running in virtual machines.

M41 this method is only applicable to valueof() once, but it occurs twice in the bytecode, indicating that valueof() is also called during automatic boxing.

The following is the concrete implementation of valueof()

For the number between [- 128127], valueof returns the object in the cache, so the two calls return the same object.

Thank you for reading, hope to help you, thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>