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

What is the default value of local variables in Java?

WBOY
Release: 2023-08-20 21:41:37
forward
2050 people have browsed it

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();
   }
}
Copy after login

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
Copy after login

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();
   }
}
Copy after login

In the above program , a local variable num can be initialized to a value of 100

output

The number is : 100
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template