# Thread: casting from int to Integer question

1. Member
Join Date
Jul 2012
Posts
3
Rep Power
0

## casting from int to Integer question

Hi All,
I'm newbie to Java so please execue me if my question is a bit lame.

I have the following code in the main section of my program:

int num = 100;

Object[] anArray = new Object[10];

for (int i = 0; i < anArray.length; i++) {
if(num % (i+1) == 0){
anArray[i] = num / (i+1);
}
else{
anArray[i] = (double)num / (i+1);
}
}
System.out.println("-------Integers-------");
for (int i = 0; i < anArray.length; i++) {
if(anArray[i] instanceof Integer){
System.out.println(anArray[i]);
}
}
System.out.println("-------Doubles-------");
for (int i = 0; i < anArray.length; i++) {
if(anArray[i] instanceof Double){
System.out.println(anArray[i]);
}
}

What I don't understand is the 'Integer' of this line "if(anArray[i] instanceof Integer)".
When and when did I cast from int Integer?

Shay

2. Senior Member
Join Date
Apr 2010
Location
Posts
278
Rep Power
11

## Re: casting from int to Integer question

^Difference between 'int' and 'Integer' is that you can use 'Integer' like object, but 'int' is just primitive type.

"if(anArray[i] instanceof Integer)"
In this line we are asking if object of anArray at index i is Integer object. If it's Integer object (int type can't be object it's just primitive type) then we are printing result.

3. Member
Join Date
Jul 2012
Posts
3
Rep Power
0

## Re: casting from int to Integer question

Originally Posted by cselic
^Difference between 'int' and 'Integer' is that you can use 'Integer' like object, but 'int' is just primitive type.

"if(anArray[i] instanceof Integer)"
In this line we are asking if object of anArray at index i is Integer object. If it's Integer object (int type can't be object it's just primitive type) then we are printing result.
Hello cselic and thank you for you answer.

So the anArray @ i is of type Integer ("if(anArray[i] instanceof Integer)") because of this line (Object[] anArray = new Object[10];)?

4. Moderator
Join Date
Apr 2009
Posts
13,541
Rep Power
27

## Re: casting from int to Integer question

Originally Posted by Shayy
When and when did I cast from int Integer?

Shay
When you added the 'int' to the array.
It's called autoboxing.
The compiler saw you wanted to add an int to something that holds Objects so autoboxed the int into an Integer.

Same with the Doubles.

5. Member
Join Date
Jul 2012
Posts
3
Rep Power
0

## Re: casting from int to Integer question

I understand now.