refresh java logo

Variables in Java

Variables in a computer program is similar to variables in mathematics. In mathematics we use to define variable to solve a problem, similarly in computer programming we use to define variables in a program to solve a problem or accomplish a task.

Think of variable as a "Bucket" or "Envelope" where you can store information. These bucket has a name called as variable name. The information stored in a bucket can be accessed later in program by it's name. They are called variables because the information stored in it can be changed. Basic syntax of declaring a variable in java is:

 DataType variable_name = value;
  • DataType of variable - Mandatory
  • Name of variable - Mandatory
  • Value of variable - Optional
variable in java
  int age = 20; // variable name age with value as 20	

Each variable must have a Name. Name of a variable is used to refer that variable value later in program. The name of a variable must be unique.

Each variable must also have a Data Type. The Data Type represents what type of data that variable can store. This can be Primitive or Non Primitive data type.

Each variable will also have a value, either it is given by programmer or a default value is assigned by java as per it's data type.

What is default value ?

If programmer doesn't specify a value to the variable, java itself assign a value to that variable at runtime according to data type of variable. This value is know as default value.

Declaration and Initialization of Variable

Declaration and initialization of variable are two terms that is used most frequently with variables. Declaration means declaring or creating a variable while Initialization means assigning some value to that variable.

  int speed; // Declaring or creating a variable name speed
  speed = 100;  // Initializing variable speed with value as 100
  int speed = 10;  // Declaration and initialization together	

Java Program of Variable

 class VariableProgram
   {
      public static void main(String [] args)
         {          
            // declaring single variable
            int a = 20;  
            // declaring multiple variable
            int b = 30, c = a, d; 
            d = a + b;
            System.out.println("d = " +d);            	
            double pi = 3.14159; 
            System.out.println("value of pi = " +pi);            
            boolean e = true, f = a>c;  
            System.out.println("e = "+e+ "\nf = "+f);             
         }
   }

Output:

d = 50
value of pi = 3.14159
e = true
f = false

★★★
  • Always remember to add semicolon(;) at the end of variable declaration.
  • To Access a variable simply means to read the information stored in that variable. To access a variable, simply type its name.
  • To Assign a value to a variable means to give a value to that variable or store some value in that variable.