Java Reference
In-Depth Information
results in the value of myCharacter being changed to 'Y' . This is because the Unicode code for 'Y' is one
more than the code for 'X' . You could use the increment operator ++ to increase the code stored in myChar-
acter by just writing the following:
++myCharacter; // Increment to next character
When you use variables of type char in an arithmetic expression, their values are converted to type int
to carry out the calculation. It doesn't necessarily make a whole lot of sense, but you could write the follow-
ing statements that calculate with values of type char :
char aChar = 0;
char bChar = '\u0028';
aChar = (char)(2*bChar + 8);
These statements leave the aChar variable holding the code for the letter X — which is 0x0058 .
TRY IT OUT: Arithmetic with Character Codes
This example demonstrates arithmetic operations with values of type char :
public class CharCodeCalcs {
public static void main(String[] args){
char letter1 = 'A'; // letter1 is 'A'
char letter2 = (char)(letter1+1); // letter2 is 'B'
char letter3 = letter2; // letter3 is also 'B'
System.out.println("Here\'s a sequence of letters: "+ letter1 +
letter2 +
(++letter3));
// letter3 is now 'C'
System.out.println("Here are the decimal codes for the
letters:\n"+
letter1 + ": " + (int)letter1 +
" " + letter2 + ": " + (int)letter2 +
" " + letter3 + ": " + (int)letter3);
}
}
This example produces the output:
Here's a sequence of letters: ABC
Here are the decimal codes for the letters:
A: 65 B: 66 C: 67
How It Works
The first three statements in main() define three variables of type char :
char letter1 = 'A'; // letter1 is 'A'
char letter2 = (char)(letter1+1); // letter2 is 'B'
char letter3 = letter2; // letter3 is also 'B'
Search WWH ::




Custom Search