Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 02 / Stage 1

Language fundamentals

Goal: Declare typed variables, pick the right primitive type, work with String, cast safely between types, read input with Scanner, and use var and text blocks. Time: ~6 hours

Assumes: Part 1 only — you can compile with javac and run with java, and you know a Java program needs a class and a main method. Nothing from Part 3 onward is used here: no if/else, no loops, no arrays/collections, no methods other than main. Every example runs top to bottom, one line at a time.

What you will learn

  • Variables: a fixed type, a name, a value — and how that is different from Python
  • The eight primitive types, their ranges, and String (not a primitive)
  • Operators: arithmetic, comparison, logical, assignment, bitwise, and precedence
  • String methods, concatenation, and why strings never change in place
  • Type casting: widening (automatic) vs. narrowing (explicit), and the int/double division trap
  • Reading input with Scanner
  • var: local type inference (not dynamic typing)
  • Text blocks for multi-line text
  • Putting it together: a restaurant bill splitter

Topics in this part

Practice

Write each answer as its own class ExNN with a main method, saved as solutions/exNN.java (lowercase file, matching class ExNN inside — see solutions/ex01.java for the pattern). Use only what Part 1 and Part 2 teach: no if/else, no loops, no arrays/collections, no methods beyond main. Every program runs top to bottom, one line at a time. Where the exercise reads input, the sample output shows the prompt and the typed answer together, the way they appear in a real terminal.


Exercise 1: A chai stall order

Scenario: Ravi runs a small chai stall and wants a quick order summary printed to the screen. What to do: Inside main():

  1. Declare String itemName = "Masala Chai", int quantity = 3, double unitPrice = 15.0, boolean isPaid = false.
  2. Compute double total = quantity * unitPrice.
  3. Print itemName, quantity, unitPrice, total and isPaid, each on its own labelled line.
  4. Set isPaid = true and print it again with a different label.

Sample output:

Item     : Masala Chai
Quantity : 3
Price    : 15.0
Total    : 45.0
Paid     : false
Paid now : true

💡 Hint: int * double widens the int automatically, so total is a double without any cast.


Exercise 2: Grams, kilometres and a truck full of parcels

Scenario: A courier app stores weight in grams and needs kilograms; it also needs a rough, rounded-down distance, and a quick check on how many truck trips a batch of parcels needs. What to do: Inside main():

  1. int weightGrams = 2750; then compute weightKg by dividing by 1000.0 (a double literal) and print it.
  2. double distanceKm = 12.8; then narrow it to an int with an explicit cast and print it.
  3. int totalParcels = 7; and int truckCapacity = 2;. Print totalParcels / truckCapacity (plain int division).
  4. Print the same division again, this time casting one side to double first.

Sample output:

2.75
12
3
3.5

💡 Hint: dividing by 1000.0 (not 1000) is what forces the division to produce a double — the type of the variable you store the result in does not matter, only the types of the two values being divided.


Exercise 3: Cleaning up a messy customer name

Scenario: An online order form hands you " asha KULKARNI " — extra spaces, wrong case — and you need it ready for an invoice. What to do: Inside main(), with String rawName = " asha KULKARNI ";:

  1. Trim it into cleaned and print it inside square brackets, e.g. [asha KULKARNI], so the trimming is visible.
  2. Print the length of rawName and of cleaned.
  3. Lower-case cleaned, then build titled by capitalising only the very first letter (substring(0, 1).toUpperCase() plus the rest) and print it.
  4. Print whether the lower-cased, trimmed name contains "kulkarni" and whether it starts with "asha".
  5. Print an "initial" made from the first letter of cleaned, upper-cased, plus a full stop.

Sample output:

Cleaned    : [asha KULKARNI]
Raw length : 17
Trim length: 13
Titled     : Asha kulkarni
Contains kulkarni: true
Starts with asha : true
Initial    : A.

💡 Hint: substring(0, 1) is a one-character String, not a char; that is why .toUpperCase() works directly on it.


Exercise 4: A kirana store calculator

Scenario: A kirana (grocery) store owner wants to type in one item at a time and see the bill with GST added. What to do: Inside main(), using Scanner:

  1. Read the item name with nextLine(), the quantity with nextInt(), and the price per unit with nextDouble(), in that order (no leftover-newline fix is needed for this order).
  2. Compute subtotal = quantity * price, gst = subtotal * 0.05 (store the rate in a final double GST_RATE), and total = subtotal + gst.
  3. Print the item name, then subtotal, GST and total, each formatted to 2 decimal places with System.out.printf.

Sample run (typed: Toor Dal, 5, 140.0):

Item name: Toor Dal
Quantity: 5
Price per unit (₹): 140.0
---
Item     : Toor Dal
Subtotal : ₹700.00
GST (5%) : ₹35.00
Total    : ₹735.00

💡 Hint: printf's %% prints one literal % character — you need it for the "GST (5%%)" label.


Exercise 5: Rewriting with var

Scenario: A junior developer wrote a cart-discount calculation with explicit types and asked you to shorten it with var without changing what it computes. What to do: Inside main(), write every variable below with var (add a same-line comment stating the inferred type, as practice):

  1. cartTotal = 1499.0, memberDiscountRate = 0.10, finalPrice = cartTotal - cartTotal * memberDiscountRate. Print all three, labelled.
  2. customerCity = "PUNE", isPune = customerCity.equalsIgnoreCase("pune"). Print both, labelled.
  3. orderCount = 3, averageOrderValue = finalPrice / orderCount. Print both, labelled.

Sample output:

Cart total  : 1499.0
Discount    : 0.1
Final price : 1349.1
City        : PUNE
Is Pune     : true
Orders      : 3
Avg order   : 449.7

💡 Hint: var's inferred type for finalPrice is double, because cartTotal (a double) is on both sides of the subtraction — var reads the type from the expression on the right, just like the compiler always does.


Exercise 6: A text-block thank-you note

Scenario: A shop wants a short, neatly formatted thank-you note printed after every order, built from a text block instead of a string full of \n. What to do: Inside main():

  1. Declare String shopName = "Spice Garden", String customerName = "Meera", int orderId = 1042, double amount = 875.50.
  2. Build a text block with four lines: the shop name, "Order #<id>", "Dear <name>," then "Your bill amount is ₹<amount>." on the next line, and a closing thank-you line — using %s, %d and %.2f placeholders and .formatted(...).
  3. Print it with System.out.print (not println, since the text block already ends in a newline).

Sample output:

Spice Garden
Order #1042
Dear Meera,
Your bill amount is ₹875.50.
Thank you for ordering with us!

💡 Hint: the text block's closing """ must be the least-indented line, or the printed text keeps unwanted leading spaces.


Exercise 7: Restaurant bill splitter

Scenario: This is the part's capstone — the full restaurant bill splitter, built from everything above: typed variables, Scanner input, careful int/double division, and a text-block receipt. What to do: Inside main(), using Scanner:

  1. Read the restaurant name (nextLine()), the food subtotal (nextDouble()), the number of people (nextInt()) and a tip percent as a whole number like 12 meaning 12% (nextInt()).
  2. GST is a fixed final double GST_RATE = 0.05. Compute gst = subtotal * GST_RATE.
  3. Compute tip = subtotal * (tipPercent / 100.0) — note the 100.0, not 100, so the division is not thrown away.
  4. Compute total = subtotal + gst + tip and perPerson = total / people.
  5. Print a text-block receipt with the restaurant name, subtotal, GST, tip (showing the percent used), total and per-person share, money formatted as ₹%,.2f.

Sample run (typed: Cafe Rupee, 1800, 3, 12):

Restaurant name: Cafe Rupee
Food subtotal (₹): 1800
Number of people: 3
Tip percent (e.g. 10 for 10%): 12
---------------------------
Cafe Rupee
---------------------------
Subtotal  : ₹1,800.00
GST (5%)  : ₹90.00
Tip (12%) : ₹216.00
---------------------------
Total     : ₹2,106.00
Per head  : ₹702.00 (3 people)
---------------------------

💡 Hint: read the String (nextLine()) before the numbers here, and there is no leftover-newline problem, because no nextLine() call follows a nextInt()/nextDouble() in this exercise. If you reorder the reads so a nextLine() comes right after a nextInt()/nextDouble(), you will need the throwaway scanner.nextLine(); fix from section 6 of the lesson.

Show the solutions for Part 2 (7 files)

solutions/ex01.java

class Ex01 {
    public static void main(String[] args) {
        String itemName = "Masala Chai";
        int quantity = 3;
        double unitPrice = 15.0;
        boolean isPaid = false;

        double total = quantity * unitPrice;

        System.out.println("Item     : " + itemName);
        System.out.println("Quantity : " + quantity);
        System.out.println("Price    : " + unitPrice);
        System.out.println("Total    : " + total);
        System.out.println("Paid     : " + isPaid);

        isPaid = true;
        System.out.println("Paid now : " + isPaid);
    }
}

solutions/ex02.java

class Ex02 {
    public static void main(String[] args) {
        int weightGrams = 2750;
        double weightKg = weightGrams / 1000.0;    // int divided by a double literal: widens first
        System.out.println(weightKg);

        double distanceKm = 12.8;
        int roundedDown = (int) distanceKm;         // narrowing cast: cuts the decimal, no rounding
        System.out.println(roundedDown);

        int totalParcels = 7;
        int truckCapacity = 2;
        System.out.println(totalParcels / truckCapacity);              // int / int: decimal part thrown away
        System.out.println((double) totalParcels / truckCapacity);     // cast one side first
    }
}

solutions/ex03.java

class Ex03 {
    public static void main(String[] args) {
        String rawName = "  asha KULKARNI  ";

        String cleaned = rawName.trim();
        System.out.println("Cleaned    : [" + cleaned + "]");
        System.out.println("Raw length : " + rawName.length());
        System.out.println("Trim length: " + cleaned.length());

        String lower = cleaned.toLowerCase();
        String titled = lower.substring(0, 1).toUpperCase() + lower.substring(1);
        System.out.println("Titled     : " + titled);

        System.out.println("Contains kulkarni: " + cleaned.toLowerCase().contains("kulkarni"));
        System.out.println("Starts with asha : " + cleaned.toLowerCase().startsWith("asha"));

        String initial = cleaned.substring(0, 1).toUpperCase() + ".";
        System.out.println("Initial    : " + initial);
    }
}

solutions/ex04.java

import java.util.Scanner;

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

        System.out.print("Item name: ");
        String itemName = scanner.nextLine();

        System.out.print("Quantity: ");
        int quantity = scanner.nextInt();

        System.out.print("Price per unit (₹): ");
        double price = scanner.nextDouble();

        final double GST_RATE = 0.05;
        double subtotal = quantity * price;
        double gst = subtotal * GST_RATE;
        double total = subtotal + gst;

        System.out.println("---");
        System.out.printf("Item     : %s%n", itemName);
        System.out.printf("Subtotal : ₹%.2f%n", subtotal);
        System.out.printf("GST (5%%) : ₹%.2f%n", gst);
        System.out.printf("Total    : ₹%.2f%n", total);

        scanner.close();
    }
}

solutions/ex05.java

class Ex05 {
    public static void main(String[] args) {
        var cartTotal = 1499.0;              // double
        var memberDiscountRate = 0.10;        // double
        var finalPrice = cartTotal - cartTotal * memberDiscountRate;   // double

        System.out.println("Cart total  : " + cartTotal);
        System.out.println("Discount    : " + memberDiscountRate);
        System.out.println("Final price : " + finalPrice);

        var customerCity = "PUNE";             // String
        var isPune = customerCity.equalsIgnoreCase("pune");   // boolean
        System.out.println("City        : " + customerCity);
        System.out.println("Is Pune     : " + isPune);

        var orderCount = 3;                    // int
        var averageOrderValue = finalPrice / orderCount;   // double
        System.out.println("Orders      : " + orderCount);
        System.out.println("Avg order   : " + averageOrderValue);
    }
}

solutions/ex06.java

class Ex06 {
    public static void main(String[] args) {
        String shopName = "Spice Garden";
        String customerName = "Meera";
        int orderId = 1042;
        double amount = 875.50;

        String note = """
                %s
                Order #%d
                Dear %s,
                Your bill amount is ₹%.2f.
                Thank you for ordering with us!
                """.formatted(shopName, orderId, customerName, amount);

        System.out.print(note);
    }
}

solutions/ex07.java

import java.util.Scanner;

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

        System.out.print("Restaurant name: ");
        String restaurantName = scanner.nextLine();

        System.out.print("Food subtotal (₹): ");
        double subtotal = scanner.nextDouble();

        System.out.print("Number of people: ");
        int people = scanner.nextInt();

        System.out.print("Tip percent (e.g. 10 for 10%): ");
        int tipPercent = scanner.nextInt();

        final double GST_RATE = 0.05;                     // 5% GST on restaurant food, fixed
        double gst = subtotal * GST_RATE;
        double tip = subtotal * (tipPercent / 100.0);      // int percent -> fraction, needs a double divisor
        double total = subtotal + gst + tip;
        double perPerson = total / people;

        String receipt = """
                ---------------------------
                %s
                ---------------------------
                %-10s: ₹%,.2f
                %-10s: ₹%,.2f
                %-10s: ₹%,.2f
                ---------------------------
                %-10s: ₹%,.2f
                %-10s: ₹%,.2f (%d people)
                ---------------------------
                """.formatted(restaurantName,
                "Subtotal", subtotal,
                "GST (5%)", gst,
                "Tip (" + tipPercent + "%)", tip,
                "Total", total,
                "Per head", perPerson, people);

        System.out.print(receipt);

        scanner.close();
    }
}

Common mistakes

Mistake Why it is wrong Fix
int total = 7 / 2; then expecting 3.5 Both operands are int, so the division is int division first Cast one side: (double) 7 / 2
price = "249"; A variable's type is fixed forever Cast the text instead: price = Integer.parseInt("249");
if (name == "Asha") (Part 3, mentioned here as a trap to avoid) == on strings checks object identity, not text name.equals("Asha")
scanner.nextInt(); scanner.nextLine(); expecting the next real line The leftover Enter key newline is read as an empty line Add a throwaway scanner.nextLine(); right after nextInt()/nextDouble()
var x; var needs a value to infer the type from Always initialise: var x = 0;
byte b = 127; b = b + 1; and expecting 128 Silent overflow: no error, just wraps to -128 Pick a bigger type (int, long) when the value might not fit
float price = 19.99; for money float/double cannot represent most decimals exactly Use double and round only for display (%.2f), or BigDecimal for exact money math (Stage 2)
Forgetting final on a value that should never change Nothing stops a later line from changing it by mistake Mark true constants final, in UPPER_SNAKE_CASE

Quick recap

  • A Java variable has one fixed type, forever; == on a primitive compares the value directly.
  • The eight primitives: byte, short, int, long, float, double, char, boolean. String is a class, not a primitive.
  • Widening is automatic and safe; narrowing needs (type) and can lose data or overflow silently.
  • int / int is always int — cast one side to double before dividing if you need a decimal answer.
  • Strings are immutable; every method returns a new string. Compare text with equals(), never ==.
  • Scanner reads nextInt()/nextDouble()/nextLine(); clear the leftover newline before a nextLine() call.
  • var infers the type once, at compile time — it is not dynamic typing.
  • Text blocks (""") make multi-line text easy to read; .formatted(...) fills in values.

Checklist

  • I can declare variables of each primitive type and explain why String is not one of them.
  • I can explain widening vs. narrowing, and predict when a cast loses data.
  • I know why 7 / 2 is 3 and how to get 3.5 instead.
  • I can use at least six String methods and explain why none of them change the original string.
  • I know to use equals(), never ==, to compare string text.
  • I can read mixed int/double/String input with Scanner without the leftover-newline bug.
  • I can use var correctly and explain why it is not dynamic typing.
  • I can write a multi-line text block and fill in values with .formatted(...).
  • I built the restaurant bill splitter end to end, using only tools from this part.

Search the guide