Home Local variable array of ints defaults to zero
Reply: 1

Local variable array of ints defaults to zero

Jeremy Levett
1#
Jeremy Levett Published in 2017-12-07 22:06:45Z

This question already has an answer here:

  • int array initialization 7 answers

Why is it that when an array of 'ints' is made as a local variable they default to zero?

       public static void main(String [] args) {
           int []arrayInts = new int[5];
           for(int i: arrayInts)
                System.out.println(i);
           //Prints out zeros 
       }

While if an 'int' variable is declared as a local variable it does not get initialized.

       public static void main(String [] args) {            
           int a;
            System.out.println(a);
           //Compilation error: The local variable a may not have been initialized
       }       
Makoto
2#
Makoto Reply to 2017-12-07 22:09:32Z

These two examples aren't comparable.

In the first one, you are actively initializing your array. The default value for an array of ints is 0.

In the second example, you've not initialized the variable a, either explicitly or implicitly, and you're attempting to make use of it. Java will complain about this action.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.33151 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO