Variables in Java - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Wednesday, October 31, 2018

Variables in Java

Variables in Java

Variables in Java

The variable is the name to memory location. It is the basic unit of storage in program.

  • A variable is defined by the combination of an identifier, a type, and an optional initializer.
  • The value of variable can change during the execution of program.
  • All the operations done on the variable effects the value store in memory because variable is name to memory location.
  • In Java, all variables must be declared before using it.
  • All variables have a scope, which defines their visibility, and a lifetime.

Declaring a variable

All variables must be declared before they can be used. The basic form of variable declaration:

type identifier [ = value ][, identifier [= value ] ...];

Here, type is either primitive data type or non-primitive data type. The identifier is the name of the variable.

You can initialize the variable by specifying an equal sign and value. The value must be compatible type as the specified for the variable.

Examples:

int a, b; // declare two int variable a and b
int c = 10, d = 20; // declare two ints, and initializing c and d
float f = 5.201f; // declare float variable and initialized f
double pi = 3.14159; // declares an approximation of pi
char charX = 'x'; // char variable has the value 'x'

Dynamic initialization of variable

In the previous example all the variables have constant value. We can initialized the varibles dynamically, using the valid expression at the time the variable is declared.

A short Java program demonstrate the dynamic initialization of a variable. We calculate the hypotenuse of a right triangle given the lengths of its two opposing sides.

Pythagoras' theorem states that the square of the hypotenuse (the side opposite the right angle) is equal to the sum of the squares of the other two sides.

public class DynamicInitializationDemo {
  public static void main(String[] args) {
    double a = 3.0;
    double b = 4.0;
    double c;
    c = Math.sqrt(a * a + b * b);
    System.out.println("Hypotenuse of right angle triangle is " + c);
  }
}

Two variables a and b are declared and initialized by constants. However, c is initialized dynamically to the length of hypotenuse of a right angle triangle. To compute the square root, We have used the sqrt() built in method of Math class.

Output of the above program

Hypotenuse of right angle triangle is 5.0

Type of variable

There are three types of variables in Java:

  • Local Variable
  • Instance Variable
  • Static Variable

Let's learn about each of these variables in details.

1. Local Variable

A variable defined inside a block, method or constructor is called local variable.

  • A local variable can't defined with "static" keyword.
  • A local variable can't defined with access modifier like public, private or protected.
  • Local variable is created when entered into block or the method called and destroyed when exiting from block or the call returned from the method call.
  • The scope of the variables exists only within the block in which variables are declared. i.e we can not access these variables outside the block.
  • There is no default value for local variables, so local variables should be declared and an initial value should be assigned before use.

Example:

public class PersonDetails {

  /*getPersonAge is a public method which is available within the class
  and outside the class which means visible everywhere.
  It returns int value.*/
  public int getPersonAge() {
    int age = 0; // declare variable age and assign 0 to it
    age = age + 20;
    return age;
  }

  /**
   * inside main method a local variable age is declared. Creating an object of PersonDetails using
   * the new keyword. calling the getPersonAge() method on obj object which gets the age of the person
   * and assign the value to age variable.
   */
  public static void main(String[] args) {
    int age; // local variable
    PersonDetails obj = new PersonDetails();

    age = obj.getPersonAge();
    System.out.println(age);
  }
}

Output:

20

2. Instance Variable

An instance variable is non-static variable and declared inside a class but outside any method, constructor or block. It is called instance variable because it is belong to instance specific and is not shared among instances.

  • An instance variable is declared inside a class, it is created when an object or instance of a class is created and destroyed when the object/instance is destroyed.
  • Unlike a local variable, we may use access modifier for instance variable. If we do not specify any access modifier to instance variable then default access modifier will be used.
  • Instance variable has default value. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor.

Example:

public class Person {
  public int age;
  public String name;

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public void printPerson() {
    System.out.println("Age of person: " + age);
    System.out.println("Name of person: " + name);
  }

  public static void main(String[] args) {
    Person person1 = new Person();
    person1.setAge(20);
    person1.setName("Priyanka");
    System.out.println("Detail of the first person.");
    person1.printPerson();

    Person person2 = new Person();
    person2.setAge(30);
    person2.setName("Virat");
    System.out.println("\nDetail of the second person.");
    person2.printPerson();
  }
}

Output:

Detail of the first person.
Age of person: 20
Name of person: Priyanka

Detail of the second person.
Age of person: 30
Name of person: Virat

As you can see in the above program the variables, age, name are instance variables. We have two object of Person class. Each object has its own copy of instance variable. It is clear from the above output that each object will have its own copy of instance variable.

3. Static Variable

A variable which is declared with static keyword is called static variable. Static variable can't be a local variable. Static variable belongs to the class that why it is also called class variable. The static variable is shared among all the instances.

  • Static variable is declared same as instance variable with "static" keyword.
  • Unlike instance variable, We can have only one copy of static variable per class irrespective of the number of objects we have created.
  • Memory allocation for static variable happens only once when the class is loaded in the memory.
/*
This example demonstrate the static variable.
static variable belongs to class, not to an instance.
 */
public class PersonDemo {
  public static int salary; //  static variable
  public String name; // instance variable
  public int age; // instance variable

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public void printPerson() {
    System.out.println("Salary of person: " + salary);
    System.out.println("Age of person: " + age);
    System.out.println("Name of person: " + name);
  }

  public static void main(String[] args) {
    // static variable can access using the ClassName.staticVariable
    PersonDemo.salary = 10000;

    PersonDemo person1 = new PersonDemo();
    person1.setAge(20);
    person1.setName("Priyanka");
    System.out.println("Detail of the first person.");
    person1.printPerson();

    PersonDemo person2 = new PersonDemo();
    person2.setAge(30);
    person2.setName("Virat");
    System.out.println("\nDetail of the second person.");
    person2.printPerson();
  }
}

Output:

Detail of the first person.
Salary of person: 10000
Age of person: 20
Name of person: Priyanka

Detail of the second person.
Salary of person: 10000
Age of person: 30
Name of person: Virat

Note: A static variable should always use with the class, not with an object. You can also use static variable using object as you access instance variable.

No comments :

Post a Comment