Java.Core.What values are variables initialized to by default ?

🔹 Default Values of Variables in Java

In Java, the default value of a variable depends on its data type and where it’s declared (instance variable, static variable, or local variable).


1️⃣ Instance and Static Variables

(i.e., fields of a class)
These automatically get default values if not explicitly initialized.

Data TypeDefault Value
byte0
short0
int0
long0L
float0.0f
double0.0d
char'\u0000' (null character)
booleanfalse
Reference types (String, objects, arrays)null

Example:

class Example {
    int num;       // Default: 0
    double price;  // Default: 0.0
    boolean flag;  // Default: false
    String text;   // Default: null

    static int staticNum; // Default: 0 (static fields also get default values)
}

2️⃣ Local Variables (Inside Methods)

⚠️ Local variables do NOT get default values!
You must initialize them before use, otherwise compilation fails.

Example:

void test() {
    int x;  
    System.out.println(x); // ❌ Compilation Error: "variable x might not have been initialized"
}

3️⃣ Array Elements

Array elements do get default values based on their type.

Example:

int[] numbers = new int[5]; // All elements are initialized to 0
String[] texts = new String[3]; // All elements are initialized to null

🔹 Summary

Variable TypeGets Default Value?
Instance Variables (fields)✅ Yes
Static Variables✅ Yes
Local Variables❌ No (must initialize before use)
Array Elements✅ Yes
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.