Java Programming - Java.lang Class - Discussion
Discussion Forum : Java.lang Class - Finding the output (Q.No. 16)
16.
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");
}
}
}
Answer: Option
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.
Discussion:
5 comments Page 1 of 1.
Salik said:
7 years ago
I think this will do compilation error because the string is an immutable object. We can't append any without creating a new object.
Artspade said:
8 years ago
Ceil reduces, how comes it's rounded to nearest?
Krishna said:
9 years ago
Yes, you are right @Rajesh.
Rajesh said:
1 decade ago
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);
BIKASHJYOTI said:
1 decade ago
How can we parse a String value to Double. Is it possible?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers