For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
In Java programming, converting data from one type to another is a basic yet essential skill. One of the most common conversions you'll encounter is turning a String into an int. For example, user inputs, file data, or API responses often come as Strings—even if they represent numbers.
Converting these Strings to integers allows you to perform calculations, comparisons, and logic-based operations with ease. Java offers several methods to make this conversion straightforward and reliable, each suited for different use cases.
In this blog, we’ll explain various ways to convert a String to an int in Java, complete with working code examples and solutions to common errors.
Online software engineering courses can be a smart next step for gaining a stronger grasp of Java fundamentals and best practices.
Before diving into conversion methods, let's quickly understand the two data types we're working with:
Converting between these types is necessary because:
Let’s see several ways on how to convert String to int in Java programming. Each approach has its advantages and specific use cases.
The most common and straightforward method for string to int conversion in Java is using the parseInt() method from the Integer class.
int value = Integer.parseInt(string);
public class StringToIntExample {
public static void main(String[] args) {
// String containing a numeric value
String numberStr = "123";
// Convert String to int using parseInt
int number = Integer.parseInt(numberStr);
// Verify the conversion
System.out.println("String value: " + numberStr);
System.out.println("Integer value: " + number);
System.out.println("Integer value + 7: " + (number + 7));
}
}
Output:
String value: 123
Integer value: 123
Integer value + 7: 130
This example successfully converts the string "123" to the integer value 123. The addition operation confirms that we're working with a numeric type.
Stay ahead with these handpicked, high-impact courses.
Another approach is to use the valueOf() method, which returns an Integer object rather than a primitive int.
int value = Integer.valueOf(string);
public class StringToIntValueOf {
public static void main(String[] args) {
// String containing a numeric value
String numberStr = "456";
// Convert String to Integer object first
Integer integerObj = Integer.valueOf(numberStr);
// Get the primitive int value
int number = integerObj.intValue();
// Alternatively, use auto-unboxing
int numberDirect = Integer.valueOf(numberStr);
System.out.println("String value: " + numberStr);
System.out.println("Integer object value: " + integerObj);
System.out.println("Primitive int value: " + number);
System.out.println("Direct conversion with auto-unboxing: " + numberDirect);
}
}
Output:
String value: 456
Integer object value: 456
Primitive int value: 456
Direct conversion with auto-unboxing: 456
This example demonstrates how to use valueOf() to first get an Integer object, and then extract the primitive int. Thanks to auto-unboxing in modern Java, you can also directly assign the Integer object to an int variable.
While both methods accomplish string to int conversion, there are some differences:
Feature | parseInt() | valueOf() |
Return type | primitive int | Integer object |
Memory efficiency | More efficient for primitive operations | Less efficient due to object creation |
Caching | No caching | Caches small values (-128 to 127) |
Usage in generics | Cannot be used directly with generic types | Can be used with generic types |
Performance | Slightly better for primitive operations | Slightly worse due to boxing/unboxing |
For parsing input from various sources, the Scanner class provides convenient methods for string to int conversion.
import java.util.Scanner;
public class StringToIntScanner {
public static void main(String[] args) {
// String containing a numeric value
String input = "789";
// Create a Scanner from the String
Scanner scanner = new Scanner(input);
// Check if the next token is an integer
if (scanner.hasNextInt()) {
int number = scanner.nextInt();
System.out.println("Converted value: " + number);
} else {
System.out.println("Input is not a valid integer");
}
// Close the scanner
scanner.close();
}
}
Output:
Converted value: 789
This approach is particularly useful when reading from input streams or when you need to validate if the string contains a valid integer before attempting conversion.
Let's explore some more complex scenarios for string to int conversion in Java.
The parseInt() and valueOf() methods support an optional radix parameter to specify the numeral system (base) of the input string.
public class StringToIntRadix {
public static void main(String[] args) {
// Binary (base 2) string
String binaryStr = "1010";
int binaryToDecimal = Integer.parseInt(binaryStr, 2);
System.out.println("Binary " + binaryStr + " to decimal: " + binaryToDecimal);
// Octal (base 8) string
String octalStr = "77";
int octalToDecimal = Integer.parseInt(octalStr, 8);
System.out.println("Octal " + octalStr + " to decimal: " + octalToDecimal);
// Hexadecimal (base 16) string
String hexStr = "1A";
int hexToDecimal = Integer.parseInt(hexStr, 16);
System.out.println("Hexadecimal " + hexStr + " to decimal: " + hexToDecimal);
// Custom base (e.g., base 5)
String base5Str = "431";
int base5ToDecimal = Integer.parseInt(base5Str, 5);
System.out.println("Base-5 " + base5Str + " to decimal: " + base5ToDecimal);
}
}
Output:
Binary 1010 to decimal: 10
Octal 77 to decimal: 63
Hexadecimal 1A to decimal: 26
Base-5 431 to decimal: 116
This example demonstrates how to convert strings representing numbers in different numeral systems to decimal integers.
String to int conversion can throw a NumberFormatException if the string doesn't represent a valid integer. It's important to handle this exception properly.
public class StringToIntExceptionHandling {
public static void main(String[] args) {
// Array of strings to convert
String[] inputs = {"123", "456", "abc", "123f", "-789", " 42 "};
for (String input : inputs) {
try {
int number = Integer.parseInt(input.trim());
System.out.println("Successfully converted '" + input + "' to: " + number);
} catch (NumberFormatException e) {
System.out.println("Failed to convert '" + input + "': Not a valid integer");
}
}
}
}
Output:
Successfully converted '123' to: 123
Successfully converted '456' to: 456
Failed to convert 'abc': Not a valid integer
Failed to convert '123f': Not a valid integer
Successfully converted '-789' to: -789
Successfully converted ' 42 ' to: 42
This example demonstrates proper exception handling when converting various strings to integers. Notice that we also use the trim() method to remove leading and trailing whitespace.
Often, you'll also need to perform the reverse operation: converting an int to a String. Let's cover the main methods for completeness.
The most straightforward approach is to use the valueOf() method from the String class.
public class IntToStringValueOf {
public static void main(String[] args) {
// Integer values to convert
int number1 = 123;
int number2 = -456;
// Convert int to String using String.valueOf()
String str1 = String.valueOf(number1);
String str2 = String.valueOf(number2);
// Verify the conversion
System.out.println("Original int: " + number1 + ", Converted String: " + str1);
System.out.println("Original int: " + number2 + ", Converted String: " + str2);
// Demonstrating that we have strings (concatenation)
System.out.println("Concatenation test: " + str1 + str2);
}
}
Output:
Original int: 123, Converted String: 123
Original int: -456, Converted String: -456
Concatenation test: 123-456
Another approach is to use the toString() method from the Integer class.
public class IntToStringToString {
public static void main(String[] args) {
// Integer value to convert
int number = 789;
// Convert int to String using Integer.toString()
String str = Integer.toString(number);
// Verify the conversion
System.out.println("Original int: " + number + ", Converted String: " + str);
// Converting with different radix (base)
String binaryStr = Integer.toString(number, 2);
String hexStr = Integer.toString(number, 16);
System.out.println("Number " + number + " in binary: " + binaryStr);
System.out.println("Number " + number + " in hexadecimal: " + hexStr);
}
}
Output:
Original int: 789, Converted String: 789
Number 789 in binary: 1100010101
Number 789 in hexadecimal: 315
This example also shows how to convert integers to strings in different number systems by specifying the radix parameter.
The simplest (though not always the most efficient) way to convert int to String is using string concatenation with an empty string.
public class IntToStringConcatenation {
public static void main(String[] args) {
// Integer value to convert
int number = 42;
// Convert int to String using concatenation with empty string
String str = "" + number;
// Verify the conversion
System.out.println("Original int: " + number + ", Converted String: " + str);
// Demonstrate string operations
System.out.println("Length of the string: " + str.length());
System.out.println("First character: " + str.charAt(0));
}
}
Output:
Original int: 42, Converted String: 42
Length of the string: 2
First character: 4
This method is simple but less efficient than using String.valueOf() or Integer.toString() because it creates more temporary objects.
When converting between String and int in Java, be aware of these common issues:
Always validate input or use proper exception handling when converting strings that might not be valid integers.
public static Integer safeParseInt(String str) {
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
return null; // or a default value
}
}
Remember to trim strings before conversion to avoid NumberFormatException:
String input = " 123 ";
int number = Integer.parseInt(input.trim());
The standard conversion methods don't handle locale-specific number formats like thousands separators:
String localizedNumber = "1,234,567";
// This will fail with NumberFormatException:
// int number = Integer.parseInt(localizedNumber);
// Correct approach using NumberFormat:
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
try {
Number parsedNumber = NumberFormat.getNumberInstance(Locale.US).parse(localizedNumber);
int number = parsedNumber.intValue();
System.out.println("Parsed number: " + number);
} catch (ParseException e) {
System.out.println("Failed to parse localized number");
}
Be cautious when parsing strings that might represent numbers outside the int range (-2,147,483,648 to 2,147,483,647):
public static void checkIntegerOverflow(String str) {
try {
int number = Integer.parseInt(str);
System.out.println("Parsed as int: " + number);
} catch (NumberFormatException e) {
try {
long longValue = Long.parseLong(str);
System.out.println("Number too large for int, parsed as long: " + longValue);
} catch (NumberFormatException e2) {
System.out.println("Not a valid number");
}
}
}
When choosing a method for string to int conversion, consider these performance aspects:
To ensure reliable and maintainable code when working with String to int conversions:
Converting string to int in Java is a fundamental operation that's essential for many programming tasks. With methods like Integer.parseInt(), Integer.valueOf(), and proper exception handling, you can safely and efficiently convert between these data types in your applications.
Remember to consider the specific requirements of your application when choosing a conversion method, and always handle potential exceptions to create reliable code. Whether you're processing user input, working with files, or building database queries, mastering string to int conversion will make your Java code more effective and error-resistant.
You can convert a String to an int in Java using Integer.parseInt(string) or Integer.valueOf(string). The parseInt() method returns a primitive int, while valueOf() returns an Integer object which can be auto-unboxed to int.
If you try to convert a non-numeric String to an int using parseInt() or valueOf(), Java will throw a NumberFormatException. Always use exception handling when converting user input or data from external sources.
To convert a String with decimal places to an int, you have two options: First parse it as a double and then cast to int (which truncates the decimal part), or parse it as a double and use Math.round() to round to the nearest integer:
String decimalStr = "123.45";
int truncated = (int) Double.parseDouble(decimalStr); // 123
int rounded = (int) Math.round(Double.parseDouble(decimalStr)); // 123
Yes, both parseInt() and valueOf() accept a second parameter for the radix (base). For hexadecimal (base 16), use Integer.parseInt(hexString, 16). For binary (base 2), use Integer.parseInt(binaryString, 2).
Always wrap your conversion code in a try-catch block to handle potential exceptions:
try {
int number = Integer.parseInt(stringValue);
// Process the number
} catch (NumberFormatException e) {
// Handle the exception (log error, provide default value, etc.)
}
The main difference is that parseInt() returns a primitive int, while valueOf() returns an Integer object. In terms of functionality, valueOf() internally calls parseInt() and wraps the result in an Integer object. For caching, valueOf() caches Integer objects for values between -128 and 127.
The standard parseInt() and valueOf() methods don't handle thousands separators. You need to either remove the separators first or use NumberFormat:
String numWithSeparator = "1,234,567";
String cleanNum = numWithSeparator.replace(",", "");
int number = Integer.parseInt(cleanNum);
The most efficient methods are String.valueOf(int) and Integer.toString(int). Avoid using string concatenation ("" + number) in performance-critical code as it creates more temporary objects.
If the String might represent a value outside the int range (-2,147,483,648 to 2,147,483,647), use Long.parseLong() or BigInteger.parse() to avoid overflow issues:
String largeNumberStr = "9999999999";
try {
long longValue = Long.parseLong(largeNumberStr);
System.out.println("As long: " + longValue);
} catch (NumberFormatException e) {
System.out.println("Number too large even for long type");
}
You can use String.format() to create a string with leading zeros:
int number = 42;
String withLeadingZeros = String.format("%05d", number); // "00042"
First parse it as a double to handle the scientific notation, then convert to int:
String scientific = "1.23E2"; // 123 in scientific notation
int number = (int) Double.parseDouble(scientific);
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.