File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes About args to main() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "About args to main()" Watch "About args to main()" New topic
Author

About args to main()

Rashmi Tambe
Ranch Hand

Joined: Aug 07, 2001
Posts: 418
Hello,
I tried following code...

I u run it as java testMain
the o/p is
in main 0
Exception in thread "main" java.lang.NullPointerException
at testMain.m1(testMain.java:12)
at testMain.main(testMain.java:8)

Even if args to main are not initialised while running the program, args.length prints '0'. But if static arr a1 is not initialised and a.length is tried , it throws NullPointerException. Why so??? or i am missing something?? or args to main are automatically initialised???
Thanx in advance.
Rashmi
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1871
Hi Rashmi,
static arguments are also initialized. Here a[] is reference and so it's initialized to null. so when u say a.length it raises an exception.
but true, u r right about the main() method. even if u don pass anything at run time to the program it's not initialized to null but it's something like args[] = new String[0]. and so when u do args.length on main() methods parameter it says '0' as result.
if u do same thing with that static int[] a (meaning initializing like static int[] a = new int[0]) it wont give u exception but answer as '0' when u try to do a.length
HTH
Maulin
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: About args to main()