How do I convert a String to an int in Java?

0 votes
My String contains only numbers, and I want to return the number it represents.

For example, given the string "1234" the result should be the number 1234.

How can I convert a String to an int in Java?
Jul 28 in Java by kartik
• 36,040 points
89 views

1 answer to this question.

0 votes

Hello @kartik,

We can use the parseInt(String str) method of the Integer wrapper class for converting a String value to an integer value.

For example:

String strValue = "12345";
Integer intValue = Integer.parseInt(strVal);

The Integer class also provides the valueOf(String str) method:

String strValue = "12345";
Integer intValue = Integer.valueOf(strValue);

We can also use toInt(String strValue) of NumberUtils Utility Class for the conversion:

String strValue = "12345";
Integer intValue = NumberUtils.toInt(strValue);

Hope it helps!!
Thank you!

answered Jul 28 by Niroj
• 78,520 points

Related Questions In Java

0 votes
2 answers

How can I convert a String variable to a primitive int in Java

 Here are two ways illustrating this: Integer x ...READ MORE

answered Aug 20, 2019 in Java by Sirajul
• 58,210 points
559 views
0 votes
2 answers
0 votes
2 answers

How to convert an int array to string using tostring method in java?

Use java.util.Arrays: String res = Arrays.toString(array); System. ...READ MORE

answered Aug 16, 2019 in Java by Sirajul
• 58,210 points
922 views
0 votes
2 answers

How do I read and convert an InputStream object to string type?

You can also use Java Standard Library ...READ MORE

answered Jul 17, 2018 in Java by Sushmita
• 6,890 points
10,793 views
0 votes
1 answer

How to avoid Java code in JSP files?

Hello @kartik, JSTL offers tags for conditionals, loops, sets, ...READ MORE

answered Jul 28 in Java by Niroj
• 78,520 points
52 views
0 votes
1 answer

How to directly initialize a HashMap?

Hello @Kartik, In plain java 8 you also ...READ MORE

answered Jul 28 in Java by Niroj
• 78,520 points
76 views
0 votes
1 answer

How can I get the current stack trace in Java?

Hello @kartik, Try this: Thread.currentThread().getStackTrace(); is fine if you don't ...READ MORE

answered Jul 28 in Java by Niroj
• 78,520 points
78 views
0 votes
1 answer
0 votes
1 answer

How to get an enum value from a string value in Java?

Hello @kartik, Yes, Blah.valueOf("A") will give you Blah.A. Note that the name ...READ MORE

answered Jul 28 in Java by Niroj
• 78,520 points
163 views
0 votes
1 answer

How do I make a list with checkboxes in Java Swing?

Hii @kartik, Create a custom ListCellRenderer and asign it to ...READ MORE

answered May 7 in Java by Niroj
• 78,520 points
355 views