OCA Java SE 8 Mock Exam Review - Java Variables Review

Scope of variables

Variables can have multiple scopes:

  • class,
  • instance,
  • local, and
  • method parameters.

Local variables are defined within a method.

Loop variables are local to the loop within which they're defined.

The scope of local variables is less than the scope of a method if they're declared in a sub-block within braces, {}.

A sub-block can be an if statement, a switch construct, a loop, or a try-catch block.

Local variables can't be accessed outside the method in which they're defined.

  • Instance variables are defined and accessible within an object.
  • Instance variables are accessible to all the instance methods of a class.

Class variables are shared by all of the objects of a class.

Class variables can be accessed even if there are no objects of the class.

Method parameters are used to accept arguments in a method. Their scope is limited to the method where they're defined.

A method parameter and a local variable inside the method can't use the same name.

Class and instance variables can't be defined using the same name.

Local and instance variables can be defined using the same name.

In a method, if a local variable has the same name as an instance variable, the local variable takes precedence.

Object's lifecycle

An object's lifecycle starts when it's initialized and ends until it is out of scope or no longer referenced by a variable.

Declaring a reference object variable is not creating an object.

An object is created using the operator new.

Strings have special shorthand built into the compiler.

Strings can be created by using double quotes, as in "Hello".

An object is marked as eligible for garbage collection when it can no longer be accessed.

An object can become inaccessible if it can no longer be referenced by any variable. It happens when a reference variable is explicitly set to null or when it goes out of scope.

You never know whether an object has been garbage collected.