Week 1

Environment setup

How Java works

Types and Variables

Arrays

Basic IO

Control Flow

Packages

OOP in Java

Static Members

Practice

Assignment

Back end Track

🎯 Learning Objectives

By the end of this module, you will be able to:


1. Printing Output — Three Ways

Java gives you three methods for printing to the terminal. Choosing the right one keeps your output clean and predictable.

System.out.println — print and move to next line

The one you've used most so far. Prints the value and adds a newline at the end.

System.out.println("Hello");
System.out.println("World");
// Hello
// World

System.out.print — print without a newline

Output stays on the same line. The next print continues from where this one left off.

System.out.print("Hello");
System.out.print(", ");
System.out.print("World");
// Hello, World

System.out.printf — formatted print

The most powerful option. Lets you control exactly how values are embedded and displayed in a string using format specifiers. No automatic newline — you add \\\\n yourself when needed.

System.out.printf("Hello, %s! You are %d years old.%n", "Alice", 28);
// Hello, Alice! You are 28 years old.

💡 %n is the platform-safe newline for printf — it works correctly on Windows, Mac, and Linux. You can also use \\\\n but %n is preferred in formatted strings.


2. String Formatting with printf

printf works by placing format specifiers as placeholders inside a string. Each specifier is replaced by the corresponding argument in order.

System.out.printf("Name: %s, Age: %d, Score: %.2f%n", "Bob", 22, 94.5678);
// Name: Bob, Age: 22, Score: 94.57

Common Format Specifiers

Specifier Type Example Output
%s String printf("%s", "Alice") Alice
%d Integer (int, long) printf("%d", 42) 42
%f Decimal (double, float) printf("%f", 3.14) 3.140000
%.2f Decimal, 2 decimal places printf("%.2f", 3.14159) 3.14
%b Boolean printf("%b", true) true
%c Character printf("%c", 'A') A
%n Newline printf("Hi%n") Hi + newline

Controlling Width & Alignment

You can pad output to a fixed width — useful for building aligned tables:

System.out.printf("%-15s %5d %8.2f%n", "Apple",  120, 1.50);
System.out.printf("%-15s %5d %8.2f%n", "Banana",  85, 0.75);
System.out.printf("%-15s %5d %8.2f%n", "Blueberry", 200, 3.99);
// Apple             120     1.50
// Banana             85     0.75
// Blueberry         200     3.99

🔍 Coming from JS, printf is similar to template literals but more explicit about types and alignment. There's no direct equivalent in vanilla JS — you'd typically use a library or manual padding for formatted tables.


3. Reading User Input with Scanner

To read input from the terminal, Java uses the Scanner class from java.util. You need to import it and create one Scanner object connected to System.in (the keyboard).

import java.util.Scanner;

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

        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        System.out.println("Hello, " + name + "!");

        scanner.close(); // good practice — release the resource when done
    }
}

Reading Different Types

Use the right method for the type of input you expect:

Scanner scanner = new Scanner(System.in);

System.out.print("Enter your name: ");
String name = scanner.nextLine();       // reads a full line of text

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

System.out.print("Enter your height (m): ");
double height = scanner.nextDouble();   // reads a decimal number

System.out.printf("Name: %s | Age: %d | Height: %.2fm%n", name, age, height);
Method Reads Notes
nextLine() Full line (including spaces) Reads until Enter
nextInt() Integer only Stops at whitespace
nextDouble() Decimal number Stops at whitespace
next() Single word Stops at whitespace

4. The Scanner Newline Quirk

This is one of the most common gotchas for beginners. When you call nextInt() or nextDouble(), Scanner reads the number but leaves the newline character (\\\\n) from pressing Enter still waiting in the input buffer.

The very next nextLine() call will immediately consume that leftover newline and return an empty string — skipping your input prompt entirely.

Scanner scanner = new Scanner(System.in);

System.out.print("Enter your age: ");
int age = scanner.nextInt();        // reads "25", leaves "\\\\n" in buffer

System.out.print("Enter your name: ");
String name = scanner.nextLine();   // ⚠️ instantly reads the leftover "\\\\n"
                                    // name = "" — user never got to type!

System.out.println("Name: " + name); // Name:   ← empty!

The Fix — consume the leftover newline

Call scanner.nextLine() immediately after nextInt() or nextDouble() to flush the buffer before reading a String:

Scanner scanner = new Scanner(System.in);

System.out.print("Enter your age: ");
int age = scanner.nextInt();
scanner.nextLine();                  // ✅ flush the leftover newline

System.out.print("Enter your name: ");
String name = scanner.nextLine();    // now reads correctly

System.out.printf("Name: %s, Age: %d%n", name, age);

💡 A simple rule: always add scanner.nextLine() after nextInt() or nextDouble() if you plan to read a String next. Make it a habit and you'll never hit this bug.


✏️ Exercise — Build a CLI Personal Profile Card

Put everything in this module together to build a small interactive CLI program.

What it should do

  1. Greet the user and ask for the following inputs — in this order:
  2. Calculate:
  3. Print a formatted profile card that looks exactly like this (values will vary):
╔══════════════════════════════════════╗
         PERSONAL PROFILE CARD
╚══════════════════════════════════════╝
  Name        : Alice van der Berg
  Age         : 31
  City        : Amsterdam
  Rate        : €22.50 / hr
  Hours       : 160 hrs
  Monthly Pay : €3,600.00
══════════════════════════════════════

Requirements

Bonus Challenge

Add input validation: if the user enters an age below 0 or above 120, print an error message and ask again. Hint: you'll need a loop from Module 4 — Control Flow.


📚 Key Takeaways