You are here: Home / Topics / What are the default values assigned to variables and instances in Java?

What are the default values assigned to variables and instances in Java?

Filed under: Java Interview Questions on 2024-10-25 14:43:47

In Java, variables and instances are assigned default values depending on their data types when they are declared but not explicitly initialized. Here’s a summary of the default values for each data type:

Primitive Data Types

  1. byte: 0
  2. short: 0
  3. int: 0
  4. long: 0L
  5. float: 0.0f
  6. double: 0.0
  7. char: '\u0000' (null character)
  8. boolean: false

Reference Data Types

  • Objects (including arrays): null

Example in a Class

When you declare instance variables in a class, they receive these default values:

class Example {
   byte b;         // default 0
   int i;          // default 0
   boolean flag;   // default false
   String str;     // default null
}
 

Local Variables

Local variables, on the other hand, do not receive default values. They must be explicitly initialized before use:

void method() {
   int localVar; // must be initialized before use
   // System.out.println(localVar); // This will cause a compilation error
}
 

Summary

  • Instance variables get default values based on their type.
  • Local variables do not have default values and must be initialized before they can be accessed.

About Author:
J
Java     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.