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

Instance Variables in Java – Definition and Usage

By Chaitanya Singh | Filed Under: java

In Java, an instance variable is a variable that belongs to an instance of a class, rather than to the class itself. An instance variable is declared within a class, but outside of any method, and is defined for each object or instance of the class. This article provides an overview of instance variables in Java, including their definition, usage, and limitations.

Here’s an example of how to declare and use an instance variable in Java:

public class MyDemoClass {
    int num;  // this is an instance variable
    
    public MyClass(int val) {
        num = val;  // initialize instance variable in constructor
    }
    
    public void display() {
        System.out.println("The value of num is: " + num);
    }
}

In this example, num is an instance variable of the class MyDemoClass. It’s declared outside of any method, which makes it available to all methods within the class. In the constructor for the class, the instance variable is initialized with a value passed in as an argument.

To use the instance variable in a method, we can simply refer to it by name, as we have done in the display() method above. When an instance of the class is created, a separate copy of the instance variable is created for that instance, so each instance of the class has its own value for the instance variable.

Example of Using Instance Variables in Java

Let’s take an example to understand the usage of instance variable.

public class Cat {
    // Instance variable
    private String name;

    // Constructor
    public Cat(String name) {
        this.name = name;
    }

    // Instance method that uses the instance variable
    public void sound() {
        System.out.println(name + " says Meow!");
    }

    // Main method
    public static void main(String[] args) {
        // Create an instance of Cat
        Cat myCat = new Cat("Lucy");

        // Call the instance method on the instance
        myCat.sound(); // Output: Lucy says Meow!
    }
}

In this example, we have a class called Cat that has an instance variable called name. The name variable is a String that holds the name of the cat. We also have an instance method called sound() that uses the name variable to print out a message saying that the cat is meowing.

In the main() method, we create an instance of the Cat class with the name “Lucy”. We then call the sound() method on that instance, which prints out the message “Lucy says Meow!” to the screen.

This is just a simple example, but it demonstrates how you can use an instance variable in Java to store data that can be accessed and modified by any method or block in the class where it is declared.

Limitations of instance variable

While instance variables are useful in Java, they do have some limitations:

  1. Inefficient use of memory: When we have several instances of a class, each instance has its own copy of the instance variables, which can lead to inefficient use of memory.
  2. Instance variables are not thread-safe: If multiple threads access the same instance variable, it can cause synchronization problems and potentially lead to bugs or other issues.
  3. Cannot store class-level data: Instance variables cannot store the class level data as they are tied to the instances of the class. To store class-level data, you can use static variables.
  4. Complex code: When we have multiple instances in the class, it becomes difficult to manage the instance variables associated with each instances. It makes the code complex and difficult to understand

Java local vs instance vs static variable

We have discussed the variables in the Java variable Tutorial, however let’s summarize the difference between three types of variables in Java.


ScopeLifetimeAccess
LocalLimited to method or blockCreated on method or block entry and destroyed on exit.Only within the method or block where declared.
InstanceBelongs to an instance of the classCreated with instance, destroyed with instance.Any method or block in the class where in scope.
StaticBelongs to the class itselfCreated when class is loaded into memory, destroyed when program exits.Any method or block in the class, and can be accessed using the class name from outside the class.

Let’s see a program where we are using all three types of variables:

public class JavaExample {
    // Instance variable
    private int instanceVar = 100;

    // Static variable
    private static int staticVar = 100;

    public void myMethod() {
        // Local variable
        int localVar = 100;

        // Increment all three variables
        instanceVar++;
        staticVar++;
        localVar++;

        // Print the values of all three variables
        System.out.println("instanceVar: " + instanceVar);
        System.out.println("staticVar: " + staticVar);
        System.out.println("localVar: " + localVar);
    }

    public static void main(String[] args) {
        // Create an instance of the class
        JavaExample obj = new JavaExample();

        // Call the method on the instance
        obj.myMethod();
        obj.myMethod();
    }
}

Output:

instanceVar: 101
staticVar: 101
localVar: 101
instanceVar: 102
staticVar: 102
localVar: 101

In this program, we have a class called JavaExample that has an instance variable called instanceVar, a static variable called staticVar, and a method called myMethod() that contains a local variable called localVar.

In the myMethod() method, we increment all three variables and then print out their values. Note that the local variable localVar is reset to 100 each time the method is called, while the instance variable instanceVar and the static variable staticVar retain their values across multiple method calls.

In the main() method, we create an instance of the JavaExample class and call the myMethod() method on it twice. This allows us to see how the values of the instance, local, and static variables change over time.

Related Articles:

  • Java Variable Tutorial
  • Java Data Types Tutorial
  • Java Static Variable Tutorial

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 – 2022 BeginnersBook . Privacy Policy . Sitemap