Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Instance Variable in Java

Last Updated on March 22, 2023 by Prepbytes

There are numerous programming languages available for the users but in every programming language the user has to store the data in some identifiers and these identifiers are known as variables. There are many types of variables available here we will discuss instance variable in java. Instance variable in java has their own use cases. We will discuss instance variable in java, how to declare and initialize them, and advantages, limitations, features, and examples of them which will tell you how to use them in your code.

What is a Variable in Java?

In simple words variable in java is a named memory location that stores a value. With the help of variables, we can refer to the objects or the value and use them throughout the program. The variable in java has a data type, a name, and a value. The data type of the variable specifies the type of value that can be stored in the variable such as integer, boolean, or string value. The name will be used to refer to the variable in the code and the value is the data that is stored in the variable.

There are various types of variables present in java and they are mentioned below.

  • Local variable in java
  • Instance variable in java
  • Class or static variable in java

We will discuss instance variable in java in a further section of the blogs.

What are Instance Variables in Java?

Instance variables in java are the variables that are declared in a class but outside of any constructor, method, or block. They only belong to a single object of that class but will not be shared by all instances of the class. Every object o the class has its own copy of the instance variable which means they can store different values for different objects. Here they are different from static variables as static variables are shared by all the instances of the class.

Instance variable in java define the state of an object, they hold the information about the properties and attributes of the object. They can store the information in the form of any data type like integer, boolean, and double, as well as in reference types like Arrays, strings, and other objects.

Declaring and Initializing Instance Variables

Instance variable in java are declared by specifying the data type, access level, and variable name. The access level determines who can access the variable, and it can be public, private, or p(it is also known as default). The data type will specify the type of value that can be stored whereas the variable name will be used to store the name of the variable by which it is called in the program and the name will be unique.

You can declare the instance variable in java as shown below.

public class Person {
private String name;
private int age;
private double height;
}

In the above example we have declared three instance variables for the class “Person”. The name is of type string the height is of type double and the age is of type int. They all have been set to the access level of private so they can only be accessed within the class.

To initialize the instance variable in java we can use the setter method, or constructor, or directly assign the values to the variables. Constructors are used to initialize the instance variables with specific values whereas the setter methods are used to set the value of instance variables after they have been created.

An example of initializing instance variables is given below.

public class Person {
private String name;
private int age;
private double height;
public Person(String name, int age, double height) {
this.name = name;
this.age = age;
this.height = height;
}
}

We are using a constructor for the class person to initialize the instance variable using this pointer.

Features of Instance Variable in Java

There are many features of the instance variable in java that make them different from the rest of the variables some of them are given below.

  • Instance variable in java have limited space and can be only accessed within the class and its objects.
  • The memory to an instance variable in java is allocated only at the time of object creation.
  • They are encapsulated within the class hence they cannot be accessed or modified outside the class.
  • Evey object of the class will have its unique instance variables.
  • They can be declared with different access modifiers that will control their visibility and accessibility.

Default Value of Instance Variable

The instance variable in Java can be different data types and they have given below:

Instance Variable Type Default Values
boolean false
short (short)0
double 0.0d
long 0L
char \u0000
byte (byte)0
int 0
float 0.0
Object null

Using Instance Variables in Java

Instance variables are used to store information about the state of an object, and they can be accessed and manipulated using methods or directly from other objects. To access an instance variable, you must first create an object of the class that contains the variable. You can then use the dot notation to access the variable from the object.

Example of Instance Variable in Java

Below is an example of the instance variable in java:

  public class Person {
    // instance variables
    String name;
    int age;
    
    // constructor
    public Person(String n, int a) {
        name = n;
        age = a;
    }

    // instance method
    public void display() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
    
    // main method
    public static void main(String[] args) {
        // create objects
        Person p1 = new Person("John", 25);
        Person p2 = new Person("Jane", 30);
        
        // call instance method on objects
        p1.display();
        p2.display();
    }
}

Output

Name: John
Age: 25
Name: Jane
Age: 30

Explanation of the above example
In the above example the person class has two instance variables with the name of “Name” and “Age”. They are not declared in any method that makes them instance variable in java. We have used the constructor to initialize them with the value which is passed in the argument of the constructor to the corresponding instance.

We have created two objects p1 and p2 of the class person. In both of the objects, we have passed different values of the same instance variable with the help of a display function that will print the corresponding value of the instance variable.

Advantages of Instance Variable in Java

Instance variable in java have several advantages some of which are given below:

  • They provide a way to store information about the state of an object, which allows objects to have unique characteristics and behavior.
  • They allow objects to interact with each other by sharing information through their instance variables.
  • They provide a way to encapsulate data within an object, which improves code organization and reduces the risk of errors and bugs.
  • They allow objects to be reused and modified without affecting other objects or the overall functionality of the program.

Difference between Class Variable and Instance Variable in Java

Feature Class Varible Instance Variable
Declaration They are declared with the static keyword. They are declared without the static keyword.
Memory Allocation The memory is allocated when the class is loaded. The memory is allocated when the object is initialized.
Access They can be accessed using the class name. Accessed using the object reference.
Value Same value for all the instances of the class. The value may or may not vary with each object.
Scope Visible to all the instances of the class. Visible to only the instance in which it is declared.

Limitations of Instance Variable in Java

There are certain limitations of the instance variable in java.

  • There is a bit of security risk as the value of the instance variable in java can be modified by the object.
  • Instance variable in java are not synchronized properly so they have thread safety issues.
  • They have some serialization issues as they can be saved with the object’s state and can lead to issues when deserialized.
  • Instance variables in java are difficult to make if they are not properly organized.

Frequently Asked Questions

Below are some of the frequently asked questions about the instance variable in java.

1. Can you change the value of an instance variable in Java?
Yes, you can change the value of an instance variable using a method or by accessing it directly.

2. Can an instance variable be static in Java?
No, an instance variable cannot be static. Static variables belong to the class, not to individual objects.

3. Can an instance variable be final in Java?
Yes, an instance variable can be final. A final variable cannot be changed once it has been initialized.

4. How many copies of an instance variable exist in Java?
Each instance of a class has its own copy of the instance variables.

5. What is the scope of an instance variable in Java?
The scope of an instance variable is the entire class, but it can only be accessed through an instance of the class.

Leave a Reply

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