Variables in java

Let’s learn variables in java.

Variables in java

Variable is the name given to reserved memory location to store some value.

The size of reserved memory depends on data type. Data type should be mentioned before running java program.

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,

public class VariableDemo
{
   public static void main(String[] args)
   {
      // declare and initialize integer variable
      int age = 10, houseNo = 64;
      // declare float variable
      float interest;
      // declare and initialize character variable
      char gender = 'm';
   }
}



Types of variables in java with examples,

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

Local variable in java: variable defined inside a method or constructor of a class. It has visibility inside a method.

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

public class LocalVariableDemo 
{
   public void EmployeeDetails() 
   { 
      // local variable empAge and name 
      int empAge = 22; 
      String name = "Sachin"; 
      System.out.println("Employee name is : " + name + ", and age : " + empAge); 
   }

   public static void main(String[] args) 
   {
      LocalVariableDemo obj = new LocalVariableDemo();
      obj.EmployeeDetails();
   }
}



Output:

Employee name is : Sachin, and age : 22

Compiler will throw “cannot be resolved to a variable” error if you use variable outside a method.

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


Instance variables in java: 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 it is “null”.

class Department 
{ 
   // instance variables 
   int mechDepartment; 
   int csDepartment; 
   int ecDepartment; 
}

public class InstanceVariableDemo 
{
   public static void main(String[] args) 
   {
      Department de = new Department(); 
      de.mechDepartment = 150; 
      de.csDepartment = 50; 
      de.ecDepartment = 70;

      System.out.println("Students in each department - "); 
      System.out.println("Mechanical : " + de.mechDepartment); 
      System.out.println("Computer science : " + de.csDepartment); 
      System.out.println("Electronics : " + de.ecDepartment);
   }
}



Output:

Students in each department –
Mechanical : 150
Computer science : 50
Electronics : 70


Static variable in java

are variables declared inside a class. Here variables are declared with keyword “static”.

Also read – static keyword in java

Static variables are also called “Class variables in java”. 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 is 0. Static variables are created within a class.

class Student
{ 
   // static variables 
   public static int ID; 
   public static String name = "Sachin"; 
}

public class StaticVariableDemo 
{
   public static void main(String[] args) 
   {
      // accessing static variable without creating object 
      Student.ID = 155668; 
      System.out.println("Student name : " + Student.name + ", and ID : " + Student.ID);
   }
}



Output:

Student name : Sachin, and ID : 155668

NOTE:

  • If you access static variable without class name compiler itself adds class name.
  • Like instance variable if you access static variable using object, a warning message is shown. It won’t cease the program, instead compiler restores object with class name.
  • Memory allocation for static variable happens once when class is loaded into memory.

Scope of variables in java

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

  1. class scope
  2. method scope
  3. loop scope
  4. bracket scope

class scope: in class scope, variables can be used anywhere within the class, but not outside the class.

For example member variables declared inside a class can be accessed within that class.

public class ClassScopeDemo 
{
   int a;
   private String str;
   void methodDemo1() 
   {

   }
   void methodDemo2()
   {

   }
   char ch;
}



method scope: variable declared inside a method is valid only within that method.

public class MethodScopeDemo 
{
   public void methodDemo1() 
   {
      Integer number = 26;
   }
   public void methodDemo2() 
   {
      // compiler error
      // number cannot be resolved to a variable
      number = number + 2;
   }
}



loop scope: variable declared inside a loop is valid only inside the loop.

public class LoopScopeDemo 
{
   List<String> playerNames = Arrays.asList("virat", "rohit", "dhoni");
   public void allNames()
   {
      String strNames = "";
      for(String players : playerNames) 
      {
         strNames = strNames + " " + players;
      }
      // compiler error, players cannot be resolved to a variable
      String namesUsed = players;
   }
}



bracket scope:

public class BracketScopeDemo 
{
   public void demo() 
   {
      Integer a = 0;
      {
         Integer b = 6;
         a = a + b;
      }
      // compiler error, b cannot be resolved to a variable
      b++;
   }
}



Global variable in java

Basically in java there is no variable called global variable. Instead we can use ‘public static’ as global variable for referring.

Let’s see global variable in java: declaration and examples,

class Demo
{
   // declaration
   public static final String NAME = "flowerbrackets";
   public static final int NUMBER = 6;
}

public class JavaExample
{
   public static void main(String[] args) 
   {
      System.out.println(Demo.NAME);
      System.out.println(Demo.NUMBER);
   }
}



Output:

flowerbrackets
6

Local and global variables in java

Let’s learn local and global variables in java with the help of a program,

class LocalGlobalDemo
{
   static int empCompany;
   static void employeeMethod()
   {
      int salary = 100000;
      System.out.println(salary);
      System.out.println(empCompany);
   }
   
   public static void main(String[] args)
   {
      int empSalary = 60000;
      System.out.println(empSalary);
      System.out.println(salary);// salary cannot be resolved to a variable
   }
}



In the above java program global variable ’empCompany’ can be used inside class LocalGlobalDemo and declared anywhere inside class LocalGlobalDemo but not inside a method.

As you can see in the above java program global variable is used inside employeeMethod() and also in main() method.

Meanwhile local variable ‘salary’ is declared inside employeeMethod() can be used inside the same method but not outside employeeMethod().

If you access local variable ‘salary’ outside employeeMethod(), that is, in main() method you get compile time error “salary cannot be resolved to a variable”.