Java convert input string to int

Java Convert String to Integer

Converting a String to an int , or its respective wrapper class Integer , is a common and simple operation. The same goes for the other way around, converting a Integer to String.

There are multiple ways to achieve this simple conversion using methods built-in to the JDK.

Converting String to Integer

For converting String to Integer or int, there are four built-in approaches. The wrapper class Integer provides a few methods specifically for this use — parseInt() , valueOf() and decode() , although we can also use its constructor and pass a String into it.

These three methods have different return types:

  • parseInt() — returns primitive int .
  • valueOf() — returns a new or cached instance of Integer
  • decode() — returns a new or cached instance of Integer

That being said, it’s valid to raise a question:

«What’s the difference between valueOf() and decode() then?

The difference is that decode() also accepts other number representations, other than regular decimal — hex digits, octal digits, etc.

Note: It’s better practice to instantiate an Integer with the help of the valueOf() method rather than relying on the constructor. This is because the valueOf() method will return a cached copy for any value between -128 and 127 inclusive, and by doing so will reduce the memory footprint.

Integer.parseInt()

The parseInt() method ships in two flavors:

  • parseInt(String s) — Accepting the String we’d like to parse
  • parseInt(String s, int radix) — Accepting the String as well as the base of the numeration system

The parseInt() method converts the input String into a primitive int and throws a NumberFormatException if the String cannot be converted:

String string1 = "100"; String string2 = "100"; String string3 = "Google"; String string4 = "20"; int number1 = Integer.parseInt(string1); int number2 = Integer.parseInt(string2, 16); int number3 = Integer.parseInt(string3, 32); int number4 = Integer.parseInt(string4, 8); System.out.println("Parsing String \"" + string1 + "\": " + number1); System.out.println("Parsing String \"" + string2 + "\" in base 16: " + number2); System.out.println("Parsing String \"" + string3 + "\" in base 32: " + number3); System.out.println("Parsing String \"" + string4 + "\" in base 8: " + number4); 

Running this piece of code will yield:

Parsing String "100": 100 Parsing String "100" in base 16: 256 Parsing String "Google" in base 32: 562840238 Parsing String "20" in base 8: 16 

Integer.valueOf()

The valueOf() ships in three flavors:

  • valueOf(String s) — Accepts a String and parses it into an Integer
  • valueOf(int i) — Accepts an int and parses it into an Integer
  • valueOf(String s, int radix) — Accepts a String and returns an Integer representing the value and then parses it with the given base
Читайте также:  Algorithm codes in java

The valueOf() method, unlike the parseInt() method, returns an Integer instead of a primitive int and also throws a NumberFormatException if the String cannot be converted properly and only accepts decimal numbers:

int i = 10; String string1 = "100"; String string2 = "100"; String string3 = "Google"; String string4 = "20"; int number1 = Integer.valueOf(i); int number2 = Integer.valueOf(string1); int number3 = Integer.valueOf(string3, 32); int number4 = Integer.valueOf(string4, 8); System.out.println("Parsing int " + i + ": " + number1); System.out.println("Parsing String \"" + string1 + "\": " + number2); System.out.println("Parsing String \"" + string3 + "\" in base 32: " + number3); System.out.println("Parsing String \"" + string4 + "\" in base 8: " + number4); 

Running this piece of code will yield:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Parsing int 10: 10 Parsing String "100": 100 Parsing String "Google" in base 32: 562840238 Parsing String "20" in base 8: 16 

Integer.decode()

The decode() method accepts a single parameter and comes in one flavor:

The decode() method accepts decimal, hexadecimal and octal numbers, but doesn’t support binary:

String string1 = "100"; String string2 = "50"; String string3 = "20"; int number1 = Integer.decode(string1); int number2 = Integer.decode(string2); int number3 = Integer.decode(string3); System.out.println("Parsing String \"" + string1 + "\": " + number2); System.out.println("Parsing String \"" + string2 + "\": " + number2); System.out.println("Parsing String \"" + string3 + "\": " + number3); 

Running this piece of code will yield:

Parsing String "100": 50 Parsing String "50": 50 Parsing String "20": 20 

Conclusion

We’ve covered one of the fundamental topics of Java and common problem developers face — Converting a String to an Integer or int using tools shipped with the JDK.

Источник

Java convert input string to int

Java String to Integer Example: Integer.valueOf()

The Integer.valueOf() method converts String into Integer object. Let’s see the simple code to convert String to Integer in Java.

NumberFormatException Case

If you don’t have numbers in string literal, calling Integer.parseInt() or Integer.valueOf() methods throw NumberFormatException.

Exception in thread "main" java.lang.NumberFormatException: For input string: "hello" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.base/java.lang.Integer.parseInt(Integer.java:652) at java.base/java.lang.Integer.parseInt(Integer.java:770) at StringToIntegerExample3.main(StringToIntegerExample3.java:4)

References

Youtube

For Videos Join Our Youtube Channel: Join Now

Feedback

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry
Читайте также:  Как создать бота в дискорде python

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Вопрос-ответ: как в 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 () и ему подобные.

Источник

How to convert String to Integer in Java

In Java, we can use Integer.valueOf(String) to convert a String to an Integer object; For unparsable String, it throws NumberFormatException .

 Integer.valueOf("1"); // ok Integer.valueOf("+1"); // ok, result = 1 Integer.valueOf("-1"); // ok, result = -1 Integer.valueOf("100"); // ok Integer.valueOf(" 1"); // NumberFormatException (contains space) Integer.valueOf("1 "); // NumberFormatException (contains space) Integer.valueOf("2147483648"); // NumberFormatException (Integer max 2,147,483,647) Integer.valueOf("1.1"); // NumberFormatException (. or any symbol is not allowed) Integer.valueOf("1-1"); // NumberFormatException (- or any symbol is not allowed) Integer.valueOf(""); // NumberFormatException, empty Integer.valueOf(" "); // NumberFormatException, (contains space) Integer.valueOf(null); // NumberFormatException, null 

1. Convert String to Integer

Below example uses Integer.valueOf(String) to convert a String "99" to an object Integer .

 package com.mkyong.string; public class ConvertStringToInteger < public static void main(String[] args) < String number = "99"; // String to integer Integer result = Integer.valueOf(number); // 99 System.out.println(result); >> 

2. NumberFormatException

2.1 For unparsable String, the Integer.valueOf(String) throws NumberFormatException .

 String number = "D99"; Integer result = Integer.valueOf(number); 
 Exception in thread "main" java.lang.NumberFormatException: For input string: "D99" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67) at java.base/java.lang.Integer.parseInt(Integer.java:668) at java.base/java.lang.Integer.valueOf(Integer.java:999) at com.mkyong.string.ConvertStringToInteger.main(ConvertStringToInteger.java:10) 

2.2 Try and catch the NumberFormatException .

 package com.mkyong.string; public class ConvertStringToInteger < public static void main(String[] args) < String number = "D99"; try < Integer result = Integer.valueOf(number); System.out.println(result); >catch (NumberFormatException e) < //do something for the exception. System.err.println("Invalid number format : " + number); >> > 

3. Convert String to Integer (Java 8 Optional)

Below is a Java 8 example of converting a String to an Integer object and returning an Optional .

 package com.mkyong.string; import java.util.Optional; public class ConvertStringToIntegerJava8 < public static void main(String[] args) < String number = "99"; Optionalresult = convertStringToInteger(number); if (result.isPresent()) < System.out.println(result.get()); >else < System.err.println("Unable to convert the number : " + number); >> private static Optional convertStringToInteger(String input) < if (input == null) return Optional.empty(); // remove spaces input = input.trim(); if (input.isEmpty()) return Optional.empty(); try < return Optional.of(Integer.valueOf(input)); >catch (NumberFormatException e) < return Optional.empty(); >> > 

4. Integer.parseInt(String) vs Integer.valueOf(String)

The Integer.parseInt(String) convert a String to primitive type int ; The Integer.valueOf(String) convert a String to a Integer object. For unparsable String, both methods throw NumberFormatException .

 int result1 = Integer.parseInt("100"); Integer result2 = Integer.valueOf("100"); 

5. Download Source Code

6. References

Источник

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

Источник

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