Java - Convert String to primitive

Introduction

Primitive Wrapper classes help in working with strings containing primitive values.

  • Use the valueOf() methods to convert strings into wrapper objects.
  • Use the parseXxx() methods to convert strings into primitive values.

The Byte, Short, Integer, Long, Float, and Double classes contain parseByte(), parseShort(), parseInt(), parseLong(), parseFloat() and parseDouble() methods to parse strings into primitive values, respectively.

The following snippet of code converts a string containing an integer in binary format into an Integer object and an int value:

String str = "01111111";
int radix = 2;

// Creates an Integer object from the string
Integer intObject = Integer.valueOf(str, radix);

// Extracts the int value from the string
int intValue = Integer.parseInt(str, 2);

System.out.println("str = " + str);
System.out.println("intObject = " + intObject);
System.out.println("intValue = " + intValue);

The following snippet of code attempts to parse two strings into double values.

The first string contains a valid double and the second one an invalid double. A NumberFormatException is thrown when the parseDouble() method is called to parse the second string.

String str1 = "123.89";
try {
        double value1 = Double.parseDouble(str1);
        System.out.println("value1 = " + value1);
}
catch (NumberFormatException e) {
        System.out.println("Error in parsing " + str1);
}

String str2 = "abc"; // An invalid double
try {
        double value2 = Double.parseDouble(str2);
        System.out.println("value2 = " + value2);
}
catch (NumberFormatException e) {
   System.out.println("Error in parsing " + str2);
}

Related Topic