What is the default value of a local variable in Java?

JavaObject Oriented ProgrammingProgramming

The local variables can be declared in methods, code blocks, constructors, etc in Java. 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 can be declared and assigned a value before the variables are used for the first time, otherwise, the compiler throws an error.

Example

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

In the above program, a local variable num can't be initialized with a value, so an error will be generated like “variable num might not have been initialized”.

Output

LocalVariableTest.java:4: error: variable num might not have been initialized
 System.out.println("The number is : " + num);
^
1 error

Example

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

In the above program, a local variable "num" can be initialized with a value of '100'

Output

The number is : 100
raja
Published on 06-Sep-2019 10:47:59
Advertisements