Home > Mobile >  why is it giving numbers as output instead of elements in the array?
why is it giving numbers as output instead of elements in the array?

Time:10-17

char[] np={'a','s','d','f'};
System.out.println(np[1] np[np.length-1]);

// this print statement is giving output:217

System.out.println("" np[1] np[np.length-1]);
// this print statement is giving output:af

I just want to know why the first one is giving numbers as output ? and this is in java.

CodePudding user response:

'a' 3 will convert a will use the byte representation based on the encoding and auto convert it to an int value. These are based on the widening primitive conversions rules. Basically, char is treated as a more specific type of int and when added together, the more general of the two (int) will be the type returned.

To solve this, you can convert one of the variables to a type which will prevent the compiler from interpreting it as an int addition. One way would be to add a String at the start as you have above. Another way could be to modify np[1] to String.valueOf(np[1]) in the equation.

CodePudding user response:

Syntax np[1] np[np.length-1 is converted to 's' 'f', which is treated by java as an addition operation. Hence JAVA converts 's' and 'f' to their ASCII integer values 115 and 102 and adds them to 217.

On the second statement including a double quote("") locks the that value as a string and hence, JAVA no longer treats the operation as an addition but a string combination, thus the result.

  • Related