Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to convert a String to an int in Java language?

How can I convert a String to an int in Java?
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.
by

3 Answers

Kajalsi45d

String myString = "1234";
int foo = Integer.parseInt(myString);


On the off chance that you take a gander at the Java documentation, you'll see the "get" is that this capacity can toss a NumberFormatException, which obviously you need to deal with

int foo;
try {
foo = Integer.parseInt(myString);
}
catch (NumberFormatException e)
{
foo = 0;
}


(This treatment defaults a deformed number to 0, however you can accomplish something different on the off chance that you like.)

On the other hand, you can utilize an Ints technique from the Guava library, which in mix with Java 8's Optional, makes for an amazing and brief approach to change over a string into an int:

import com.google.common.primitives.Ints;

int foo = Optional.ofNullable(myString)
.map(Ints::tryParse)
.orElse(0)
Bharatv4tg1
Returns null if the string couldn't be parsed, for example:

Integer fooInt = Ints.tryParse(fooString);
if (fooInt != null) {
...
}
hawaiian
In Java, you can convert a String to an int using various methods provided by the language. Here are some common approaches:

Using Integer.parseInt():
java
Copy code
String str = "123";
int intValue = Integer.parseInt(str);
System.out.println(intValue); // Output: 123
Using Integer.valueOf():
java
Copy code
String str = "456";
int intValue = Integer.valueOf(str);
System.out.println(intValue); // Output: 456
Using Integer.decode() (accepts decimal, octal, or hexadecimal representations):
java
Copy code
String str1 = "789";
String str2 = "0xFF"; // Hexadecimal representation for 255
int intValue1 = Integer.decode(str1);
int intValue2 = Integer.decode(str2);
System.out.println(intValue1); // Output: 789
System.out.println(intValue2); // Output: 255
It's important to note that these methods will throw a NumberFormatException if the input String cannot be parsed as a valid integer. So, when using any of these methods, make sure to handle this exception appropriately, especially if you're getting the String input from user input or external sources. You can use try-catch blocks to handle the exception and take appropriate action if the input is not a valid integer.

Login / Signup to Answer the Question.