Java Programming - Java.lang Class
- Java.lang Class - General Questions
- Java.lang Class - Finding the output
- Java.lang Class - Pointing out the correct statements
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");
}
}
}
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.
What will be the output of the program?
System.out.println(Math.sqrt(-4D));
It is not possible in regular mathematics to get a value for the square-root of a negative number therefore a NaN will be returned because the code is valid.
interface Foo141
{
int k = 0; /* Line 3 */
}
public class Test141 implements Foo141
{
public static void main(String args[])
{
int i;
Test141 test141 = new Test141();
i = test141.k; /* Line 11 */
i = Test141.k;
i = Foo141.k;
}
}
The variable k on line 3 is an interface constant, it is implicitly public, static, and final. Static variables can be referenced in two ways:
Via a reference to any instance of the class (line 11)
Via the class name (line 12).
String a = "newspaper";
a = a.substring(5,7);
char b = a.charAt(1);
a = a + b;
System.out.println(a);
Both substring() and charAt() methods are indexed with a zero-base, and substring() returns a String of length arg2 - arg1.
public class StringRef
{
public static void main(String [] args)
{
String s1 = "abc";
String s2 = "def";
String s3 = s2; /* Line 7 */
s2 = "ghi";
System.out.println(s1 + s2 + s3);
}
}
After line 7 executes, both s2 and s3 refer to a String object that contains the value "def". When line 8 executes, a new String object is created with the value "ghi", to which s2 refers. The reference variable s3 still refers to the (immutable) String object with the value "def".