# casting from int to Integer question

• 07-19-2012, 01:39 PM
Shayy
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
• 07-19-2012, 02:19 PM
cselic
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.
• 07-19-2012, 02:39 PM
Shayy
Re: casting from int to Integer question
Quote:

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];)?
• 07-19-2012, 02:45 PM
Tolls
Re: casting from int to Integer question
Quote:

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.
• 07-19-2012, 03:01 PM
Shayy
Re: casting from int to Integer question