What is the difference between a String and a Character?
Simply put, a char is a single character, whereas a String can be zero or more characters. Additionally, char is a primitive type while String is a class. Strings are created with double quotes, and chars are created with single quotes.
What issues arise when working with Java characters?
Some issues may come up when working with Java characters and mathematical expressions. Since String addition is pretty straightforward, one would expect that character addition is also straightforward. The expression (“Hello ” + “world”) gives “Hello world”. However, the expression (‘n’ + ‘o’) gives 221.
How does Java work with chars?
When printing chars separately, the output is what is expected. Each char would get printed. However, with the example of (‘n’ + ‘o’) above, Java uses a process called widening primitive conversion. This extends the 16-bit char value to a 32-bit int value.
What is widening primitive conversion?
Widening primitive conversion is when a smaller type is converted to a bigger type. In Java, when considering operations involving two types, widening primitive conversion is a collection of the following rules:
- If either operand is of type double, the other is converted to double.
- Otherwise, if either operand is of type float, the other is converted to float.
- Otherwise, if either operand is of type long, the other is converted to long.
- Otherwise, both operands are converted to type int
In the example of (‘n’ + ‘o’), ‘n’ is converted to 110 and ‘o’ is converted to 111. So, (‘n’ + ‘o’) gets converted to (110 + 111) which gives 221.