English

Can member variables of a Java class be initialized when the class is defined?

Advertisements

Question

Can member variables of a Java class be initialized when the class is defined?

Long Answer
Advertisements

Solution

  • Yes, member variables of a Java class can be initialized at the time of their declaration within the class definition. These variables are declared inside a class but outside any method, constructor, or block.
  • Both instance variables and static (class) variables can be assigned initial values directly when they are declared.
  • If member variables are not explicitly initialized, Java automatically assigns default values according to their data types. For example, numeric variables receive 0 or 0.0, boolean variables receive false, and reference variables receive null.

Thus, Java allows member variables to be initialized during class definition, but explicit initialization is not compulsory.

shaalaa.com
  Is there an error in this question or solution?
Chapter 6: Variables and Expressions - SHORT ASSIGNMENTS [Page 136]

APPEARS IN

Dheeraj Mehrotra Computer Science [English] Class 12
Chapter 6 Variables and Expressions
SHORT ASSIGNMENTS | Q 39. | Page 136
Advertisements
Share
Notifications



      Forgot password?
Use app×