What are the default values assigned to variables and instances in Java?
In Java, when you declare variables and instances of classes, they are assigned default values if they are not explicitly initialized. The default values depend on the type of the variable. Here are the default values for different data types in Java:
0
0
0
0L
0.0f
0.0d
'\u0000'
(null character)false
null
When you create an instance of a class, the instance variables (fields) of that class will be initialized to their default values if you do not provide explicit initial values. For example:
public class Example {
int number; // default value is 0
boolean flag; // default value is false
String text; // default value is null
public void printValues() {
System.out.println("Number: " + number);
System.out.println("Flag: " + flag);
System.out.println("Text: " + text);
}
}
public class Main {
public static void main(String[] args) {
Example example = new Example();
example.printValues();
}
}
Output:
Number: 0
Flag: false
Text: null
In this example, the number
is initialized to 0
, flag
to false
, and text
to null
because they are not explicitly initialized.