user3725988 user3725988 - 11 months ago 46
Java Question

Need help on understanding user input in Java

Can someone explain the below code to me? Having a hard time understanding how the flow works. When the animal constructor is called in main(), it prints out "please input the name", but how does the user is able to input anything here? And how does it get assigned to the userInput? Lastly, why do we use this.setName(userInput.nextLine()) here?

import java.util.Scanner;
import java.util.*;

public class animal{

private String name;
static Scanner userInput = new Scanner(;

public void setName(String name){ = name;

public animal(){
System.out.println("please input the name");



public static void main(String[] args){

animal Dog1 = new animal();


When you run your program, the method:


Will block until the user type something and press enter (cf javadoc).

Once is done, you get the result from:


Then set the name of the dog with this value.

Finally, it returns the new animal instance with the name entered by the user.