Java string to int mapping

Java String to int Conversion – 10 Examples

Java String to int conversion can be done using the Integer wrapper class. There are two static methods for this purpose – parseInt() and valueOf().

Java String to int Conversion Methods

The Integer class provides 5 overloaded methods for the string to int conversion.

  • parseInt(String s): parses the string as a signed decimal value. The string should have only decimal digits. The first character can be ASCII minus sign (-) or plus sign (+).
  • parseInt(String s, int radix): parses the given string as the signed integer in the radix.
  • parseInt(CharSequence s, int beginIndex, int endIndex, int radix): The method is useful in parsing a substring to an integer. If the index values are invalid, IndexOutOfBoundsException is thrown. If the CharSequence is null, NullPointerException is thrown.
  • valueOf(String s): This method returns an Integer object. The string is parsed as a signed decimal value. It calls parseInt (s, 10) internally.
  • valueOf(String s, int radix): internally calls the parseInt(s, radix) method and returns the Integer object.
Читайте также:  Удалить данные приложения java

Important Points for String to int Parsing

  • All the parseInt() and valueOf() methods throw NumberFormatException if the string is not parsable.
  • The radix value should be in the supported range i.e. from Character.MIN_RADIX (2) to Character.MAX_RADIX(36), otherwise NumberFormatException is thrown.
  • The parseInt() methods return int primitive data type.
  • The valueOf() methods return an Integer object.
  • The valueOf() methods internally calls parseInt() methods.
  • Since Java supports autoboxing, we can use int and Integer in our program interchangeably. So we can use either parseInt() or valueOf() method to convert a string to integer.
  • The parseInt() method to parse substring was added to String class in Java 9 release.
  • The string should not contain the prefix used to denote an integer in the different radix. For example, “FF” is valid but “0xFF” is not a valid string for the conversion.
  • The valueOf() methods are present because it’s present in every wrapper class and String to convert other data types to this object. Recommended Read: Java String valueOf() method.

Java String to integer Examples

Let’s look at some examples for parsing a string to an integer using the parseInt() and valueOf() methods.

1. parseInt(String s)

jshell> Integer.parseInt("123"); $69 ==> 123 jshell> Integer.parseInt("-123"); $70 ==> -123 jshell> Integer.parseInt("+123"); $71 ==> 123 jshell> Integer.parseInt("-0"); $72 ==> 0 jshell> Integer.parseInt("+0"); $73 ==> 0

2. parseInt(String s, int radix)

jshell> Integer.parseInt("FF", 16); $74 ==> 255 jshell> Integer.parseInt("1111", 2); $75 ==> 15

3. parseInt(CharSequence s, int beginIndex, int endIndex, int radix)

jshell> String line = "Welcome 2019"; line ==> "Welcome 2019" jshell> Integer.parseInt(line, 8, 12, 10) $77 ==> 2019 jshell> String lineMixed = "5 in binary is 101"; lineMixed ==> "5 in binary is 101" jshell> Integer.parseInt(lineMixed, 0, 1, 10) $79 ==> 5 jshell> Integer.parseInt(lineMixed, 15, 18, 2) $80 ==> 5

Java String To Int Example

4. valueOf(String s)

jshell> Integer io = Integer.valueOf(123); io ==> 123 jshell> int i = Integer.valueOf(123); i ==> 123

The valueOf() method returns Integer object. But, we can assign it to int also because Java supports autoboxing.

Читайте также:  Unicode в html конвертер

5. valueOf(String s, int radix)

jshell> Integer.valueOf("F12", 16) $84 ==> 3858 jshell> int i = Integer.valueOf("F12", 16) i ==> 3858 jshell> int i = Integer.valueOf("077", 8) i ==> 63

6. NumberFormatException Example

jshell> Integer.parseInt("abc"); | Exception java.lang.NumberFormatException: For input string: "abc" | at NumberFormatException.forInputString (NumberFormatException.java:68) | at Integer.parseInt (Integer.java:658) | at Integer.parseInt (Integer.java:776) | at (#87:1) jshell> Integer.parseInt("FF", 8); | Exception java.lang.NumberFormatException: For input string: "FF" under radix 8 | at NumberFormatException.forInputString (NumberFormatException.java:68) | at Integer.parseInt (Integer.java:658) | at (#88:1) jshell>

7. NullPointerException when parsing substring

jshell> Integer.parseInt(null, 1, 2, 10); | Exception java.lang.NullPointerException | at Objects.requireNonNull (Objects.java:221) | at Integer.parseInt (Integer.java:701) | at (#89:1) jshell>

8. IndexOutOfBoundsException when parsing substring

jshell> Integer.parseInt("Hello 2019", 1, 100, 10); | Exception java.lang.IndexOutOfBoundsException | at Integer.parseInt (Integer.java:704) | at (#90:1) jshell>

9. NumberFormatException when radix is out of range

jshell> Integer.parseInt("FF", 50); | Exception java.lang.NumberFormatException: radix 50 greater than Character.MAX_RADIX | at Integer.parseInt (Integer.java:629) | at (#91:1) jshell>

10. Java String to int Removing Leading Zeroes

If the string is prefixed with zeroes, they are removed when converted to int.

jshell> Integer.parseInt("00077"); $95 ==> 77 jshell> Integer.parseInt("00077", 16); $96 ==> 119 jshell> Integer.parseInt("00077", 12); $97 ==> 91 jshell> Integer.parseInt("00077", 8); $98 ==> 63

Conclusion

Java String to int conversion is very easy. We can use either parseInt() or valueOf() method. Java 9 added another utility method to parse substring to an integer.

References:

Источник

Convert String to int or Integer in Java

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Introduction

Converting a String to an int or Integer is a very common operation in Java. In this article, we will show multiple ways of dealing with this issue.

There are a few simple ways to tackle this basic conversion.

2. Integer.parseInt()

One of the main solutions is to use Integer‘s dedicated static method: parseInt(), which returns a primitive int value:

@Test public void givenString_whenParsingInt_shouldConvertToInt()

By default, the parseInt() method assumes the given String is a base-10 integer. Additionally, this method accepts another argument to change this default radix. For instance, we can parse binary Strings as follows:

@Test public void givenBinaryString_whenParsingInt_shouldConvertToInt()

Naturally, it’s also possible to use this method with any other radix such as 16 (hexadecimal) or 8 (octal).

3. Integer.valueOf()

Another option would be to use the static Integer.valueOf() method, which returns an Integer instance:

@Test public void givenString_whenCallingIntegerValueOf_shouldConvertToInt()

Similarly, the valueOf() method also accepts a custom radix as the second argument:

@Test public void givenBinaryString_whenCallingIntegerValueOf_shouldConvertToInt()

3.1. Integer Cache

At first glance, it may seem that the valueOf() and parseInt() methods are exactly the same. For the most part, this is true — even the valueOf() method delegates to the parseInt method internally.

However, there is one subtle difference between these two methods: the valueOf() method is using an integer cache internally. This cache would return the same Integer instance for numbers between -128 and 127:

@Test public void givenString_whenCallingValueOf_shouldCacheSomeValues() < for (int i = -128; i >

Therefore, it’s highly recommended to use valueOf() instead of parseInt() to extract boxed integers as it may lead to a better overall footprint for our application.

4. Integer‘s Constructor

You could also use Integer‘s constructor:

@Test public void givenString_whenCallingIntegerConstructor_shouldConvertToInt()

As of Java 9, this constructor has been deprecated in favor of other static factory methods such as valueOf() or parseInt(). Even before this deprecation, it was rarely appropriate to use this constructor. We should use parseInt() to convert a string to an int primitive or use valueOf() to convert it to an Integer object.

5. Integer.decode()

Also, Integer.decode() works similarly to the Integer.valueOf(), but can also accept different number representations:

@Test public void givenString_whenCallingIntegerDecode_shouldConvertToInt()

6. NumberFormatException

All mentioned above methods throw a NumberFormatException, when encountering unexpected String values. Here you can see an example of such a situation:

@Test(expected = NumberFormatException.class) public void givenInvalidInput_whenParsingInt_shouldThrow()

7. With Guava

Of course, we do not need to stick to the core Java itself. This is how the same thing can be achieved using Guava’s Ints.tryParse(), which returns a null value if it cannot parse the input:

@Test public void givenString_whenTryParse_shouldConvertToInt()

Moreover, the tryParse() method also accepts a second radix argument similar to parseInt() and valueOf().

8. Conclusion

In this article, we have explored multiple ways of converting String instances to int or Integer instances.

All code examples can, of course, be found over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

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