Introduction to Java | Programming Basics

Input/Output in Java

Understanding input and output (I/O) is fundamental to interacting with users and other systems. In Java, input is typically handled using the Scanner class, while output is managed using System.out.println. This section demonstrates how to take user input and display output in Java.

1. Basic Concepts of Input and Output

Java categorizes I/O into three main areas:

2. Java I/O Streams

Java uses the concept of streams to handle input and output. Streams are a sequence of data. There are two types of streams:

Common stream classes in Java:

Code Example: Input and Output

Code Example


import java.util.Scanner; // Import the Scanner class

public class InputOutputExample {
    public static void main(String[] args) {
        // Create a Scanner object for input
        Scanner scanner = new Scanner(System.in);

        // Ask the user for their name
        System.out.println("Enter your name: ");
        String name = scanner.nextLine(); // Read a line of input

        // Ask the user for their age
        System.out.println("Enter your age: ");
        int age = scanner.nextInt(); // Read an integer input

        // Display the output
        System.out.println("Hello, " + name + "! You are " + age + " years old.");
    }
}
            

Output

Enter your name: 
John
Enter your age: 
25
Hello, John! You are 25 years old.
            

Explanation of the Code:

💡 Pro Tip

Always close the Scanner object after use to avoid resource leaks. This is a good habit when working with I/O operations!

Why Input/Output is Important in Java?

Input and Output allow Java programs to interact dynamically with users and systems. Mastering basic I/O operations is crucial before delving into file handling, networking, and more advanced topics in Java programming.

First Program in Java

The first program that most developers write in any programming language is the "Hello, World!" program. In Java, this is how you can print "Hello, World!" to the console. It demonstrates the basic syntax of a Java program, including the structure of a class, the main method, and how to output text using System.out.println.

Code Example: Hello, World!

Code Example


public class HelloWorld {
    public static void main(String[] args) {
    // Output "Hello, World!" to the console
    system.out.println("Hello, World!");
            }
        }
                    

Explanation of the Code:

Output

Hello, World!

💡 Pro Tip

Always start with small programs to practice basic syntax before moving on to more complex projects!

What is Java?

Java is a versatile, object-oriented programming language developed by Sun Microsystems (now owned by Oracle). Known for its platform independence and strong community support, Java has become a staple for developing everything from desktop to web applications.