Understanding Variables in Java
Have you ever wondered how data is stored and manipulated in Java programs? Variables in Java are the answer, acting as containers for data values. Each variable is defined with a specific data type and is uniquely identified by its name, making it a fundamental tool for coding in Java. Let's understand more!
Variables in Java are fundamental elements that act as containers to store data values. They serve as named storage locations in your program, where each variable is associated with a specific data type and a value. The variable's name is a unique identifier used to refer to and manipulate its stored value within the code. In this blog, we will learn about variables in Java in detail.
Table of Content
Best-suited Java courses for you
Learn Java with these high-rated online courses
What are Variables in Java?
In Java, variables are fundamental elements used to store data that can be modified during program execution. A variable in Java is essentially a container that holds values while the Java program is executed. These values can be accessed, modified, and stored in memory.
Variables store data of various types, such as numbers, characters, strings, or even more complex data structures. The type of data a variable can store is determined by its data type.
Variable Declaration and Initialization
In Java, declaring and initializing variables are key steps in the process of variable usage.
Variable Declaration
Declaration of a variable in Java involves specifying its data type and name. This informs the compiler about the type of data the variable will hold and how much memory to allocate for it.
Syntax
data_type variable_name;
Examples
int age; // Declaring an integer variable named 'age'double salary; // Declaring a double variable named 'salary'String name; // Declaring a String variable named 'name'
In these examples int, double, and String are data types, while age, salary, and name are variable names.
Variable Initialization
Initialization is the process of assigning a value to a declared variable. This can be done at the time of declaration or later in the code.
Syntax for Initialization at Declaration
data_type variable_name = value;
int age = 30; // Initializing 'age' with the value 30double salary = 4500.50; // Initializing 'salary' with the value 4500.50String name = "Esha"; // Initializing 'name' with the string "Esha"
Syntax for Separate Initialization
variable_name = value;
age = 30; // Assuming 'age' was already declaredsalary = 4500.50; // Assuming 'salary' was already declaredname = "Esha"; // Assuming 'name' was already declared
Points to keep in mind
- The value assigned to a variable must be compatible with its declared data type.
- If a variable is not explicitly initialized, it gets a default value (like 0 for numeric types, false for boolean, null for objects).
- The point in your code where a variable is declared influences where it can be used. (its scope, which is covered in the later part of this blog)
- You can declare a variable as final (constant), meaning its value cannot be changed once initialized.
Types of Variables in Java
- Local Variables
- Instance Variables
- Static Variables
Let's understand each type one by one in detail.
1. Local Variables
Local variables are variables that are declared within a function or a block of code and can only be accessed within that function or block. They are not known outside their respective context, meaning they have a limited scope restricted to where they are declared.
For example
public class Example { public void myMethod() { // 'a' is a local variable within the myMethod function int a = 10; if (a == 10) { // 'b' is a local variable within this 'if' block int b = 20; System.out.println("Inside if block, b = " + b); }
// This line is commented out because it would cause a compile-time error // System.out.println("Outside if block, b = " + b);
System.out.println("Value of a = " + a); // This is fine as 'a' is within its scope }
public static void main(String[] args) { Example example = new Example(); example.myMethod(); }}
Output
Inside if block, b = 20
Value of a = 10
In the example above,
- The variable a is a local variable to the myMethod method. It is created when myMethod is invoked and remains accessible throughout the entire method.
- The variable b is a local variable within the if block. Its scope and lifetime are confined to this block. It gets created when the if block is entered and is destroyed when the block is exited. Accessing b outside of this block results in a compile-time error.
This example illustrates how the scope and lifetime of local variables are constrained to the blocks in which they are declared, allowing for better control and reducing the chance of unintended interactions with other parts of the code.
2. Instance Variables
Instance variables, also known as non-static fields, are variables declared within a class but outside any method. These variables are created when an object of the class is instantiated and are specific to each instance of the class. Each instance has its own copy of these variables. Instance variables represent the properties or state of an object.
For example
public class Car { // Instance variables // These variables are specific to each instance of the Car class. String brand; int year; boolean isElectric;
// Constructor to initialize the instance variables public Car(String brand, int year, boolean isElectric) { this.brand = brand; this.year = year; this.isElectric = isElectric; }
// Method to display car information public void displayInfo() { System.out.println("Car Brand: " + brand); System.out.println("Manufacture Year: " + year); System.out.println("Is Electric: " + isElectric); }
public static void main(String[] args) { // Creating objects (instances) of the Car class Car car1 = new Car("Tesla", 2020, true); Car car2 = new Car("Toyota", 2015, false);
// Each object has its own set of instance variables car1.displayInfo(); // Displays information about car1 car2.displayInfo(); // Displays information about car2 }}
Output
Car Brand: Tesla
Manufacture Year: 2020
Is Electric: true
Car Brand: Toyota
Manufacture Year: 2015
Is Electric: false
In the example above,
- brand, year, and isElectric are instance variables of the Car class. They define the state of each Car object.
- When a new Car object is created (like car1 and car2 in the main method), each object gets its own copy of these instance variables.
- The constructor Car(String brand, int year, boolean isElectric) initializes the instance variables with the values provided at the time of object creation.
- The displayInfo method uses these instance variables to display information about the car.
Instance variables are essential in object-oriented programming as they allow each object to maintain its state independently of other objects.
3. Static Variables
Static variables (class variables) are variables declared with the static keyword within a class but outside any method or constructor. These variables are not tied to any specific instance of the class but belong to the class itself. As a result, they are shared among all instances of the class. A static variable is created when the class is loaded and destroyed when the program stops or the class is unloaded.
For example
public class Counter { // Static variable // This variable is shared among all instances of the Counter class. static int count = 0;
// Constructor to increment the static variable 'count' public Counter() { count++; }
// Method to display the value of the static variable 'count' public static void displayCount() { System.out.println("Number of instances created: " + count); }
public static void main(String[] args) { // Creating instances of the Counter class Counter c1 = new Counter(); Counter c2 = new Counter(); Counter c3 = new Counter();
// All instances share the same static variable 'count' Counter.displayCount(); // Output will be: Number of instances created: 3 }}
Output
Number of instances created: 3
In the example above,
- count is a static variable in the Counter class. It is used to keep track of the number of instances created from the Counter class.
- Every time a new instance of Counter is created, the constructor increments the static variable count.
- The displayCount static method displays the value of count. Since count is a static variable, it is shared across all instances of Counter and can be accessed directly using the class name (e.g. Counter.displayCount()).
Static variables are useful when you need a common property that should be shared by all instances of a class, such as a counter, configuration settings, or any common resource.
Scope and Lifetime of Variables
The scope and lifetime of variables are two important concepts in programming that dictate where a variable can be accessed (scope) and how long it exists in memory (lifetime).
1. Scope
The scope of a variable refers to the region of the code where a variable is visible and can be accessed. It's essentially the context in which a variable is recognized by the compiler or interpreter. The scope is determined by where the variable is declared.
Scope of Local Variables: Local variables are declared within a method, block, or constructor, and their scope is limited to that method, block, or constructor. They can only be accessed within that defined area.
Scope of Instance Variables: Instance variables are declared in a class but outside any method. They are associated with an instance of the class, meaning each object created from the class has its own copy of these variables. They can be accessed by any method of the class but require an instance of the class to do so.
Scope of Static Variables: Static variables (also known as class variables) are declared with the static keyword inside a class but outside any method or constructor. These variables are shared among all instances of the class and can be accessed directly by the class name, without needing any instance.
2. Lifetime
The lifetime of a variable refers to the duration during which the variable exists in memory and can hold a value. It's about how long a variable "lives" from its creation to its destruction.
Lifetime of Local Variables: The lifetime of a local variable is confined to the execution of the block in which it is defined. The variable is created when the block is entered and is destroyed when the block is exited.
Lifetime of Instance Variables: The lifetime of an instance variable is tied to the lifecycle of the object. The variable is created when a new object is instantiated and is destroyed when the object is garbage-collected.
Lifetime of Static Variables: The lifetime of a static variable is throughout the entire runtime of the program. They are created when the class is loaded into memory and destroyed when the class is unloaded or when the program terminates.
Understanding the scope and lifetime of variables helps in managing memory, avoiding bugs, and ensuring proper access to the data stored in these variables.
Examples of Variables in Java
Let's see a few examples to see how and where variables are used.
Example 1: Tracking Student Enrollment
Problem Statement: Create a system to track the total number of students enrolled in a school and the name of each student. Use static variables to keep count of the total number of students, and instance variables for each student's name.
public class Student { // Static variable to keep track of total student count static int studentCount = 0;
// Instance variable for each student's name String name;
// Constructor to initialize the student's name and increment student count public Student(String name) { this.name = name; studentCount++; // Incrementing the total number of students }
// Method to display student's information public void displayStudentInfo() { System.out.println("Student Name: " + name); }
// Static method to display the total number of students public static void displayTotalStudents() { System.out.println("Total Students: " + studentCount); }
public static void main(String[] args) { Student student1 = new Student("Esha"); Student student2 = new Student("Hrisha");
student1.displayStudentInfo(); student2.displayStudentInfo(); Student.displayTotalStudents(); // Static method called using class name }}
Output
Student Name: Esha
Student Name: Hrisha
Total Students: 2
Each time a new Student object is created, the studentCount is incremented. The name of each student is stored in the instance variable name. The output will display the name of each student followed by the total number of students.
Example 2: Bank Account Management
Problem Statement: Manage a user's bank account, allowing deposit and withdrawal operations. Use instance variables to store the account balance for each user.
public class BankAccount { // Instance variable to store the account balance private double balance;
// Constructor to initialize the balance public BankAccount(double initialBalance) { this.balance = initialBalance; }
// Method to deposit money public void deposit(double amount) { balance += amount; }
// Method to withdraw money public void withdraw(double amount) { balance -= amount; }
// Method to display account balance public void displayBalance() { System.out.println("Account Balance: ₹" + balance); }
public static void main(String[] args) { BankAccount account = new BankAccount(1000); // Starting with ₹1000 account.deposit(500); // Depositing ₹500 account.withdraw(200); // Withdrawing ₹200 account.displayBalance(); // Displaying current balance }}
Output
Account Balance: ₹1300.0
The account starts with an initial balance (e.g.₹1000). After depositing and withdrawing money, the current balance is displayed, showing the result of these operations.
Example 3: Temperature Converter
Problem Statement: Convert a temperature value from Celsius to Fahrenheit. Use a method with local variables to perform the conversion.
public class TemperatureConverter { // Method to convert Celsius to Fahrenheit public static void celsiusToFahrenheit(double celsius) { // Local variable for the Fahrenheit temperature double fahrenheit = (celsius * 9/5) + 32; System.out.println(celsius + "°C is " + fahrenheit + "°F"); }
public static void main(String[] args) { celsiusToFahrenheit(25); // Convert 25°C to Fahrenheit }}
Output
25.0°C is 77.0°F
The method celsiusToFahrenheit takes a Celsius temperature as input and calculates its Fahrenheit equivalent using a local variable fahrenheit. The output displays the converted temperature.
Conclusion
Thus, understanding variables in Java enables programmers to manage data effectively, utilize memory efficiently, and implement object-oriented principles correctly. Moreover, a good grasp of variable types aids in understanding the flow of data through different parts of a program and in designing robust and scalable software.
FAQs
What is a Variable in Java?
A variable in Java is a basic unit of storage in a program. It is a named memory location that holds a value, which can be changed during the execution of the program. Variables in Java must be declared with a specific data type, which determines the size and layout of the variable's memory, as well as the range of values that can be stored within it.
What are the Different Types of Variables in Java?
In Java, there are three main types of variables:
- Local Variables: Declared inside a method, constructor, or block, and are accessible only within it.
- Instance Variables: Declared in a class, but outside a method. Each object of the class has its own copy of the instance variable.
- Static (or Class) Variables: Declared as static, which means they are associated with the class, not individual objects. All instances of the class share the same static variable.
How Do You Declare a Variable in Java?
A variable in Java is declared by first specifying its data type, followed by the variable name.
Can a Variable in Java Change Its Type After Declaration?
No, once a variable in Java is declared with a certain data type, it cannot change its type. Java is a statically-typed language, which means that all variables must be declared with a data type, and this type cannot be altered during runtime.
What is the Difference Between Primitive and Reference Variables in Java?
In Java, primitive variables store primitive data types (like int, char, double, etc.), which hold the actual value. Reference variables, on the other hand, store references to objects. For primitive types, the value is stored directly in the memory location associated with the variable. For reference types, the variable holds the address (or reference) to the location where the object is stored in memory.
Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio