In Java are primitive fields instantiated to a default value, but a primitive variable…
- User
In Java are primitive fields instantiated to a default value, but a primitive variable in a method is not? If it's not instantiated to a default value, what value does it have? Null or what?
- Assistant
In Java, primitive fields (instance variables) are indeed instantiated with default values, while primitive variables declared within a method (local variables) are not automatically initialized.
The default values for primitive fields in Java are as follows:
byte,short,int,long: 0float,double: 0.0char: '\u0000' (null character)boolean:false
For example, consider the following class:
public class MyClass { private int num; private boolean flag; public static void main(String[] args) { MyClass myObj = new MyClass(); System.out.println(myObj.num); // Output: 0 System.out.println(myObj.flag); // Output: false } }In this case, the
numfield has a default value of 0, while theflagfield has a default value of .