Parsing Strings

All primitive data types — except char — have methods that allow you to convert a string value to the primitive type. These methods are listed in the following table.

Wrapper

parse Method

Example Statement

Integer

parseInt(String)

int x = Integer.parseInt(“100”);

Short

parseShort(String)

short x = Short.parseShort(“100”);

Long

parseLong(String)

long x = Long.parseLong(“100”);

Byte

parseByte(String)

byte x = Byte.parseByte(“100”);

Float

parseByte(String)

float x = Float.parseFloat (“19.95”);

Double

parseByte(String)

double x = Double.parseDouble (“19.95”);

Boolean

parseBoolean

boolean x = Boolean.parseBoolean

Here’s an example that converts a String to an int:

String s = “10”;

int x = Integer.parseInt(s);

Note: An exception is thrown if the string does not contain a value that can be converted to a number of the appropriate type.

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.