How to Convert String to Int in Java- Tutorials, Tips, Tricks. Must have bookmarked them all. But how many of these are continuously being updated? How many of them are so simple that you could easily understand them. If you are a novice at Java and want to learn more about int data type and int parse method, we sure we will help our readers to understand the concept with this post and apply in their daily projects and can also share your thoughts in comment section below.
If you are familiar with Java that is fine, but sometimes you want to know how to convert string to int in java without parseint. Or how to convert string to int in java 8 . A lot of new ways can help our learning Java
Table of Contents
What is Java?
Java is a general-purpose, class-based, object-oriented programming language designed for having lesser implementation dependencies. It is a computing platform for application development. Java is fast, secure, and reliable, therefore. It is widely used for developing Java applications in laptops, data centers, game consoles, scientific supercomputers, cell phones, etc.
What is Java Platform?
Java Platform is a collection of programs that help programmers to develop and run Java programming applications efficiently. It includes an execution engine, a compiler, and a set of libraries in it. It is a set of computer software and specifications. James Gosling developed the Java platform at Sun Microsystems, and the Oracle Corporation later acquired it.
If you have worked in Java Swing, it has components such as JTextField and JTextArea which we use to get our input from the GUI. It takes our input as a string.
If we want to make a simple calculator using Swing, we need to figure out how to convert a string to an integer. This leads us to the question – how can we convert a string to an integer?
What is Java used for?
Here are some important Java applications:
- It is used for developing Android Apps
- Helps you to create Enterprise Software
- Wide range of Mobile java Applications
- Scientific Computing Applications
- Use for Big Data Analytics
- Java Programming of Hardware devices
- Used for Server-Side Technologies like Apache, JBoss, GlassFish, etc.
In Java, we can use Integer.valueOf()
and Integer.parseInt()
to convert a string to an integer.
1. Use Integer.parseInt() to Convert a String to an Integer
This method returns the string as a primitive type int. If the string does not contain a valid integer then it will throw a NumberFormatException.
So, every time we convert a string to an int, we need to take care of this exception by placing the code inside the try-catch block.
Let’s consider an example of converting a string to an int using Integer.parseInt()
:
String str = "25";
try{
int number = Integer.parseInt(str);
System.out.println(number); // output = 25
}
catch (NumberFormatException ex){
ex.printStackTrace();
}
Let’s try to break this code by inputting an invalid integer:
String str = "25T";
try{
int number = Integer.parseInt(str);
System.out.println(number);
}
catch (NumberFormatException ex){
ex.printStackTrace();
}
As you can see in the above code, we have tried to convert 25T
to an integer. This is not a valid input. Therefore, it must throw a NumberFormatException.
Here’s the output of the above code:
java.lang.NumberFormatException: For input string: "25T"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at OOP.StringTest.main(StringTest.java:51)
Next, we will consider how to convert a string to an integer using the Integer.valueOf()
method.
2. Use Integer.valueOf() to Convert a String to an Integer
This method returns the string as an integer object. If you look at the Java documentation, Integer.valueOf()
returns an integer object which is equivalent to a new Integer(Integer.parseInt(s))
.
We will place our code inside the try-catch block when using this method. Let us consider an example using the Integer.valueOf()
method:
String str = "25";
try{
Integer number = Integer.valueOf(str);
System.out.println(number); // output = 25
}
catch (NumberFormatException ex){
ex.printStackTrace();
}
Now, let’s try to break the above code by inputting an invalid integer number:
String str = "25TA";
try{
Integer number = Integer.valueOf(str);
System.out.println(number);
}
catch (NumberFormatException ex){
ex.printStackTrace();
}
Similar to the previous example, the above code will throw an exception.
Here’s the output of the above code:
java.lang.NumberFormatException: For input string: "25TA"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.valueOf(Integer.java:766)
at OOP.StringTest.main(StringTest.java:42)
We can also create a method to check if the passed-in string is numeric or not before using the above mentioned methods.
I have created a simple method for checking whether the passed-in string is numeric or not.
public class StringTest {
public static void main(String[] args) {
String str = "25";
String str1 = "25.06";
System.out.println(isNumeric(str));
System.out.println(isNumeric(str1));
}
private static boolean isNumeric(String str){
return str != null && str.matches("[0-9.]+");
}
}
The output is:
true
true
The isNumeric()
method takes a string as an argument. First it checks if it is null
or not. After that we use the matches()
method to check if it contains digits 0 to 9 and a period character.
Convert String to Double in Java
- Double.parseDouble()We can parse String to double using
parseDouble()
method. String can start with “-” to denote negative number or “+” to denote positive number. Also any trailing 0s are removed from the double value. We can also have “d” as identifier that string is a double value. This method returns double primitive type. Below code snippet shows how to convert string to double using Double.parseDouble() method.String str = "+123.4500d"; double d = Double.parseDouble(str); // returns double primitive System.out.println(d); //-123.45, trailing 0s are removed System.out.println(Double.parseDouble("123.45001")); //123.45001 System.out.println(Double.parseDouble("123.45001d")); //123.45001 System.out.println(Double.parseDouble("123.45000")); //123.45 System.out.println(Double.parseDouble("123.45001D")); //123.45001
- Double.valueOf()This method works almost similar as parseDouble() method, except that it returns Double object. Let’s see how to use this method to convert String to Double object.
String str = "123.45"; Double d = Double.valueOf(str); // returns Double object System.out.println(d); //123.45 System.out.println(Double.valueOf("123.45d")); //123.45 System.out.println(Double.valueOf("123.4500d")); //123.45 System.out.println(Double.valueOf("123.45D")); //123.45
- new Double(String s)We can convert String to Double object through it’s constructor too. Also if we want double primitive type, then we can use
doubleValue()
method on it. Note that this constructor has been deprecated in Java 9, preferred approach is to useparseDouble()
orvalueOf()
methods.String str = "98.7"; double d = new Double(str).doubleValue(); //constructor deprecated in java 9 System.out.println(d); //98.7
- DecimalFormat parse()This is useful to parse formatted string to double. For example, if String is “1,11,111.23d” then we can use DecimalFormat to parse this string to double as:
String str = "1,11,111.23d"; try { double l = DecimalFormat.getNumberInstance().parse(str).doubleValue(); System.out.println(l); //111111.23 } catch (ParseException e) { e.printStackTrace(); }
Note that parse() method returns instance ofNumber
, so we are callingdoubleValue()
to get the double primitive type from it. Also this method throwParseException
if the string is not properly formatted.
Conclusion:
Java developers always need to deal with string and int, especially when the task is to parse an input string into an int value. You can use built-in methods such as Integer.parseInt() or Integer.valueOf() which we will discuss in this article, but the code is not always readable and hard to maintain. This article introduces a few different solutions to convert a string into an int value.