Java - Variable


There are several kinds of variables:

  • Member variables in a class—these are called fields.
  • Variables in a method or block of code—these are called local variables.
  • Variables in method declarations—these are called parameters.
  • Reference variable : an object




Member variables in a class are called fields.

public class MyMain {

private static boolean myField;



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, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.

boolean myLocalVariable = true;


Java - Parameter: The important thing to remember is that parameters are always classified as “variables” not “fields”. This applies to other parameter-accepting constructs as well (such as constructors and exception handlers).

public static void myFunction(boolean myParameter) {

How to

Declare a variable

To declare a variable, you write:

type name;

This notifies the compiler that you will use name to refer to data whose type is type. With a primitive variable, this declaration also reserves the proper amount of memory for the variable.

Simply declaring a reference variable does not create an object, you have to use the new operator. The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory.

Documentation / Reference

Powered by ComboStrap