public class test { public static void main( String[] args ) { int i = 3; System.out.println(" From command line " + args.length); // works fine and prints 0 //int[] iArr; //System.out.println(" Length of array " + iArr.length); // compile error - Array needs to be //initialized
Why does printing the length of the argument String[] args not give any compile time error ? While this is not the case with the local declared array iArr.
Hi Anjela, The String[] args of the main is initialized by the JVM.However, locally defined array needs to be initialized before you calculate its length. Alternatively, you could declare the array as a class variable for compilation.However, still you will get RuntimeException, unless you initialize the array. So the following code will compile but not run correctly :
The following code will compile and run properly :
The following code will not compile :
The following code will compile and run correctly
Hope this helps, Sandeep SCJP2, OCSD(Oracle JDeveloper), OCED(Oracle Internet Platform)
<b>Sandeep</b> <br /> <br /><b>Sun Certified Programmer for Java 2 Platform</b><br /> <br /><b>Oracle Certified Solution Developer - JDeveloper</b><br /><b>-- Oracle JDeveloper Rel. 3.0 - Develop Database Applications with Java </b><br /><b>-- Object-Oriented Analysis and Design with UML</b><br /> <br /><b>Oracle Certified Enterprise Developer - Oracle Internet Platform</b><br /><b>-- Enterprise Connectivity with J2EE </b><br /><b>-- Enterprise Development on the Oracle Internet Platform </b>