1. What do you mean by static variable? Explain with help of example.
Answers
Answered by
0
Hi
--》A static variable is common to all the instances (or objects) of the class because it is a class level variable. In other words you can say that only a single copy of static variable is created and shared among all the instances of the class. Memory allocation for such variables only happens once when the class is loaded in the memory.
Like variables we can have static block, static method and static class, to read about them refer: static keyword in java.
--》Static variable syntax
static data_type variable_name;
--》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).
--》Example:
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
♡I hope u got urgent answer♡
--》A static variable is common to all the instances (or objects) of the class because it is a class level variable. In other words you can say that only a single copy of static variable is created and shared among all the instances of the class. Memory allocation for such variables only happens once when the class is loaded in the memory.
Like variables we can have static block, static method and static class, to read about them refer: static keyword in java.
--》Static variable syntax
static data_type variable_name;
--》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).
--》Example:
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
♡I hope u got urgent answer♡
Similar questions
Chemistry,
8 months ago
English,
8 months ago
English,
8 months ago
Hindi,
1 year ago
Political Science,
1 year ago