How to convert string to int in java

The propose of this tutorial is to guide you how to convert a string data to int in Java, it’s very basic skill for a Java developer.

(1). Use method parseInt() in class Integer to covert string object to int.

public class ConvertStringToInt {
  public static void main(String[] args){
  String str = "124";
  int strInt = Integer.parseInt(str);
}
}

(2). Alternatively, method valueOf() in class Integer can also be used to covert string to int, this is a piece of codes to covert string to int.

  String str = "124";
  int strInt = Integer.valueOf(str);

Notice if the string is not a number pattern, the conversation will fail and a NumberFormatException will be thrown, in case you should handle in a try/catch block.

Оцените статью
ASJAVA.COM
Добавить комментарий

Your email address will not be published. Required fields are marked *

*

code