SyntaxStudy
Sign Up
Java Java Program Structure and Basic I/O
Java Beginner 1 min read

Java Program Structure and Basic I/O

Every Java program is organized around classes. A public class must be declared in a file whose name matches the class name exactly. A class can contain fields (data), constructors (initialization), and methods (behaviour). The main method is the starting point from which all execution flows. Java is strictly typed, meaning every variable must have a declared type before use. Reading input from the user is handled through System.in, which is typically wrapped in a Scanner for convenient line and token reading. Writing output is done through System.out (for normal output) and System.err (for error messages). The println method appends a newline; print does not; printf allows C-style format strings. Exception handling is built into Java via the try-catch-finally construct. Checked exceptions must be declared or handled; unchecked exceptions (subclasses of RuntimeException) do not need to be declared. Good Java programs handle exceptions gracefully, logging errors or providing user-friendly messages rather than letting the program crash with a stack trace.
Example
import java.util.InputMismatchException;
import java.util.Scanner;

// File: BasicIO.java - demonstrates Scanner input and formatted output

public class BasicIO {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("=== Java Basic I/O Demo ===");
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        int age = 0;
        boolean valid = false;
        while (!valid) {
            System.out.print("Enter your age: ");
            try {
                age = scanner.nextInt();
                if (age < 0 || age > 150) {
                    System.out.println("Age must be between 0 and 150. Try again.");
                } else {
                    valid = true;
                }
            } catch (InputMismatchException e) {
                System.out.println("Please enter a whole number.");
                scanner.nextLine(); // discard bad input
            }
        }

        // Formatted output using printf
        System.out.printf("%nHello, %s! You are %d years old.%n", name, age);
        System.out.printf("In 10 years you will be %d.%n", age + 10);

        scanner.close(); // always close resources
    }
}