Newsletter

How to Convert String to int in Java

Core Java » on Oct 15, 2016 { 1 Comment } By Sivateja

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

Java String to int Example

public class StringtoInt {
  
   public static void main(String[] args) {

       String str = "4"; 
       int in = Integer.parseInt(str);    
       System.out.println(in);

   }
}

Output:
4

 

Note:

  • parseInt() will convert string “4” to integer
  • In order to use Integer.parseInt() method, we should pass string having numbers only. If input string contains other than numbers parseInt() function will throw java.lang.NumberFormatException. Would you like to see this scenario with an example ? 🙂 …
public class StringtoInt {
  
   public static void main(String[] args) {

       String str = "4s"; 
       int in = Integer.parseInt(str);    
       System.out.println(in);

   }
}

Output:
Exception in thread “main” java.lang.NumberFormatException: For input string: “4s”
                     at java.lang.NumberFormatException.forInputString(Unknown Source)
                    at java.lang.Integer.parseInt(Unknown Source)
                    at java.lang.Integer.parseInt(Unknown Source)
                    at StringtoInt.main(StringtoInt.java:10)

​ ​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

One Response to “How to Convert String to int in Java”
  1. Anurag Singh says:

    Nice explanation about String to int conversion in java.
    thanks for this useful article.

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.