user3725988 user3725988 - 2 years ago 84
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();

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download