• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A rather silly one

 
Angela Narain
Ranch Hand
Posts: 327
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
Desai Sandeep
Ranch Hand
Posts: 1157
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic