New Integer/Long parse method in java 9

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

However, I found two additional pares method for long/Integer –

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

both Integer and Long have these two 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.

I found a question that a few people usually ask, is why we need a radix. Let me try to answer it shortly-

Radix is the base of a system of numeration. Actually there a whole lot of numeric system out there but only few of them are most popular which are – 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 be represents as 2 in decimal.

So when you have a character sequence and that as a base unlink decimal, you want to parse it , you have to provide the base.

Example –

Say you want to parse portion of a sequence of binary values into long

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
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s