Input and Output in Java
Cal Afun

Cal Afun @cal_afun_2475adb4b562023b

About: Hi, I’m Cal, a Computer Engineering student passionate about software development and learning by teaching. My goal is to break down concepts in a simple, beginner-friendly way.

Joined:
Aug 17, 2025

Input and Output in Java

Publish Date: Aug 23
0 0

In Java, input and output (I/O) are how a program interacts with the outside world. Most beginner programs use the console, a simple text interface, to read input from users and display output.

Printing Output
Printing messages to the console is straightforward using:

System.out.println("Hello, world!");

Enter fullscreen mode Exit fullscreen mode

This prints the text but is followed by a newline. If you do not want it to create a new line at the end, then use;

System.out.print("Hello, ");
System.out.print("world!");
Enter fullscreen mode Exit fullscreen mode

Reading Input
Reading input from the user is slightly more involved. Java provides the Scanner class for this purpose, which can read text, numbers, and more from the console.

First, you need to import the class:

import java.util.Scanner;

Enter fullscreen mode Exit fullscreen mode

Then, you create a Scanner object attached to System.in:

Scanner in = new Scanner(System.in);

Enter fullscreen mode Exit fullscreen mode

Reading a string
If the input may contain spaces, use nextLine():

System.out.print("What is your name? ");
String name = in.nextLine();

Enter fullscreen mode Exit fullscreen mode

For a single word (no spaces), use next():

System.out.print("Enter your first name: ");
String firstName = in.next();

Enter fullscreen mode Exit fullscreen mode

Reading Numbers
To read integers or floating-point numbers:

System.out.print("How old are you? ");
int age = in.nextInt();

System.out.print("Enter your height in meters: ");
double height = in.nextDouble();

Enter fullscreen mode Exit fullscreen mode

Note

  1. Scanner is a class In Java, a class is like a blueprint for creating objects. The Scanner class is defined in the java.util package, and it provides methods to read input from different sources—like the console, files, or strings. When you do:
Scanner in = new Scanner(System.in);

Enter fullscreen mode Exit fullscreen mode

You are creating a Scanner object called in. Think of it like saying:
“I want a tool (Scanner object) that can read input, and I’ll attach it to this input source (System.in).”

_An input stream in Java is basically a channel through which data flows into your program. Think of it like a pipe that carries information from some source (keyboard, file, network, etc.) into your program so it can be read and processed.
_

System.in is an InputStream
System is a built-in class in Java (in the java.lang package, so you don’t need to import it).
in is a static member (variable) of the System class. Its type is InputStream.
InputStream represents a source of bytes—here, it’s the console (keyboard input).
So when you pass System.in to the Scanner constructor, you’re telling the Scanner:
“Read the bytes that come from the console and let me interpret them as text, numbers, etc.”

Collecting Sensitive Input (Passwords) in Java

When reading input from users, sometimes the data is sensitive, like passwords. Using Scanner isn’t safe for this, because the input appears plainly on the console as the user types. To handle this securely, Java provides the Console class.

Using the Console Class
import java.io.Console
You can get a Console object like this:

Console cons = System.console();

Enter fullscreen mode Exit fullscreen mode

Once you have a Console, you can read input:

// Read username
String username = cons.readLine("User name: ");

// Read password securely
char[] passwd = cons.readPassword("Password: ");

Enter fullscreen mode Exit fullscreen mode

Why char[] Instead of String?
Passwords are returned as character arrays rather than strings for security reasons:
Strings in Java are immutable, so they stay in memory until garbage-collected.
Character arrays can be overwritten immediately after use to reduce the risk of exposure:

// Overwrite the password array after processing
for (int i = 0; i < passwd.length; i++) {
    passwd[i] = '*';
}

Enter fullscreen mode Exit fullscreen mode

Key Points
Console input is line-based, unlike Scanner.
There are no methods to read individual words or numbers—you read one line at a time.
Always process sensitive data carefully and clear it from memory when done.

Tips: If you run your Java program in some IDEs (like Eclipse or IntelliJ), System.console() may return null. For secure password input, run your program in a terminal or command prompt.

Example code;

import java.io.Console;

public  class proto{
    public static void main(String [] args){
        Console cons = System.console();

        if (cons == null){
            System.out.println("No console available, try in terminal");
            return;
        }

        String username = cons.readLine("Username: ");
        char[] password = cons.readPassword("Password: ");

        System.out.println("Welcome, " + username + "!");
        for (int i = 0; i < password.length; i++) { // pver here we use indices so it could also be for(int i = 0; i <= password.length-1; i++)
            password[i] = '*';  // Overwrite each character
        }

    }

}
Enter fullscreen mode Exit fullscreen mode

Tips & FAQs: Understanding Console Input and Passwords in Java

  1. Why don’t we use Scanner for passwords? Scanner shows everything typed on the console, which is insecure for passwords. Use Console.readPassword() to hide input.
  2. Why is System.console() sometimes null? System.console() only works in real terminals (macOS Terminal, Windows CMD, Linux shell). Some IDEs like Eclipse, IntelliJ, or VS Code use an internal console that isn’t a full terminal. Always check for null before using Console to avoid crashes
  3. Why do we use char[] for passwords instead of String? Strings are immutable; they remain in memory until garbage-collected. char[] can be overwritten immediately to reduce the risk of exposing passwords.
  4. Why do we overwrite the password array after use? Overwriting ensures sensitive data does not stay in memory. You still can log in again—the source of truth (like a database) still stores the password. For example;
for (int i = 0; i < password.length; i++) {
    password[i] = '*';
}

Enter fullscreen mode Exit fullscreen mode
  1. Why is there a return in the null check? return exits the main method early if the console is not available. Prevents a NullPointerException if you try to use cons later.
  2. Why is char[] used instead of a single char? char[] is an array of characters, representing the full password. Allows you to overwrite each character after processing for security.

Comments 0 total

    Add comment