Java Variables

Java variable is an identifier that store a value within the program. The value of the variable is stored in memory. Every Java variable has a scope and lifetime. Each variable must be declared, initialized before you use them. The general convention is to create unique, meaningful names for variables.

Variable Declaration

The variable declaration is given a name and data type to the variable. This also allocates memory to the variable object and a default value depending on type. In Java, this is a safety measure to avoid unexpected values.

The syntax for variable declaration.

<data_type> <variable_name>;

Example #1

int account;

char fruits;

You can declare multiple variables at a time of the same type.

Example #2

int a, b, c;

Variable Initialization

The variable initialization assigns initial values to the variable. When the program executes and terminates, the variable value may not be the same.

Syntax to initialize a variable.

<data_type> <variable_name> = <value>;
<data_type> <variable_name>; //declared
<variable_name> = <value>;

Example #3

int number = 4000;

float circle;

circle = 5.88;

Scope of Variables

The scope of variable decides visibility of the variable within the Java program. The scope has two parts.

  • Class declaration
  • Method declaration

A variable inside the class has class based visibility and scope. We will discuss class based visibility when you learn about Java classes.

The method based scope is divided into global scope and local scope. Consider an example,

class GlobalTest {

           public static void main(String args[]) {

                int box1 = 100;  //global variable

               if(box1 > 60) {

                    int box2 = 200;

                   System.out.println("Box1  and  Box2:" + " " + box1 + box2);





Box1 and Box2: 1oo 200

From the example program above, it is very clear that global variable (box1) is visible to if block and the output has value of box1. However, you cannot access local variable (box2) outside of its block.

Nested Blocks

A nested block contains another block of code. In case of nested blocks global and local access behavior remains same.