Start the book by building one connected story instead of isolated snippets. In this chapter, the learner uses plain Java to model product prices, discounts, quantities, cart totals, and checkout rules. The goal is not Spring Boot yet. The goal is to make variables, expressions, conditions, loops, and methods feel useful inside a small e-commerce flow.

Why This Book Starts With One Store Story Instead of Random Java Snippets

EASY

Many Java books teach syntax first and meaning later. This curriculum takes the opposite approach. From the first chapter, the learner works inside one small e-commerce story so every variable, condition, and loop has a job to do. That makes the code easier to remember because it belongs to a real flow: pick a product, apply a discount, count quantity, compute a total, and decide whether checkout is allowed.

This matters because backend work is rarely about isolated syntax. In real systems, logic connects. A price is stored, adjusted, validated, formatted, and later persisted. If you start with connected examples, later chapters about classes, controllers, databases, tests, and microservices feel like natural extensions instead of topic jumps.

At this stage, keep the scope intentionally small. We are not building Spring Boot yet. We are not designing services yet. We are learning how Java code behaves when simple business rules must be expressed clearly and correctly.

  • One continuous project teaches context better than disconnected examples.
  • This chapter focuses on store logic, not frameworks.
  • Every syntax rule is introduced through a price, cart, or checkout example.
  • The end of the chapter should feel like a small but real program milestone.

System.out.println("Welcome to the starter shop");
System.out.println("Today you will calculate totals, discounts, and checkout rules in plain Java.");

Variables and Data Types for Product Names, Prices, Quantities, and Stock

EASY

Variables are the named pieces of information your program must remember while it runs. In a store example, that information might be a product name, a unit price, a quantity, a stock count, or a boolean flag saying whether the customer is premium. The point of learning variables is not to recite syntax. The point is to choose names and types that make the business logic readable.

Begin with simple choices. A product name can be a `String`. A quantity can be an `int`. A customer eligibility flag can be a `boolean`. A beginner example may still use `double` for a price so the syntax stays accessible, but you should already know that money handling becomes more careful later. Good first-step code is not perfect production code. It is clear code that teaches the right mental model.

Naming matters more than many beginners realize. `price` is better than `p`. `quantity` is better than `x`. `premiumCustomer` is better than `flag`. If you can read the variable names and guess the rule before reading the rest of the line, your Java is already improving.

  • Choose a type that matches the meaning of the value.
  • Use names that explain the business idea, not just the storage slot.
  • A boolean should usually sound like a yes-or-no statement.
  • Readable variables make later debugging and refactoring much easier.

String productName = "Wireless Mouse";
double unitPrice = 24.99;
int quantity = 2;
int stockAvailable = 10;
boolean premiumCustomer = true;

Operators and Expressions That Turn Raw Values Into Store Logic

EASY

A variable by itself is only stored data. Expressions turn that data into meaning. In an e-commerce workflow, expressions compute subtotals, compare stock against requested quantity, and decide whether a customer qualifies for a promotion. This is why operators matter so early: they are the glue between facts and decisions.

Arithmetic operators such as `+`, `-`, `*`, and `/` let you build price formulas. Comparison operators such as `>`, `<`, and `==` let you compare values. Logical operators such as `&&` and `||` let you combine rules. The challenge for beginners is not memorizing the symbols. The challenge is seeing when a long line has become too dense to trust.

A good beginner habit is to split one giant expression into two or three smaller named values. For example, compute `subtotal`, then `discountAmount`, then `finalTotal`. The CPU does not care, but the reader does. That reader is often your future self.

  • Arithmetic expressions calculate business values like subtotal and tax.
  • Comparison operators answer questions such as stock sufficiency or discount eligibility.
  • Logical operators combine multiple business rules into one decision.
  • If one expression feels hard to read, break it into smaller named steps.

double subtotal = unitPrice * quantity;
double discountRate = premiumCustomer ? 0.10 : 0.0;
double discountAmount = subtotal * discountRate;
double totalAfterDiscount = subtotal - discountAmount;

Conditions and Branching for Discounts, Shipping, and Checkout Decisions

MID

A store backend constantly asks decision questions. Is the item in stock? Is the customer premium? Does the order qualify for free shipping? Should checkout continue or stop? Java expresses those questions with branching structures such as `if`, `else if`, and `else`.

Conditions are where beginner code often becomes tangled. The mistake is usually not that the syntax is wrong. The mistake is that the rule order is unclear. For example, an out-of-stock case should usually stop the flow before you worry about shipping discounts. A rule that blocks checkout belongs near the top of the decision chain, not buried near the bottom.

The strongest beginner solutions keep each branch readable and purposeful. If the branches start to feel too large, that is often a sign that a helper method should take over part of the logic. That exact instinct becomes more important in later chapters when the codebase grows.

  • Branching is how business rules become executable decisions.
  • Put blocking rules early so the flow is easier to trust.
  • Prefer clear, ordered branches over clever compressed conditionals.
  • If a branch gets too large, it may want to become a method.

if (quantity > stockAvailable) {
    System.out.println("Checkout blocked: not enough stock.");
} else if (subtotal >= 100.0) {
    System.out.println("Order qualifies for free shipping.");
} else {
    System.out.println("Standard shipping applies.");
}

Loops and Iteration for Cart Totals, Item Counts, and Validation Passes

MID

One product is enough to teach variables. A cart teaches iteration. As soon as multiple items exist, you need a way to process them one by one. That is where loops stop being syntax drills and become actual business tools.

A `for` loop is a natural place to compute a running total, count how many items are in a cart, or find whether any line item breaks a rule. A `while` loop is useful when the program should keep asking for input until the user enters a valid value. The main lesson is not which loop is more 'Java'. The lesson is that repeated work should be expressed clearly and safely.

Loop bugs are common because small boundary mistakes have big effects. Starting at the wrong index, stopping one step too early, or forgetting to update an accumulator can produce totals that look believable but are still wrong. That is why cart examples are excellent beginner training: the output is simple enough to verify with your own eyes.

  • Loops process repeated cart data one item at a time.
  • Accumulators are the backbone of total and count logic.
  • Off-by-one mistakes are easy to write and hard to notice without checking examples.
  • A believable output can still be wrong if the loop logic is wrong.

double[] lineTotals = {19.99, 8.50, 42.00};
double grandTotal = 0.0;

for (int i = 0; i < lineTotals.length; i++) {
    grandTotal += lineTotals[i];
}

System.out.println("Grand total: " + grandTotal);

Methods That Keep Price Rules and Checkout Flow Small Enough to Trust

MID

Beginners often write the whole program inside `main`, which works for tiny demos but quickly becomes hard to read. Methods solve that by giving names to reusable pieces of logic. In a store example, one method can calculate a subtotal, another can decide the discount rate, and another can print the receipt.

The key benefit is not only reuse. The deeper benefit is separation of intent. When you read `calculateDiscountRate(…)`, you immediately know what the code is trying to do even before opening the method body. That is a major step toward clean backend design.

At this stage, methods should stay small and focused. A method that calculates a subtotal should not also print the receipt and validate shipping eligibility. One method, one job, clear name. That habit scales well into later chapters on classes, services, and testing.

  • Methods reduce duplication and improve readability.
  • A good method name explains intent before you read the body.
  • Small focused methods are easier to test and debug later.
  • If one method does many unrelated things, split it.

static double calculateSubtotal(double unitPrice, int quantity) {
    return unitPrice * quantity;
}

static double calculateDiscountRate(boolean premiumCustomer, double subtotal) {
    if (premiumCustomer && subtotal >= 50.0) {
        return 0.10;
    }
    return 0.0;
}

Console Input and Output for a First Shop Prototype

MID

Even a very small program feels more real when it accepts input and produces output that a user can follow. Console work is not the final destination for a backend engineer, but it is a practical training ground because it forces you to think about what information enters the system and what result the system should report.

Input is where beginner programs first meet messy reality. Users can type values in the wrong order or use unexpected formats. Output is where clarity matters: if the receipt text is confusing, the code may still run but the feature is still poor. Good output is part of good programming.

This chapter uses console input and output as a lightweight interface around the store logic. Later chapters will move that logic behind classes and APIs, but the mental model starts here: receive a request, compute the result, and present the outcome clearly.

  • Input introduces uncertainty, so reading and validating values matters.
  • Output should explain the result, not just dump raw numbers.
  • Business calculations should stay separate from formatting when possible.
  • Console work is simple, but it teaches the same request-response mindset used later in APIs.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter quantity: ");
int quantity = scanner.nextInt();
System.out.println("Items requested: " + quantity);

Mini Project: Build a Starter Checkout Estimator in Plain Java

ADVANCED

By this point, the learner has enough Java to build a small but complete console workflow. The program can collect a few values, compute a subtotal, apply a discount, evaluate shipping, and print a result. That is still a small program, but it is already recognizably product logic.

The most important lesson here is composition. Variables, expressions, conditions, loops, and methods are not isolated topics anymore. They now cooperate inside one workflow. That is the shift from 'I learned syntax' to 'I used syntax to build behavior'.

A good Chapter 1 mini project does not aim to be architecturally complete. It aims to be coherent. The code should be small enough to understand in one sitting, but rich enough to reveal why later chapters on classes, encapsulation, testing, and Spring Boot are worth learning.

  • The first milestone is a working flow, not a perfect architecture.
  • This mini project combines all core Chapter 1 skills in one place.
  • The result should be easy to run, read, and improve.
  • The next chapter exists because this code will soon want better structure.

double subtotal = calculateSubtotal(unitPrice, quantity);
double discountRate = calculateDiscountRate(premiumCustomer, subtotal);
double discountAmount = subtotal * discountRate;
double shippingFee = subtotal >= 100.0 ? 0.0 : 7.99;
double finalTotal = subtotal - discountAmount + shippingFee;

System.out.println("Subtotal: " + subtotal);
System.out.println("Discount: " + discountAmount);
System.out.println("Shipping: " + shippingFee);
System.out.println("Final total: " + finalTotal);

Reading Bugs Early and Preparing for the Move Into Classes

ADVANCED

The last step in a beginner chapter should be reflection, not just celebration. This is the moment to ask which mistakes now feel recognizable. Maybe a discount was applied before checking stock. Maybe a loop skipped the last item. Maybe a method did too many jobs. These are not advanced framework bugs. They are foundational reasoning bugs, and learning to spot them now pays off later.

This is also the point where Chapter 1 reaches its natural limit. The code works, but the data is still loose. Product information is scattered across variables. Cart logic is procedural. Receipt output is mixed with calculation steps. That is exactly why Chapter 2 should introduce classes and objects.

In other words, Chapter 1 succeeds when the learner can do two things at once: write correct beginner Java and feel the need for better structure. That tension is what makes the next chapter meaningful.

  • Debugging starts with reading the business rule, not guessing at syntax.
  • Foundational bugs often come from wrong order, wrong boundary, or wrong variable use.
  • Procedural code can work and still signal that structure is missing.
  • Classes become useful when the program starts carrying richer state.

double subtotal = unitPrice * quantity;
if (subtotal > 100.0) {
    subtotal = subtotal - 10.0;
}
if (quantity > stockAvailable) {
    System.out.println("Not enough stock");
}

// The program applied a discount before validating stock.
// That kind of rule-order bug is exactly what this chapter should teach you to notice.

Chapter takeaway

Strong beginner Java means you can read and write store logic with confidence: choose the right variable, build a safe expression, branch on a business rule, loop through cart data, and extract clear helper methods before moving into classes.