ㅤㅤ

Difference between static and non-static variables in Java

Difference between static and non-static variables in Java

Difference between static and non-static variables in Java

What's difference between Static and Non-Static fields of a class?

Non-Static values are also called as instance variables. Each object of the class has its own copy of Non-Static instance variables. So when a new object is created of the same class it will have completely its own copy of instance variables.

While Static values have only one copy of instance variables and will be shared among all the objects of the class.

Here's a small practical stuff we will do to understand the concept. Let's create a small sample project to demonstrate the static and non-static concepts. In CD, in the source code folder there is a sample provided for the same in "StaticNonStatic" folder. Below is the file structure. Basically the project has two main classes "clsStatieNonStatic.java" and "Cls TestRun.java". We will be explaining the above two classes in the coming sections.

"CisTestRun.java" is the class who will run create objects of "clsStaticNonStatic.java" and run it. Below is the figure which has TestRun.java" in action. It does nothing special but creates four objects and increments the static and non-static properties. In the below figure at the left hand side you can see the static variables values are preserved as they are. So the "intStar" value goes up to "4" and "intNonStat" has value "1".

Difference between static and non-static variables in Java.

Post a Comment

Thanks for Comment

Previous Post Next Post