Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Basics Using your New Tools Multiple Strings

Getting a Null pointer exception, even though I am using the same code as the teacher.

public class Main { public static void main(String[] args) {

    Console console = System.console();

    String name = console.readLine("Enter your name:  ");
    String adjective = console.readLine("Enter an adjective  ");
    console.printf("%s is very %s", name, adjective);

error: Exception in thread "main" java.lang.NullPointerException at com.teamtreehouse.Main.main(Main.java:16)

Emmanuel C
Emmanuel C
10,635 Points

Are you running this in workspace or a separate IDE?

2 Answers

Emmanuel C
Emmanuel C
10,635 Points

Hey Mike,

This has to do with how you run the program. System.console() will return the console that is connected with it. The command line is itself a console, so when you run it from there that console will be automatically connected and thats what returns from System.console().

However if you run the program from an IDE, like IntelliJ the console will not connect automatically therefore that System.console() will return null. Which causes that error when you try to readLine() from it. To accomplish the same task from an IDE, you can use the scanner class, try...

import java.util.Scanner;

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter you name: ");
    String name = scanner.nextLine();

    System.out.print("Enter an adjective: ");
    String adjective = scanner.nextLine();

    System.out.printf("%s is very %s", name, adjective);

Alternatively if you run your code from the command line like how its done in the lesson with workspace, itll work


Intelli J