Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

New Integer/Long Parse Method in Java 9

DZone's Guide to

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 ·
Free Resource

Automist automates your software deliver experience. It's how modern teams deliver modern software.

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

Get the open source Atomist Software Delivery Machine and start automating your delivery right there on your own laptop, today!

Topics:
numeric methods ,java 9 ,conversion

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}