Tuesday, 26 December 2017

How to Convert String to int in Java

In Java we can convert string to integer with Integer.parseInt() function.

Syntax:
int in = Integer.parseInt(str); 

Example:


package com.tutorial4u;

public class StringToInt {
       public static void main(String[] args) {
             String str = "4";
              int in = Integer.parseInt(str);   
              System.out.println(in);
       }


}

Output:  4

Note:

In order to use Integer.parseInt() method, we should pass string numbers only. If input string contains other than numbers parseInt() function will throw java.lang.NumberFormatException.


Example:
package com.tutorial4u;

public class StringToInt {
       public static void main(String[] args) {
             String str = "Tutorial4u";
              int in = Integer.parseInt(str);   
              System.out.println(in);
       }


}

Output: 


Exception in thread "main" java.lang.NumberFormatException: For input string: "Tutorial4u"

at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at com.tutorial4u.StringToInt.main(StringToInt.java:6)

No comments:

Post a Comment

No of Occurrence in Array

package com.tutorial4u; import java.util.HashMap; /************************************************************  No of Occurrence in Array...