Home  >  Article  >  Java  >  What is the default value of local variables in Java?

What is the default value of local variables in Java?

WBOY
WBOYforward
2023-08-20 21:41:372024browse

What is the default value of local variables in Java?

Local variables can be declared in method, code blocks, constructors, etc. in Java. When program control enters a method, code block, constructor, etc., local variables are created, and when program control leaves a method, code block, constructor, etc., local variables are destroyed. In Java, local variables do not have default values ​​. This means that they can be declared and assigned before the variable is first used, otherwise, the compiler will throw 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 cannot be initialized to a value, so an error will be generated, similar to “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

is translated into Chinese as:

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 to a value of 100

output

The number is : 100

The above is the detailed content of What is the default value of local variables in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete