2

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);
    }

}
5
  • 2
    Yes it works. You could also do passIntToInteger(new Integer(a)); Commented Jul 9, 2014 at 14:01
  • 4
    @Pphoenix Always use valueOf with the wrappers instead of new. Commented Jul 9, 2014 at 14:03
  • 1
    @chrylis: Thank you! Is there a reason to always do so, or is it just standard? :) Commented Jul 9, 2014 at 14:04
  • @Pphoenix It is actually a performance improvement (micro optimization). valueOf uses a cache for some "common" values, i.e. -127 to +127 internally - that means no object creation needs to happen for these values. One general piece of advice to the OP is to generally avoid using auto-boxing and wrapped types when possible because it hides things that are happening and can bite back: You can get a NullPointerException when unboxing an Integer wrapper type that is null for example. The equals method also has some quirks when working with longs if I remember correctly. Commented Jul 9, 2014 at 14:07
  • @PermaFrost: Thank you, I did not know this before Commented Jul 9, 2014 at 14:08

4 Answers 4

7

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

Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

1

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

Comments

1

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.