Font size

Variable declaration

Variable declarations are considered in the section Variables. There are two syntax forms:

<type> <variable name> ;
<type> <variable name> = <initial value>;


double x;
Person customer = null;
ArrayList<Person> colleagues = new ArrayList<Person>();
Keep in mind that:
  • A local variable must be declared before it is first used.
  • A local variable declared within a block {…} or a function body exists only while this block is being executed.
  • If the name of a variable declared in a block or function body is the same as the name of the variable declared in an enclosing (higher level) block or of the current class variable, the lower level local variable is meant by default when the name is used. We however strongly recommend to avoid duplicate names.

The image below illustrates the code areas where local variables exist and can be used.

Code areas where local variables exist and can be used

How can we improve this article?