Reputation: 51
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.
Upvotes: 0
Views: 169
Reputation: 43
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 that value as a string and hence, JAVA no longer treats the operation as an addition but a string combination, thus the result.
Upvotes: 0
Reputation: 8135
With the new String formatted, You can simplify this.
char[] np = { 'a', 's', 'd', 'f' };
System.out.println("%s%s".formatted(np[1], np[np.length - 1]));
By default, np[1] trying to use the ASCII code value int+int
Upvotes: 0
Reputation: 964
's' + 'f'
will convert each character to its 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.
Upvotes: 2