简体   繁体   中英

What happens when we create instance of Integer class in java

I have a confusion regarding the following code:

import java.util.*;

public class HelloWorld {
    private int x;
    public HelloWorld(int x) {
       this.x = x;
    }
    public static void main(String[] args) {
       HelloWorld o1 = new HelloWorld(5);
       HelloWorld o2 = new HelloWorld(5);
       System.out.println(o1);
       System.out.println(o2);
       Integer i = new Integer(1);
       Integer j = new Integer(10);
       System.out.println(i);
       System.out.println(j);
    } 
}

Clearly, I made two objects of HelloWorld class and two objects of Integer class. When I print them the output is like:

HelloWorld@6d06d69c
HelloWorld@7852e922
1
10

My doubt is when I created Object of helloWorld class the objects store some references but when I create instance of Integer class, the values are stored in objects. Why is this happening.

Is there a way to directly store values in HelloWorld class objects also.

I have also noticed that whenever I create objects for any inbuilt class in java like String, Character, List, Map... they all store values. So what is that present additionally in these inbuilt classes.

My doubt is when I created Object of helloWorld class the objects store some references but when I create instance of Integer class, the values are stored in objects.

No, the value is being stored as a field within the instance (of HelloWorld or Integer ) in both cases.

Is there a way to directly store values in HelloWorld class objects also.

That's what your code does.

If you want to change how instances of your HelloWorld class are converted to string, override toString . For instance:

@Override
public String toString() {
    return String.valueOf(this.x);
}

The output you're seeing now is the output of the default toString from Object .

Java's compiler supports autoboxing and unboxing for primitives and wrapper classes.

You can read about it here .

In your example, method println expects int , which is primitive. So compiler automatically unboxes it from Integer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM