Home / Java Programming / Java.lang Class :: Discussion

Discussion :: Java.lang Class

  1. What will be the output of the program?

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

  2. A.
    42
    B.
    42.5
    C.
    43
    D.
    bad number

    View Answer

    Workspace

    Answer : Option C

    Explanation :

    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.


Be The First To Comment