Sub topic 2
Characters: char and Unicode
Characters
A char is a primitive type for one UTF-16 code unit. Unicode is a system that assigns numbers to characters. UTF-16 is one way to represent those numbers.
Many characters, such as A and Ω, fit in one char. Some, including many emoji, need two char values.
Boolean Values
A boolean is a primitive type with two values: true and false. Use it for a yes-or-no state, such as whether a test passed. Java does not use 0 and 1 as boolean values.
Writing Primitive Literals
A literal is a value written directly in code. For example:
'A'is acharliteral. Single quotes surround it.'\u03A9'is acharliteral forΩ. The\uescape gives its Unicode value in hexadecimal, a base-16 number system.trueis a boolean literal.10Lis alongliteral, and2.5fis afloatliteral. The letters at the end mark their types.
Double quotes, as in "A", make a String, not a char.
Save this program as CharacterExample.java, then compile and run it:
class CharacterExample {
int score;
boolean ready;
void show() {
char grade = 'A';
char symbol = '\u03A9';
boolean passed = true;
int score = 3;
System.out.println(grade);
System.out.println(symbol);
System.out.println(passed);
System.out.println(score);
System.out.println(this.score);
System.out.println(ready);
}
public static void main(String[] args) {
new CharacterExample().show();
}
}It prints A, Ω, true, 3, 0, and false, each on its own line.
Scope and Shadowing
Scope is the part of a program where a name can be used. The local variables, such as grade, are declared inside show and can be used within that method’s braces.
A field is a variable declared in a class, outside its methods. The local score shadows the field score: the local name hides the field’s name in show. Write this.score to reach the field on the current object, an instance of the class.
A local variable cannot redeclare another local variable whose scope includes it, even inside nested braces.
Default Values and Definite Assignment
Fields get default values. Numeric fields start at zero, char fields start at the character value zero, and boolean fields start at false. That is why the example prints 0 for this.score and false for ready.
Local variables have no default value. Java requires definite assignment: a local variable must be assigned a value on every possible path before it is used.
Exercise
If you remove = true from the local declaration of passed, can the program still print it?
Show answer
No. The local variable must be assigned before it is used.