DEV Community

Ranjith Ranjith
Ranjith Ranjith

Posted on

Day 7 (instance variable,local variable,static variable ,static method )

1) What is an instance variable
Instance variable is a variable declared inside a class, but outside methods, and it belongs to each object (instance) of that class.

Every time you create a new object, a new copy of instance variable is created.

2) Where is an instance variable declared
Instance variable is declared inside the class, but outside any method.

class Student {
String name; // instance variable
int age; // instance variable
}
3) Use of instance variable (Why useful)?
To store object-specific data.

Every object will have its own values.

Example: Different students have different names and ages.

Example:

class Student {
String name; // instance variable
int age; // instance variable

// Constructor to initialize instance variables
Student(String n, int a) {
    name = n;
    age = a;
}

void display() {
    System.out.println("Name: " + name);
    System.out.println("Age: " + age);
}

public static void main(String[] args) {
    Student s1 = new Student("Arun", 20);
    Student s2 = new Student("Divya", 22);

    s1.display();
    s2.display();
}
Enter fullscreen mode Exit fullscreen mode

}
Output:

Name: Arun
Age: 20
Name: divya
Age:22

Instance variable is a variable that is specific to an object (instance) of a class.
Each object will have its own copy of that variable.

Class is like a blueprint.
Object is something created using that blueprint.
Instance variable is the data stored inside each object.


2) Where is an instance variable

Instance variable is defined inside a class, but inside methods using self.

class Student:
def init(self, name, age):
self.name = name # instance variable
self.age = age # instance variable

self.name and self.age are instance variables.

They belong to a particular object of the Student class.

3) Use of instance variable (Why it's useful)?

To store data unique to each object.

Example: Every student has different name and age — so you store them as instance variables.

Example:

class Student:
def init(self, name, age):
self.name = name # instance variable
self.age = age # instance variable

def display(self):
    print("Name:", self.name)
    print("Age:", self.age)
Enter fullscreen mode Exit fullscreen mode

Creating objects (instances)

student1 = Student("Arun", 20)
student2 = Student("Divya", 22)

student1.display()
student2.display()

Output:
Name: Arun
Age: 20
Name: Divya
Age:22

  2] Local variable 
Enter fullscreen mode Exit fullscreen mode

1) What is a Local Variable
A local variable is a variable that is declared inside a method, constructor, or block, and it can be used only inside that method or block.

2) Where is Local Variable
Local variables are created inside methods and disappear when the method finishes. They are not accessible outside the method.

3) Use of Local Variable

Example

public class Main {
public static void main(String[] args) {
int number = 10; // local variable
System.out.println("Number is: " + number);
}
}
3] Static variable

1) What is a static variable

Tamil Explanation:
static variable ஒரு class level variable. Object-ஓட property இல்ல. Class-ஓட common variable.

class Example {
static int count = 0; // This is a static variable
}

3) Use of static variable
Static variable useful when you want to share common data between all objects.

Ex.

class Student {
int id;
String name;

// Static variable
static String college = "ABC College";

// Constructor
Student(int i, String n) {
    id = i;
    name = n;
}

void display() {
    System.out.println(id + " " + name + " " + college);
}
Enter fullscreen mode Exit fullscreen mode

}

public class TestStaticVariable {
public static void main(String[] args) {
Student s1 = new Student(1, "Ravi");
Student s2 = new Student(2, "Priya");

    s1.display();
    s2.display();
}
Enter fullscreen mode Exit fullscreen mode

}

Output:

1 Ravi ABC College
2 Priya ABC College

college is a static variable

Learn to Code, Prepare for Interviews, and Get Hired
By DotNetTricks
Learn to Code, Prepare for Interviews, and Get Hired
By DotNetTricks
Live Training
Job Oriented Training
DSA Problems
Free Courses
Free Books
Membership Plans
Explore
Tutorials
Cart

Summer Sale is Live! Unlock 40% OFF on All Job-Oriented Training Programs – Limited Time Only! Offer Ending in00 D05 H30 M54 S Get Now
Home
Tutorials
Java
Types Of Variables In Jav..
Types of variables in Java with examples: Local, Instance & Static
Types of variables in Java with examples: Local, Instance & Static
27 May 2025
Beginner
15.3K Views
18 min read

Learn with an interactive course and practical hands-on labs
Free Java Course With Certificate
A variable in Java is like a container or box that stores some values, such as numbers, text, or any data. You give the box a name, and you can use and change the value stored inside it during a program.

In this Java tutorial, we'll get into the details of Java variables. Java Online Training is a convenient option for gaining expertise in Java and harnessing its power for various applications.

Start coding with confidence—join our Java Certification Course for Free and gain hands-on experience.

Read More - Top 50 Java Interview Questions For Freshers

What is a Variable in Java?
A variable in Java is a name for a memory location used to store data. It must be declared with a data type like int, String, or float. A variable in Java can hold only one type of data, and its value can be changed during the program. You should always initialize the variable before using it. Overall, variable in Java helps in storing, changing, and reusing data throughout the program.

Declaration of Variable in Java
A variable in Java is used to store different types of data like numbers, text, or true/false values. Based on the type of data, there are different ways to declare a variable in Java.

String is used to store text, like "Hello World".
int is used to store whole numbers without decimals, like 10 or 100.
float is used to store numbers with decimal points, like 3.14 or 5.75.
char is used to store single characters, like 'x' or 'y', and is always written in single quotes.
boolean is used to store only two values: true or false.
To declare a variable in Java, programmers must follow two main parts:

Data type: This tells what kind of data the variable will store, such as int, float, or String.
Variable name: This is the name you give to the variable, so you can use it later in your code.
In short, declaring a variable in Java helps you store data in a proper format and use it again when needed.

Rules for Declaring Variables in Java
When you declare a variable in Java, you need to follow some simple rules to avoid errors. Let’s look at them one by one.

A variable in Java must start with a letter (like a or B), a dollar sign ($), or an underscore (_). You cannot start it with other special characters like @ or #. int $count = 5; or int _total = 10; are valid.
A variable in Java cannot have more than 64 characters in its name.int studentMarksInMathAndScience = 90; is okay, but avoid names that are too long.
You are not allowed to use blank spaces in the name of a variable in Java.int student age = 20; is wrong. You should write it as studentAge.
You cannot use Java's reserved keywords (like class, public, static) as variable names. int class = 10; is not allowed because class is a keyword.
The name of the variable must come before the assignment operator (=). int age = 25; is correct, but 25 = age; is incorrect.
Let's look at the variable declaration in our Java Playground.

Example
class Example
{
public static void main ( String[] args )
{
long payAmount = 184; //the declaration of the variable

System.out.println("The variable contains: " + payAmount );
}
}
Run Code >>
Output
Long payAmount = 184;
Variable Initialization
To initialize a variable in Java, there are three main components:

Data type: It defines the type of data that will be stored, such as int, float, String, etc.
Variable name: This is the specific name given to the variable so you can use it in the program.
Value: This is the actual data that you assign to the variable when initializing it.

Read More - Java Web Developer Salary

Types of Variables in Java
There are three main types of variables in Java: local variables, instance variables, and static variables, each used in different parts of a program

Types of Variables in Java

  1. Local Variables in Java A local variable in Java can be declared inside a method, a constructor, or a block, and can be used within the method, constructor, or block.

Scope: A local variable is only accessible within the method, constructor, or block where it is declared. You cannot use it outside that block.
Lifetime: The lifetime of a local variable is limited to the time the method or block is running. Once the block finishes, the variable is destroyed.
Default Value: Local variables do not have a default value. You must initialize them before using, or it will cause a compile-time error.
Example
import java.io.*;
class DNT
{
public static void main(String[] args)
{
int var = 89; // Declared a Local Variable
// This variable is local to this main method only
System.out.println("Local Variable: " + var);
}}
Run Code >>
This demonstration in our Java Compiler illustrates the concept of local variables with a scope that is only the main method by declaring and initializing a local variable "var" with the value 89.

Output
Local Variable: 89

  1. Instance Variables in Java An instance variable in Java is a non-static variable declared inside a class but outside any method, and it is associated with an object. An instance variable is created when an object class is generated.

Scope: An instance variable is accessible in all non-static methods of the class. It belongs to a specific object, so each object has its own copy.
Lifetime: The lifetime of an instance variable lasts as long as the object exists. When the object is destroyed, the variable is also destroyed.
Default Value: Instance variables do have default values. For example, int is 0, boolean is false, and object types are null if not initialized.
Example
import java.io.*;
class DNT
{
public String student; // Declared Instance Variable
public DNT()
{ // Default Constructor
this.student= "Urmi Bose"; // initializing Instance Variable
}
//Main Method
public static void main(String[] args)
{
// Object Creation
DNT name = new DNT();
System.out.println("Student name is: " + name.student);
}
}
Run Code >>
In this Java example, the class "DNT" contains a declaration for an instance variable named "student" that is initialized in the default constructor to demonstrate the use of instance variables. An object of the class is then constructed to allow access to and printing of the student's name.

Output
Student name is : Urmi Bose

  1. Static Variables in Java A static variable in Java belongs to the class itself, not to any specific object. This means all class objects share the same static variable.

Shared Value: A static variable is shared among all class objects. If one object changes its value, it affects all others.
Declared with the static keyword: You must use the static keyword while declaring it. Example: static int count;
Scope: It can be accessed by all methods in the class, including static methods.
Lifetime: The static variable exists as long as the program runs, and it is created when the class is loaded.
Default Value: Static variables have default values, such as 0 for int, false for boolean, and null for objects.
Accessing: You can access it using the class name like ClassName.variableName.
Example
import java.io.*;
class DNT
{
public static String student= "Urmi Bose"; //Declared static variable

public static void main (String[] args) {

//student variable can be accessed without object creation
System.out.println("Student Name is : "+DNT.student);
}
}
Run Code >>
This Java example prints the value "Urmi Bose" from a static variable named "student" that is declared inside the class "DNT," enabling access by class name simply without creating an object.

Output
Student Name is: Urmi Bose
Difference between Instance and Static Variable in Java
Understanding the differences between instance variables and static variables in Java is crucial. So, let's look at the differences in the following table.

Features Instance Variable in Java Static Variable in Java
Belongs To Belongs to one object Belongs to the class, not any one object
Keyword Used No special keyword needed Uses the static keyword
Memory Each object gets its own copy One copy is shared by all objects
How to Use Use it with the object name Use it with the class name
When Created Created when you make a new object Created when the class is loaded into memory
Lifetime Lives as long as the object is in use Lives as long as the program is running
Default Value Gets the default value, like 0, false, or null Also gets a default value like 0, false, or null
Used for When you need different values for each object When you want a common value for all objects
This makes it easy to remember that an instance variable is personal to each object, and a static variable in Java is shared by everyone.

Top comments (0)