-2

Syntax : public static Integer valueOf(String val, int radix) throws NumberFormatException Parameters : val : String to be parsed into int value radix : radix to be used while parsing Throws : NumberFormatException : if String cannot be parsed to a int value in given radix. What exactly is radix here ? Please explain me use of radix. I am confused with it's usage. I know alternative to do what i want! I just want to know use of radix! you can refer these prog. as prog 1, 2 and so on if you want to explain using these as examples.

public class Main
{

    public static void main(String[] args) throws NumberFormatException{

        String ba = "123456789";

        int ab = Integer.valueOf(ba,16);

        System.out.println(ab);

    }

}

this throws NumberformatException

public class Main
{

    public static void main(String[] args) throws NumberFormatException{

        String ba = "ABCDEF";

        int ab = Integer.valueOf(ba,16);

        System.out.println(ab);

    }

}

but this prints a result

Checked GFG but didn't quiet got there explanation!

public class Main
{

    public static void main(String[] args) throws NumberFormatException{

        String ba = "123ABCDEF";

        int ab = Integer.valueOf(ba,16);

        System.out.println(ab);

    }

}

Throws error

I just want to know radix! I guess that will fix my problem.

Minn
  • 5,688
  • 2
  • 15
  • 42
  • Your numbers are too big for an integer. 2 digits of a base16 (hex) number represent 1 byte. You have 9 digits which requires at least 5 bytes. An integer is 4 bytes. The number cannot exceed 8 digits if you use base16. – Minn May 25 '19 at 17:17

1 Answers1

2

Case - 1

Theory - A Java NumberFormatException usually occurs when you try to do something like converting a String to a numeric value, like an int, float, double, long, etc.

so in this case number, 123456789 is bigger for an Integer, therefore the number is not passed. So it Java cannot convert something is not number to a number.

*So going through your main problem => "What is radix"

it is base of the number which you have given in the String format. For example, if you give to like,

String ba = "24";

int ab = Integer.valueOf(ba,5);

it returns ab=14 (in the base ten, as a normal number)

explanation:- 24(in base 5) = 4*1 + 2*5 = 14 (in base 10 , as a decimal)