In programming, Input/Output (I/O) refers to the communication between your program and the outside world.
Input: Data that your program receives from an external source. This could be user input from the keyboard, data from a file, or information from a network connection.
Output: Data that your program sends to an external destination. This could be text displayed on the console, data written to a file, or information sent over a network.
For introductory programming, we'll focus on the most common forms of basic I/O:
Standard Output: Displaying text and data to the console (the screen where your program runs).
Standard Input: Reading data entered by the user from the keyboard.
Basic I/O is fundamental because it allows your programs to interact with users, receive data to process, and present results.
1. Standard Output: System.out.print() and System.out.println()
In Java, the System.out object is your primary tool for sending output to the standard output stream, which is typically your console.
You'll primarily use two methods of System.out:
System.out.print(value): Prints the specifiedvalueto the console. The cursor remains on the same line after printing.System.out.println(value): Prints the specifiedvalueto the console, and then moves the cursor to the next line (prints a "new line" character). This is equivalent toSystem.out.print(value + "\n");.
Syntax:
System.out.print("Your message here");
System.out.println("Another message");
System.out.println(variableName); // Prints the value of a variable
Example: Displaying Output
// BasicOutput.java
public class BasicOutput {
public static void main(String[] args) {
// Using System.out.println() - each statement starts on a new line
System.out.println("Hello, Java!");
System.out.println("This is my first output program.");
// Using System.out.print() - stays on the same line
System.out.print("This text will be ");
System.out.print("on the same line.");
System.out.println(); // Prints a new line character to move to the next line
// Combining text and variables
String name = "Alice";
int age = 30;
System.out.println("My name is " + name + " and I am " + age + " years old.");
// Printing numbers directly
System.out.println(123);
System.out.println(3.14);
}
}
2. Standard Input: The Scanner Class
To get input from the keyboard in Java, you use the Scanner class, which is part of the java.util package. The Scanner class provides convenient methods for reading various types of input from the console.
Steps to use Scanner:
Import the
Scannerclass: You need to tell Java where to find theScannerclass. This is done at the top of your Java file, outside of any class definition:import java.util.Scanner;Create a
Scannerobject: You need to create an instance of theScannerclass, typically linked to the standard input stream (System.in).Scanner scanner = new Scanner(System.in);Read input using
Scannermethods: TheScannerobject has various methods to read different data types:nextInt(): Reads the next integer.nextDouble(): Reads the next double (decimal number).nextBoolean(): Reads the next boolean (trueorfalse).next(): Reads the next word (stops at whitespace).nextLine(): Reads the entire line of input, including spaces, until a new line character is encountered.
Close the
Scanner: It's good practice to close theScannerobject when you are finished using it to release system resources.scanner.close();
Example: Getting Input from the User
// BasicInput.java
import java.util.Scanner; // Step 1: Import the Scanner class
public class BasicInput {
public static void main(String[] args) {
// Step 2: Create a Scanner object, linked to System.in (keyboard input)
Scanner keyboardInput = new Scanner(System.in);
System.out.println("--- Getting String Input ---");
System.out.print("Enter your full name: ");
// Step 3: Read a full line of text
String fullName = keyboardInput.nextLine();
System.out.println("Hello, " + fullName + "!");
System.out.println("\n--- Getting Integer Input ---");
System.out.print("Enter your age: ");
// Step 3: Read an integer
int age = keyboardInput.nextInt();
System.out.println("You are " + age + " years old.");
// IMPORTANT NOTE about nextLine() after nextInt()/nextDouble()/next():
// When you use nextInt(), nextDouble(), or next(), they only read the value,
// but leave the "new line" character (pressed after typing input) in the input buffer.
// If you immediately call nextLine() after these, it will consume that leftover new line,
// resulting in an empty string. To fix this, add an extra nextLine() call.
keyboardInput.nextLine(); // Consume the leftover new line character
System.out.println("\n--- Getting a Single Word Input ---");
System.out.print("Enter your favorite color (single word): ");
String color = keyboardInput.next(); // Reads only one word
System.out.println("Your favorite color is: " + color);
keyboardInput.nextLine(); // Consume the leftover new line character
System.out.println("\n--- Getting Double Input ---");
System.out.print("Enter a decimal number (e.g., 3.14): ");
double decimalNumber = keyboardInput.nextDouble();
System.out.println("You entered: " + decimalNumber);
// Step 4: Close the Scanner object to release resources
keyboardInput.close();
System.out.println("\nScanner closed. Program finished.");
}
}
Combining Input and Output: A Simple Interactive Program
Let's put both input and output together to create a simple interactive program that asks the user for information and then uses it to display a personalized message.
Example: Simple Interactive Program
// SimpleInteractiveProgram.java
import java.util.Scanner; // Import the Scanner class
public class SimpleInteractiveProgram {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in); // Create a Scanner object
System.out.println("Welcome to the Interactive Greeter!"); // Output
// Get user's name
System.out.print("Please enter your name: "); // Output prompt
String userName = userInput.nextLine(); // Input
// Get user's favorite programming language
System.out.print("What is your favorite programming language? "); // Output prompt
String favLanguage = userInput.nextLine(); // Input
// Get user's experience level (integer)
System.out.print("How many years have you been programming? "); // Output prompt
int yearsExperience = userInput.nextInt(); // Input
userInput.nextLine(); // Consume the leftover newline character after nextInt()
// Display a personalized summary
System.out.println("\n--- Your Profile ---"); // Output
System.out.println("Name: " + userName); // Output
System.out.println("Favorite Language: " + favLanguage); // Output
System.out.println("Years of Experience: " + yearsExperience); // Output
// Give a little message based on experience
if (yearsExperience < 2) {
System.out.println("Keep learning and happy coding!");
} else {
System.out.println("Great to see your dedication to programming!");
}
userInput.close(); // Close the Scanner
System.out.println("Thank you for using the program!");
}
}
Conclusion
Basic Input/Output is your program's window to the world. System.out.print() and System.out.println() allow you to display information, while the Scanner class empowers your program to gather information from the user, making your applications interactive and dynamic. Mastering these fundamental I/O techniques is a crucial step in building engaging and functional Java programs.
Key Takeaways
-
I/O is how your program interacts with the outside world.
Input: Data received by your program (e.g., from the keyboard, files).
Output: Data sent out by your program (e.g., to the console, files).
-
Import the Scanner class
Create Scanner object
Use Scanner object
Close Scanner object