While doing binary to hex conversions in java, my answers always have a null in front of them

2020-02-15 java eclipse

So my code works and outputs the correct answer however it gives me a null in the answer.

private void toHex() {
    char hexNum[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    String binary = num;

    if(binary.length() % 4 != 4) {
        while(binary.length() % 4 != 0) {
            binary = "0" + binary;
        }
    }
    for(int i = 0; i < binary.length(); i+=4) {
        String temp2 = binary.substring(i, i+4);
        int sum = 0;
        sum += Integer.parseInt(temp2.charAt(0) + "")*8; 
        sum += Integer.parseInt(temp2.charAt(1) + "")*4; 
        sum += Integer.parseInt(temp2.charAt(2) + "")*2; 
        sum += Integer.parseInt(temp2.charAt(3) + "")*1; 
        hex = hex + hexNum[sum];
        sum = 0;
        temp2 = "";
    }
}
private void outHex() {
    System.out.print("Your number from binary to hexadecimal is: 0x" + hex);
    pw.print("Your number from binary to hexadecimal is: 0x" + hex);
}

Btw I declare num as a string outside the method and it is user inputted data. The hex is declared as a string outside the methods as well.

Answers

I would bet you declared hex as.

String hex;

Which defaults to null.

Try the following:

String hex = "";

Which is an empty string.

Related