How do I convert a String to an int in Java?
String myString = "1234";
int foo = Integer.parseInt(myString);
If you look at the Java documentation you'll notice the "catch" is that this function can throw a NumberFormatException
, which you can handle:
int foo;
try {
foo = Integer.parseInt(myString);
}
catch (NumberFormatException e) {
foo = 0;
}
(This treatment defaults a malformed number to 0
, but you can do something else if you like.)
Alternatively, you can use an Ints
method from the Guava library, which in combination with Java 8's Optional
, makes for a powerful and concise way to convert a string into an int:
import com.google.common.primitives.Ints;
int foo = Optional.ofNullable(myString)
.map(Ints::tryParse)
.orElse(0)
Java String to Integer Conversion
use int month = Integer.parseInt(stringMonth);
how to convert a string to an int in java and and separate the values of the string?
If your string is strictly of the form "a b" where a is in the range a a - z, and b is a number in the range 0 - 9 then do something like
/* s is your string */
int row = s.charAt(0) - 'a' + 1;
int col = s.charAt(2) - '0' + 1;
where I've exploited the ASCII character number values and the fact that 'a' is a byte data type.
Of course, in production, you ought to pre-validate s
(check its length, whether or not the second character is a space etc. You could even use a regular expression check via Java's String.matches
method). All you'd have to do is check if
s.matches("[a-z] [0-9]")
is true. My method is a throwback to the good old C days.
Manually converting a string to an integer in Java
And what is wrong with this?
int i = Integer.parseInt(str);
EDIT :
If you really need to do the conversion by hand, try this:
public static int myStringToInteger(String str) {
int answer = 0, factor = 1;
for (int i = str.length()-1; i >= 0; i--) {
answer += (str.charAt(i) - '0') * factor;
factor *= 10;
}
return answer;
}
The above will work fine for positive integers, if the number is negative you'll have to do a little checking first, but I'll leave that as an exercise for the reader.
How to convert String to int and call method on it?
Try using Integer.valueOf(age)
insted of (int) age
Converting a String with spaces to an Integer in java
Would .trim work? And if so, how would I use that?
Yes, trim()
will work, it will remove leading and trailing spaces from String
,
int integer = Integer.parseInt(string.trim());
convert string to int in java
try String.replaceAll
String str = "No. of Days : 365";
str = str.replaceAll(".*?(\\d+).*", "$1");
System.out.println(str);
you will get
365
Converting String to Number in Java
Use NumberFormat. Number cannot be instantiated because it is an abstract class.
Number number = NumberFormat.getInstance().parse(string);
Related Topics
Java Refuses to Start - Could Not Reserve Enough Space For Object Heap
Why Maven Uses Jdk 1.6 But My Java -Version Is 1.7
Eclipse/Tomcat: Deploy Doesn't Work Any More (Classnotfoundexception)
Rjava Load Error in Rstudio/R After "Upgrading" to Osx Yosemite
Selenium: How to Stop Geckodriver Process Impacting Pc Memory, Without Calling Driver.Quit()
Is Java "Pass-By-Reference" or "Pass-By-Value"
The Use of Multiple Jframes: Good or Bad Practice
Should I Avoid the Use of Set(Preferred|Maximum|Minimum)Size Methods in Java Swing
Providing White Space in a Swing Gui
What Is Pecs (Producer Extends Consumer Super)
How to Fix Java.Lang.Unsupportedclassversionerror: Unsupported Major.Minor Version
Connect Java to a MySQL Database
How to Round a Number to N Decimal Places in Java
Non-Static Variable Cannot Be Referenced from a Static Context