BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Difference between local, instance and static variables in Java

Last Updated: June 2, 2024 by Chaitanya Singh | Filed Under: java

In Java, we have three types of variables: local, instance and static. We have briefly covered them in Java Variables Tutorial. In this guide, we will discuss the difference between local, instance and static variables in Java with examples.

Local Variables

  1. Declaration:
    • Local variables are declared inside a method, constructor, or block.
  2. Scope:
    • Their scope is limited to the method, constructor, or block in which they are declared.
  3. Lifetime:
    • The lifetime of local variables starts when the method, constructor, or block is entered and destroyed when it is exited.
  4. Initialization:
    • A local variable must be initialized before you can use them.

Example of local variable

public class LocalVariableExample {

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

// You cannot access local variables outside their scope
// The scope of num1 and num2 is limited to the method
// Uncommenting the following lines will cause a compilation error
// System.out.println("Trying to access num1: " + num1);
// System.out.println("Trying to access num2: " + num2);
}

public void calculateSum() {
// Local variables declared inside the method
int num1 = 10;
int num2 = 20;

// Another local variable to store the result
int sum = num1 + num2;

// Print the result
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
}
}

Instance Variables

  1. Declaration:
    • Instance variables are declared inside a class but outside any method, constructor, or block.
  2. Scope:
    • They are accessible from any method, constructor, or block within the class (non-static context).
  3. Lifetime:
    • The lifetime of an instance variable starts when an object is created and ends when the object is destroyed.
  4. Initialization:
    • If these variables are not initialized, they are by default initialized to their default values (e.g., 0 for integers, null for objects).

Example of Instance variable

public class Person {

// Instance variables
String name;
int age;

// Constructor to initialize instance variables
public Person(String name, int age) {
this.name = name;
this.age = age;
}

// Method to display information of a Person
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}

public static void main(String[] args) {
// Creating an instance of class Person
Person person1 = new Person("Chaitanya", 37);
Person person2 = new Person("Rahul", 35);

// Calling the displayInfo method to print details of each instance
person1.displayInfo();
person2.displayInfo();
}
}

Static Variables

  1. Declaration:
    • Declared inside a class with the static keyword.
  2. Scope:
    • They are accessible inside the class. They can be accessed using class name.
  3. Lifetime:
    • The lifetime of a static variable starts when a class is loaded into the memory by JVM and ends when the class is unloaded.
    • There is a single copy of static variable shared among all the instances of that particular class. Changes made by one instance are visible to another instance. For example, if an instance increase the value of a static variable from 10 to 11, when the second instance of class access this variable, the value they find would be 11.
  4. Initialization:
    • Similar to instance variables, if these variables are not initialized, they are by default initialized to their default values (e.g., 0 for integers, null for objects).

Example of Static Variable

public class Counter {

// Static variable
static int count = 0;

// Constructor
public Counter() {
// Increment the static variable count whenever
// a new instance(object) is being created
count++;
}

// Static method to find the current value of static variable
public static int getCount() {
return count;
}

public static void main(String[] args) {
// Creating several instances of class Counter
// Each instance share same copy so every time an instance
// is created, it increases the value of static variable
// through constructor
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

// Calling the static method to print the value of static variable
System.out.println("Number of instances created: " + Counter.getCount());
}
}

Summary

Local Variables:

  • The scope is limited to the method, constructor or block in which they are declared.
  • They must be initialized before use.
  • They have short lifespan.

Instance Variables

  • The scope is within the class but outside the methods.
  • Each object has a separate copy of each instance variable.
  • Lifespan is same as the lifespan of instance (object).

Static Variables

  • The scope is within the class.
  • All instances (objects) of the class share the same copy of static variables.
  • They have a long lifespan, their lifespan is same as the lifespan of the class.

Top Related Articles:

  1. Difference between for loop and for-each loop in Java
  2. Java Variables: Declaration, Scope, and Naming Conventions
  3. Unary Operators in Java with Examples
  4. Final Keyword In Java – Final variable, Method and Class
  5. Static and dynamic binding in java

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap