• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Doubt on Arrays

 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Class A{
static char[] a;
public static void main( String[] args ) {

System.out.println(a);

}

}
Here why it showing exception while iam trying for int[] a ,it is not showing any exception.Here a is the array .So in both cases it should show the null value.But not in the above programme.Please explain?
 
Ranch Hand
Posts: 99
Mac Eclipse IDE
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
According to )]javadoc, System.out.println(char[] x) calls the method System.out.print(char[] x) which throws NullPointerException when x is null.
[ August 22, 2007: Message edited by: Al Mamun ]
 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You should take a look at the Javadoc for answering your question....
)]Javadoc - println()

First let us consider this...
...
int []a;
/*some code*/
System.out.println(a);
...
When System.out.println() is called by the program, the following happens internally
i) public void println(Object x) of PrintStream is called
ii) This in turn invokes print(x) and println()
iii) print(x) will print the value of Object x, which is NULL here

Then let us see the other code...
...
char []a;
/*some code*/
System.out.println(a);
...
When System.out.println() is called by the program, the following happens internally
i) public void println(char[] x) of PrintStream is called
ii) This in turn invokes print(char[] x) and println()
iii) print(char[] x) will print the character array and throws NullPointerException if the array has not been initialized.

So the answer to your question - There is a difference in behavior when using int array and char array because overloaded print() methods of PrintStream are called in each scenarios. Latter throws a NullPointerException while the former does not throw.

HTH
 
Wink, wink, nudge, nudge, say no more, it's a tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic