M.Moi - 3 months ago 20

Java Question

I am confused between these three codes

`int a = 5;`

int b = 6;

int c = 5;

and

`Integer x = new Integer(5);`

Integer y = new Integer(6);

Integer z = new Integer(5);

and

`Integer i = 5;`

Integer j = 6;

Integer k = 5;

I know that the first one are some variables that contain values and the second one are some variables reference to some different objects, but what is the third one? I know that they are reference data types.

But I can't understand why and how many objects created... if any!

Answer

`Integer`

is a (wrapper) class name and so the variables of this type are objects. When `x`

is assigned the value of `new Integer(5)`

then, ethically, you cannot use x directly for mathematical operations. To use x in operations, you have to use the wrapper class method `intValue()`

to get x's value in numeric (primitive) form from object form.

Eg.:

```
Integer x = new Integer(5);
int my_x = x.intValue();
int y = 10 + my_x; //y = 15
```

However, using x directly in mathematical ops would not produce an error and, in fact, will produce the same output as going through the above step will. This is because the JVM **implicitly** converts the object to primitive data value and this process is called **Auto boxing**. The inverse, when implicitly done, is called **Un-boxing**. Therefore, in the above example, you can also do this:

```
Integer x = new Integer(5);
int y = 10 + x; //y = 15;
```

Hope you now understand.