Over a million developers have joined DZone.

New Integer/Long Parse Method in Java 9

In the latest release of Java 9 early access, you'll be quite interested in the pair of new methods for Long/Integer

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

I have just installed the Java 9 early access release and started playing around. I know that this is not a major release and it is more of a bug fix release with a few tiny features.

However, I found a pair of additional methods for Long/Integer

public static long parseLong(CharSequence s, int beginIndex, int endIndex, int radix)
throws NumberFormatException {}
public static long parseUnsignedLong(CharSequence s, int beginIndex, int endIndex, int radix)
throws NumberFormatException {}

both Integer and Long have these methods.

So they basically parse a CharSequence argument as a signed int or long in the specified radix, beginning at the specified beginIndex and extending to endIndex – 1.

Occasionally people ask why we need a radix. Let me try to answer it shortly-

Radix is the base of a numeration system. Actually there a whole lot of numeric system out there but only few of them are popular, these being – decimal (base 10) , binary (base 2), octal (base 8), hexadecimal ( base16) .

One numerical value can be converted to different bases. For example – the number 10 in binary is represented as 2 in decimal.

So when you have a character sequence that is base 10 and you want to parse it, you have to provide the base.

For example:

If you want to parse part of a sequence of binary values into long, here's how it can be done now.

int result = Integer.parseInt("010010000100001001000100", 0, 7, 2);
System.out.println(result); //36

int result2 = Integer.parseInt("-6B4A", 0, 3, 16); 
System.out.println(result2); //-107

int result2 = Integer.parseUnsignedInt("6B4A", 0, 3, 16);
System.out.println(result2); //1716

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

Topics:
numeric methods ,java 9 ,conversion

Published at DZone with permission of Bazlur Rahman. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}