Java Programming - Java.lang Class - Discussion


What will be the output of the program?

public class NFE 
    public static void main(String [] args) 
    String s = "42";
            s = s.concat(".5");  /* Line 8 */
            double d = Double.parseDouble(s);
            s = Double.toString(d);
            int x = (int) Math.ceil(Double.valueOf(s).doubleValue());
        catch (NumberFormatException e) 
            System.out.println("bad number");

[A]. 42
[B]. 42.5
[C]. 43
[D]. bad number

Answer: Option C


All of this code is legal, and line 8 creates a new String with a value of "42.5". Lines 9 and 10 convert the String to a double and then back again. Line 11 is fun— Math.ceil()'s argument expression is evaluated first. We invoke the valueOf() method that returns an anonymous Double object (with a value of 42.5). Then the doubleValue() method is called (invoked on the newly created Double object), and returns a double primitive (there and back again), with a value of (you guessed it) 42.5. The ceil() method converts this to 43.0, which is cast to an int and assigned to x.

Bikashjyoti said: (Apr 30, 2013)  
How can we parse a String value to Double. Is it possible?

Rajesh said: (Oct 25, 2013)  
Yes it is possible because all Wrapper classes are having a constructor which accepts the String as it's argument. i.e Double(String obj);

Krishna said: (Apr 19, 2016)  
Yes, you are right @Rajesh.

Artspade said: (Jul 27, 2017)  
Ceil reduces, how comes it's rounded to nearest?

Salik said: (Jul 22, 2018)  
I think this will do compilation error because the string is an immutable object. We can't append any without creating a new object.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.