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
0or0.0, boolean variables receivefalse, and reference variables receivenull.
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?
