Variables

The Java programming language defines the following kinds of variables:

  • Instance Variables (Non-Static Fields)
  • Class Variables (Static Fields)
  • Local Variables
  • Parameters

java_variables

Instance Variables (Non-Static Fields)

Technically, objects store their individual states in non-static fields, that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class:

For example, the name & task of a dog is independent from the names & tasks of other dogs.

Class Variables (Static Fields)

A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence; regardless of how many times the class has been instantiated.

A field defining the number of dog legs could be marked as static since conceptually the same number of legs will be applied to all instances of the Dog class.

The code below would declare such a static field.

Additionally, the keyword final could be added to indicate that the number of dog legs will never change.

Note: for variable stores a constant value as above capitalizing every letter and separating subsequent words with the underscore character. That’s about naming convention. But we don’t go in details in this tutorial.

Local Variables

Similar to how an object stores its state in fields, a method will often store its temporary state in local variables.

The syntax for declaring a local variable is similar to declaring a field. For example,

There is no special keyword designating a variable as local. The determination comes entirely from the location in which the variable is declared — which is between the opening ({) and closing (}) curly braces of a method. As such, a local variable are only visible to the method in which it’s declared. It’s not accessible from the rest of the class.

Parameters

You’ve already seen examples of parameters, in the Dog class and in the main method of every java application. Recall that the signature for the main method is:

The args variable is the parameter to this method. The important thing to remember is that parameters are always classified as “variables” not “fields”.