Varun
Varun

Reputation: 209

Passing int to a method taking Integer as parameter?

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

Answers (4)

Christian Tapia
Christian Tapia

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

Elliott Frisch
Elliott Frisch

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

peter.petrov
peter.petrov

Reputation: 39447

Yes, it is OK, it will be auto-boxed.

The reverse is also OK and is called auto unboxing.

More info here:

Autoboxing and Unboxing

Upvotes: 7

FrancescoDS
FrancescoDS

Reputation: 995

Yes it is possible to do it, and it is possible to do also the opposite (from Integer to int)

Upvotes: 1

Related Questions