Computer Applications
In the following code, identify the statement where autoboxing is taking place :
Integer i = new Integer(10);
if (i < 100)
System.out.println(i);
else
System.out.println(i + 10);
Answer
Autoboxing is not taking place in this code as in the statement Integer i = new Integer(10);, we are explicitly making an Integer object.
if(i < 100)
Auto-unboxing is taking place in this statement, as the value of an object cannot be compared to a numeric value 100 directly but a primitive integer type value can be compared. So, unboxing takes place before the value of i gets compared to 100.
System.out.println(i);
Auto-unboxing is happening in this statement as directly an object cannot be printed but a primitive value can be printed. So, unboxing occurred before the value of i gets printed.
System.out.println(i + 10);
Auto-unboxing is taking place in this statement, as the value of an object cannot be used with + operator like a primitive integer type value. Thus, i gets auto-unboxed to a primitive type value and the value of i gets modified by the + operator.
Related Questions
Predict the output :
double n1 = Double.parseDouble("8.0"); double n2 = Double.parseDouble("2"); System.out.println(n1 + " " + n2);What important is automatically happening in following code ?
long a = 124235L; Long b = new Long(a); long c = b.longValue(); System.out.println(c);Predict the output :
Integer c = 155; Integer d = 155; System.out.println(c == d); System.out.println(c.equals(d));From the following code, do the following :
(i) find its output.
(ii) find out the statements where autoboxing is taking place.
(iii) find out the statements where auto-unboxing is taking place.
Short age = Short.valueOf("35"); Integer salary = Integer.valueOf("2400"); Float height = Float.valueOf("1.78"); // in meters Double weight = Double.valueof ("72.6"); double b = weight / (height * height); System.out.println(age + "takes home" + salary); System.out.println("bmi : " + b);