DEV Community

Deva I
Deva I

Posted on

Static Variable vs Non-Static Variable(Instance Variable)

Static Variable

  • Static refers to class specific information.

  • Declared using the static keyword.

  • It belongs to the Class.

  • Only one copy exists, shared by all objects.

  • Memory is allocated once when the class is loaded.

  • Accessed directly via the Class Name (ClassName.variable).

  • EX : The company name on an employee badge same for everyone.

Non-Static Variable(Instance Variable).

  • Non-Static refers to object specific information.

  • Declared without the static keyword.

  • Every object gets its own unique copy.

  • Memory is allocated every time a new object is created.

  • Requires an Object Reference (objectName.variable).

  • EX : The employee's specific name or ID number.

Example program

public class Building
{
static int age= 10;
static String name="Payilagam";


String studName1="mohan";
int studAge1= 22;

String studName2="deva";
int studAge2= 23;

String studName3="madhavan";
int studAge3= 24;

public static void main(String[] args)
{
Building student1= new Building();
Building student2= new Building();
Building student3= new Building();


System.out.println(Building.name);
System.out.println(Building.age);

System.out.println(student1.studName1 +" "+student1.studAge1);
System.out.println(student1.studName2 +" "+student1.studAge2);
System.out.println(student1.studName3+" "+student1.studAge3);


}
}
Enter fullscreen mode Exit fullscreen mode

=> In this program static variable using class name.because the static variable accessed by class name Building. `System.out.println(Building.name);

=> A static method cannot directly access non-static variables because those variables belong to objects.

=> If you give non-static variable using class name java give error like,
non-static variable studName2 cannot be referenced from a static context.

=> So, first create a object using new keyword like,
Building student1= new Building();

=> Then access the variable through that object.
System.out.println(student1.studName2);

=> student is the the object.
studName2 that object's value.

=> I created the three students information but, each object still contains all three students' information.

System.out.println(student1.studName1 +" "+student1.studAge1);
System.out.println(student1.studName2 +" "+student1.studAge2);
System.out.println(student1.studName3+" "+student1.studAge3);

=> I use the same object name student1 to print all students information.because the student1,student2, and student3each object have all three students information.

=> Logically one object own one student information, not multiple students.

=> To overcome this problem using Constructor method.(TO BE DISCUSSED).

Output

Top comments (0)