Computer Science, asked by JayBhagat4143, 1 year ago

What is meant by static in java with example?

Answers

Answered by Anonymous
4
As I mentioned above that the static variables are shared among all the instances of the class, they are useful when we need to do memory management. In some cases we want to have a common value for all the instances like global variable then it is much better to declare them static as this can save memory (because only single copy is created for static variables).

lets understand this with an example:

Static variable example in Java

class VariableDemo { static int count=0; public void increment() { count++; } public static void main(String args)
{ VariableDemo obj1=new VariableDemo(); VariableDemo obj2=new VariableDemo(); obj1.increment(); obj2.increment(); System.out.println("Obj1: count is="+obj1.count); System.out.println("Obj2: count is="+obj2.count); } }

Output:

Obj1: count is=2 Obj2: count is=2

As you can see in the above example that both the objects are sharing a same copy of static variable that’s why they displayed the same value of count.

Similar questions