159.
160.
A String can be converted to a Double using the
Double.parseDouble() method as shown below:
Double doubleValue = Double.parseDouble(“100.55”);
A Double can be converted to a String using the
Double.toString() method as shown below:
String stringValue = Double.toString(100.55);
What will be the output the following code?
Double doubleValue = Double.parseDouble(“Java”);
System.out.println(doubleValue);
Answer:
The above code compiles fine. However,
on execution it throws a
NumberFormatException. This is because the JVM cannot
convert the String Java to a Double value.
What is a Wrapper class in Java? What are the special
properties of Wrapper class objects?
Answer:
Java is an Object–oriented language.
The primitive data types in
Java are not objects. Sometimes, you will need object
equivalents of the primitive types.
A good example is when you
want to use Collections. Collections can only contain objects and
not primitive types. To solve this issue,
Java introduced wrapper
classes that wrap primitive types into objects. Each primitive has
a corresponding wrapper class and you can create an object of
that type. In the same way you can
convert a wrapper object to
the primitive type too. For example, corresponding to the “int”
primitive type, Java has the java.lang.Integer wrapper class. Java
161.
automatically converts between the primitive types and the
corresponding wrapper classes.
Explain Autoboxing with an example.
Answer:
Autoboxing referred to as Boxing
or Unboxing is a feature
introduced in Java 5 which helps programmers to reduce some
lines of code.
For example, in order to assign a primitive value to a wrapper
class, you will need to write wrapping code as follows:
Integer integerValue = new Integer(1000); //wrapping
With autoboxing, the above code can be re–written as follows:
Integer integerValue = 1000;
So also, in order to assign a wrapper class
to a primitive you will
need to write unwrapping code as follows:
Integer integerValue = 1000;
int iValue = integerValue.intValue(); //unwrapping
With autoboxing, the above code can be re–written as follows:
Integer integerValue = 1000;
int iValue = integerValue;