1.

Default value of local variable in Java?

Answer»

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.

The local variables do not have any default values in Java. This means that they should be declared and ASSIGNED a value before the variables are used for the first time. Other the compiler THROWS an error.

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

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

The above program contains a local variable num. It leads to an error “variable num might not have been initialized”

The correct version of the above program 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 : 50


Discussion

No Comment Found