User Input

In Java, user input refers to the data or information provided by the user during the execution of a program. This input is usually taken through the console (command line) and can be used to perform various operations in your program. Java provides different ways to collect input, with the most common being the Scanner class.

Syntax

  • Import the Scanner class from the java.util package.
  • Create an object of the Scanner class.
  • Use methods like nextLine(), nextInt(), or nextDouble() to capture input.

User Input Methods (Scanner Class)

Method Data Type Description Example
nextLine() String Reads a full line of text input. String name = scanner.nextLine();
next() String Reads a single word (stops at space). String word = scanner.next();
nextInt() int Reads an integer input. int age = scanner.nextInt();
nextDouble() double Reads a decimal (floating-point) number. double price = scanner.nextDouble();
nextFloat() float Reads a floating-point number. float weight = scanner.nextFloat();
nextLong() long Reads a long integer. long bigNumber = scanner.nextLong();
nextShort() short Reads a short integer. short smallNumber = scanner.nextShort();
nextByte() byte Reads a byte value. byte tinyNumber = scanner.nextByte();
nextBoolean() boolean Reads a boolean (true or false). boolean isJavaFun = scanner.nextBoolean();

Example