What is the difference between instance variable and class variable and static variable | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is the difference between instance variable and class variable and static variable

1st Sep 2019, 5:22 AM
LOKESHA E J
LOKESHA E J - avatar
2 Answers
+ 3
1.Instance Variables - Instance Variables hold values that must be referenced by than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.  2.Class or static variables  - Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.
1st Sep 2019, 6:17 AM
Prathvi
Prathvi - avatar
+ 1
for instance variables you need create object instance, and variable cannot be in method or block declared class C { int instvar=10; public static void main(String[] args) { C object1 = new C(); System.out.print( object1.instvar ); } } class variables are static class S { static int classvar=20; public static void main(String[] args) { System.out.print( S.classvar ); } }
1st Sep 2019, 7:04 AM
zemiak