Wednesday, 10 January 2018

Default Array Values in Java

Tags

In Java, If we try to access the simple variable without assign any value to it then compiler will produce error. But if we don't assign the values to an array elements then compiler will assign a value to them which are not garbage.

Here are the default assigned values of arrays:

int: 0
double: 0.0
short: 0
String: null
boolean: false

EXAMPLE:

import java.util.*;

class array_default_values{
 
      public static void main(String args[]){

          System.out.print("\n\n");

            int[] arr_int=new int[6];
            System.out.println("The default values of integer array is: ");
            for(int i=0;i<arr_int.length;i++){
                 System.out.print(arr_int[i]+" ");
            }

            System.out.print("\n\n");

            boolean[] arr_bool=new boolean[6];
            System.out.println("The default values of boolean array is: ");
            for(int i=0;i<arr_bool.length;i++){
                  System.out.print(arr_bool[i]+" ");
            }

            System.out.print("\n\n");

            double[] arr_double=new double[6];
            System.out.println("The default values of double array is: ");
            for(int i=0;i<arr_double.length;i++){
                  System.out.print(arr_double[i]+" ");
            }

            System.out.print("\n\n");

            String[] arr_string=new String[6];
            System.out.println("The default values of string array is: ");
            for(int i=0;i<arr_string.length;i++){
                  System.out.print(arr_string[i]+" ");
            }

            System.out.print("\n\n");

            short[] arr_short=new short[6];
            System.out.println("The default values of short array is: ");
            for(int i=0;i<arr_short.length;i++){
                  System.out.print(arr_short[i]+" ");
            }


            System.out.print("\n\n");

            byte[] arr_byte=new byte[6];
            System.out.println("The default values of byte array is: ");
            for(int i=0;i<arr_byte.length;i++){
                  System.out.print(arr_byte[i]+" ");
            }


            System.out.print("\n\n");




      }
}

OUTPUT:



EmoticonEmoticon