Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Basics

Java Practice Lab: A Cafe Bill with Variables, Operators and Casting

A small cafe order desk in Java: Riya orders three cups at 180, tax is 27.0, the total is 567, and two friends pay 283 each with 1 left over. Plus the four traps that give a wrong number with no error.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Basics

What you will learn

  • Combine variables, primitive types, strings, operators and casting in one program
  • Work out tax and a bill split with int division and modulo
  • Spot four silent traps: int overflow, text joining with +, int division and narrowing casts
  • Read operator precedence in a mixed && / || condition

Before you start

  • Java operators and expressions
  • Java type casting and conversions

Time to use the fundamentals together. This lab is a small cafe order desk: Riya orders three cups, and the program prints a bill with tax, a total and a split between friends. Along the way you'll hit the four traps that give a wrong number with no error at all.

The full cafe bill

package org.studyeasy.s02l08;

public class Lab1_CafeBill {
    public static void main(String[] args) {
        String customer = "Riya";                      // variables
        int cups = Integer.parseInt("3");              // text -> number
        int pricePerCup = 180;                         // primitive type
        double tax = cups * pricePerCup * 0.05;        // operators
        int total = (int) (cups * pricePerCup + tax);  // casting
        int friends = 2;

        System.out.println("""
                ---- StudyEasy Cafe ----""");
        System.out.println("Customer: " + customer);
        System.out.println("Cups: " + cups + " x " + pricePerCup);
        System.out.println("Tax: " + tax);
        System.out.println("Total: " + total);
        System.out.println("Each pays: " + total / friends);
        System.out.println("Leftover: " + total % friends);
    }
}
---- StudyEasy Cafe ----
Customer: Riya
Cups: 3 x 180
Tax: 27.0
Total: 567
Each pays: 283
Leftover: 1

Each line uses one idea:

  • customer is a String; cups and pricePerCup are ints.
  • Integer.parseInt("3") turns text (as it might arrive from an order form) into the number 3.
  • 3 x 180 x 0.05 gives the tax, 27.0. One side is a double, so the result is a double.
  • 540 + 27.0 is 567.0, and the (int) cast turns it into 567. Remove the cast and javac reports a lossy conversion from double to int.
  • / and % split it: 283 each, 1 left over.
The bill flows: text "3" is parsed to 3 cups; 3 times 180 is 540; tax at 5 percent is 27.0; total 567.0 is cast to 567; 567 divided by 2 is 283 each with 1 left over. "3"parseInt 3 x 180= 540 tax 5%= 27.0 (double) (int) 567.0= 567 567 / 2 = 283567 % 2 = 1 Variables, operators, strings and casting each do one job on the way to the bill.
From the text "3" to 283 each: every step uses one fundamental.

The four silent traps

The lab's smaller programs each set up one trap. All four compile and run; they just print the wrong thing.

1. An int runs out of room

int maxCups = Integer.MAX_VALUE;
System.out.println("int max: " + maxCups);
System.out.println("max + 1: " + (maxCups + 1)); // overflow!
int max: 2147483647
max + 1: -2147483648

Add 1 to the biggest int and it wraps to the smallest. That's why Ex02_CafeTypes stores 3.45 billion cups in a long (3_450_000_000L), picks char for the cup size 'M' and a byte for three baristas: the smallest type that fits.

2. Text joins left to right

System.out.println("Total: " + 2 + 3);   // trap: joins text
System.out.println("Total: " + (2 + 3)); // brackets do maths first
Total: 23
Total: 5

Once the left side is text, every + joins. Brackets make the numbers add first.

3. Int division and a hidden zero

package org.studyeasy.s02l08;

public class Ex04_BillOperators {
    public static void main(String[] args) {
        int subtotal = 180 * 3;          // 3 cups at 180
        int tax = subtotal * 5 / 100;    // 5% tax, whole rupees
        int total = subtotal + tax;
        System.out.println("Total: " + total);

        int friends = 4;
        System.out.println("Each pays: " + total / friends);
        System.out.println("Leftover: " + total % friends);

        boolean isMember = false;
        boolean isBirthday = true;
        boolean freeCookie = total > 500 && isMember || isBirthday;
        System.out.println("Free cookie? " + freeCookie);
    }
}
Total: 567
Each pays: 141
Leftover: 3
Free cookie? true

Java goes left to right: 540 x 5 = 2700, then / 100 = 27. Write subtotal * (5 / 100) instead and 5 / 100 is 0 in int maths, so the tax disappears. Four friends pay 141 each with 3 left over (4 x 141 + 3 = 567).

The cookie line shows precedence: && runs before ||. total > 500 && isMember is false (not a member), then false || isBirthday is true.

4. Narrowing casts cut and wrap

int cupsSold = 7;
int days = 2;
System.out.println("Avg (int maths): " + cupsSold / days);
System.out.println("Avg (widened): " + (double) cupsSold / days);

double bill = 567.90;
int cash = (int) bill;           // cuts decimals, no rounding
System.out.println("Cash register: " + cash);

byte tiny = (byte) 130;          // byte only holds -128..127
System.out.println("(byte) 130 = " + tiny);

String amountText = String.valueOf(cash);
System.out.println(amountText + 10);                    // text
System.out.println(Integer.parseInt(amountText) + 10);  // number
Avg (int maths): 3
Avg (widened): 3.5
Cash register: 567
(byte) 130 = -126
56710
577

Cast before dividing to keep the .5. (int) 567.90 cuts to 567; it never rounds. 130 doesn't fit in a byte, so it wraps to -126. And "567" + 10 joins to 56710, while the parsed number gives 577.

Recap

TrapExampleFix
OverflowInteger.MAX_VALUE + 1 is negativeUse long for big counts
Text joining"Total: " + 2 + 3 is 23Brackets: (2 + 3)
Int division5 / 100 is 0Multiply first, or use a double
Narrowing cast(byte) 130 is -126Pick a type that fits

Try it yourself: change the lab to three friends and a 10% tax. Work out the expected total, each share and the leftover on paper first, then run it and compare.

Keep going in Java · 10 of 79

Previous
Java Type Casting: Widening, Narrowing and Converting Text to Numbers
Next post
Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program

Install JDK 25 (Microsoft Build of OpenJDK) with JAVA_HOME, install IntelliJ IDEA, then point a run configuration at the JDK and the main class and run Hello World.

Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA

Open IntelliJ's AI Chat, pick Claude Agent (the agent behind Claude Code) or Copilot and a model, ask in plain words for Main.java to print the date and time, review the change, and run it.

Java Hello World with Maven: What the JDK Does and What Maven Adds

javac compiles HelloWorld.java into bytecode and java runs it on the JVM. Maven adds one pom.xml, the same folders in every project and one build command. Then a real Maven Hello World in IntelliJ.

Java Variables, Keywords and Naming Rules

A variable is a labelled jar that holds one value at a time. Four small programs show declaring, reassigning, the names Java accepts, the keywords it reserves, and why daysUntilLaunch beats d.

On this page

  • The full cafe bill
  • The four silent traps
  • 1. An int runs out of room
  • 2. Text joins left to right
  • 3. Int division and a hidden zero
  • 4. Narrowing casts cut and wrap
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.