Java examples for Language Basics:Primitive Types
To convert a string to a primitive type, you use a parse method of the appropriate wrapper class.
For example, to convert a string value to an integer, you use statements like this:
public class Main { public static void main(String[] args) { String s = "10"; int x = Integer.parseInt(s); System.out.println(x);/*from w w w. j a va 2 s. co m*/ } }
Methods That Convert Strings to Numeric Primitive Types
Wrapper Class | Parse Method | Example |
---|---|---|
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(String) | boolean x = Boolean.parseBoolean ("true"); |