Skip to content
Related Articles

Related Articles

Default Array Values in Java

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 24 Jan, 2022
View Discussion
Improve Article
Save Article

If we don’t assign values to array elements and try to access them, the compiler does not produce an error as in the case of simple variables. Instead, it assigns values that aren’t garbage. 

Below are the default assigned values. 

S. No.DatatypeDefault Value
1booleanfalse
2int0
3double0.0
4Stringnull
5User-Defined Typenull

Example:

Java




// Java program to demonstrate default
// values of array elements
 
class ArrayDemo {
    public static void main(String[] args)
    {
        System.out.println("String array default values:");
        String str[] = new String[5];
        for (String s : str)
            System.out.print(s + " ");
 
        System.out.println(
            "\n\nInteger array default values:");
        int num[] = new int[5];
        for (int val : num)
            System.out.print(val + " ");
 
        System.out.println(
            "\n\nDouble array default values:");
        double dnum[] = new double[5];
        for (double val : dnum)
            System.out.print(val + " ");
 
        System.out.println(
            "\n\nBoolean array default values:");
        boolean bnum[] = new boolean[5];
        for (boolean val : bnum)
            System.out.print(val + " ");
 
        System.out.println(
            "\n\nReference Array default values:");
        ArrayDemo ademo[] = new ArrayDemo[5];
        for (ArrayDemo val : ademo)
            System.out.print(val + " ");
    }
}

Output

String array default values:
null null null null null 

Integer array default values:
0 0 0 0 0 

Double array default values:
0.0 0.0 0.0 0.0 0.0 

Boolean array default values:
false false false false false 

Reference Array default values:
null null null null null 

This article is contributed by Twinkle Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!