Sitemap
NextGenML

NextGenML

i am AI Engineer who write about latest trends for AI and ML and help to get job in tech world for high pay jobs

1 min readOct 19, 2024

--

Difference between static and instance variables

1. Static Variables:

• Belong to the class: Shared among all instances of the class.

• Single copy: Only one copy exists in memory, regardless of how many objects are created.

• Accessed via the class: Can be accessed using the class name (ClassName.variable).

• Use case: For constants or values shared across all objects.

2. Instance Variables:

Get NextGenML’s stories in your inbox

Join Medium for free to get updates from this writer.

• Belong to the object: Each object has its own copy.

• Multiple copies: Every object created has its own separate memory space for instance variables.

• Accessed via objects: Requires an object to access.

Example:

class Car {
static String manufacturer = "Tesla"; // static variable
String model; // instance variable

Car(String model) {
this.model = model;
}
}

public class Main {
public static void main(String[] args) {
Car car1 = new Car("Model S");
Car car2 = new Car("Model 3");

// Static variable (shared among all objects)
System.out.println(Car.manufacturer); // Tesla

// Instance variables (unique to each object)
System.out.println(car1.model); // Model S
System.out.println(car2.model); // Model 3
}
}

• Static variables are class-level and shared by all objects.

• Instance variables are object-level, with each object having its own copy.

--

--

NextGenML
NextGenML

Written by NextGenML

i am AI Engineer who write about latest trends for AI and ML and help to get job in tech world for high pay jobs