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
  • Fields declared without static.
  • They store individual states of objects.
 Yes
 Class variables  Static fields
  • Fields declared with the static modifier.
  • They store the state of classes.
 Yes
 Local variables
  • Declared between opening and closing braces of a constructor or method.
  • They store temporary state of methods.
 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 or null 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.

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!

Leave a Reply