1.

What are the types of variables a class can have?

Answer»

The different types of variables in Java are local variables, INSTANCE variables and class variables. Details about these are given as follows:

Local Variables

Local variables in Java are those declared locally in methods, code blocks, constructors etc. When the program control enters the methods, code blocks, constructors etc. then the local variables are created and when the program control leaves the methods, code blocks, constructors etc. then the local variables are destroyed.

A program that demonstrates local variables in Java is given as follows:

public class Demo {   public void func()   {      int num = 50;      System.out.println("The number is : " + num);   }   public static void main(String args[])   {      Demo obj = new Demo();      obj.func();   } }

The output of the above program is as follows:

The number is : 50Instance Variables

Instance variables in Java are those variables that are declared OUTSIDE a block, method, constructor etc. but inside a class. These variables are created when the class object is created and similarly, they are destroyed when the class object is destroyed.

A program that demonstrates instance variables in Java is given as follows:

public class Demo {   int num;   Demo(int N)   {      num = n;   }   public void display()   {      System.out.println("The number is: " + num);   }   public static void main(String args[])   {      Demo obj = new Demo(20);      obj.display();   } }

The output of the above program is as follows:

The number is: 20Class Variables

Class variables or Static variables are defined using the static keyword. These variables are declared inside a class but outside a method, code block etc. Class variables last for the program lifetime i.e. they are created at the START of the program and destroyed at the end of the program.

A program that demonstrates class variables in Java is given as follows:

public class Demo {   int num;   static int count;   Demo(int n)   {      num = n;      count ++;   }   public void display()   {      System.out.println("The number is: " + num);   }   public static void main(String args[])   {      Demo obj1 = new Demo(20);      obj1.display();      Demo obj2 = new Demo(50);      obj2.display();      System.out.println("The total objects of class Demo are: " + count);   } }

The output of the above program is as follows:

The number is: 20 The number is: 50 The total objects of class Demo are: 2


Discussion

No Comment Found