To convert a String to an int in Java, use Integer.parseInt() for a primitive int or Integer.valueOf() for an Integer object.
Integer.parseInt(String s):Returns a primitive
int.Throws a
NumberFormatExceptionif the string is invalid (e.g., contains non-numeric characters, is empty, or isnull).Example:
String str = "123"; int num = Integer.parseInt(str); System.out.println(num); // Output: 123
Integer.valueOf(String s):Returns an
Integerobject (wrapper class).Also throws
NumberFormatExceptionfor invalid inputs.Useful when working with collections like
ArrayList<Integer>.Internally uses
parseInt().
Always handle exceptions when converting strings to integers to avoid runtime crashes:
String str = "123x";
try {
int num = Integer.parseInt(str);
System.out.println("Converted: " + num);
} catch (NumberFormatException e) {
System.out.println("Invalid number format: " + str);
}✅ Best Practice: Use
Integer.parseInt()for primitiveintand wrap it in atry-catchblock to handle invalid inputs safely.
❌ Avoid using the deprecatedInteger(String s)constructor.
There are multiple ways:
String.valueOf(number)(my preference)"" + number(I don't know how the compiler handles it, perhaps it is as efficient as the above)Integer.toString(number)
There are multiple ways:
String.valueOf(number)(my preference)"" + number(I don't know how the compiler handles it, perhaps it is as efficient as the above)Integer.toString(number)
Integer class has static method toString() - you can use it:
int i = 1234;
String str = Integer.toString(i);
Returns a String object representing the specified integer. The argument is converted to signed decimal representation and returned as a string, exactly as if the argument and radix 10 were given as arguments to the toString(int, int) method.
Java convert an Int to a String | Go4Expert
Converting a Number to a String
how to convert int to string
JAVA: How to turn stringbuilder to Int.
Q1. Why do we need to convert a string to an int in Java?
Q3. How to convert a string to an integer without using any direct method in Java?
Q2. What is the difference between Integer.valueOf() and Integer.parseInt()?
Videos
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)
For example, here are two ways:
Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);
There is a slight difference between these methods:
valueOfreturns a new or cached instance ofjava.lang.IntegerparseIntreturns primitiveint.
The same is for all cases: Short.valueOf/parseShort, Long.valueOf/parseLong, etc.
Hey, all. I was working on some Codewars fundamentals and I came across this problem. My solution was accepted and, on the list of acceptable solutions, I see what seems to be an equally useful solution. I just wondered if there's any reason to use one over the other in any particular situation or if they do the same thing all the time. The passed in variable was some integer num.
My solution was:
return Integer.toString(num);
The other solution I saw was:
return String.valueOf(num);
Any insight would be much appreciated. Thanks!
Things I like about your code
- The idea to calculate the length of a number with the logarithm is really good!
- In my opinion you are writing good comments.
- Good variable names
- Works as intended, without (to my knowledge) any bugs.
Criticism
returnDigitString()
- It is considered bad practice to put more than one command into one line. So please make line breaks after every ";".
- Your solution is pretty long (over 30 lines) in comparison to the complexity of the problem. You could also have done something like that:
public static String returnDigitString(int digit) {
String res = "";
String[] digits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
for(int i = 0; i <= 9; i++) {
if(digit == i) {
res += digits[i];
break;
}
}
return res;
}
main()
- You are not using the array "reverseStr". The String "digits" is not used either.
- When I started your program the first time, I didn't know what to do, because your program didn't tell me. Before scanning a user input, I would tell the user to input something.
System.out.println("Please enter number:");
Scanner scn = new Scanner(System.in);
int number = scn.nextInt();
If you want to improve this point even further (which is highly recommended!), you can use something like that (you will have to use import java.util.InputMismatchException;):
System.out.println("Please enter number:");
Scanner scn = new Scanner(System.in);
int number;
while(true) {
try {
number = scn.nextInt();
break;
}
catch(InputMismatchException e) {
System.out.println("That's not a number!");
scn.nextLine();
}
}
This will check, whether the user really enters a number. If the user enters something else, the program will ask him again to enter a number.
- Something like that is considered bad practice:
if(number != 0) {
length = ( int ) (Math.log10(number) + 1 );}
Please write
if(number != 0) {
length = (int) (Math.log10(number) + 1);
}
instead.
- "valStr" is not necessary. You can just write:
strSeq = returnDigitString(remainder) + strSeq;
But this really is a minor point and just my personal opinion. It's fine to use an extra variable for this.
Codestructure
- I would use an extra method for the content of the main-method. Just use the main-method to call the new method.
Personally I think your algorithm has been made a lot more complex than needed.
Is the concatenation a requirement? If not, you can simplify by directly converting each digit into a char and storing it in a char[]. This way instead of inefficiently concatenating each digit onto the string, you can use the string constructor overload that takes a char[].
With this simplification, the method can be reduced to just a few lines:
public static String intToString(int num) {
if(num == 0){
return "0";
}
int count = 0;
boolean isNeg = false;
if (num < 0) {
num *= -1;
count = 1;
isNeg = true;
}
count += (int) Math.log10(num) + 1;
char[] digits = new char[count];
if (isNeg) {
digits[0] = '-';
}
--count;
while(num > 0) {
digits[count--] = (char) ((num % 10) + '0');
num /= 10;
}
return new String(digits);
}