You probably know everything about variables, but there are three things you need to grasp well for the Java SE Programmer exams:
- Kinds of variables
- Default values
- Naming
Kinds of Variables
Kind | Also known as | Description | Default values |
---|---|---|---|
Instance variables | Non-static fields |
|
Yes |
Class variables | Static fields |
|
Yes |
Local variables | – |
|
No |
Default Values
There are many questions in the exam that can be tricky if you don’t consider default values, but they become easy if you remember the following three key points:- Only fields have default values
- These values are
0
,false
ornull
depending on the field data type - There are no default values for local variables, so accessing an uninitialized local variable will result in a compile-time error.
1 2 3 4 5 6 7 8 9 10 11 |
class DefaultValues { static int i; // A field has a default value (0) static String s; // A field has a default value (null) public static void main(String[] args) { int j; // Local variable (no default value) i = j + 1; // Compiler error: j is not initialized } } |
Naming
There is no need to worry about recommended rules and conventions for naming variables (e.g. camelCase). You must only need to be able to determine if a name is valid or not for the Java compiler, regardless of how ugly it could seem:- Valid names start with currency (
$
), underscore (_
) or letter - Subsequent characters can also be digits
You may wonder what letters and digits exactly mean. Well, according to the Java Language Specification letters and digits may be drawn from the entire Unicode character set, but for the exam purposes the following is enough:
- Letter:
a-z
,A-Z
(or the corresponding Unicode codes) - Digit:
0-9
(or the corresponding Unicode codes)
Believe it or not, variable names can include Unicode codes like \u0041
(code for A
), but don’t worry: you don’t need to know the valid Unicode codes. The following are examples of valid (and not recommended) variable names:
$
$123_
$___
_
_abc123
_\u0041_
a$_1bc
A____
\u0041___
Finally, two more important things about variable names that you must remember:
- It’s not allowed to use any Java reserved word or literal (
null
,true
,false
) as a variable name - Java variables are case-sensitive. Be careful about similar names that are really different variables!