Distinction Between Static and non-Static Variable in Java

Distinction Between Static and non-Static Variable in Java

The variable of any class are characterized into two sorts;
  • Static or class variable
  • Non-static or occurrence variable

Static variable in Java

Memory for static variable is made stand out in the system at the season of stacking of class. These variables are gone before by static watchword. tatic variable can access with class reference.
Non-static variable in Java
Memory for non-static variable is made at the season of make an object of class. These variable ought not be gone before by any static catchphrase Example: These variables can access with item reference.

Contrast between non-static and static variable

Non-static variable      Static variable
1          These variable ought not be gone before by any static catchphrase Example:
class A


{


int a;


}           These variables are gone before by static watchword.


Illustration


class A


{


static int b;


}
2          Memory is assigned for these variable at whatever point an item is created            Memory is designated for these variable at the season of stacking of the class.
3          Memory is dispensed different time at whatever point another article is created.     Memory is apportioned for these variable just once in the system.
4          Non-static variable otherwise called example variable while in light of the fact that memory is dispensed at whatever point occasion is created.   Memory is allotted at the season of stacking of class so that these are otherwise called class variable.
5          Non-static variable are particular to an object            Static variable are basic for each article that implies there memory area can be sharable by each item reference or same class.
6          Non-static variable can access with article reference.
Language structure
obj_ref.variable_name            Static variable can access with class reference.
Language structure
class_name.variable_name
Note: static variable can be access with class reference as well as some time it can be gotten to with article reference.
Case of static and non-static variable.

Example

class Student
{
int roll_no;
float marks;
String name;
static String College_Name="ITM";
}
class StaticDemo
{
public static void main(String args[])
{
Student s1=new Student();
s1.roll_no=100;
s1.marks=65.8f;
s1.name="abcd";
System.out.println(s1.roll_no);
System.out.println(s1.marks);
System.out.println(s1.name);
System.out.println(Student.College_Name); 
//or System.out.println(s1. College_Name); but first is use in real time.
Student  s2=new  Student();
s2.roll_no=200;
s2.marks=75.8f;
s2.name="zyx";
System.out.println(s2.roll_no);
System.out.println(s2.marks);
System.out.println(s2.name);
System.out.println(Student.College_Name); 
}
}

Output

100
65.8
abcd
ITM
200
75.8
zyx
ITM
Note: In the above example College_Name variable is commonly sharable by both S1 and S2 objects.