Converting strings to primitives - Java Language Basics

Java examples for Language Basics:Primitive Types

Introduction

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:

Demo Code

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 ClassParse Method Example
Integer parseInt(String) int x = Integer.parseInt("100");
Short parseShort(String)short x = Short.parseShort("100");
LongparseLong(String) long x = Long.parseLong("100");
ByteparseByte(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");

Related Tutorials