I have the following code:
class Example{
public static void main(String args[]){
System.out.println('1'+'1');
}
}
Why does it output 98
?
“Possible loss of precision” occurs when more information is assigned to a variable than it can hold. If this happens, pieces will be thrown out. If this is fine, then the code needs to explicitly declare the variable as a new type.
When you place 2L in code, that is a long literal, so the multiplications promote the other int s to long before multiplication, making your calculations correct by preventing overflow. The basic rules here to know here are: Java has operator precedence.
In java, every character literal is associated with an ASCII value which is an Integer
.
You can find all the ASCII values here
'1'
maps to ASCII value of 49 (int
type).
thus '1'
+ '1'
becomes 49 + 49
which is an integer 98.
If you cast this value to char
type as shown below, it will print ASCII value of 98 which is b
System.out.println( (char) ('1'+'1') );
If you are aiming at concatenating 2 chars (meaning, you expect "11"
from your example), consider converting them to string first. Either by using double quotes, "1" + "1"
or as mentioned here .
'1'
is a char
literal, and the +
operator between two char
s returns an int
. The character '1'
's unicode value is 49, so when you add two of them you get 98.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With