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 .
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”.
LocalVariableTest.java:4: error: variable num might not have been initialized System.out.println("The number is : " + num); ^ 1 error
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
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!