How to convert to string to integer in java

How to convert a string to an integer in Java?

I wanted to create this question/answer on how to convert a string to an integer in Java as this is something that I often get asked a lot about.

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Introduction

Java was first released in 1995 and is one of the most popular programming languages right now. It is mainly used for the back-end side, for computing, and game development. Java is fast and secure, and it is also used almost everywhere.

The difference between a string and an int

There are 8 primitive data types in Java, but the ones that we are going to take a look at today are String and integer . Strings are a sequence of characters. They can have up to 2,147,483,647 characters. They can be letters, numbers, or symbols. In order to set a string variable, we have to use the keyword String , and after it, we set our variables name, and then we put in its value wrapped in quotations marks( » » ) or single quotation marks( » ) like this:

Integers are whole numbers. They can be any number from -2147483648 to 2147483647. Setting an integer is just like setting up a string, the only difference is that you need to use the int keyword at the beginning, and the value that you are going to store in, doesn’t need to be wrapped in quotation marks. But what exactly is the difference if, for example, we had a string with a whole number for its value and an integer? Integers always hold in numeric values, but strings hold in just characters. If an integer sees its value as a number, the string sees its value as a character. This means that you can do math with integers, but not with strings. So if you want to convert your string into an integer, there is a solution for you. Let’s say you make a variable called data with the value «23» in it:

Читайте также:  Elasticsearch client pool java

Convert a string into an integer in Java using Integer.parseInt()

Now luckily for us, there is a method called Integer.parseInt() , which makes our life much easier. Let’s say, that we want to convert our data variable into an integer. we can just make a new variable with the name number , and add the method in its value like this:

int number = Integer.parseInt(data); 

Use the Integer.valueOf() method to return the string as an integer object

There is also another way to do this. You set a variable with the Integer keyword and then pass into its value the Integer.valueOf() method. This will return an integer object, which would be extracted from the specified string. Here is how this would look like:

Integer number = Integer.valueOf(data); 

This would also return 23 . A benefit of using Integer.valueOf() is that you can pass a String as well as an integer as the parameter, whereas Integer.parseInt() only accepts a String as the parameter. Another thing to keep in mind is that Integer.valueOf() returns an Integer object compared to Integer.parseInt() which only returns a primitave int value.

Conclusion

What I would recommend is that you try to do this a couple of times by yourself to see how it works. I hope that this post has helped you! Best, Bobby

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Источник

How to easily Convert String to Integer in JAVA

How to convert a Java String to Integer?

Let’s say you have a string – strTest – that contains a numeric value.

Try to perform some arithmetic operation like divide by 4 – This immediately shows you a compilation error.

/StrConvert.java:4: error: bad operand types for binary operator '/' System.out.println("Using String:" + (strTest/4));

Hence, you need to convert a String to int before you peform numeric operations on it

Example 1: Convert String to Integer using Integer.parseInt()

Syntax of parseInt method as follows:

Pass the string variable as the argument.

This will convert the Java String to java Integer and store it into the specified integer variable.

Check the below code snippet-

Expected Output:

Actual String:100 Converted to Int:100 Arithmetic Operation on Int: 25

Example 2: Convert String to Integer using Integer.valueOf()

Integer.valueOf() Method is also used to convert String to Integer in Java.

Following is the code example shows the process of using Integer.valueOf() method:

Expected Output:

Actual String:100 Converted to Int:100 Arithmetic Operation on Int:25

NumberFormatException

NumberFormatException is thrown If you try to parse an invalid number string. For example, String ‘Guru99’ cannot be converted into Integer.

Читайте также:  Последовательность фибоначчи python массив

Above example gives following exception in output:

Exception in thread "main" java.lang.NumberFormatException: For input string: "Guru99"

Источник

String to Int in Java – How to Convert a String to an Integer

Ihechikara Vincent Abba

Ihechikara Vincent Abba

String to Int in Java – How to Convert a String to an Integer

When working with a programming language, you may want to convert strings to integers. An example would be performing a mathematical operation using the value of a string variable.

In this article, you’ll learn how to convert a string to an integer in Java using two methods of the Integer class — parseInt() and valueOf() .

How to Convert a String to an Integer in Java Using Integer.parseInt

The parseInt() method takes the string to be converted to an integer as a parameter. That is:

Integer.parseInt(string_varaible)

Before looking at an example of its usage, let’s see what happens when you add a string value and an integer without any sort of conversion:

In the code above, we created an age variable with a string value of «10».

When added to an integer value of 20, we got 1020 instead of 30.

Here’s a quick fix using the parseInt() method:

In order to convert the age variable to an integer, we passed it as a parameter to the parseInt() method — Integer.parseInt(age) — and stored it in a variable called age_to_int .

When added to another integer, we got a proper addition: age_to_int + 20 .

How to Convert a String to an Integer in Java Using Integer.valueOf

The valueOf() methods works just like the parseInt() method. It takes the string to be converted to an integer as its parameter.

The explanation for the code above is the same as the last section:

  • We passed the string as a parameter to valueOf() : Integer.valueOf(age) . It was stored in a variable called age_to_int .
  • We then added 20 to the variable created: age_to_int + 20 . The resulting value was 30 instead of 1020.

Summary

In this article, we talked about converting strings to integers in Java.

We saw how to convert a string to an integer in Java using two methods of the Integer class — parseInt() and valueOf() .

Источник

Java String to Int – How to Convert a String to an Integer

Thanoshan MV

Thanoshan MV

Java String to Int – How to Convert a String to an Integer

String objects are represented as a string of characters.

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?

In Java, we can use Integer.valueOf() and Integer.parseInt() to convert a string to an integer.

Читайте также:  Np linalg svd python

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)

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)

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)

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)

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 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.

This is a simple way to check numeric values. You can write or search Google for more advanced regular expressions to capture numerics depending on your use case.

It is a best practice to check if the passed-in string is numeric or not before trying to convert it to integer.

You can connect with me on Medium.

Happy Coding!

Источник

Оцените статью