Reputation: 209
Is it Ok to pass int to a method which is taking Integer as parameter. Here is the code
public class PassingInt
{
public static void main(String args[])
{
int a = -1;
passIntToInteger(a);//Is this Ok?
}
private static void passIntToInteger(Integer a)
{
System.out.println(a);
}
}
Upvotes: 2
Views: 15775
Reputation: 34146
Yes, it is.
Why? Because of auto-boxing. Primitives are converted to an object of its corresponding wrapper class. From Java Tutorials:
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on.
In your case:
primitive type: int -> wrapper class: Integer
Upvotes: 5
Reputation: 201429
Yes, in your example it would be autoboxed (converted from an int
primitive to an Integer
object) -
public static void main(String args[]) {
int a = -1;
passIntToInteger(a); // <-- Auto Boxing
}
private static void passIntToInteger(Integer a) {
System.out.println(a);
}
Java also has (auto-)unboxing (converting from an Integer
object to an int
primitive) -
public static void main(String args[]) {
Integer a = -1;
passIntegerToInt(a); // <-- Auto Un-Boxing
}
private static void passIntegerToInt(int a) {
System.out.println(a);
}
This allows you to use primitives with collections, otherwise List<Integer>
could not store int
(s) (for example).
Upvotes: 1
Reputation: 39447
Yes, it is OK, it will be auto-boxed.
The reverse is also OK and is called auto unboxing.
More info here:
Upvotes: 7
Reputation: 995
Yes it is possible to do it, and it is possible to do also the opposite (from Integer to int)
Upvotes: 1