Computer Applications
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);
Answer
(i)
Output
35takes home2400
bmi : 22.913774881799036
(ii) Autoboxing is not happening in this code as the valueOf() method returns the Wrapper class object. Thus, we are explicitly boxing the primitive type values to Wrapper objects in the following statements:
Short age = Short.valueOf("35");
Integer salary = Integer.valueOf("2400");
Float height = Float.valueOf("1.78"); // in meters
Double weight = Double.valueof ("72.6");
(iii) Auto-unboxing is taking place in the following statements:
double b = weight / (height * height);
The Wrapper class objectsweightandheightare being auto-unboxed before mathematical operations can be performed on them.System.out.println(age + "takes home" + salary);
The Wrapper class objectsageandsalaryare being auto-unboxed before they can be printed as objects cannot be printed directly like primitive data type values.
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));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);