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

Java Library Classes

17 Likes

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:

  1. double b = weight / (height * height);
    The Wrapper class objects weight and height are being auto-unboxed before mathematical operations can be performed on them.
  2. System.out.println(age + "takes home" + salary);
    The Wrapper class objects age and salary are being auto-unboxed before they can be printed as objects cannot be printed directly like primitive data type values.

Answered By

12 Likes


Related Questions