When adding 'a' + 'b' it produces 195. Is the output datatype char or int?
When adding ‘a’ + ‘b’ it produces 195. Is the output datatype char or
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The result of adding Java chars, shorts, or bytes is an int:
Java Language Specification on Binary Numeric Promotion:
But note what it says about compound assignment operators (like +=):
For example:
One way you can find out the type of the result, in general, is to cast it to an Object and ask it what class it is:
If you’re interested in performance, note that the Java bytecode doesn’t even have dedicated instructions for arithmetic with the smaller data types. For example, for adding, there are instructions
iadd(for ints),ladd(for longs),fadd(for floats),dadd(for doubles), and that’s it. To simulatex += ywith the smaller types, the compiler will useiaddand then zero the upper bytes of the int using an instruction likei2c(“int to char”). If the native CPU has dedicated instructions for 1-byte or 2-byte data, it’s up to the Java virtual machine to optimize for that at run time.If you want to concatenate characters as a String rather than interpreting them as a numeric type, there are lots of ways to do that. The easiest is adding an empty String to the expression, because adding a char and a String results in a String. All of these expressions result in the String
"ab":'a' + "" + 'b'"" + 'a' + 'b'(this works because"" + 'a'is evaluated first; if the""were at the end instead you would get"195")new String(new char[] { 'a', 'b' })new StringBuilder().append('a').append('b').toString()String.format("%c%c", 'a', 'b')