0

I'm trying to create a program in which the first step is for the user to input their name (in the User class). I wanted to create a method (in another class) that specifically reads the input and then implement that method in my User class.

However, I'm getting a NullPointerException error and I don't quite understand why.

 public class Main {
     public static void main(String[] args) {
         User newUser=new User();
         newUser.CreateName(); 
     }
 }
 public class User {
     UserInput ui;
     public void CreateName(){
         System.out.println("Enter your name:");
         String name= ui.Input();
     }
 }
 public class UserInput {
     public String Input(){
         Scanner input=new Scanner(System.in);
         String s=input.nextLine();
         return s;
     }
 }
Arun Sudhakaran
  • 2,167
  • 4
  • 27
  • 52
vort3x
  • 1

2 Answers2

0

The instance of UserInput is not initialized, it has null value.

Try changing in User class:

UserInput ui;

to

UserInput ui = new UserInput();
Nik
  • 173
  • 2
  • 17
0

When you instantiate User class in your main method, all the global instance attributes (In your case UserInput ui) of User class gets loaded into the memory, with its default values, and hence it is derived data type automatically its default value will be set to null.

Now you are calling a method on that reference which is null, calling any method on a null reference causes NullPointerException. So you need to initialize your UserInput reference to an object.

Either while declaring your attribute UserInput ui = new UserInput();, so this object is getting a global scope within your User class, and can be accessed across the current class and also in the other classes in same package.

Or you can initialize that attribute inside your CreateName() method like

public void CreateName(){
    System.out.println("Enter your name:");
    ui = new UserInput();
    String name= ui.Input();
}

So that object becomes local to the method, and hence you are not passing its reference to any other method, it will be garbage collected before the method execution finishes.

Arun Sudhakaran
  • 2,167
  • 4
  • 27
  • 52