Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

NullPointerException when using java.io.Console

 
kevinn lee
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

what causes the exception?
thanks
 
Jayanath Amaranayake
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 java.io.Console 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
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Normally you'd tell us *when* you get the NPE.
 
Campbell Ritchie
Sheriff
Posts: 48930
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jayanath Amaranayake is correct: this is a rather obscure pitfall with the Console class, which everybody falls for at some time or other.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic