java-entrada-salida-scanner-println-console

Input and Output in Java: System.out and Scanner

  • 4 min

The input and output encompass the mechanisms by which a program receives data and communicates results.

So far, our programs haven’t received data from the outside. We defined variables within the code, calculated something, and displayed it. An interactive application needs to ask the user and respond.

Today we’re going to look at basic I/O (Input/Output) on the console.

It seems simple, but Java has its peculiarities. If you come from C# (Console.ReadLine) or Python (input), you’ll see that reading from the keyboard in Java requires a small “ritual” with the Scanner class.

Outputting Data: System.out

We already know our old friend System.out.println. But let’s break it down a bit more, because there’s life beyond println.

System.out is a standard output stream that is already open and ready to use.

  1. println() (Print Line): Prints the text and adds a newline at the end.
  2. print(): Prints the text and stays waiting on the same line.
  3. printf() (Print Formatted): If you come from C, this will feel familiar. It allows formatting text using placeholders.
int edad = 25;
double altura = 1.75;

System.out.print("Hello, ");
System.out.println("user.");
// Output: Hello, user. (with a newline at the end)

// Using classic concatenation (a bit ugly)
System.out.println("You are " + edad + " years old and " + altura + "m tall.");

// Using printf (cleaner and more professional)
System.out.printf("You are %d years old and %.2fm tall.%n", edad, altura);
Copied!

In printf, %d is for integers, %f for floats (we can limit decimals with %.2f), %s for text, and %n is the cross-platform newline.

Input Data: the Scanner class

Java doesn’t have a simple global function for reading (like cin in C++). Instead, it uses the java.util.Scanner class, which is a text parser.

Scanner is very powerful: it can read from the console, a text file, or a string, and it can automatically break down the information (tokens).

Step 1: Import and Initialize

Scanner is not in the basic java.lang package, so you must import it.

import java.util.Scanner; // 1. Import

public class Main {
    public static void main(String[] args) {
        // 2. Create an instance connected to the keyboard (System.in)
        Scanner scanner = new Scanner(System.in);

        // ... use the scanner ...

        // 3. Best practice: close the scanner when done
        scanner.close();
    }
}
Copied!

Step 2: Read Data

Scanner has specific methods for each primitive data type.

System.out.print("Enter your age: ");
int edad = scanner.nextInt();     // Reads an integer

System.out.print("Enter your weight: ");
double peso = scanner.nextDouble(); // Reads a double (be careful with comma or period depending on your locale)

System.out.print("Enter your name: ");
String nombre = scanner.next();     // Reads ONE single word (up to the first space)
Copied!

Watch out for the locale: If your computer is set to Spanish, scanner.nextDouble() will expect a comma (2,5) as the decimal separator. If you type a period (2.5), it will throw an InputMismatchException. You can force the period with scanner.useLocale(Locale.US);.

Reading Full Lines

If you want to read an entire phrase (with spaces), scanner.next() won’t work because it stops at the first space. You must use scanner.nextLine().

The Pending Newline in Scanner

This is the error that everyone has run into when learning Java. Pay attention.

If you mix methods for reading numbers (nextInt, nextDouble) with methods for reading lines (nextLine), something strange will happen:

System.out.print("Give me a number: ");
int numero = scanner.nextInt();

System.out.print("Give me a phrase: ");
String frase = scanner.nextLine(); // The program skips this!

System.out.println("Read: " + numero + " and " + frase);
Copied!

What happened?

  1. You type 42 and press Enter.
  2. In the input buffer, there is: 42 + \n (the newline).
  3. nextInt() takes the 42, but leaves the \n in the buffer.
  4. You call nextLine(). This function reads until it finds a newline. Since the first thing it finds is the leftover \n, it thinks: “Ah, an empty line!”, consumes it, and finishes.

The Solution: Whenever you read a number and then plan to read text, you must do an extra read to “clear” the buffer.

int numero = scanner.nextInt();
scanner.nextLine(); // <--- CONSUME THE LEFTOVER ENTER (Cleanup)

System.out.print("Give me a phrase: ");
String frase = scanner.nextLine(); // Now it works
Copied!

The Alternative: The Console Class

Java 6 introduced System.console(). It’s a more direct way to read, especially designed for passwords because it doesn’t show what you type.

Console consola = System.console();

if (consola != null) {
    String usuario = consola.readLine("User: ");
    char[] pass = consola.readPassword("Password: ");
}
Copied!

The Problem with Console

If you try the above code in IntelliJ or Eclipse, it will most likely give you an error (NullPointerException). This is because System.console() only works if you run the program from a real terminal (CMD, Bash). IDEs often wrap the console, and System.console() returns null.