Basic data types and wrapper classes in Java __java

Source: Internet
Author: User
Tags float double wrapper wrappers

Reference: Deep analysis of Java in the boxing and unboxing;
The use of buffering mechanisms in Java for basic data types and wrapper classes in the interchange;
Java Learning notes: Boxing and unboxing, wrappers and buffer pools
Java various types of data in memory allocation in a detailed Java memory allocation

Here is just some information found on the Internet;
The data types in Java are divided into
1. Basic type (original data type) byte short int long float double char Boolean
A variable of the base type holds the original value.
2. Conforms to the data type (reference type), the reference type holds the reference value (that is, a reference to an object, not the object itself).

General Java involves the following areas when allocating memory:
1. Registers: We cannot control in the program
2. Stack: Hold the base type of data and object references , but the object itself is not stored in the stack, but stored in the heap
3. Heap: Storing data produced with new
4. Static domain: Static members that are stored in the object with static definitions
5. Constant pool: Storing constants
6. Non-RAM storage: Hard disk and other permanent storage space
Which is mainly the heap, the storage of the stack. Heap, Stack

Some of the basic types of data variables defined in the function and the reference variables of the objects are allocated in the function's stack memory.
The Advantage of the stack is that the access rate is faster than the heap, second only to the registers directly located in the CPU, and the data can be shared. However, the data size and life cycle in the stack must be determined.
When a variable is defined in a block of code, Java allocates memory space for the variable in the stack , and when the variable exits the scope, Java automatically releases the memory space allocated for the variable, which can be used as an immediate alternative.

heap Memory is used to store objects and arrays created by new. The memory allocated in the heap is managed by the automatic garbage collector of the Java Virtual machine.
After generating an array or object in the heap, you can also define a special variable in the stack so that the value of the variable in the stack equals the first address of the array or object in the heap memory, and the variable in the stack becomes the reference variable for the array or object.
A reference variable is a normal variable that is assigned in the stack when defined, and the reference variable is released after the program runs beyond its scope. and the arrays and the objects themselves are allocated in the heap, even if the program runs to a block of code that uses new to produce an array or an object's statements, the memory occupied by the array and the object itself is not freed, and the array and object become garbage when they point to it without a reference variable, and cannot be used, but still occupy the memory space. Be taken Away (released) by the garbage collector at a later uncertain time. two basic data types

This type is passed through such as int a=7; To define the form, called an automatic variable. Here the automatic variable is a literal value. is not an instance of a class, that is, a reference to a class , where there is no class. A is a reference to an int type, pointing to the literal value of 7. Because its size determines the lifetime known (these definitions are in a program block, the field values disappear after the program block exits), so there is a stack .
Because the stack of data can be shared, so int a=3; int b=3; This code, the compiler first deals with int a = 3; , you will first create a reference to a in the stack, and then look for an address with a literal value of 3, and if not, open an address that holds the value of 3, and then point A to the address of 3. Next process int b = 3; After creating the reference variable, B points to the address of 3 because the value of 3 is already in the stack. "Define variable, assign value to variable" three packing class data

The basic types in Java are not object-oriented, they are purely data, and the underlying type data has no other information or operational method other than the information in the value itself. There are many deficiencies in the actual use, in order to solve this problem, * for each basic type is a reference type *, called the boxed basic type.
1, unpacking, packing

Boxing: Creates the corresponding wrapper object based on the data.

Integer i = new Integer (3);
Integer j = 4;//jdk1.5 can be automatically boxed in this way after

Unboxing: Converts a wrapper type to the base data type.

int  index2 = J.intvalue ();
int  index1 = i;//Automatic unboxing

JDK1.5 adds a whole new way to Integer: public static integer valueof (int i) when the automatic boxing process, the compiler calls the static integer valueof (int i) This method is thus integer a=3; ==> Integer a=integer.valueof (3);.

The difference between this method and the new Integer (i) is:
Method invokes a class method to return an Integer instance that represents the specified int value. Method two produces a new integer object.

2, buffer mechanism

There is a clear explanation for this new valueof method in the JDK API documentation:
If you do not need a new integer instance, it is generally preferable to use the method instead of constructing the method Integer (int) because it is possible to significantly improve space and time performance by caching frequently requested values .

To view the valueof method of an integer:

    public static Integer valueof (int i) {
        assert integercache.high >= 127;
        static final int low = -128;
        When -128=<i<=127, the I-de Integer type object is fetched directly in the cache
        if (i >= integercache.low && i <= Integercache.high) return
            Integercache.cache[i + (-integercache.low)];
        Otherwise, the return
        new Integer (i) is created in the heap memory;
    

See for integers of range [-128,127], the valueof method makes special treatment. Adopt Integercache.cache[i + (-integercache.low)]; This method.

View the implementation of the Integercache class as:

    private static class Integercache {static final int low =-128;///min value is fixed static final int high; The static final integer Cache[];//cache cache is an array of type Integer static {//initialized, the maximum can be configured//high value MA
            Y is configured by property int h = 127;
            String Integercachehighpropvalue = Sun.misc.VM.getSavedProperty ("Java.lang.Integer.IntegerCache.high");
                if (integercachehighpropvalue!= null) {int i = parseint (Integercachehighpropvalue);
                i = Math.max (i, 127);
            Maximum array size is integer.max_value h = math.min (i, Integer.max_value-(-low)-1);

            High = h;  cache = new Integer[(high-low) + 1];
            Initialize array int j = low; Buffer data for (int k = 0; k < cache.length k++)///pack -128~127 into 256 objects cache Cache[k
        = new Integer (j + +);

        }Private Integercache () {}} 

There is an integer buffer cache[in memory after initialization of Integercache, and the int value of the -128~127 interval has its corresponding wrapper object. This is the real optimization method of the ValueOf method , when -128=

public class Zhuangxaing {public

    static void Main (string[] args) {
        integer i= new Integer (a);
        Integer j=12;
        Integer k=integer.valueof (a);


        Integer l= new Integer (232);
        Integer m=232;
        Integer n=232;

        Double  q = 232.0;

        System.out.println ("Use = = ...");    
        System.out.println (i==12);
        System.out.println (i==j);
        System.out.println (j==k);

        System.out.println (l==232);
        System.out.println (l==m);
        System.out.println (m==n);

        System.out.println ("Use equals ...");
        System.out.println (M.equals (n));
        System.out.println (M.equals (q));

    }

Output results:

Use = = ...
.. True to true false to false to use
equals ...
. True
false

Integer i= new Integer (12); Refers to the creation of objects in heap memory;
Integer j=12; is automatic boxing, calling the ValueOf method, returning return INTEGERCACHE.CACHE[12 + 128], resulting in an object in the integer buffer pool. Integer k=integer.valueof (12); and integer j=12; Essentially the same, point to the same object in the buffer pool. Packaging objects and numerical comparison, automatic unpacking .
For a value greater than 127, the return new Integer (i) is executed in heap memory, but the address is different.

The value size is compared for the Equals method:

public boolean equals (Object obj) {
        if (obj instanceof Integer) {return
            value = = ((Integer) obj). Intvalue ()
        ; return
        false;
    }

You can see that the comparison of obj, if it is an instance of Integer, compares the values after the unboxing to be equal. otherwise returns false.

2, what is the output of the following code:

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);
    }
False
//false

Because the valueof method of the double class uses a different implementation than the ValueOf method of the integer class. It's simple: the number of integer values within a range is limited, but the floating-point numbers are not.

Other wrappers:
Boolean: (All cached)
Byte: (All cached)

Character (<=127 Cache)
Short ( -128~127 cache)
Long ( -128~127 Cache)

Float (no cache)
Doulbe (no cache)

3, what is the output of the following code:

public class Main {public
    static void Main (string[] args) {

        Boolean i1 = false;
        Boolean i2 = false;
        Boolean i3 = true;
        Boolean I4 = true;

        System.out.println (I1==I2);
        System.out.println (I3==I4);
    }

First look at the Boolean source, the implementation of the ValueOf method:

public static Boolean valueof (Boolean b) {return
        (b) True:false);
    }

And what is TRUE and false in it. 2 static member properties are defined in Boolean:

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);

It can be shown that the above code output is true.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.