We can have two types of variables i.e. reference variable or local variable.
Default value means if we do not initialize a variable what is its value by default.
class Demo{
int x;//default value is 0
Integer y;//default value is null
public static void main(String[] args){
int x;//no dafault value
Integer y;//no default value
the primitive has dafault value for instance variable and object reference(inside class).
byte, short, int, long- 0
float, double- 0.0
boolean- false
char- '\u0000'
Object reference-null

The wrapper type has default value null for instance variable.Because it is object reference.
An array is an object; thus, an array instance variable that's declared but not
explicitly initialized will have a value of null,
int[] arr;
Integer[] arr;
Both will give null.
int [] x=new int[5];
System.out.println(x[3]);//output is 0
Integer [] x=new Integer[5];
System.out.println(x[3]);//output is null

For local variables(inside method) there is no default value.
For array all the elements of are initialized to zero/null regardless local or instace array.
int [] x=new int[5];//consider this is inside main(local)
System.out.println(x);//Gives output 0
Integer [] x=new Integer[5];//consider this is inside main(local)
System.out.println(x);//Gives output null

If you declare a local variable without initialization then it is not error but when you try to use this then it will be compilation error.

No comments:

Post a Comment