Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Integer to int and vice versa

Tags:

java

Just wondered why is it possible to pass Integer as argument where method parameter is of int type and vice versa?

public class Salmon {

 public static Integer foo(Integer a, int b){
  return a - b;
 }
 public static void main(String[] args) {
  Integer a = 10;
  int b = 1;
  foo(b, a);
 }
}
like image 553
Eugene Avatar asked Oct 29 '10 12:10

Eugene


People also ask

Can you pass an int into a double parameter?

Because you can set a double to an integer, then integer as argument is ok to function with double as parameter.

Can you pass an int as a double Java?

We can convert int to double in java using assignment operator. There is nothing to do extra because lower type can be converted to higher type implicitly. It is also known as implicit type casting or type promotion.


1 Answers

This is auto-boxing and auto-unboxing. Basically the compiler puts in calls to Integer.valueOf() or x.intValue() appropriately.

The exact mechanism isn't actually specified, but the relevant sections of the spec are 5.1.7 and 5.1.8.

like image 77
Jon Skeet Avatar answered Nov 01 '22 12:11

Jon Skeet