English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)/O)

Java Reader/Writer

Java Other Topics

Java program converts string (string) type variable to int

Java Examples Comprehensive

In this program, we will learn how to convert a String type variable to an integer (int) in Java.

To understand this example, you should understand the followingJava ProgrammingTopic:

Example1: Java program that uses parseInt() to convert string to int

class Main {
  public static void main(String[] args) {
    //Create a string variable
    String str1 "23";
    String str2 "4566";
    //Convert string to int
    //use parseInt()
    int num1 = Integer.parseInt(str1);
    int num2 = Integer.parseInt(str2);
    //Print int value
    System.out.println(num1);    // 23
    System.out.println(num2);    // 4566
  }
}

In the above example, we used the parseInt() method of the Integer class to convert a string variable to an int.

Here, Integer is a wrapper class in Java. For more information, please visitJava Wrapper Class.

Note: A string variable should represent an int value. Otherwise, the compiler will throw an exception. For example,

class Main {
  public static void main(String[] args) {
    //Create a string variable
    String str1 = "w3codebox";
    //Convert string to int
    //use parseInt()
    int num1 = Integer.parseInt(str1);
    //Print int value
    System.out.println(num1);    // throws an exception NumberFormatException
  }
}

Example2: Java program uses valueOf() to convert string to int

We can also use the valueOf() method to convert a string variable to an Integer object. For example,

class Main {
  public static void main(String[] args) {
    //Create a string variable
    String str1 "643";
    String str2 "1312";
    //Convert string to int
    //Using valueOf()
    int num1 Integer.valueOf(str1);
    int num2 Integer.valueOf(str2);
    // Print int value
    System.out.println(num1);    // 643
    System.out.println(num2);    // 1312
  }
}

In the above example, the valueOf () method of the Integer class converts the string variable to int.

In this case, the valueOf () method actually returns an Integer object of the class. However, the object is automatically converted to the primitive type. This is called unboxing in Java. For more information, please visitJava Auto-boxing and Unboxing.

That is,

// valueOf() returns an Integer object
// Object to int conversion
int num1 Integer obj = Integer.valueOf(str1)

  Java Examples Comprehensive