July 2, 2022

Java Variables - Declaration, Initialization And Types

Variables are used to store values that are used in your Java program. A Java variable is a name to a memory location that contains the value assigned to that variable. In this post we’ll see how to declare and initialize a variable in Java, types of variables in Java and their scope.

Declaring a variable in Java

In Java it is mandatory to declare a variable before use. Syntax for variable declaration in Java is as follows-

type variable_name = value

Here type can be a primitive data type, or a Class name or interface, variable_name is the name of the variable. Value is a value of a compatible type, “=value” part is optional and required only if you are initializing a variable when declared.

For example-

int age = 65;

Here age is the variable name which is of type int and initialized with the value 65.

Same variable declaration and initialization can be done separately too.

//declaration		
int age;
..
..
// initialization
age = 65;

Some other examples of variable declaration and initialization.

//declaration and initialization of a char variable
char ch = 'a';
//declaration variable of type double
double d;

You can also declare more than one variable of the same type in a single line as a comma-separated variables.

int i = 10, j = 20;

Types of variables in Java

The Java programming language defines the following kinds of variables:

  • Instance Variables (Non-Static Fields)
  • Class Variables (Static Fields)
  • Local Variables
  • Parameters

Instance variable in Java

Instance variables in Java (also known as non-static fields) are those variables which are created for each instance (object) of the class. Each object of the class will have a separate copy of instance variable.

Instance variables are declared in a class not in any method or constructor.

Instance variables Java example
class Employee{
  private String name;
  private int age;
  private String dept;
  Employee(String name, int age, String dept){
    this.name = name;
    this.age = age;
    this.dept = dept;
  }
  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 String getDept() {
    return dept;
  }
  public void setDept(String dept) {
    this.dept = dept;
  }
}
public class InstanceExp {
  public static void main(String[] args) {
    Employee emp1 = new Employee("Mark", 32, "Engineering");
    Employee emp2 = new Employee("Amy", 28, "Human Resources");
    System.out.println("First Employee details- ");
    System.out.println("Name- " + emp1.getName() + " Age- " + emp1.getAge() + " Dept- " + emp1.getDept());		
    System.out.println("Second Employee details- ");
    System.out.println("Name- " + emp2.getName() + " Age- " + emp2.getAge() + " Dept- " + emp2.getDept());
  }
}
Output
First Employee details- 
Name- Mark Age- 32 Dept- Engineering
Second Employee details- 
Name- Amy Age- 28 Dept- Human Resources

In the example there are three instance variables in class Employee. Then two objects of Employee class are created both have their own copy of instance variables with different values.

Class variables (static variables) in Java

Class variables are also declared in a class not in any method or constructor and these variables also use static keyword. A static variable is associated with the class and all the instances of the class share the same variable i.e. there is only one copy of static variable.

Static variable Java example
class Employee{
  private String name;
  private int age;
  private String dept;
  private int wages;
  //static variable
  static final int DAYS_PAID = 22;
  Employee(String name, int age, String dept, int wages){
    this.name = name;
    this.age = age;
    this.dept = dept;
    this.wages = wages;
  }
  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 String getDept() {
    return dept;
  }
  public void setDept(String dept) {
    this.dept = dept;
  }
  public int getWages() {
    return wages;
  }
  public void setWages(int wages) {
    this.wages = wages;
  }
}
public class InstanceExp {
  public static void main(String[] args) {
    Employee emp1 = new Employee("Mark", 32, "Engineering", 50*8*Employee.DAYS_PAID);
    Employee emp2 = new Employee("Amy", 28, "Human Resources", 30*8*Employee.DAYS_PAID);
    System.out.println("First Employee details- ");
    System.out.println("Name- " + emp1.getName() + " Age- " + emp1.getAge() + " Dept- " + emp1.getDept() + " Salary- "+ emp1.getWages());		
    System.out.println("Second Employee details- ");
    System.out.println("Name- " + emp2.getName() + " Age- " + emp2.getAge() + " Dept- " + emp2.getDept()+ " Salary- "+ emp2.getWages());
  }
}
Output
First Employee details- 
Name- Mark Age- 32 Dept- Engineering Salary- 8800
Second Employee details- 
Name- Amy Age- 28 Dept- Human Resources Salary- 5280

In the example there is a static variable DAYS_PAID which is accessed using the class name (Employee.DAYS_PAID).

Local variables in Java

A variable defined between the start and closing curly braces of a method is known as a local variable. Scope of a local variable is with in the method where it is declared. In fact every block of code creates a new scope and any variable declared with in the opening and closing braces of that block has the scope with in that block.

public void sum(int x, int y){
  //local variable
  int sum = x + y;
  if(sum > 10){
    // scope with in if condition block
    int temp = sum;
  }
  // Not visible here 
  //temp = 40;
}

In the code sum is a local variable having its scope with in the method where it is declared. Another variable temp is declared with in the if statement so its scope is with in the opening and closing braces of the if condition block.

Parameters in Java

Arguments passed to a method are known as parameters. Modifying value of a primitive type parameter in a method doesn't change the original value.

public class InstanceExp {
  public static void main(String[] args) {
    InstanceExp obj = new InstanceExp();
    int x = 5;
    obj.test(x);
    System.out.println("Value of x after method call- " + x);
  }

  public void test(int x){
    x++;
    System.out.println("Value of x in method- " + x);

  }
}
Output
Value of x in method- 6
Value of x after method call- 5

As you can see x is passed as a method parameter which is modified in the method but it doesn’t change the original value.

Local Variable Type Inference in Java 10

From Java 10 it is possible to declare type of local variable as "var". Java compiler infers the type of a local variable using the value it is initialized with.

For example-
var name = "knpcode"; // infers type as String

var list = new ArrayList<Integer>(); // infers type as ArrayList

Local Variable Type Inference can be used only with local variables with initializer, indexes in for-each loop, local variables declared in for loop.

Read more about var type in Java 10 in this post- Java var Type (Local Variable Type Inference)

That's all for the topic Java Variables - Declaration, Initialization And Types. If something is missing or you have something to share about the topic please write a comment.
You may also like

No comments:

Post a Comment