Конвертация string to int java

Convert String to int in Java

In this article, we will take a look at how to convert String to int in Java. Converting String to an int or Integer is a common task and we will take a look at the following options for this conversion.

  1. Java – Convert String to int using Integer.parseInt() method.
  2. Java – Convert String to int using Integer.valueOf() method.

1. Convert String to Int using Integer.parseInt()

The parseInt method provide the following 2 options to convert a String to int in Java.

  1. parseInt(String s) – String for converting to int.
  2. parseInt(String s , int radix) – String with base of the number system.

In the first option, we pass a string as input parameter “345” and parseInt() return the integer value after parsing the input String.Here is a high level signature:

String input ="345"; int output = Integer.parseInt(input);

parseInt() can throws a NumberFormatException if the String can’t be converted.

public class ParseStringToInt < public static void main(String[] args) < String input ="345"; String invalid = "javadevjournal"; /** * Convert String to * integer with default radix */ int output = Integer.parseInt(input); System.out.println(output); //345 //base 16 conversion using the radix int base16 = Integer.parseInt(input, 16); System.out.println(base16); //837 //base 8 conversion using radix int base8 = Integer.parseInt(input, 8); System.out.println(base8); //229 //number format exception int number1 = Integer.parseInt(invalid); System.out.println(number1); //Exception in thread "main" java.lang.NumberFormatException: For input string: "javadevjournal" >>

Integer.ParseInt() will return an int primitive value.If efficiency is your concern and you only need primitive value, then using Integer.ParseInt() is the best option.

There are few other important point when you are converting String to integer using Integer.parsseInt() method.

  • Ensure that all characters in the String are digits.
  • The first character of the String can be a “-” sign
Читайте также:  Установка python для kali

Here is a modified version of above example with “-” in the input string value.

public class ParseStringToInt < public static void main(String[] args) < String input = "-345"; int number = 445; /** * Convert String to * integer with default radix */ int output = Integer.parseInt(input); System.out.println(output); // -345 /*Let's do some calculation to make sure number conversion is working as expected */ number = number + output; System.out.println(number); //100 >>

2. Convert String to Int using Integer.valueOf()

The Integer.valueOf() method internally use the Integer.parsseInt() method. Here is the method definition from the JDK.

public static Integer valueOf(String s) throws NumberFormatException

There are few distinction between the Integer.valueOf() and Integer.parseInt() method. Let’s take a look at them for better understanding.

  1. The valueOf(String) method returns an object of Integer class whereas the parseInt(String) method returns a primitive int value.
  2. We can choose the output as int or Integer class based on our requirement, however keep in mind that there will be Unboxing.
  3. You should use Integer.parseInt() method if you need int value and efficiency is your primary target.

The Integer.valueOf() method provides the following variations

  1. valueOf(String s) – Accepts String and parse it to Integer.
  2. valueOf(int i) – takes int and parse it to Integer.
  3. valueOf(String s, int radix) – String with base of the number system.

Here is a snapshot for the method

String input ="345"; Integer output = Integer.valueOf(input);

Let’s take a look at the complete example to convert String to int

public class ParseStringToInt < public static void main(String[] args) < String input = "345"; int number = 445; /** * Convert String to * integer */ Integer output = Integer.valueOf(input); System.out.println(output); // 345 /* pass int to convert it to the Integer class */ Integer output1 = Integer.valueOf(number); System.out.println(output1); // 445 /* Conversion with a specific base type */ Integer base16 = Integer.valueOf(input, 16); System.out.println(base16); //837 Integer base32 = Integer.valueOf(input, 32); System.out.println(base32); //3205 >>

The valueOf uses parseInt internally. If efficiency is your concern do not use this method to convert String to int or Integer.

3. NumberFormat Exception

Both Integer.parseInt() and Integer.valueOf() can throw NumberFormatException if the string cannot be parsed as an integer or int

public class NumberFormatExceptionExample < public static void main(String[] args) < String invalidNumber = "abc"; parseIntNFException(invalidNumber); >public static void parseIntNFException(String number) < Integer result = Integer.parseInt(number); System.out.println(result); >public static void valueOfNFException(String number) < Integer result = Integer.valueOf(number); System.out.println(result); >>
Exception in thread "main" java.lang.NumberFormatException: For input string: "abc" 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 NumberFormatExceptionExample.parseIntNFException(NumberFormatExceptionExample.java:13) at NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:8)

Note: PraseInt() return a primitive value while valueOf() will always return new Integer object, ideally, if you just want to convert String to an int, it’s always better to avoid creating new Object.

4. Convert String to int using Integer.valueOf()

The Integer.decode(String s) method can also be used to convert String to int in Java. This method takes String as input parameter and decode it to Integer. It accepts the following

public class ParseStringToInt < public static void main(String[] args) < String input1 = "100"; String input2 = "0x12"; String input3 = "012"; /** * Convert String to * integer using Integer.decode() */ Integer output1 = Integer.decode(input1); System.out.println(output1); // 100 Integer output2 = Integer.decode(input2); System.out.println(output2); // 18 Integer output3 = Integer.decode(input3); System.out.println(output3); // 10 >>

Summary

In this article, we discussed the different options to convert string to int in Java. We saw how to convert it using Integer.valueOf() , Integer.parseInt() and Integer.decode() method.Follow our Java articles to get more in depth knowledge.

1 thought on “Convert String to int in Java”

Hi article is nice,
In Java there are two methods to convert String to Int, they are.
Integer.parseInt()
Integer.valueOf()

Источник

Вопрос-ответ: как в Java правильно конвертировать String в int?

Java-университет

int в String — очень просто, и вообще практически любой примитивный тип приводится к String без проблем.

 int x = 5; String text = "X lang-java line-numbers">int i = Integer.parseInt (myString);

Если строка, обозначенная переменной myString , является допустимым целым числом, например «1», «200», Java спокойно преобразует её в примитивный тип данных int . Если по какой-либо причине это не удается, подобное действие может вызвать исключение NumberFormatException , поэтому чтобы программа работала корректно для любой строки, нам нужно немного больше кода. Программа, которая демонстрирует метод преобразования Java String в int , управление для возможного NumberFormatException :

 public class JavaStringToIntExample < public static void main (String[] args) < // String s = "fred"; // используйте это, если вам нужно протестировать //исключение ниже String s = "100"; try < // именно здесь String преобразуется в int int i = Integer.parseInt(s.trim()); // выведем на экран значение после конвертации System.out.println("int i = " + i); >catch (NumberFormatException nfe) < System.out.println("NumberFormatException: " + nfe.getMessage()); >> 

Обсуждение

Когда вы изучите пример выше, вы увидите, что метод Integer.parseInt (s.trim ()) используется для превращения строки s в целое число i , и происходит это в следующей строке кода:

int i = Integer.parseInt (s.trim ())
  • Integer.toString (int i) используется для преобразования int в строки Java.
  • Если вы хотите преобразовать объект String в объект Integer (а не примитивный класс int ), используйте метод valueOf () для класса Integer вместо метода parseInt () .
  • Если вам нужно преобразовать строки в дополнительные примитивные поля Java, используйте такие методы, как Long.parseLong () и ему подобные.

Источник

Converting Between Numbers and Strings

Frequently, a program ends up with numeric data in a string object—a value entered by the user, for example.

The Number subclasses that wrap primitive numeric types ( Byte , Integer , Double , Float , Long , and Short ) each provide a class method named valueOf that converts a string to an object of that type. Here is an example, ValueOfDemo , that gets two strings from the command line, converts them to numbers, and performs arithmetic operations on the values:

public class ValueOfDemo < public static void main(String[] args) < // this program requires two // arguments on the command line if (args.length == 2) < // convert strings to numbers float a = (Float.valueOf(args[0])).floatValue(); float b = (Float.valueOf(args[1])).floatValue(); // do some arithmetic System.out.println("a + b = " + (a + b)); System.out.println("a - b = " + (a - b)); System.out.println("a * b = " + (a * b)); System.out.println("a / b = " + (a / b)); System.out.println("a % b = " + (a % b)); >else < System.out.println("This program " + "requires two command-line arguments."); >> >

The following is the output from the program when you use 4.5 and 87.2 for the command-line arguments:

a + b = 91.7 a - b = -82.7 a * b = 392.4 a / b = 0.0516055 a % b = 4.5

Note: Each of the Number subclasses that wrap primitive numeric types also provides a parseXXXX() method (for example, parseFloat() ) that can be used to convert strings to primitive numbers. Since a primitive type is returned instead of an object, the parseFloat() method is more direct than the valueOf() method. For example, in the ValueOfDemo program, we could use:

float a = Float.parseFloat(args[0]); float b = Float.parseFloat(args[1]);

Converting Numbers to Strings

Sometimes you need to convert a number to a string because you need to operate on the value in its string form. There are several easy ways to convert a number to a string:

int i; // Concatenate "i" with an empty string; conversion is handled for you. String s1 = "" + i;
// The valueOf class method. String s2 = String.valueOf(i);

Each of the Number subclasses includes a class method, toString() , that will convert its primitive type to a string. For example:

int i; double d; String s3 = Integer.toString(i); String s4 = Double.toString(d);

The ToStringDemo example uses the toString method to convert a number to a string. The program then uses some string methods to compute the number of digits before and after the decimal point:

public class ToStringDemo < public static void main(String[] args) < double d = 858.48; String s = Double.toString(d); int dot = s.indexOf('.'); System.out.println(dot + " digits " + "before decimal point."); System.out.println( (s.length() - dot - 1) + " digits after decimal point."); >>

The output of this program is:

3 digits before decimal point. 2 digits after decimal point.

Источник

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.

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!

Источник

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