Constructors and Parsing Methods of Wrapper Classes in Java
Constructors and Parsing Methods of Wrapper Classes in Java
Java
javaconceptoftheday.com /constructors-methods-wrapper-classes-java/
pramodbablad
Skip to content
Today we will discuss about constructors and parsing methods of Wrapper Classes In Java.
Notes :
The string passed to second constructor should be parse-able to number , otherwise you will get run time
NumberFormatException.
Wrapper Class Character has only one constructor which takes char type as an argument. It doesnt have
a constructor which takes String as an argument. Because, String can not be converted into Character.
Wrapper class Float has three constructors. The third constructor takes double type as an argument.
Following example shows constructors in wrapper classes.
Important Note :
If you pass a string other than true or false to the second constructor of Boolean wrapper class, the object is
initialized with false.
public class WrapperClasses
{
public static void main(String[] args)
{
Boolean BLN1 = new Boolean("true"); //passed string "true"
System.out.println(BLN1); //output : true
Boolean BLN2 = new Boolean("false"); //passed string
"false"
System.out.println(BLN2); //output : false
Boolean BLN3 = new Boolean("abc"); //passed string "abc"
System.out.println(BLN3); //output : false
}
}
All wrapper classes in java have methods to parse the given string to corresponding primitive data provided the
string should be parse-able. If the string is not parse-able, you will get NumberFormatException. All parsing
methods of wrapper classes are static i.e you can refer them directly using class name.
public class WrapperClasses
{
public static void main(String[] args)
{
byte b = Byte.parseByte("10");
System.out.println(b); //Output : 10
short s = Short.parseShort("25");
System.out.println(s); //Output : 25
int i = Integer.parseInt("123");
System.out.println(i); //Output : 123
long l = Long.parseLong("100");
System.out.println(l); //Output : 100
float f = Float.parseFloat("12.35");
System.out.println(f); //Output : 12.35
double d = Double.parseDouble("12.87");
System.out.println(d); //Output : 12.87
boolean bln = Boolean.parseBoolean("true");
System.out.println(bln); //Output : true
boolean bln1 = Boolean.parseBoolean("abc");
System.out.println(bln1); //Output : false
char c = Character.parseChar("abc"); //compile time
error
//parseChar() is not defined for Character wrapper class
}
}
Today we will conclude here. Tomorrow, we will discuss about some other methods of wrapper classes in java.
Previous: Wrapper Classes In Java
Next: ValueOf() Method Of Wrapper Classes In Java