Wednesday, 15 March 2017

Kinds of Variables in Java

As mentioned in the post object in Java, object is an instance of the class, which gets its state and related behavior from the class. At the same time an object stores its state in variables.

So in this post we’ll see what all types of variables are there in Java, what are the scopes for those variables and their visibility.

We’ll also see what is meant by declaring a variable and what is meant by initialization of the variable.

Declaring and Initializing a variable

In Java it is mandatory that a variable should be declared before it is used. Declaring a variable means telling what type of a variable it is. Variable may be of primitive data type (int, float, char), or having class or interface as type.

As exp.

int age, number;

double amount;

Person person;

As you see here in the first statement two variables of type int are declared. Note here that you can declare two or variable of same type as a comma separated list.

In the second statement a variable amount of type double is declared. Where as in third statement a variable person is declared which is of type Person. Here Person is a class.

Initialization

Initialization means providing initial value of the variable. Generally, both declaration and initialization are done in a single statement.

 
int age = 30;

char a = ‘A’;

But that is not necessary you may declare a variable first and initialize it later.

 
int age;

...... 
......
age = 50;

An expression can also be used to initialize a variable -

 
double amount;

amount = 67/9;

Here amount will have the value of 67 divided by 9.

Types of variables

The Java programming language defines the following kinds of variables:

  1. Instance Variables (Non-Static Fields) – As already mentioned object is an instance of the class and there can be many objects of the same class. Every object has its own state for the non-static fields which is unique for each instance (object). That is why the fields of each object are referred as instance variables as they are unique for each instance.

    As example – If you have a class Person and two objects of it person1 and person2 then the instance variables of these two objects will have independent values.

    public class Person {
     private String firstName;
     private String lastName;
     private int age;
     private char gender;
     public Person(String firstName, String lastName, int age, char gender){
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
      this.gender = gender;
     }
     
     public String getFirstName() {
      return firstName;
     }
    
     public String getLastName() {
      return lastName;
     }
    
     public int getAge() {
      return age;
     }
     public char getGender() {
      return gender;
     }
    }
    
    public class InstanceDemo {
    
     public static void main(String[] args) {
      Person person1 = new Person("Ram", "Mishra", 23, 'M');
      Person person2 = new Person("Amita", "Chopra", 21, 'F');
      
      System.out.println("Values in object person1 - " + 
        person1.getAge() + " " + person1.getFirstName() + " " + 
        person1.getLastName()+ " " + person1.getGender());
      System.out.println("Values in object person2 - " + 
        person2.getAge() + " " + person2.getFirstName() + " " + 
        person2.getLastName()+ " " + person2.getGender());
    
     }
    
    }
    

    Output

    Values in object person1 - 23 Ram Mishra M
    Values in object person2 - 21 Amita Chopra F
    

    Here you can see how using the constructor of the class, variables are initialized for both the objects and output shows that each instance of the class has its own values for the fields.

  2. Class Variables (Static Fields) - A class variable is any field declared with the static modifier. As the name suggests class variable is at the class level and there will be exactly one copy of this variable in existence. Doesn’t matter how many instances (objects) of the class you have the class variable will have the same value, moreover you don’t even need the object to refer to the class variable.

    As example - One common use of static fields is to create a constant value that's at a class level and applicable to all created objects.

    public class Employee {
     int empId;
     String name;
     String dept;
     // static constant
     static final String COMPANY_NAME = "XYZ";
     Employee(int empId, String name, String dept){
      this.empId = empId;
      this.name = name;
      this.dept = dept;
     }
     
     public void displayData(){
      System.out.println("EmpId = " + empId + " name= " + name + " dept = " + 
      dept + " company = " + COMPANY_NAME);
     }
     public static void main(String args[]){  
      Employee emp1 = new Employee(1, "Ram", "IT");
      Employee emp2 = new Employee(2, "Krishna", "IT");
      emp1.displayData();
      emp2.displayData();
     }
    }
    

    Output

    EmpId = 1 name= Ram dept = IT company = XYZ
    EmpId = 2 name= Krishna dept = IT company = XYZ
    
  3. Local Variables – Similar to how object store its state in fields, a method will store its temporary state in local variables. Scope of local variable is in between the start and closing curly braces of a method. There is also a nested scope, suppose with in a method you have a if condition with its own starting and closing curly braces, then that block of code with in the if condition creates a nested scope. One more thing to note is you can have a local variable with the same name as class level variable with in the method and with in the method the local variable will take priority.

    As example

    public class InstanceDemo {
     // class level variable
     int x = 8;
     public static void main(String[] args) {
      
      InstanceDemo id = new InstanceDemo();
      
      id.display();
      System.out.println("value of class level variable x " + id.x);
     }
     
     public void display(){
      int x = 5;
      boolean flag = true;
      System.out.println("value of local variable x " + x);
      if (flag){
       int y = 10;
       System.out.println("value of local variable y inside if " + y);
      }
      // This will cause compile-time error
      //System.out.println("value of local variable y inside if " + y); 
     }
     
    }
    

    Output

    value of local variable x 5
    value of local variable y inside if 10
    value of class level variable x 8
    

    Here you see there is a class level variable and again it the method display() there is a variable with the same name x. When in the method value of local variable x takes priority and that is printed. Once out of method x that is recognized is the class level variable x.

    Another thing to note is the nested scope created by the if condition with in the display() method. Scope of variable y is in between the starting and closing braces of the if condition. Once you are out of if condition y won’t be recognized. Any attempt to print value of y outside the if condition scope will result in compile-time error.

  4. Parameters - Variables passed to any method are known as parameter. Any changes made to the primitive types parameter won’t change the original value.

    As example

    public class InstanceDemo {
     public static void main(String[] args) {
      
      InstanceDemo id = new InstanceDemo();
      int x = 10;
      id.display(x);
      System.out.println("value of x after method call " + x);
     }
     
     public void display(int x){
      
      x++;
      System.out.println("value of local variable x " + x);
     }
     
    }
    

    Output

    value of local variable x 11
    value of x after method call 10
    

    Here you have a variable x that is passed to display method as an int parameter. With in the method display() value of x is changed. But that change is local only and doesn’t change the original value of x. This is because copy of a variable is passed as a method parameter.

    If an object is passed as a parameter and any of that object’s field is changed, that change will be visible in other scopes too.

That's all for this topic Kinds of Variables in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Primitive Data Types in Java
  2. Access modifiers in Java
  3. What are JVM, JRE and JDK in Java
  4. Object creation using new operator in Java
  5. Ternary operator in Java

You may also like -

>>>Go to Java Basics page

No comments:

Post a Comment