This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes NullPointerException when using Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "NullPointerException when using" Watch "NullPointerException when using" New topic

NullPointerException when using

kevinn lee
Ranch Hand

Joined: Feb 15, 2010
Posts: 87

what causes the exception?
Jayanath Amaranayake

Joined: Dec 06, 2009
Posts: 7
If you debug your code, you will find that you are not getting a Console object, hence c is null.

According to the API doc for class.

Whether a virtual machine has a console is dependent upon the underlying platform and also upon the manner in which the virtual machine is invoked. If the virtual machine is started from an interactive command line without redirecting the standard input and output streams then its console will exist and will typically be connected to the keyboard and display from which the virtual machine was launched. If the virtual machine is started automatically, for example by a background job scheduler, then it will typically not have a console.

I believe you tried this using some IDE. If you execute the same code using the command prompt, then you will not get a null pointer.
David Newton

Joined: Sep 29, 2008
Posts: 12617

Normally you'd tell us *when* you get the NPE.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46429
Jayanath Amaranayake is correct: this is a rather obscure pitfall with the Console class, which everybody falls for at some time or other.
I agree. Here's the link:
subject: NullPointerException when using
It's not a secret anymore!