Converting String to other datatypes


You can convert a numeric string to various Java numeric types as follows:

String to int:
 
	String number = "12";
	int num = Integer.parseInt(number);
 
String to float:
 
	String number = "12.0";
	float num = Float.parseFloat(number);
 
String to double:
 
	String double = "1.47";
	double num = Double.parseDouble(double);
 
String to boolean:
 
	String falseString = "False";
	boolean falseBool = Boolean.parseBoolean(falseString); // falseBool = false
 
	String trueString = "True";
	boolean trueBool = Boolean.parseBoolean(trueString); // trueBool = true
 
String to long:
 
	String number = "47";
	long num = Long.parseLong(number);
 
String to BigInteger:
 
	String bigNumber = "21";
	BigInteger reallyBig = new BigInteger(bigNumber);
 
String to BigDecimal:
 
	String bigFraction = "17.21455";
	BigDecimal reallyBig = new BigDecimal(bigFraction);

Conversion Exceptions:

The numeric conversions above will all throw an (unchecked) NumberFormatException if you attempt to parse a string that is not a suitably formatted number, or is out of range for the target type. The Exceptions topic discusses how to deal with such exceptions.

If you wanted to test that you can parse a string, you could implement a tryParse... method like this:

boolean tryParseInt (String value) { 
	try { 
		String somechar = Integer.parseInt(value);
		return true; 
	} catch (NumberFormatException e) {
		return false; 
	} 
}

However, calling this tryParse... method immediately before parsing is (arguably) poor practice. It would be better to just call the parse... method and deal with the exception.


Base64 Encoding / Decoding

Occasionally you will find the need to encode binary data as a base64-encoded string.

For this we can use the DatatypeConverter class from the javax.xml.bind package:

import javax.xml.bind.DatatypeConverter;
import java.util.Arrays;
 
// arbitrary binary data specified as a byte array
byte[] binaryData = "some arbitrary data".getBytes("UTF-8");
 
// convert the binary data to the base64-encoded string
String encodedData = DatatypeConverter.printBase64Binary(binaryData);
// encodedData is now "c29tZSBhcmJpdHJhcnkgZGF0YQ=="
 
// convert the base64-encoded string back to a byte array
byte[] decodedData = DatatypeConverter.parseBase64Binary(encodedData);
 
// assert that the original data and the decoded data are equal
assert Arrays.equals(binaryData, decodedData)

Apache commons-codec

Alternatively, we can use Base64 from Apache commons-codec.

import org.apache.commons.codec.binary.Base64;
 
// your blob of binary as a byte array
byte[] blob = "someBinaryData".getBytes();
 
// use the Base64 class to encode
String binaryAsAString = Base64.encodeBase64String(blob);
 
// use the Base64 class to decode
byte[] blob2 = Base64.decodeBase64(binaryAsAString);
 
// assert that the two blobs are equal
System.out.println("Equal : " + Boolean.toString(Arrays.equals(blob, blob2)));

If you inspect this program wile running, you will see that someBinaryData encodes to c29tZUJpbmFyeURhdGE=, a very managable UTF-8 String object.

Version ≥ Java SE 8

Details for the same can be found at Base64

// encode with padding
String encoded = Base64.getEncoder().encodeToString(someByteArray);
 
// encode without padding
String encoded = Base64.getEncoder().withoutPadding().encodeToString(someByteArray);
 
// decode a String
byte [] barr = Base64.getDecoder().decode(encoded);

Basic Programs