Variables in java

Let’s learn variables in java.

Variables in java

Variable is the name given to memory location to store some value. Size of memory depends on data type.

Syntax:

datatype variableName = value;

To declare a variable, first write data type; Data type can be integer, float, double, long etc. followed by variable name then its value. Like this,

int number = 5;

Variable naming convention in java

A variable name in java

  1. is case sensitive. Variable ‘number’ is not same as ‘NUMBER’.
  2. must begin with letter of alphabet or underscore (_) or dollar sign ($).
  3. after alphabet variable name can contain digits from 0 to 9.
  4. space between variable name is not allowed.
  5. can be of any length.
  6. cannot use java keywords.

Valid variable names:

Valid
EmployeeSalary
Employee_Salary
Employee

Not valid
Employee(Dhoni)
Employee Salary
EmployeeSalary&5
5th_Employee_Salary



Types of variables in java

  1. local variable
  2. instance variable
  3. static variable
variables in java

Local variables in java: A variable declared inside a method, block or constructor is called local variable. It is only accessible inside a method.

Local variables in java cannot be accessed outside the method in which it is declared.

Local variable scope is limited to the method in which it is declared.

Compiler will throw “cannot be resolved to a variable” error if you use local variables ’empAge’ and ‘name’ outside ’employeeDetails method.

public class LocalVariableExample
{
   public void employeeDetails()
   {
      // local variable empAge and name
      int empAge = 22;
      String name = "Sachin";
   }
   public static void main(String[] args)
   {
      LocalVariableExample obj = new LocalVariableExample();
      // name and empAge cannot 
      // be resolved to a variable
      System.out.println("Employee name is : " + name + ", and age : " + empAge);
   }
}



NOTE: local variable cannot be declared as “static”.


Instance variables in java: A variable declared inside the class is called instance variable. Value of instance variable are instance specific.

Instance variable is non-static variable used to store state of an object.

Instance variable in java are declared inside a class but outside method or constructor.

It can be accessed by creating objects. Default value of instance variable is zero, for boolean it is “false” and for object reference “null”.

public class InstanceVariableDemo
{
   // instance variable declared inside the class and outside the method
   int c;
   public void subtract()
   {
      int x = 100;
      int y = 50;
      c = x - y;
      System.out.println("Subtraction: " + c);
   }
   public void multiply()
   {
      int m = 10;
      int n = 5;
      c = m * n;
      System.out.println("Multiplication: " + c);
   }
   public static void main(String[] args)
   {
      InstanceVariableDemo obj = new InstanceVariableDemo();
      obj.subtract();
      obj.multiply();
   }
}


Output:

Subtraction: 50
Multiplication: 50


Static variable in java

Static variables in java are also called “Class variables”.

To access static variables we don’t need to create object. Instead we can access static variable using class name like this,

ClassName.variableName;

Default value of static variable for primitive integers (long, short) is 0; for floating points is 0.0; for ‘boolean’ it is false and for object reference it is null.

Also read – static keyword in java

Static variables are created within a class. Static variable once created is common to all objects.

Memory allocation for static variable happens once when class is loaded in the memory.

Here’s static variable example in java.

public class StaticVariableExample
{
   // static variable
   static int a = 0;
   public void add()
   {
      a++;
   }
   public static void main(String[] args)
   {
      StaticVariableExample obj1 = new StaticVariableExample();
      StaticVariableExample obj2 = new StaticVariableExample();
      obj1.add();
      obj2.add();
      // both objects are sharing same copy of static variable
      System.out.println("Object 1 value is: " + a);
      System.out.println("Object 2 value is: " + a);
   }
}


Output:

Object 1 value is: 2
Object 2 value is: 2


Scope of variables in java

In a java program every variable has a scope. Let’s learn different scope of variables.

Here scope of variable means the visibility of a variable between left curly brace ({) and right curly brace (}).

We have three types of variables in java local, instance and static.

Now let’s learn the scope of these three variables.

Local variable: Local variable scope is within a block or a method.

More specifically scope of local variable is between opening curly braces and closing curly braces of a method. Here’s an example,

public class VariablesScope
{
   void display()
   { // local variable scope
      int a = 5; // local variable
      System.out.println(a);
   } // local variable scope
   public static void main(String[] args)
   {
      // a cannot be resolved to a variable
      System.out.println("Value of a = " + a);
   }
}


Instance variable: Instance variable scope is within a class except in static methods and not in the method. Here’s an example,

public class VariablesScope
{// instance variable scope
   int a = 5; // instance variable
   void display()
   {
      System.out.println(a);
   }// instance variable scope
   public static void main(String[] args)
   {
      VariablesScope obj = new VariablesScope();
      obj.display();
   }
}


Output:

5

Static variable: Static variable scope is within or all over the class not inside method.

Static variable value can’t be changed. Here’s an example,

public class VariablesScope
{
   // static variable scope
   static int a = 5; // static variable
   public static void main(String[] args)
   {
      System.out.println(VariablesScope.a);
   }// static variable scope
}


Output:

5


scope and lifetime of variables in java

I have discussed scope of variables in java in the above section. Coming to lifetime of variables in java –

Local variable lifetime is until control exits the block in which local variable is declared.

Instance variable lifetime is until object is there in memory.

Static variable lifetime is until the end of java program.