- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the default value of a local variable in Java?n
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
- Related Articles
- What is the default value of a local variable in Java?
- final local variable in Java
- Initialization of local variable in a conditional block in Java
- What are the rules for a local variable in lambda expression in Java?
- How to declare a local variable in Java?
- Do local variables in Java have default values?
- What is a default value in Python?
- Setting a default variable value to undefined in a function - JavaScript?
- What is the default type of a hexadecimal value in MySQL?
- What is the purpose of a default constructor in Java?
- What is the scope of local variables in Java?
- Local Variable Type Inference or LVTI in Java 10
- What is the use of default methods in Java?
- What is a final variable in java?
- Default value of primitive data types in Java
- What is the scope of default access modifier in Java?
