Variables in Java


Introduction

In Java, variables are fundamental for storing data that can be manipulated by the program. Understanding the different types of variables and their scopes is essential for writing efficient and effective Java code. This chapter covers the basics of variables in Java, how to declare them, and the various types of variables available.

What is a Variable in Java?

A variable is a container that holds a value while the Java program is executed. Each variable is assigned a data type, which determines the kind of values it can hold. In Java, a variable is a name given to a memory location that stores data.

Characteristics of Variables:

  1. Changeable Values: The value stored in a variable can be changed during program execution.
  2. Memory Location: A variable is a reference to a memory location, and all operations done on the variable affect that memory location.
  3. Declaration Requirement: In Java, all variables must be declared before they can be used.

Declaring a Variable

In Java, variables must be declared before they can be used. The basic syntax for declaring a variable is as follows:

type identifier [ = value ][, identifier [ = value ] …];
  • type: The data type of the variable (e.g., int, float, String).
  • identifier: The name of the variable.
  • value: The initial value of the variable (optional).

Example Declarations:

int a, b, c; // declares three integers: a, b, and c
int d = 3, e, f = 5; // declares three more integers and initializes d and f
byte z = 22; // initializes z
double pi = 3.14159; // declares and initializes pi
char x = 'x'; // declares and initializes x with the value 'x'

Different Types of Variables in Java

Java defines three types of variables:

  1. Instance Variables (Non-Static Fields)
  2. Class Variables (Static Fields)
  3. Local Variables

1. Instance Variables (Non-Static Fields)

Instance variables are declared inside a class but outside any method. They are unique to each class instance, meaning each object created from the class has its own copy of these variables.

Example:

public class Employee {
    int id; // instance variable
    String empName; // instance variable
    int age; // instance variable
}
public class InstanceVariableExample {
    public static void main(String[] args) {
        Employee emp1 = new Employee();
        Employee emp2 = new Employee();

        emp1.id = 101;
        emp1.empName = "John";
        emp1.age = 30;

        emp2.id = 102;
        emp2.empName = "Doe";
        emp2.age = 25;

        System.out.println(emp1.empName + " is " + emp1.age + " years old.");
        System.out.println(emp2.empName + " is " + emp2.age + " years old.");
    }
}

2. Class Variables (Static Fields)

Class variables are declared with the static keyword inside a class but outside any method. They are shared among all instances of the class.

Example:

Consider there are 100 students in a college named "ABC", each student has their own unique roll number and name but the college remains the same among all the 100 students. The college field is declared as static so it can occupy memory only once.
public class Student {
    int rollNo;
    String name;
    static String college = "ABC College"; // static variable

    Student(int r, String n) {
        rollNo = r;
        name = n;
    }
}

public class StaticVariableExample {
    public static void main(String[] args) {
        Student s1 = new Student(101, "John");
        Student s2 = new Student(102, "Doe");

        System.out.println(s1.name + " studies at " + Student.college);
        System.out.println(s2.name + " studies at " + Student.college);
    }
}

3. Local Variables

Local variables are declared inside a method, constructor, or block. They are created when the method, constructor, or block is entered and destroyed when it is exited. Local variables are only accessible within the method, constructor, or block where they are declared.

Example:

public class LocalVariableExample {
    public void calculateSum() {
        int sum = 0; // local variable
        for (int i = 1; i <= 10; i++) {
            sum += i;
        }
        System.out.println("Sum of first 10 numbers: " + sum);
    }

    public static void main(String[] args) {
        LocalVariableExample example = new LocalVariableExample();
        example.calculateSum();
    }
}

Variable Naming Conventions in Java

  1. No White Spaces: Variable names cannot contain white spaces.
  2. Special Characters: Variable names can begin with special characters such as $ and _.
  3. Case Sensitivity: Variable names are case-sensitive.
  4. LowerCamelCase: Parameter names, member variable names, and local variable names should be written in lowerCamelCase.

Conclusion

Understanding the different types of variables in Java and how to use them is crucial for effective programming. Local variables are used within methods for temporary storage, instance variables hold data unique to each object, and class variables are shared among all instances of a class. Proper use of these variables helps in writing clear, maintainable, and efficient code.


Comments