-1

if local variables need to be assigned some default value then why java provide default value for arrays declared locally.

import java.util.Arrays;
import java.util.Scanner;

public class MatrixMultiplication {

int a;
int a1[][]=new int[2][2];

      public static void main(String[] args) {

        int a2[][]=new int[2][2];
        int b;

        MatrixMultiplication mm=new MatrixMultiplication();
        System.out.println(mm.a);
        System.out.println(mm.a1[1][0]);
        System.out.println(b);
        System.out.println(a2[1][0]);

    }

}

Like in above code for varible a default value is 0 and for b we have to setsome value. Then for a1[][] the dafult value of each element is 0. Till here everything is understood that have they are provided with deafult values but as a2[][] is locally declared then its elements should not be initialised by default as the java rule so how are they initialised by default with each element as 0

Ankit
  • 95
  • 1
  • 9
  • For integer and floating point primitives, it's 0, for booleans its `false` and for all other reference types it's `null`. (But for local variables there is no default. You call `new` to create a new object, which initializes the local array. So that's how the elements get set to 0, `new` does it.) – markspace Apr 23 '17 at 16:21

2 Answers2

2

but as a2[][] is locally declared then its elements should not be initialosed by deaflt

There's a big difference between a variable and an array entry.

b not being initialized is a common coding error, so the compiler calls it out.

But a2 is initialized, and the contents of an array are set to the default value for the array's element type when the array is allocated — int[] (or a2[0]) and int (for a2[0][0]), in your case.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0
public class HelloWorld{

     public static void main(String []args){
        System.out.println("sampleArray[0] is ");
        int sampleArray[]   =   new int[7];
        System.out.println(sampleArray[0]);
     }
   }

      Output 
      sampleArray[0] is 
      0
Purva
  • 383
  • 3
  • 10