Java Programming - Java.lang Class - Discussion

12. 

What will be the output of the program?

try 
{
    Float f1 = new Float("3.0");
    int x = f1.intValue();
    byte b = f1.byteValue();
    double d = f1.doubleValue();
    System.out.println(x + b + d);
}
catch (NumberFormatException e) /* Line 9 */
{
    System.out.println("bad number"); /* Line 11 */
}

[A]. 9.0
[B]. bad number
[C]. Compilation fails on line 9.
[D]. Compilation fails on line 11.

Answer: Option A

Explanation:

The xxxValue() methods convert any numeric wrapper object's value to any primitive type. When narrowing is necessary, significant bits are dropped and the results are difficult to calculate.


Div said: (Oct 20, 2011)  
How it s 9? in System.out.println + means concatenation and not (+ ie add).

Suri said: (May 30, 2012)  
Auto unboxing so they are automatticalyy convert into primitive.

Vikas Sahay said: (Apr 24, 2013)  
But how can we add two different data type?

Tanaji Sen said: (Jul 25, 2015)  
Someone please elaborate. I don't know the concept of wrapper class.

Bj Venu said: (Dec 25, 2015)  
How we can add different data types?

Ejaz said: (Feb 12, 2016)  
Automatic conversion will make all the variables in print statement to double and then add it to become 9.0.

Subha said: (Feb 8, 2019)  
I think that,

x = int means it covert tat 3.0 as 3.
b = byte so that it takes byte as 0.
z = double means it takes the value as double which is 6.0
3 + 0 + 6.0 = 9.0.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.