BRAINBIT INFOTECH · RANCHI
COMPLETE CORE JAVA COURSE · PART 1 OF 5

Java Foundations

Write your first Java programs: output, variables, data types, operators, input, decisions and loops.

5 modules~18 hours50 practice examplesNo coding needed

By the end of this part you can build

  • A fee receipt and a GST bill
  • A grade calculator and an electricity bill
  • A number guessing game and an ATM PIN check
  • Pattern printing and a multiplication table

Every code example has a ▶ Run button. Click ✎ Edit, or press L, to open the Code Lab.

ROADMAP FOR THIS PART

Module 1Meet Java & Your First Program3 h
Module 2Variables, Data Types & Operators4 h
Module 3Input & Output: Scanner, printf & Math3.5 h
Module 4Decisions: if, else & switch3.5 h
Module 5Loops: for, while & do-while4 h
{ } Java java Main.java main()
JavaBefore we begin

How to Use This Part

Suggested teaching hours per module (Part 1)012343 hM14 hM23.5 hM33.5 hM44 hM5

Every module has

  1. 1
    A "Where is it used?" diagram of real projects
  2. 2
    Concept in short + code + terminal: press ▶ Run to watch the output appear
  3. 3
    Step-through animations recorded from the real JVM: variables, method calls, objects
  4. 4
    A Code Lab: edit, copy or download the code and run it with java Main.java
  5. 5
    10 practice examples: 5 Easy, 3 Medium, 2 Hard, with solutions
  6. 6
    An animated recap + quiz
Controls→ next, ← back, M menu, L Code Lab, F fullscreen.
Running JavaEvery output on the slides was produced by compiling and running the code with a real JDK 21, so the slides work offline. On your computer (JDK 11+), run a single file with java Main.java in the folder D:\java-practice.
MODULE 1

Meet Java & Your First Program

⏱ 3 hours10 practice examplesStep-through animationsCode Lab

You will learn

  • What Java is and where it is used
  • How Java runs: javac, bytecode and the JVM
  • JDK vs JRE vs JVM and installing JDK 21
  • The structure of a Java program and the main method
  • println, print, printf, comments and reading errors

You will build

  • A welcome banner for a coaching centre
  • A bus ticket and an ID card
  • A neatly formatted fee receipt
main()javac Main.javaSystem.out
Module 1Real-world use

Where Is This Used in Real Projects?

Javawrite once, run anywhere📱Android appsmillions of phones🏦Bankingcore banking, UPI🚆Ticket bookingrailway, airline🏢IT companiesenterprise software🎮GamesMinecraft (Java)📊Big dataHadoop, Spark, Kafka

Real projects that use this

  • Android apps are built with Java and Kotlin, which both run on the Java platform
  • Banks and payment systems run their core services on Java because it is stable and secure
  • Large IT service companies in India build enterprise projects with Java + Spring Boot
  • Big-data tools like Hadoop and Kafka are written in Java
  • Java is one of the most asked skills in campus placements and fresher jobs
Why learn Java?Java is strongly typed and object-oriented. Once you learn it, C#, Kotlin and C++ feel familiar too.
Module 1The big idea

What Is Java?

Main.javayou writejavaccompilerMain.classbytecodeWindows JVMruns the same .classLinux JVMruns the same .classMac JVMruns the same .classAndroidruns the same .classWrite Once, Run Anywhere (WORA)
💡 Concept in shortJava is a programming language. You write instructions in a .java file, the javac compiler turns them into bytecode, and the JVM runs that bytecode on any computer.
📅

Created 1995

By James Gosling at Sun Microsystems; now maintained by Oracle and the OpenJDK community.
🌐

Platform independent

The same .class file runs on Windows, Linux and Mac.
📦

Object-oriented

Programs are built from classes and objects, like real-world things.
⚡

Safe and fast

Memory is managed for you (garbage collection); the JVM speeds up hot code.
Module 1Tools

JDK, JRE and JVM: Boxes Inside Boxes

JDK = Java Development KitJRE + tools: javac (compiler), jshell, javadoc, jar, debuggerJRE = Java Runtime EnvironmentJVM + standard library (String, Scanner, ArrayList ...)JVM = Java Virtual Machinereads bytecode and runs it on your computer
💡 Concept in shortTo write and compile programs you need the JDK. Inside it is the JRE (to run programs), and inside that is the JVM (the engine).
ToolWho needs itContains
JDKprogrammers (you!)javac, java, jshell + JRE
JREusers who only run appsJVM + libraries
JVMpart of every JREbytecode runner, garbage collector
RememberInstall the JDK, not just the JRE. In this course we use JDK 21 (a Long-Term Support version).
Module 1Set up

Installing JDK 21 on Windows

  1. 1
    Open adoptium.net (Eclipse Temurin, free) or oracle.com/java
  2. 2
    Download JDK 21 (LTS) for Windows x64 (.msi)
  3. 3
    Run the installer; tick Set JAVA_HOME and Add to PATH
  4. 4
    Open a new Command Prompt
  5. 5
    Type java -version and javac -version
  6. 6
    Make a folder D:\java-practice for all programs
Common mistake"javac is not recognized"? The JDK bin folder is not on PATH. Re-run the installer and tick the PATH option, then open a new terminal.
Command Prompt
C:\Users\Student> java -version
openjdk version "21.0.5" 2024-10-15 LTS
OpenJDK Runtime Environment Temurin-21.0.5+11 (build 21.0.5+11-LTS)
OpenJDK 64-Bit Server VM Temurin-21.0.5+11 (build 21.0.5+11-LTS, mixed mode)
Command Prompt
C:\Users\Student> javac -version
javac 21.0.5
EditorsEditors: VS Code + "Extension Pack for Java", or IntelliJ IDEA Community (free). Both run Java with one click.
Module 1First program

Your First Java Program

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 System.out.println("Namaste, Ranchi!");
4 System.out.println("Welcome to Java.");
5 }
6}
Terminal
D:\java-practice> java Main.java
Namaste, Ranchi!
Welcome to Java.
💡 Concept in shortEvery Java program lives inside a class. Java starts running from the main method. Each statement ends with a semicolon ;.
  1. 1
    Save as Main.java (file name = class name)
  2. 2
    Line 1: a class called Main
  3. 3
    Line 2: the main method, where the program starts
  4. 4
    Lines 3-4: print text, each on a new line
  5. 5
    { } braces mark where blocks start and end
Module 1Anatomy

Reading the main Method Word by Word

publicanyone can
call it
staticbelongs to the class,
no object needed
voidreturns
nothing
mainthe starting
point
(String[] args)command-line
inputs
Systembuilt-in class
.outthe screen
.printlnprint + new line
("Hi")what to print
;end of statement
💡 Concept in shortDo not worry about memorising every word now. You will understand public, static and void fully in Modules 6 and 10. For now: copy this line exactly.
RuleExample
Java is case-sensitiveSystem works, system does not
File name = public class nameMain.java holds public class Main
Statements end with ;System.out.println("Hi");
Blocks use { }class body, method body
Module 1Compile and run

Two Ways to Run a Java Program

Classic way: compile, then run
D:\java-practice> javac Main.java
D:\java-practice> java Main
Namaste, Ranchi!
Welcome to Java.
Quick way (JDK 11+): one command
D:\java-practice> java Main.java
Namaste, Ranchi!
Welcome to Java.
💡 Concept in shortjavac Main.java creates Main.class (bytecode). java Main starts the JVM and runs it. For a single file, java Main.java does both steps in memory.
Main.java➜javac➜Main.class➜java (JVM)➜output
In real projectsReal projects use build tools (Maven, Gradle) and IDE Run buttons, but they call javac and java behind the scenes.
Module 1Printing

println, print and printf

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 System.out.println("BrainBit Infotech"); // prints, then new line
4 System.out.print("Ranchi, "); // stays on the same line
5 System.out.print("Jharkhand");
6 System.out.println(); // just a new line
7 System.out.println("Marks: " + 92); // join text and a number
8 System.out.println(10 + 5); // maths first: 15
9 System.out.println("10 + 5 = " + 10 + 5); // careful! text joining
10 System.out.printf("Fee: Rs %d, GST: %.2f%n", 4500, 810.0);
11 }
12}
Terminal
D:\java-practice> java Main.java
BrainBit Infotech
Ranchi, Jharkhand
Marks: 92
15
10 + 5 = 105
Fee: Rs 4500, GST: 810.00
💡 Concept in shortprintln prints and moves to a new line; print stays on the same line; printf prints with a format: %d whole number, %.2f decimal, %s text, %n new line.
Common mistakeLine 9 prints 10 + 5 = 105! After a String, + joins text. Use brackets: "10 + 5 = " + (10 + 5).
Module 1Comments and escapes

Comments and Escape Sequences

Main.java  JAVA
1/*
2 * Program : Fee notice
3 * Author : Your Name
4 */
5public class Main {
6 public static void main(String[] args) {
7 // single-line comment: Java ignores this
8 System.out.println("Name:\tAman"); // \t = tab
9 System.out.println("Line 1\nLine 2"); // \n = new line
10 System.out.println("She said \"Hello\""); // \" = quote
11 System.out.println("Path: D:\\java-practice"); // \\ = one backslash
12 }
13}
Terminal
D:\java-practice> java Main.java
Name: Aman
Line 1
Line 2
She said "Hello"
Path: D:\java-practice
💡 Concept in shortComments are notes for humans: // for one line, /* ... */ for many lines. Escape sequences start with a backslash and put special characters inside text.
EscapeMeans
\nnew line
\ttab
\"double quote
\\backslash
In real projects/** ... */ is a Javadoc comment. Tools turn it into HTML documentation, like the official Java docs.
Module 1Watch it run

How Java Runs Your Program: Top to Bottom

Press Next step. The JVM runs the statements in main one by one, from top to bottom.

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 System.out.println("Good morning, students!");
4 System.out.println("Today: Java class at 10 AM");
5 // this comment is skipped
6 System.out.print("Lab ");
7 System.out.println(2);
8 System.out.println("Have a great day!");
9 }
10}
Output
Module 1Errors are normal

Compile-Time Errors vs Run-Time Errors

1. Compile-time error (javac refuses)

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 System.out.println("Fee is due on 10th")
4 System.out.println("Pay at the office");
5 }
6}
Terminal
D:\java-practice> java Main.java
Main.java:3: error: ';' expected
System.out.println("Fee is due on 10th")
^
1 error

2. Run-time error (crash while running)

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 System.out.println("Total students: 40");
4 System.out.println("Per group: " + 40 / 0);
5 }
6}
Terminal
D:\java-practice> java Main.java
Total students: 40
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:4)
💡 Concept in shortCompile errors are grammar mistakes (missing ;, wrong spelling); nothing runs. Run-time errors (exceptions) happen while running, like dividing by zero. Read the line number and the message.
Module 1Naming

Java Naming Rules and Conventions

ThingConventionExample
ClassPascalCase (each word capital)StudentReport
Method / variablecamelCasetotalMarks, printBill()
ConstantUPPER_SNAKE_CASEGST_RATE
Packageall lowercasecom.brainbit.billing

Allowed names

markstotal_2026$price_countstudentName

Not allowed

2ndPlacemy nameclassintfee-paid
💡 Concept in shortNames can use letters, digits, _ and $, cannot start with a digit, and cannot be a keyword like class or int. Following the conventions makes your code look professional.

Some Java keywords: classpublicstaticvoidintdoubleifelseforwhilereturnnewthistruefalsenull

Module 1Hands-on

Code Lab: Try It Yourself

Main.java
Output of the starter code
D:\java-practice> java Main.java
==============================
WELCOME TO JAVA CLASS
==============================
Name : Your Name
School : Your School, Ranchi
Goal : Build my own Android app!
Change the code, then run it on your computer: ⬇ Download → open a terminal in that folder → java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).
Your tasks
  1. Put your own name, school and goal
  2. Add a line that prints your favourite Jharkhand food
  3. Print the date 08-10-2026 using printf("%02d-%02d-%d%n", 8, 10, 2026)
  4. Remove a semicolon on purpose, run it, and read the error
PracticePractice 1 of 10 · Easy

Coaching Centre Welcome Banner

EasyScenario. BrainBit Infotech Computer Centre shows a welcome banner when the attendance program starts.
💡 Concept used: System.out.println() prints a line of text and moves to the next line.

Your tasks

  1. Print a border of 40 * symbols
  2. Print the centre name, address and phone
  3. Leave one empty line with System.out.println()
  4. Print the border again
🏢 Used in real projects: Command-line tools, billing software and server programs print a banner when they start.
Banner.java  JAVA
1public class Banner {
2 public static void main(String[] args) {
3 System.out.println("****************************************");
4 System.out.println(" BRAINBIT INFOTECH COMPUTER CENTRE");
5 System.out.println();
6 System.out.println(" Main Road, Ranchi, Jharkhand");
7 System.out.println(" Phone: 98765 43210");
8 System.out.println("****************************************");
9 System.out.println(" Welcome! Please mark attendance.");
10 }
11}
PracticePractice 2 of 10 · Easy

Student ID Card with Escape Sequences

EasyScenario. Print a neat student ID card using tabs and new lines.
💡 Concept used: Escape sequences: \t = tab, \n = new line inside a String.

Your tasks

  1. Use \t to line up the values
  2. Use \n to print several lines from one statement
  3. Print a border at the top and bottom
🏢 Used in real projects: Printed slips, SMS templates and text reports use \n and \t to arrange text.
IdCard.java  JAVA
1public class IdCard {
2 public static void main(String[] args) {
3 System.out.println("+-------------------------------+");
4 System.out.println("| DAV PUBLIC SCHOOL, RANCHI |");
5 System.out.println("+-------------------------------+");
6 System.out.println("Name\t: Ananya Kumari\nClass\t: 8 B\nRoll\t: 17\nBlood\t: B+");
7 System.out.println("+-------------------------------+");
8 }
9}
PracticePractice 3 of 10 · Easy

Bus Ticket: Ranchi to Jamshedpur

EasyScenario. A bus counter at Ranchi ITI bus stand prints a ticket for each passenger.
💡 Concept used: print stays on the same line, println ends the line; + joins text with numbers.

Your tasks

  1. Print a border with dashes
  2. Use print + println to build the route line
  3. Join text and numbers with +
  4. Calculate the fare as 280 + 20 inside brackets
🏢 Used in real projects: Ticket counters, parking machines and cinema booking print receipts like this.
BusTicket.java  JAVA
1public class BusTicket {
2 public static void main(String[] args) {
3 System.out.println("----------------------------------");
4 System.out.println(" JHARKHAND TRAVELS");
5 System.out.println("----------------------------------");
6 System.out.print("Route : Ranchi");
7 System.out.println(" -> Jamshedpur");
8 System.out.println("Date : 08-10-2026");
9 System.out.println("Seat : " + 14);
10 System.out.println("Fare : Rs " + (280 + 20));
11 System.out.println("----------------------------------");
12 System.out.println("Happy journey!");
13 }
14}
PracticePractice 4 of 10 · Easy

Fix the Errors (Debugging Challenge)

EasyScenario. The school clerk saved this program as Notice.java, but it does not compile. Find and fix 4 mistakes.
💡 Concept used: Java is case-sensitive, every statement needs ;, Strings need closing quotes, and the public class name must match the file name.

Your tasks

  1. Compile the buggy code and read each error message
  2. Fix one error at a time
  3. Match the expected output exactly
Notice.java (buggy)JAVA
1public class notice {
2 public static void main(String[] args) {
3 System.out.println("Exam Notice")
4 system.out.println("Class 10 maths exam on Monday");
5 System.out.println("Bring your admit card);
6 }
7}
🏢 Used in real projects: Professional developers fix compile errors all day. Reading the line number and message is the key skill.
Notice.java  JAVA
1public class Notice {
2 public static void main(String[] args) {
3 System.out.println("Exam Notice");
4 System.out.println("Class 10 maths exam on Monday");
5 System.out.println("Bring your admit card");
6 }
7}
PracticePractice 5 of 10 · Easy

Marks Calculator in println

EasyScenario. A teacher wants the total and average of 3 subject marks printed quickly.
💡 Concept used: Java can do maths inside println. Brackets make Java calculate before joining text.

Your tasks

  1. Print each subject mark
  2. Print the total with (78 + 85 + 92)
  3. Print the average with (78 + 85 + 92) / 3.0
  4. See why / 3.0 gives decimals
🏢 Used in real projects: Result-processing programs calculate totals and averages before printing report cards.
Marks.java  JAVA
1public class Marks {
2 public static void main(String[] args) {
3 System.out.println("Maths : 78");
4 System.out.println("Science : 85");
5 System.out.println("English : 92");
6 System.out.println("Total : " + (78 + 85 + 92));
7 System.out.println("Average : " + (78 + 85 + 92) / 3.0);
8 System.out.println("Whole-number average: " + (78 + 85 + 92) / 3);
9 }
10}
PracticePractice 6 of 10 · Medium

School Timetable with printf Columns

MediumScenario. The class teacher needs Monday's timetable printed in perfectly aligned columns.
💡 Concept used: printf uses format codes: %-10s = text left-aligned in 10 spaces, %5s = right-aligned in 5.

Your tasks

  1. Print a heading row with printf
  2. Print 5 periods using the same widths
  3. Use %n for new lines
  4. Add a footer line
🏢 Used in real projects: Reports, bank statements and console tables use fixed-width printf columns.
Timetable.java  JAVA
1public class Timetable {
2 public static void main(String[] args) {
3 System.out.println("CLASS 8 B - MONDAY");
4 System.out.printf("%-8s %-7s %-18s%n", "Period", "Time", "Subject");
5 System.out.println("----------------------------------");
6 System.out.printf("%-8d %-7s %-18s%n", 1, "09:00", "Mathematics");
7 System.out.printf("%-8d %-7s %-18s%n", 2, "09:45", "Science");
8 System.out.printf("%-8d %-7s %-18s%n", 3, "10:30", "Computer (Java)");
9 System.out.printf("%-8d %-7s %-18s%n", 4, "11:15", "English");
10 System.out.printf("%-8d %-7s %-18s%n", 5, "12:00", "Hindi");
11 System.out.println("----------------------------------");
12 System.out.println("Lunch break: 12:45 to 1:15");
13 }
14}
PracticePractice 7 of 10 · Medium

Java Coffee Cup in ASCII Art

MediumScenario. Draw a coffee cup (the Java symbol) with print statements for the course poster.
💡 Concept used: Each println prints one row. Backslashes must be written as \\ inside a String.

Your tasks

  1. Draw steam, the cup and the plate row by row
  2. Escape the backslashes
  3. Print "JAVA" under the cup
🏢 Used in real projects: Many command-line tools (Spring Boot, Maven) print ASCII-art logos when they start.
Cup.java  JAVA
1public class Cup {
2 public static void main(String[] args) {
3 System.out.println(" ( ) ( ) )");
4 System.out.println(" ) ( ) ( (");
5 System.out.println(" ( ) ( ) )");
6 System.out.println(" _____________");
7 System.out.println(" <_____________> ___");
8 System.out.println(" | |/ _ \\");
9 System.out.println(" | J A V A | | |");
10 System.out.println(" | |_| |");
11 System.out.println("___| |\\___/");
12 System.out.println("\\ \\___________/ /");
13 System.out.println(" \\_________________/");
14 }
15}
PracticePractice 8 of 10 · Medium

Fee Receipt with printf Formatting

MediumScenario. BrainBit Infotech issues a fee receipt with money shown with commas and 2 decimals.
💡 Concept used: Format codes: %,d adds thousand commas, %.2f shows 2 decimals, %10.2f right-aligns in 10 spaces.

Your tasks

  1. Print the header and student details
  2. Print fee, GST (18%) and total, calculated inside printf
  3. Right-align the amounts
  4. Print the amount with commas
TipTo print a percent sign in printf, write %%.
🏢 Used in real projects: Billing software and payment receipts use formatted output for money.
FeeReceipt.java  JAVA
1public class FeeReceipt {
2 public static void main(String[] args) {
3 System.out.println("======== FEE RECEIPT ========");
4 System.out.printf("Student : %s%n", "Ravi Mahto");
5 System.out.printf("Course : %s%n", "Core Java (3 months)");
6 System.out.println("-----------------------------");
7 System.out.printf("Fee : Rs %10.2f%n", 12500.0);
8 System.out.printf("GST 18%% : Rs %10.2f%n", 12500 * 0.18);
9 System.out.printf("Total : Rs %10.2f%n", 12500 * 1.18);
10 System.out.println("-----------------------------");
11 System.out.printf("Amount in figures: Rs %,d%n", 14750);
12 System.out.println("Thank you! BrainBit Infotech");
13 }
14}
PracticePractice 9 of 10 · Hard

Two Classes in One Program

HardScenario. Split a program into a helper class and the main class, the way real projects are organised.
💡 Concept used: A file can contain more than one class (only one may be public). main can call a static method of another class: Printer.line().

Your tasks

  1. Make a class Printer with static methods line() and title(String)
  2. Call them from main
  3. Notice the order in which lines print
PreviewYou will learn methods properly in Module 6. This is a preview of how code is split into reusable parts.
🏢 Used in real projects: Real Java projects have hundreds of classes, each doing one job, calling each other's methods.
Report.java  JAVA
1class Printer {
2 static void line() {
3 System.out.println("=================================");
4 }
5
6 static void title(String text) {
7 line();
8 System.out.println(" " + text);
9 line();
10 }
11}
12
13public class Report {
14 public static void main(String[] args) {
15 Printer.title("MONTHLY TEST - CLASS 9A");
16 System.out.println("Highest: Priya (96)");
17 System.out.println("Average: 71.4");
18 Printer.line();
19 }
20}
PracticePractice 10 of 10 · Hard

Command-Line Report Card

HardScenario. Print a complete report card where every number is calculated, not typed by hand.
💡 Concept used: Combine printf widths, calculations in arguments and %n to build a professional report.

Your tasks

  1. Print 4 subjects with marks out of 100
  2. Calculate the total and percentage inside printf
  3. Use %5.1f%% for the percentage
  4. Draw borders with println
🏢 Used in real projects: Console reports and generated text files in schools and offices are built exactly like this before moving to PDF/Excel.
ReportCard.java  JAVA
1public class ReportCard {
2 public static void main(String[] args) {
3 System.out.println("+---------------------------+");
4 System.out.println("| REPORT CARD - TERM 1 |");
5 System.out.println("+---------------------------+");
6 System.out.printf("| %-12s %5s |%n", "Subject", "Marks");
7 System.out.printf("| %-12s %5d |%n", "Mathematics", 88);
8 System.out.printf("| %-12s %5d |%n", "Science", 79);
9 System.out.printf("| %-12s %5d |%n", "English", 91);
10 System.out.printf("| %-12s %5d |%n", "Computer", 97);
11 System.out.println("+---------------------------+");
12 System.out.printf("| %-12s %5d |%n", "Total", 88 + 79 + 91 + 97);
13 System.out.printf("| %-12s %5.1f%% |%n", "Percentage", (88 + 79 + 91 + 97) / 4.0);
14 System.out.println("+---------------------------+");
15 }
16}
Module 1Recap

Module 1 Recap & Quiz

What you learned

  • 1Java code goes in .java files; javac makes bytecode; the JVM runs it anywhere
  • 2Install the JDK (it contains the JRE and JVM); check with java -version
  • 3Programs live in a class; execution starts at public static void main(String[] args)
  • 4Statements end with ;; Java is case-sensitive; file name = public class name
  • 5println, print, printf with %d %.2f %s %n
  • 6Compile errors stop compilation; run-time errors (exceptions) crash while running

Quick quiz

Which tool turns Main.java into bytecode?

javac is the compiler; java runs the program.

System.out.println("5 + 5 = " + 5 + 5); prints?

After a String, + joins text. Use brackets for maths.

Where does a Java program start running?

The JVM calls main.
MODULE 2

Variables, Data Types & Operators

⏱ 4 hours10 practice examplesStep-through animationsCode Lab

You will learn

  • Variables: declaring and changing values
  • The 8 primitive types plus String
  • Type casting: widening and narrowing
  • Constants with final, and var
  • Arithmetic, relational, logical and assignment operators

You will build

  • A temperature converter
  • A GST bill with correct rounding
  • An EMI calculator with Math.pow
int xdouble gst = 18.0;x++
Module 2Real-world use

Where Is This Used in Real Projects?

variablesstore & calculate🔐Loginusername, password🛒Shopping cartqty, price, total🏦Bank appbalance (double)🎮Gamesscore, lives, level📍Mapslatitude, longitude🎓School ERProll, marks, grade

Real projects that use this

  • Every app stores values while it runs: Flipkart keeps int qty and double price to make your bill
  • A bank app uses the right type for each value: long accountNo, double balance, boolean isActive
  • Choosing the wrong type causes real bugs: money in int loses paise; huge numbers in int overflow
  • Operators do all the maths: totals, discounts, interest, percentages
Module 2The big idea

A Variable Is a Named, Typed Box

"Priya"nameString14ageint92.5marksdouble'A'gradechartruepassedboolean
inttype
marksname
= store
92value
;end
💡 Concept in shortA variable is a named box in memory. In Java every box has a type that decides what it can hold: int for whole numbers, double for decimals, String for text. The type cannot change later.
  1. 1
    Declare: int marks; (make the box)
  2. 2
    Assign: marks = 92; (put a value in)
  3. 3
    Both at once: int marks = 92;
  4. 4
    Change: marks = 95; (old value is replaced)
RememberJava checks types before running. int age = "fourteen"; will not even compile. This catches many bugs early.
Module 2Data types

The 8 Primitive Types (and String)

TypeHoldsExampleSize
bytesmall whole numberbyte b = 100;1 byte
shortwhole numbershort s = 30000;2 bytes
intwhole number (default)int marks = 92;4 bytes
longvery big whole numberlong phone = 9835011111L;8 bytes
floatdecimal (less precise)float t = 36.6f;4 bytes
doubledecimal (default)double price = 499.99;8 bytes
charone characterchar grade = 'A';2 bytes
booleantrue / falseboolean paid = true;JVM decides (usually 1 byte)
Size of each primitive type (bits)02040608byte16short16char32int32float64long64double
💡 Concept in shortPrimitive types store the value directly. String (capital S) is a class: it stores text like "Ranchi". Use int and double most of the time.
Common mistakeNote L after big long numbers and f after float numbers. char uses single quotes, String uses double quotes.
Module 2Declare and use

Declaring Variables of Every Type

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 String name = "Priya Kumari";
4 int age = 14;
5 double marks = 92.5;
6 char grade = 'A';
7 boolean passed = true;
8 long mobile = 9835011111L;
9
10 System.out.println(name + " is " + age + " years old");
11 System.out.println("Marks: " + marks + ", grade " + grade);
12 System.out.println("Passed? " + passed);
13 System.out.println("Mobile: " + mobile);
14
15 age = age + 1; // birthday!
16 System.out.println("Next year: " + age);
17 }
18}
Terminal
D:\java-practice> java Main.java
Priya Kumari is 14 years old
Marks: 92.5, grade A
Passed? true
Mobile: 9835011111
Next year: 15
💡 Concept in shortWrite the type, the name, then the value. Reuse the name later without the type. Assigning a new value replaces the old one.
+

Joining with +

When one side of + is a String, Java joins text: "Age " + 14 becomes "Age 14".
Common mistakeint mobile = 9835011111; fails: the number is too big for int (max about 2.1 billion). Use long.
Module 2Casting

Type Casting: Converting Between Types

byteshortintlongfloatdoublenarrowing: needs a cast (int) and may lose datawidening: automatic and safe ➜
jshell (Java interactive shell)
// jshell: type Java and see the answer at once. Press Next line.
0 / 11
💡 Concept in shortWidening (small type to big type, like int to double) happens automatically. Narrowing (double to int) needs a cast (int) and drops the decimal part. It does not round.
CodeResultWhy
(int) 99.9999decimals cut off
Math.round(99.5)100proper rounding
(double) 7 / 23.5cast first, then divide
'A' + 166char used as a number
In real projectsBilling software must decide carefully between cutting and rounding money values.
Module 2Constants and var

Constants with final, and var

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 final double GST_RATE = 18.0; // cannot change later
4 final int MAX_STUDENTS = 40;
5 var city = "Ranchi"; // Java infers String
6 var fee = 4500; // Java infers int
7
8 double gst = fee * GST_RATE / 100;
9 System.out.println("City: " + city);
10 System.out.println("GST on Rs " + fee + " = " + gst);
11 System.out.println("Seats: " + MAX_STUDENTS);
12 // GST_RATE = 12; // ERROR: cannot assign a value to final variable
13 }
14}
Terminal
D:\java-practice> java Main.java
City: Ranchi
GST on Rs 4500 = 810.0
Seats: 40
💡 Concept in shortfinal makes a constant: a value that must never change, like a tax rate. Constants use UPPER_CASE names. var (Java 10+) lets Java work out the type from the value, but the type is still fixed.
In real projectsRates, limits and settings are constants in real code, so changing them later means editing one line.
Module 2Arithmetic

Arithmetic Operators (and Integer Division)

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 int a = 17, b = 5;
4 System.out.println("a + b = " + (a + b));
5 System.out.println("a - b = " + (a - b));
6 System.out.println("a * b = " + (a * b));
7 System.out.println("a / b = " + (a / b)); // 3, not 3.4!
8 System.out.println("a % b = " + (a % b)); // remainder 2
9 System.out.println("a / 5.0 = " + (a / 5.0)); // 3.4
10 System.out.println("Is 17 even? " + (a % 2 == 0));
11 System.out.println("Math.pow(2, 10) = " + Math.pow(2, 10));
12 }
13}
Terminal
D:\java-practice> java Main.java
a + b = 22
a - b = 12
a * b = 85
a / b = 3
a % b = 2
a / 5.0 = 3.4
Is 17 even? false
Math.pow(2, 10) = 1024.0
💡 Concept in short+ - * / work like maths, but int / int gives an int (decimals are dropped). % (modulus) gives the remainder: great for even/odd checks, last digits and "every n-th item".
ExpressionResult
17 / 53
17 % 52
17 / 5.03.4
-17 % 5-2
RememberJava has no power operator: use Math.pow(x, y), which returns a double.
Module 2Watch ++ and --

Step Through: Increment, Decrement and Shortcuts

Shortcut operators update a variable using its own value. Watch the difference between count++ and ++count.

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 int wallet = 500;
4 wallet += 200;
5 wallet -= 150;
6 wallet *= 2;
7 wallet /= 3;
8 int count = 5;
9 int a = count++;
10 int b = ++count;
11 count--;
12 System.out.println(wallet + " " + a + " " + b + " " + count);
13 }
14}
Output
Module 2Comparison and logic

Relational and Logical Operators

jshell (Java interactive shell)
// jshell: type Java and see the answer at once. Press Next line.
0 / 10
💡 Concept in shortRelational operators (== != > < >= <=) compare values and give a boolean. Logical operators combine booleans: && (AND: both true), || (OR: at least one), ! (NOT).
ABA && BA || B
truetruetruetrue
truefalsefalsetrue
falsetruefalsetrue
falsefalsefalsefalse
Common mistake= assigns, == compares. And && / || are short-circuit: if the left side already decides the answer, the right side is not checked.
Module 2Precedence

Operator Precedence: Who Goes First?

Watch Java solve 10 + 2 * (6 - 3) / 3 % 2

10 + 2 * (6 - 3) / 3 % 2brackets first
10 + 2 * 3 / 3 % 2* / % left to right
10 + 6 / 3 % 2still left to right
10 + 2 % 2still left to right
10 + 0then + and -
10final answer
1 / 6
PriorityOperators
1( )
2++ -- ! (unary)
3* / %
4+ -
5< <= > >=
6== !=
7&&
8||
9= += -= ...
💡 Concept in shortJava follows a fixed order, like BODMAS. When in doubt, add brackets: they make code clearer for the next person too.
Module 2Hands-on

Code Lab: Try It Yourself

Main.java
Output of the starter code
D:\java-practice> java Main.java
Subtotal : 3750
Discount : 375.0
GST : 607.5
TOTAL : 3982.50
Change the code, then run it on your computer: ⬇ Download → open a terminal in that folder → java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).
Your tasks
  1. Change price and quantity
  2. Make the discount 0 and check the total
  3. Print total > 5000 to see if free delivery applies
  4. Cast the total to int and compare with Math.round(total)
PracticePractice 1 of 10 · Easy

Student Profile with Variables

EasyScenario. The library software stores student details in variables of the right type and prints a card.
💡 Concept used: Pick a type per value: String for text, int for whole numbers, char for one letter, boolean for yes/no.

Your tasks

  1. Declare name, class, roll, section and isMember
  2. Print a neat card
  3. Change the roll number and print it again
🏢 Used in real projects: Every app stores user details in typed fields before saving them to a database.
Profile.java  JAVA
1public class Profile {
2 public static void main(String[] args) {
3 String name = "Ankit Oraon";
4 int studentClass = 9;
5 char section = 'A';
6 int roll = 21;
7 boolean isMember = true;
8
9 System.out.println("==== LIBRARY CARD ====");
10 System.out.println("Name : " + name);
11 System.out.println("Class : " + studentClass + section);
12 System.out.println("Roll : " + roll);
13 System.out.println("Member : " + isMember);
14 roll = 22;
15 System.out.println("New roll after re-shuffle: " + roll);
16 }
17}
PracticePractice 2 of 10 · Easy

Temperature Converter

EasyScenario. A weather display in Ranchi shows temperatures in both Celsius and Fahrenheit.
💡 Concept used: Formula F = C x 9 / 5 + 32. Use double so decimals are kept.

Your tasks

  1. Store the Celsius value in a double
  2. Convert to Fahrenheit
  3. Convert 98.6 F back to Celsius
  4. Print with printf and 1 decimal
🏢 Used in real projects: Weather apps and smart thermostats convert units with the same formulas.
Temperature.java  JAVA
1public class Temperature {
2 public static void main(String[] args) {
3 double celsius = 31.5;
4 double fahrenheit = celsius * 9 / 5 + 32;
5 System.out.printf("Ranchi today: %.1f C = %.1f F%n", celsius, fahrenheit);
6
7 double bodyF = 98.6;
8 double bodyC = (bodyF - 32) * 5 / 9;
9 System.out.printf("Body temperature: %.1f F = %.1f C%n", bodyF, bodyC);
10 }
11}
PracticePractice 3 of 10 · Easy

Simple Interest

EasyScenario. A savings scheme pays simple interest. Calculate the interest and the final amount.
💡 Concept used: Simple interest = P x R x T / 100. Use double for money.

Your tasks

  1. Store principal, rate and time
  2. Calculate interest and total
  3. Print both with 2 decimals
🏢 Used in real projects: Banking and post-office savings calculators use this formula.
SimpleInterest.java  JAVA
1public class SimpleInterest {
2 public static void main(String[] args) {
3 double principal = 25000;
4 double rate = 7.5; // percent per year
5 int years = 3;
6
7 double interest = principal * rate * years / 100;
8 double amount = principal + interest;
9 System.out.printf("Principal : Rs %.2f%n", principal);
10 System.out.printf("Interest : Rs %.2f%n", interest);
11 System.out.printf("Amount : Rs %.2f%n", amount);
12 }
13}
PracticePractice 4 of 10 · Easy

Area and Perimeter Calculator

EasyScenario. A builder needs the area and perimeter of a rectangular room and a circular water tank.
💡 Concept used: Math.PI is a ready-made constant; r * r squares a number.

Your tasks

  1. Rectangle: area = l x b, perimeter = 2(l + b)
  2. Circle: area = PI x r x r, circumference = 2 x PI x r
  3. Print results with 2 decimals
🏢 Used in real projects: Construction estimators and CAD tools compute areas and perimeters constantly.
Shapes.java  JAVA
1public class Shapes {
2 public static void main(String[] args) {
3 double length = 14.5, breadth = 10.0;
4 double radius = 3.5;
5
6 double roomArea = length * breadth;
7 double roomPerimeter = 2 * (length + breadth);
8 double tankArea = Math.PI * radius * radius;
9 double tankCircumference = 2 * Math.PI * radius;
10
11 System.out.printf("Room : area %.2f sq ft, perimeter %.2f ft%n", roomArea, roomPerimeter);
12 System.out.printf("Tank : area %.2f sq ft, circumference %.2f ft%n", tankArea, tankCircumference);
13 }
14}
PracticePractice 5 of 10 · Easy

Swap Two Values

EasyScenario. Two students exchange seats. Swap their seat numbers in variables.
💡 Concept used: To swap, use a third temporary variable so a value is not lost.

Your tasks

  1. Store seatA and seatB
  2. Swap using temp
  3. Swap back using only + and - (no temp)
  4. Print after each swap
🏢 Used in real projects: Sorting algorithms (Module 7) swap values all the time.
Swap.java  JAVA
1public class Swap {
2 public static void main(String[] args) {
3 int seatA = 12, seatB = 27;
4 System.out.println("Before: A=" + seatA + " B=" + seatB);
5
6 int temp = seatA;
7 seatA = seatB;
8 seatB = temp;
9 System.out.println("After : A=" + seatA + " B=" + seatB);
10
11 seatA = seatA + seatB; // 39
12 seatB = seatA - seatB; // 27 -> old A
13 seatA = seatA - seatB; // 12
14 System.out.println("Back : A=" + seatA + " B=" + seatB);
15 }
16}
PracticePractice 6 of 10 · Medium

Seconds to Hours, Minutes, Seconds

MediumScenario. A video player shows the length of a video as H:M:S.
💡 Concept used: Integer division / gives the whole part; % gives what is left over.

Your tasks

  1. hours = total / 3600
  2. minutes = (total % 3600) / 60
  3. seconds = total % 60
  4. Print as 02:15:25 with %02d
🏢 Used in real projects: Video players, exam timers and parking meters convert seconds this way.
Duration.java  JAVA
1public class Duration {
2 public static void main(String[] args) {
3 int total = 8125;
4 int hours = total / 3600;
5 int minutes = (total % 3600) / 60;
6 int seconds = total % 60;
7 System.out.println(total + " seconds = " + hours + "h " + minutes + "m " + seconds + "s");
8 System.out.printf("Display: %02d:%02d:%02d%n", hours, minutes, seconds);
9 }
10}
PracticePractice 7 of 10 · Medium

GST Bill with Correct Rounding

MediumScenario. A mobile shop bill must show GST to the paisa and a rounded payable amount.
💡 Concept used: Keep money in double, show 2 decimals with printf, and use Math.round (not a cast) for the final rupee amount.

Your tasks

  1. Price 749.50, quantity 3, GST 18%
  2. Calculate subtotal, GST and total
  3. Show total cut with (int) and rounded with Math.round
  4. See which one the customer should pay
🏢 Used in real projects: POS and invoicing software must round money correctly; small rounding mistakes add up to big losses.
GstBill.java  JAVA
1public class GstBill {
2 public static void main(String[] args) {
3 final double GST_RATE = 18;
4 double price = 749.50;
5 int qty = 3;
6
7 double subtotal = price * qty;
8 double gst = subtotal * GST_RATE / 100;
9 double total = subtotal + gst;
10
11 System.out.printf("Subtotal : %10.2f%n", subtotal);
12 System.out.printf("GST 18%% : %10.2f%n", gst);
13 System.out.printf("Total : %10.2f%n", total);
14 System.out.println("Cast (int) : " + (int) total);
15 System.out.println("Math.round() : " + Math.round(total));
16 }
17}
PracticePractice 8 of 10 · Medium

Character Codes and Letters

MediumScenario. A school quiz app shows each letter's code and makes simple codes by shifting letters.
💡 Concept used: char values are numbers underneath (Unicode). Adding to a char and casting back gives the next letters.

Your tasks

  1. Print the code of 'A', 'a' and '0'
  2. Shift 'R' by 3 places
  3. Convert a lowercase letter to uppercase using -32
  4. Check if a char is a digit using a range
🏢 Used in real projects: Text processing, password validators and simple encryption (Caesar cipher) work with character codes.
CharCodes.java  JAVA
1public class CharCodes {
2 public static void main(String[] args) {
3 char upper = 'A', lower = 'a', digit = '0';
4 System.out.println("A=" + (int) upper + " a=" + (int) lower + " 0=" + (int) digit);
5
6 char letter = 'R';
7 char shifted = (char) (letter + 3);
8 System.out.println(letter + " shifted by 3 -> " + shifted);
9
10 char small = 'j';
11 char big = (char) (small - 32);
12 System.out.println(small + " -> " + big);
13
14 char c = '7';
15 boolean isDigit = c >= '0' && c <= '9';
16 System.out.println(c + " is a digit? " + isDigit + ", value " + (c - '0'));
17 }
18}
PracticePractice 9 of 10 · Hard

EMI Calculator

HardScenario. A two-wheeler showroom calculates the monthly EMI for a loan.
💡 Concept used: EMI = P x r x (1+r)^n / ((1+r)^n - 1) where r = yearly rate / 12 / 100 and n = months. Math.pow(a, b) computes a to the power b.

Your tasks

  1. Loan Rs 90,000 at 10.5% for 2 years
  2. Calculate r and n
  3. Use Math.pow for (1+r)^n
  4. Print EMI, total paid and total interest
🏢 Used in real projects: Loan calculators on bank, NBFC and car-dealer websites use this exact formula.
Emi.java  JAVA
1public class Emi {
2 public static void main(String[] args) {
3 double principal = 90000;
4 double yearlyRate = 10.5;
5 int years = 2;
6
7 double r = yearlyRate / 12 / 100;
8 int n = years * 12;
9 double factor = Math.pow(1 + r, n);
10 double emi = principal * r * factor / (factor - 1);
11
12 System.out.printf("Monthly EMI : Rs %,.2f%n", emi);
13 System.out.printf("Total paid : Rs %,.2f%n", emi * n);
14 System.out.printf("Total interest : Rs %,.2f%n", emi * n - principal);
15 }
16}
PracticePractice 10 of 10 · Hard

Overflow and the Right Type

HardScenario. A data centre counts bytes. Show why int overflows and how long fixes it.
💡 Concept used: int holds up to 2,147,483,647. Going past it wraps around to a negative number with no error. long holds much bigger values.

Your tasks

  1. Print Integer.MAX_VALUE and add 1
  2. Calculate bytes in 5 GB with int (wrong) and with long (right)
  3. Print Long.MAX_VALUE
  4. Use Math.addExact to make overflow throw an error
🏢 Used in real projects: Real bugs have been caused by integer overflow in games, finance and even space software. Picking long and checked maths prevents them.
Overflow.java  JAVA
1public class Overflow {
2 public static void main(String[] args) {
3 int big = Integer.MAX_VALUE;
4 System.out.println("int max : " + big);
5 System.out.println("int max + 1 : " + (big + 1));
6
7 int wrong = 5 * 1024 * 1024 * 1024;
8 long right = 5L * 1024 * 1024 * 1024;
9 System.out.println("5 GB as int : " + wrong);
10 System.out.println("5 GB as long: " + right);
11 System.out.println("long max : " + Long.MAX_VALUE);
12 System.out.println("Safe add : " + Math.addExact(big, 1));
13 }
14}
Module 2Recap

Module 2 Recap & Quiz

What you learned

  • 1A variable has a type, a name and a value: int marks = 92;
  • 28 primitives: byte, short, int, long, float, double, char, boolean; text uses String
  • 3Widening is automatic; narrowing needs a cast (int) and drops decimals
  • 4final makes constants; var infers the type
  • 5int / int is an int; % gives the remainder; Math.pow for powers
  • 6++x changes first, x++ uses the old value first; && || ! combine booleans

Quick quiz

System.out.println(7 / 2); prints?

Both are ints, so the result is an int.

Best type for a bank balance like 1520.75?

Decimal values need double (or BigDecimal in banking).

int a = 5; int b = a++; b is?

Post-increment gives the old value, then increases a.
MODULE 3

Input & Output: Scanner, printf & Math

⏱ 3.5 hours10 practice examplesStep-through animationsCode Lab

You will learn

  • Reading keyboard input with Scanner
  • nextInt, nextDouble, next and nextLine (and the Enter-key trap)
  • Formatting output with printf and String.format
  • The Math class: pow, sqrt, round, ceil, max, min, random
  • Random numbers with java.util.Random

You will build

  • A tea-stall bill that asks quantities
  • A BMI calculator
  • An OTP generator and a dice game
Scannersc.nextInt()Math.sqrt(144)
Module 3Real-world use

Where Is This Used in Real Projects?

input / outputtalk to the user📝Formsread user details🏧ATMenter PIN & amount🧾Billingquantities in, bill out🎲Gamesrandom dice, cards🔐OTPrandom 6 digits📊Reportsneat printf tables

Real projects that use this

  • A program becomes useful when it asks the user for data: an ATM asks the PIN, a billing counter asks quantities
  • Console tools in banks and servers read input exactly like Scanner does
  • Neatly formatted output (receipts, statements, reports) uses printf
  • Games, OTPs and lucky draws use random numbers
Module 3Scanner

Reading Input with Scanner

Main.java  JAVA
1import java.util.Scanner; // 1. import
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in); // 2. create
6 System.out.print("Your name: ");
7 String name = sc.nextLine(); // 3. read a whole line
8 System.out.print("Your age: ");
9 int age = sc.nextInt(); // read a whole number
10 System.out.print("Height in metres: ");
11 double h = sc.nextDouble(); // read a decimal
12 System.out.println("Hello " + name + "! Next year you will be " + (age + 1));
13 System.out.println("Height in cm: " + h * 100);
14 sc.close();
15 }
16}
Terminal
D:\java-practice> java Main.java
Your name: Riya Kumari
Your age: 14
Height in metres: 1.52
Hello Riya Kumari! Next year you will be 15
Height in cm: 152.0
Green text = what the user typed.
Keyboarduser types 15Scannerreads System.inint age = 15your variable
💡 Concept in shortScanner reads what the user types. Three steps: import it, create it with new Scanner(System.in), then call a method for the type you want.
MethodReads
nextLine()the whole line (text with spaces)
next()one word
nextInt()a whole number
nextDouble()a decimal number
nextBoolean()true / false
Module 3The Enter-key trap

nextInt() then nextLine(): The Most Common Scanner Bug

Bug: name is empty

Main.java  JAVA
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Roll number: ");
7 int roll = sc.nextInt();
8 System.out.print("Full name: ");
9 String name = sc.nextLine(); // BUG: reads the leftover Enter
10 System.out.println("Roll " + roll + ", name = [" + name + "]");
11 }
12}
Terminal
D:\java-practice> java Main.java
Roll number: 17
Full name: Roll 17, name = []

Fixed

Main.java  JAVA
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Roll number: ");
7 int roll = sc.nextInt();
8 sc.nextLine(); // FIX: eat the leftover Enter
9 System.out.print("Full name: ");
10 String name = sc.nextLine();
11 System.out.println("Roll " + roll + ", name = [" + name + "]");
12 }
13}
Terminal
D:\java-practice> java Main.java
Roll number: 17
Full name: Aman Kumar
Roll 17, name = [Aman Kumar]
💡 Concept in shortnextInt() reads the number but leaves the Enter key in the input. The next nextLine() reads that empty line. Call an extra sc.nextLine() to clear it.
Module 3printf

Formatting Output with printf and String.format

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 String item = "Notebook";
4 int qty = 12;
5 double price = 45.5;
6 System.out.printf("%s x %d = Rs %.2f%n", item, qty, qty * price);
7 System.out.printf("[%10s]%n", "right"); // right-align in 10
8 System.out.printf("[%-10s]%n", "left"); // left-align in 10
9 System.out.printf("[%05d]%n", 42); // pad with zeros
10 System.out.printf("%,d students%n", 125000); // thousand commas
11 System.out.printf("%.1f%%%n", 87.456); // percent sign
12 String line = String.format("Roll %03d | %-8s | %6.2f", 7, "Riya", 91.5);
13 System.out.println(line);
14 }
15}
Terminal
D:\java-practice> java Main.java
Notebook x 12 = Rs 546.00
[ right]
[left ]
[00042]
125,000 students
87.5%
Roll 007 | Riya | 91.50
💡 Concept in shortprintf = print with a template. Each % code is replaced by the next value. String.format builds the same text but returns it instead of printing.
CodeForExample result
%dint / long42
%.2fdouble, 2 decimals45.50
%sString / anythingRiya
%ccharA
%10s / %-10swidth right / left[ right]
%05dzero padding00042
%,dcommas125,000
%nnew line
Module 3Math class

The Math Class: Ready-Made Maths

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 System.out.println("sqrt(625) = " + Math.sqrt(625));
4 System.out.println("pow(2, 10) = " + Math.pow(2, 10));
5 System.out.println("abs(-7) = " + Math.abs(-7));
6 System.out.println("max(45, 78) = " + Math.max(45, 78));
7 System.out.println("min(45, 78) = " + Math.min(45, 78));
8 System.out.println("round(7.5) = " + Math.round(7.5));
9 System.out.println("ceil(7.1) = " + Math.ceil(7.1));
10 System.out.println("floor(7.9) = " + Math.floor(7.9));
11 System.out.println("PI = " + Math.PI);
12 int students = 130, perBus = 40;
13 System.out.println("Buses needed: " + (int) Math.ceil((double) students / perBus));
14 }
15}
Terminal
D:\java-practice> java Main.java
sqrt(625) = 25.0
pow(2, 10) = 1024.0
abs(-7) = 7
max(45, 78) = 78
min(45, 78) = 45
round(7.5) = 8
ceil(7.1) = 8.0
floor(7.9) = 7.0
PI = 3.141592653589793
Buses needed: 4
💡 Concept in shortMath is a built-in class full of static methods: you call them with Math.name(...), no object or import needed.
⇧

ceil for "how many needed"

130 students, 40 per bus = 3.25: Math.ceil gives 4 buses. A cast would wrongly give 3.
In real projectsEngineering, finance and game physics code relies on Math every day.
Module 3Random numbers

Random Numbers: Random and Math.random()

Main.java  JAVA
1import java.util.Random;
2
3public class Main {
4 public static void main(String[] args) {
5 Random rnd = new Random(42); // 42 = seed (same numbers each run)
6 int dice = rnd.nextInt(6) + 1; // 1 to 6
7 int otp = rnd.nextInt(900000) + 100000; // 6-digit OTP
8 double chance = rnd.nextDouble(); // 0.0 to 1.0
9 boolean heads = rnd.nextBoolean();
10 System.out.println("Dice: " + dice);
11 System.out.println("OTP: " + otp);
12 System.out.printf("Chance: %.3f%n", chance);
13 System.out.println("Toss: " + (heads ? "Heads" : "Tails"));
14 int lucky = (int) (Math.random() * 100) + 1; // 1 to 100, different each run
15 System.out.println("Lucky number is between 1 and 100: " + (lucky >= 1 && lucky <= 100));
16 }
17}
Terminal
D:\java-practice> java Main.java
Dice: 3
OTP: 492763
Chance: 0.683
Toss: Tails
Lucky number is between 1 and 100: true
💡 Concept in shortrnd.nextInt(n) gives a random int from 0 to n-1; add 1 for "1 to n". A seed like new Random(42) repeats the same sequence, which is useful for testing.
Common mistakeFor real passwords and OTPs, use java.security.SecureRandom. Normal Random is predictable.
In real projectsLudo and card games, lucky draws and test-data generators all use random numbers.
Module 3Watch input

Step Through: A Tea-Stall Bill That Asks Questions

The program pauses at each nextInt() until the user types a value and presses Enter.

Main.java  JAVA
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Cups of tea: ");
7 int teas = sc.nextInt();
8 System.out.print("Samosas: ");
9 int samosas = sc.nextInt();
10 int bill = teas * 12 + samosas * 15;
11 System.out.println("Total: Rs " + bill);
12 }
13}
Output
Module 3Hands-on

Code Lab: Try It Yourself

Main.java
Output of the starter code
D:\java-practice> java Main.java
Your name: Riya
Birth year: 2012
Hi Riya, you are about 14 years old.
Square root of your age: 3.742
Change the code, then run it on your computer: ⬇ Download → open a terminal in that folder → java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).
Your tasks
  1. Run it on your computer and type your own details
  2. Also ask the city with nextLine() (remember the Enter-key trap!)
  3. Print the age in months and in days
  4. Print a random lucky number from 1 to 9
PracticePractice 1 of 10 · Easy

Greeting Card from Input

EasyScenario. A greeting kiosk asks your name and city and prints a welcome message.
💡 Concept used: nextLine() reads a whole line of text including spaces.

Your tasks

  1. Create a Scanner
  2. Ask the name and the city with nextLine()
  3. Print a framed welcome message
🏢 Used in real projects: Every sign-up screen reads text input before saving it.
Greeting.java  JAVA
1import java.util.Scanner;
2
3public class Greeting {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Your name: ");
7 String name = sc.nextLine();
8 System.out.print("Your city: ");
9 String city = sc.nextLine();
10 System.out.println("*******************************");
11 System.out.println(" Welcome, " + name + "!");
12 System.out.println(" Greetings from " + city + ".");
13 System.out.println("*******************************");
14 }
15}
PracticePractice 2 of 10 · Easy

Tea Stall Bill

EasyScenario. Raju's tea stall near Morhabadi sells tea for Rs 12 and samosa for Rs 15.
💡 Concept used: nextInt() reads whole numbers; multiply by prices and add.

Your tasks

  1. Ask cups of tea and samosas
  2. Calculate each item total and the grand total
  3. Print a bill with printf
🏢 Used in real projects: Point-of-sale counters read quantities and print bills like this.
TeaBill.java  JAVA
1import java.util.Scanner;
2
3public class TeaBill {
4 public static void main(String[] args) {
5 final int TEA = 12, SAMOSA = 15;
6 Scanner sc = new Scanner(System.in);
7 System.out.print("Cups of tea: ");
8 int teas = sc.nextInt();
9 System.out.print("Samosas: ");
10 int samosas = sc.nextInt();
11 System.out.println("---------------------------");
12 System.out.printf("Tea x %2d = Rs %4d%n", teas, teas * TEA);
13 System.out.printf("Samosa x %2d = Rs %4d%n", samosas, samosas * SAMOSA);
14 System.out.println("---------------------------");
15 System.out.printf("TOTAL = Rs %4d%n", teas * TEA + samosas * SAMOSA);
16 }
17}
PracticePractice 3 of 10 · Easy

Circle Calculator

EasyScenario. A maths teacher wants area and circumference for any radius typed by a student.
💡 Concept used: nextDouble() reads decimals; Math.PI and Math.pow(r, 2) help with the formula.

Your tasks

  1. Read the radius as a double
  2. Area = PI x r squared, circumference = 2 x PI x r
  3. Print with 2 decimals
🏢 Used in real projects: Engineering and geometry apps read measurements and apply formulas.
Circle.java  JAVA
1import java.util.Scanner;
2
3public class Circle {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Radius (cm): ");
7 double r = sc.nextDouble();
8 double area = Math.PI * Math.pow(r, 2);
9 double circumference = 2 * Math.PI * r;
10 System.out.printf("Area : %.2f sq cm%n", area);
11 System.out.printf("Circumference : %.2f cm%n", circumference);
12 }
13}
PracticePractice 4 of 10 · Easy

Rupee to Dollar Converter

EasyScenario. A travel agent converts rupees to US dollars at an example rate of Rs 84 = 1 USD.
💡 Concept used: Divide to convert; printf("%.2f") shows money with 2 decimals; %,.2f adds commas.

Your tasks

  1. Read the rupee amount as a double
  2. Convert to dollars
  3. Convert back as a check
  4. Print with commas
🏢 Used in real projects: Currency and banking apps convert amounts with live rates.
Currency.java  JAVA
1import java.util.Scanner;
2
3public class Currency {
4 public static void main(String[] args) {
5 final double RATE = 84.0; // example rate
6 Scanner sc = new Scanner(System.in);
7 System.out.print("Amount in rupees: ");
8 double rupees = sc.nextDouble();
9 double dollars = rupees / RATE;
10 System.out.printf("Rs %,.2f = $ %,.2f%n", rupees, dollars);
11 System.out.printf("Check: $ %,.2f x %.0f = Rs %,.2f%n", dollars, RATE, dollars * RATE);
12 }
13}
PracticePractice 5 of 10 · Easy

Dice Roller

EasyScenario. A board-game app rolls two dice and shows the total.
💡 Concept used: rnd.nextInt(6) + 1 gives 1 to 6. A seed makes the result repeatable for testing.

Your tasks

  1. Create new Random(7)
  2. Roll two dice
  3. Print each die and the total
  4. Print "Doubles!" using a boolean expression
🏢 Used in real projects: Ludo, Snakes and Ladders and casino-style games roll dice with random numbers.
Dice.java  JAVA
1import java.util.Random;
2
3public class Dice {
4 public static void main(String[] args) {
5 Random rnd = new Random(7);
6 int d1 = rnd.nextInt(6) + 1;
7 int d2 = rnd.nextInt(6) + 1;
8 System.out.println("Die 1: " + d1);
9 System.out.println("Die 2: " + d2);
10 System.out.println("Total: " + (d1 + d2));
11 System.out.println("Doubles? " + (d1 == d2));
12 }
13}
PracticePractice 6 of 10 · Medium

BMI Calculator

MediumScenario. A school health camp calculates Body Mass Index for each student.
💡 Concept used: BMI = weight (kg) / height (m) squared. Combine nextDouble(), Math.pow and printf.

Your tasks

  1. Read name (nextLine), weight and height
  2. Calculate BMI
  3. Print BMI with 1 decimal
  4. Print the healthy weight range for that height (BMI 18.5 to 24.9)
🏢 Used in real projects: Health and fitness apps compute BMI and ranges exactly like this.
Bmi.java  JAVA
1import java.util.Scanner;
2
3public class Bmi {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Name: ");
7 String name = sc.nextLine();
8 System.out.print("Weight (kg): ");
9 double w = sc.nextDouble();
10 System.out.print("Height (m): ");
11 double h = sc.nextDouble();
12 double bmi = w / Math.pow(h, 2);
13 System.out.printf("%s, your BMI is %.1f%n", name, bmi);
14 System.out.printf("Healthy weight for %.2f m: %.1f kg to %.1f kg%n", h, 18.5 * h * h, 24.9 * h * h);
15 }
16}
PracticePractice 7 of 10 · Medium

OTP Generator and Check

MediumScenario. A login screen sends a 6-digit OTP and asks the user to type it back.
💡 Concept used: nextInt(900000) + 100000 always gives 6 digits. Compare ints with ==.

Your tasks

  1. Generate the OTP with new Random(2026)
  2. Print it as an SMS
  3. Read the typed OTP
  4. Print whether it matches
🏢 Used in real projects: Banks, UPI apps and e-commerce sites send OTPs (generated with SecureRandom in production).
Otp.java  JAVA
1import java.util.Random;
2import java.util.Scanner;
3
4public class Otp {
5 public static void main(String[] args) {
6 Random rnd = new Random(2026);
7 int otp = rnd.nextInt(900000) + 100000;
8 System.out.println("SMS: Your BrainBit Infotech login OTP is " + otp);
9 Scanner sc = new Scanner(System.in);
10 System.out.print("Enter OTP: ");
11 int typed = sc.nextInt();
12 System.out.println("Verified? " + (typed == otp));
13 }
14}
PracticePractice 8 of 10 · Medium

Split the Restaurant Bill

MediumScenario. Friends ate litti chokha in Lalpur. Split the bill with a tip, rounding each share up to the next rupee.
💡 Concept used: Use Math.ceil so the restaurant never gets less; integer % tells how much extra is collected.

Your tasks

  1. Read the bill, tip % and number of friends
  2. Calculate the total with tip
  3. Each share = Math.ceil(total / friends)
  4. Print the extra collected because of rounding
🏢 Used in real projects: Bill-splitting apps and UPI group payments round shares like this.
SplitBill.java  JAVA
1import java.util.Scanner;
2
3public class SplitBill {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Bill amount: ");
7 double bill = sc.nextDouble();
8 System.out.print("Tip percent: ");
9 double tip = sc.nextDouble();
10 System.out.print("Friends: ");
11 int friends = sc.nextInt();
12 double total = bill + bill * tip / 100;
13 int share = (int) Math.ceil(total / friends);
14 System.out.printf("Total with tip : Rs %.2f%n", total);
15 System.out.printf("Each pays : Rs %d%n", share);
16 System.out.printf("Extra collected: Rs %.2f%n", share * friends - total);
17 }
18}
PracticePractice 9 of 10 · Hard

Number Statistics from 5 Inputs

HardScenario. A sports teacher enters 5 running times (seconds). Show the fastest, slowest, average and spread.
💡 Concept used: Use Math.min / Math.max repeatedly; the average is the sum divided by 5.0; spread = max - min.

Your tasks

  1. Read 5 doubles
  2. Find min and max with Math
  3. Average and spread
  4. Print a formatted summary
TipScanner reads numbers separated by spaces on one line too.
🏢 Used in real projects: Sports analytics and lab reports summarise measurements this way. (Loops and arrays in Modules 5 and 7 make it shorter.)
Stats.java  JAVA
1import java.util.Scanner;
2
3public class Stats {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Enter 5 times: ");
7 double a = sc.nextDouble(), b = sc.nextDouble(), c = sc.nextDouble(), d = sc.nextDouble(), e = sc.nextDouble();
8 double min = Math.min(Math.min(Math.min(a, b), Math.min(c, d)), e);
9 double max = Math.max(Math.max(Math.max(a, b), Math.max(c, d)), e);
10 double avg = (a + b + c + d + e) / 5.0;
11 System.out.printf("Fastest : %.2f s%n", min);
12 System.out.printf("Slowest : %.2f s%n", max);
13 System.out.printf("Average : %.2f s%n", avg);
14 System.out.printf("Spread : %.2f s%n", max - min);
15 }
16}
PracticePractice 10 of 10 · Hard

Mini Calculator with Math Functions

HardScenario. A scientific mini-calculator reads one number and shows many results in a formatted table.
💡 Concept used: Chain many Math methods with printf widths to build a neat table.

Your tasks

  1. Read a number
  2. Show square, cube, square root, cube root, log10
  3. Show it rounded, ceil and floor
  4. Align results in a table
🏢 Used in real projects: Engineering calculators and spreadsheet functions are built on the same Math methods.
SciCalc.java  JAVA
1import java.util.Scanner;
2
3public class SciCalc {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Enter a number: ");
7 double x = sc.nextDouble();
8 System.out.printf("%-12s %12s%n", "Function", "Result");
9 System.out.printf("%-12s %12.3f%n", "square", Math.pow(x, 2));
10 System.out.printf("%-12s %12.3f%n", "cube", Math.pow(x, 3));
11 System.out.printf("%-12s %12.3f%n", "sqrt", Math.sqrt(x));
12 System.out.printf("%-12s %12.3f%n", "cbrt", Math.cbrt(x));
13 System.out.printf("%-12s %12.3f%n", "log10", Math.log10(x));
14 System.out.printf("%-12s %12d%n", "round", Math.round(x));
15 System.out.printf("%-12s %12.0f%n", "ceil", Math.ceil(x));
16 System.out.printf("%-12s %12.0f%n", "floor", Math.floor(x));
17 }
18}
Module 3Recap

Module 3 Recap & Quiz

What you learned

  • 1import java.util.Scanner; then new Scanner(System.in)
  • 2nextLine() line, next() word, nextInt(), nextDouble()
  • 3After nextInt(), call an extra nextLine() before reading text
  • 4printf codes: %d %.2f %s %10s %-10s %,d %n
  • 5Math: sqrt, pow, abs, max, min, round, ceil, floor, PI
  • 6Random: nextInt(n) gives 0..n-1; use SecureRandom for security

Quick quiz

Which reads a full name with spaces?

nextLine reads the whole line.

rnd.nextInt(6) + 1 gives?

nextInt(6) is 0..5; +1 makes 1..6.

printf("%.1f", 3.456) prints?

%.1f rounds to 1 decimal.
MODULE 4

Decisions: if, else & switch

⏱ 3.5 hours10 practice examplesStep-through animationsCode Lab

You will learn

  • if, if-else and the else-if ladder
  • Nested if and combining conditions with && and ||
  • The ternary operator ? :
  • switch statements and modern switch expressions (Java 14+)
  • Comparing Strings correctly with equals()

You will build

  • A JAC grade calculator
  • An electricity bill with slab rates
  • A login check and a restaurant menu
if ( )else if (m >= 60)switch (day)
Module 4Real-world use

Where Is This Used in Real Projects?

if / switchchoose a path🔐Loginright password?🏧ATMenough balance?🎓Resultspass / fail, grade🏷Offersfree delivery > 499🚦Traffic systemsignal states🗳Eligibilityage >= 18

Real projects that use this

  • A banking app checks if the balance is enough, else shows "Insufficient funds"
  • Exam software gives grades with an else-if ladder
  • Food apps give free delivery if the cart total crosses a limit
  • Menu-driven programs (IVR, kiosks) use switch to pick an action
Module 4if statement

if and else: Run Code Only When a Condition Is True

ifkeyword
(marks >= 33)condition in brackets
(true / false)
{block starts
... }block ends
snippetJAVA
1int marks = 72;
2if (marks >= 33) {
3 System.out.println("Pass");
4 System.out.println("Well done!");
5} else {
6 System.out.println("Fail");
7}
8System.out.println("Result checked");
💡 Concept in shortif runs its block only when the condition is true. else runs when it is false. Exactly one of the two blocks runs.
marks = ?marks >= 33 ?truefalseprintln("Pass")println("Fail")next line
Click a button to see which path Java takes.
Module 4if-else in action

A Real Example: Voting Eligibility

Main.java  JAVA
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Enter your age: ");
7 int age = sc.nextInt();
8 if (age >= 18) {
9 System.out.println("You can vote in the Jharkhand elections.");
10 System.out.println("Carry your Voter ID card.");
11 } else {
12 int years = 18 - age;
13 System.out.println("You can vote after " + years + " year(s).");
14 }
15 System.out.println("Thank you for using Voter Help.");
16 }
17}
Terminal
D:\java-practice> java Main.java
Enter your age: 15
You can vote after 3 year(s).
Thank you for using Voter Help.
💡 Concept in shortPut the condition in round brackets and the code to run in curly braces. Always use braces, even for one line: it prevents bugs when you add lines later.
Common mistakeWriting if (age >= 18); with a semicolon ends the if immediately, so the block below ALWAYS runs. A classic bug!
Module 4else-if ladder

The else-if Ladder: Many Choices, One Answer

snippetJAVA
1int marks = sc.nextInt();
2String grade;
3if (marks >= 90) {
4 grade = "A+";
5} else if (marks >= 75) {
6 grade = "A";
7} else if (marks >= 60) {
8 grade = "B";
9} else if (marks >= 33) {
10 grade = "C";
11} else {
12 grade = "F";
13}
14System.out.println("Grade: " + grade);
Click a button to see which path Java takes.
marks >= 90truegrade = "A+"falsemarks >= 75truegrade = "A"falsemarks >= 60truegrade = "B"falsemarks >= 33truegrade = "C"falsegrade = "F"
💡 Concept in shortJava checks conditions top to bottom and runs the first true one. Order matters: put the highest range first.
Module 4Watch it decide

Step Through: The Grade Program with marks = 81

Notice how Java skips the lines it does not need.

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 int marks = 81;
4 String grade;
5 if (marks >= 90) {
6 grade = "A+";
7 } else if (marks >= 75) {
8 grade = "A";
9 } else if (marks >= 60) {
10 grade = "B";
11 } else {
12 grade = "F";
13 }
14 System.out.println("Grade: " + grade);
15 boolean merit = grade.equals("A+") || grade.equals("A");
16 System.out.println("Merit certificate? " + merit);
17 }
18}
Output
Module 4Nested and combined

Nested if and Combined Conditions

Main.java  JAVA
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Username: ");
7 String user = sc.nextLine().trim();
8 System.out.print("Password: ");
9 String pass = sc.nextLine();
10
11 if (user.equalsIgnoreCase("admin")) {
12 if (pass.equals("Ranchi@2026")) {
13 System.out.println("Login successful");
14 } else {
15 System.out.println("Wrong password");
16 }
17 } else {
18 System.out.println("No such user");
19 }
20 int age = 25;
21 boolean adultWorker = age >= 18 && age <= 60;
22 System.out.println("Working age? " + adultWorker);
23 }
24}
Terminal
D:\java-practice> java Main.java
Username: Admin
Password: Ranchi@2026
Login successful
Working age? true
💡 Concept in shortA nested if is an if inside another if: the inner check happens only when the outer one is true. Use && and || to combine conditions into one.
Common mistakeCompare Strings with .equals(), never ==. == checks if they are the same object in memory, which can be false even for equal text.
In real projectsReal sites say "Invalid username or password" without saying which part was wrong. That is safer.
Module 4Ternary

The Ternary Operator: if-else in One Expression

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 int marks = 47;
4 String result = marks >= 33 ? "Pass" : "Fail";
5 System.out.println(result);
6
7 double cartTotal = 850;
8 int delivery = cartTotal >= 499 ? 0 : 40;
9 System.out.println("Delivery charge: Rs " + delivery);
10
11 int n = 7;
12 System.out.println(n + " is " + (n % 2 == 0 ? "even" : "odd"));
13 int a = 45, b = 78;
14 System.out.println("Bigger: " + (a > b ? a : b));
15 }
16}
Terminal
D:\java-practice> java Main.java
Pass
Delivery charge: Rs 0
7 is odd
Bigger: 78
conditiontrue / false
?
valueIfTrue
:
valueIfFalse
💡 Concept in shortcondition ? a : b gives a when the condition is true, otherwise b. Use it to choose between two values. For actions or longer logic, use a normal if-else.
Module 4switch

switch: Choose by Matching a Value

Main.java  JAVA
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.println("1 Litti Chokha 2 Dhuska 3 Pitha 4 Rugra curry");
7 System.out.print("Choice: ");
8 int choice = sc.nextInt();
9 switch (choice) {
10 case 1:
11 System.out.println("Litti Chokha: Rs 60");
12 break;
13 case 2:
14 System.out.println("Dhuska with aloo: Rs 40");
15 break;
16 case 3:
17 case 4:
18 System.out.println("Seasonal special, ask the counter");
19 break;
20 default:
21 System.out.println("Invalid choice");
22 }
23 }
24}
Terminal
D:\java-practice> java Main.java
1 Litti Chokha 2 Dhuska 3 Pitha 4 Rugra curry
Choice: 2
Dhuska with aloo: Rs 40
💡 Concept in shortswitch compares one value with many case labels and jumps to the match. break stops it. default runs when nothing matches. Works with int, char, String and enums.
Common mistakeForgetting break causes fall-through: the next case also runs. Sometimes useful (cases 3 and 4 above), usually a bug.
Module 4Modern switch

Switch Expressions with Arrows (Java 14+)

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 String day = "SAT";
4 String type = switch (day) {
5 case "SAT", "SUN" -> "Weekend";
6 case "MON", "TUE", "WED", "THU", "FRI" -> "Weekday";
7 default -> "Unknown";
8 };
9 System.out.println(day + " is a " + type);
10
11 int month = 7;
12 int days = switch (month) {
13 case 2 -> 28;
14 case 4, 6, 9, 11 -> 30;
15 default -> 31;
16 };
17 System.out.println("Month " + month + " has " + days + " days");
18 }
19}
Terminal
D:\java-practice> java Main.java
SAT is a Weekend
Month 7 has 31 days
💡 Concept in shortThe arrow form case X -> value needs no break (no fall-through) and the whole switch can return a value. Several labels can share one arm: case 4, 6, 9, 11.
In real projectsModern Java projects prefer switch expressions: shorter and safer.
Module 4Avoid these

Top Mistakes with Decisions in Java

✘ Wrong

if (marks = 33)
if (marks >= 33);
if (name == "Riya")
if (0 < x < 10)
case 1: ... (no break)

✔ Right

if (marks == 33)
if (marks >= 33) { ... }
if (name.equals("Riya"))
if (x > 0 && x < 10)
case 1 -> ... or add break
  1. 1
    = vs ==: one assigns, two compares
  2. 2
    Stray semicolon after if(...) ends the if
  3. 3
    Strings: use equals() / equalsIgnoreCase()
  4. 4
    No chained ranges: use &&
  5. 5
    Missing break in old-style switch
jshell (Java interactive shell)
// jshell: type Java and see the answer at once. Press Next line.
0 / 4
Module 4Hands-on

Code Lab: Try It Yourself

Main.java
Output of the starter code
D:\java-practice> java Main.java
Age: 10
Day (MON..SUN): tue
Tuesday offer: half price!
Ticket price: Rs 60
Change the code, then run it on your computer: ⬇ Download → open a terminal in that folder → java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).
Your tasks
  1. Add a rule: students aged 12 to 18 pay Rs 180
  2. Print "Free entry!" when the price is 0
  3. Rewrite the age rules as a switch on age groups
  4. Use a ternary to print "Weekend" or "Weekday"
PracticePractice 1 of 10 · Easy

Even or Odd

EasyScenario. A maths quiz app checks whether a number is even or odd.
💡 Concept used: A number is even when n % 2 == 0.

Your tasks

  1. Read a number
  2. Check n % 2 with if-else
  3. Also say if it is a multiple of 5
🏢 Used in real projects: Even/odd logic is used for alternate row colours in tables and odd-even vehicle rules.
EvenOdd.java  JAVA
1import java.util.Scanner;
2
3public class EvenOdd {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Enter a number: ");
7 int n = sc.nextInt();
8 if (n % 2 == 0) {
9 System.out.println(n + " is EVEN");
10 } else {
11 System.out.println(n + " is ODD");
12 }
13 if (n % 5 == 0) {
14 System.out.println(n + " is also a multiple of 5");
15 }
16 }
17}
PracticePractice 2 of 10 · Easy

Pass or Fail

EasyScenario. A result screen shows PASS or FAIL for one subject (pass mark 33).
💡 Concept used: if-else chooses between two outcomes.

Your tasks

  1. Read marks
  2. Validate 0 to 100 first
  3. Print PASS or FAIL
🏢 Used in real projects: Exam portals validate input and decide pass/fail exactly like this.
PassFail.java  JAVA
1import java.util.Scanner;
2
3public class PassFail {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Marks (0-100): ");
7 int marks = sc.nextInt();
8 if (marks < 0 || marks > 100) {
9 System.out.println("Invalid marks!");
10 } else if (marks >= 33) {
11 System.out.println("PASS with " + marks + " marks");
12 } else {
13 System.out.println("FAIL: needs " + (33 - marks) + " more marks");
14 }
15 }
16}
PracticePractice 3 of 10 · Easy

Largest of Three Numbers

EasyScenario. A sports day app finds the longest jump among three attempts.
💡 Concept used: Compare with &&, or keep a running maximum.

Your tasks

  1. Read three distances
  2. Find the largest using if / else if
  3. Check your answer with Math.max
🏢 Used in real projects: Leaderboards and "best score" features compare values like this.
Largest.java  JAVA
1import java.util.Scanner;
2
3public class Largest {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Three jumps (m): ");
7 double a = sc.nextDouble(), b = sc.nextDouble(), c = sc.nextDouble();
8 double best;
9 if (a >= b && a >= c) {
10 best = a;
11 } else if (b >= c) {
12 best = b;
13 } else {
14 best = c;
15 }
16 System.out.println("Best jump: " + best + " m");
17 System.out.println("Check with Math.max: " + Math.max(a, Math.max(b, c)));
18 }
19}
PracticePractice 4 of 10 · Easy

Leap Year Checker

EasyScenario. A calendar app needs to know whether February has 29 days.
💡 Concept used: Leap year: divisible by 4 and not by 100, or divisible by 400. Combine with && and ||.

Your tasks

  1. Read the year
  2. Write the condition in one boolean
  3. Print the days in February
🏢 Used in real projects: Calendar, payroll and date libraries implement exactly this rule.
LeapYear.java  JAVA
1import java.util.Scanner;
2
3public class LeapYear {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Year: ");
7 int y = sc.nextInt();
8 boolean leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
9 System.out.println(y + (leap ? " is a leap year" : " is not a leap year"));
10 System.out.println("February has " + (leap ? 29 : 28) + " days");
11 }
12}
PracticePractice 5 of 10 · Easy

Day Name with switch

EasyScenario. A school timetable app converts a day number (1-7) to a name.
💡 Concept used: An arrow switch expression returns a value directly.

Your tasks

  1. Read a number 1-7
  2. Use a switch expression to get the name
  3. Use default for invalid input
  4. Say if it is a holiday (Sunday)
🏢 Used in real projects: Menu systems, IVR phone menus and status codes map numbers to names with switch.
DayName.java  JAVA
1import java.util.Scanner;
2
3public class DayName {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Day number (1-7): ");
7 int d = sc.nextInt();
8 String name = switch (d) {
9 case 1 -> "Monday";
10 case 2 -> "Tuesday";
11 case 3 -> "Wednesday";
12 case 4 -> "Thursday";
13 case 5 -> "Friday";
14 case 6 -> "Saturday";
15 case 7 -> "Sunday";
16 default -> "Invalid";
17 };
18 System.out.println("Day: " + name);
19 System.out.println(d == 7 ? "Holiday!" : "School day");
20 }
21}
PracticePractice 6 of 10 · Medium

JAC Grade Calculator

MediumScenario. Give a grade and remark from the percentage: 90+ A+, 75+ A, 60+ B, 45+ C, 33+ D, else F.
💡 Concept used: An else-if ladder picks exactly one grade; check the highest range first.

Your tasks

  1. Read marks obtained and total marks
  2. Calculate the percentage as a double
  3. Use an else-if ladder for the grade
  4. Use a switch on the grade for the remark
🏢 Used in real projects: School ERPs and university result portals convert marks to grades with ladders like this.
Grade.java  JAVA
1import java.util.Scanner;
2
3public class Grade {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Marks obtained: ");
7 int got = sc.nextInt();
8 System.out.print("Total marks: ");
9 int total = sc.nextInt();
10 double pct = got * 100.0 / total;
11 String grade;
12 if (pct >= 90) grade = "A+";
13 else if (pct >= 75) grade = "A";
14 else if (pct >= 60) grade = "B";
15 else if (pct >= 45) grade = "C";
16 else if (pct >= 33) grade = "D";
17 else grade = "F";
18 String remark = switch (grade) {
19 case "A+", "A" -> "Excellent";
20 case "B", "C" -> "Good";
21 case "D" -> "Needs improvement";
22 default -> "Please meet the teacher";
23 };
24 System.out.printf("Percentage: %.2f%% Grade: %s (%s)%n", pct, grade, remark);
25 }
26}
PracticePractice 7 of 10 · Medium

Electricity Bill with Slabs

MediumScenario. Example home tariff: first 100 units Rs 6.30, next 100 units Rs 6.70, above 200 units Rs 7.40, plus fixed charge Rs 75.
💡 Concept used: Each slab is a range; an else-if ladder adds the cost of earlier slabs plus the current one.

Your tasks

  1. Read units consumed
  2. Apply the slabs with if / else if
  3. Add the fixed charge
  4. Print the total and average cost per unit
🏢 Used in real projects: Electricity, water and mobile data billing systems apply slab rates.
ElectricityBill.java  JAVA
1import java.util.Scanner;
2
3public class ElectricityBill {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Units consumed: ");
7 int u = sc.nextInt();
8 double energy;
9 if (u <= 100) {
10 energy = u * 6.30;
11 } else if (u <= 200) {
12 energy = 100 * 6.30 + (u - 100) * 6.70;
13 } else {
14 energy = 100 * 6.30 + 100 * 6.70 + (u - 200) * 7.40;
15 }
16 double total = energy + 75;
17 System.out.printf("Energy charge : Rs %,.2f%n", energy);
18 System.out.printf("Fixed charge : Rs %,.2f%n", 75.0);
19 System.out.printf("Total bill : Rs %,.2f%n", total);
20 System.out.printf("Average/unit : Rs %.2f%n", total / u);
21 }
22}
PracticePractice 8 of 10 · Medium

Login with Rules

MediumScenario. A school ERP login: the username is case-insensitive; the password must be 8+ characters and match exactly.
💡 Concept used: Use equalsIgnoreCase for the username, length() and equals for the password, and order the checks well.

Your tasks

  1. Read username and password
  2. Reject short passwords first
  3. Then check both match
  4. Print a safe generic error
🏢 Used in real projects: Every login system validates input, then compares credentials (real systems compare password hashes).
Login.java  JAVA
1import java.util.Scanner;
2
3public class Login {
4 public static void main(String[] args) {
5 final String USER = "teacher01";
6 final String PASS = "Dav#Ranchi9";
7 Scanner sc = new Scanner(System.in);
8 System.out.print("Username: ");
9 String u = sc.nextLine().trim();
10 System.out.print("Password: ");
11 String p = sc.nextLine();
12 if (p.length() < 8) {
13 System.out.println("Password must have at least 8 characters.");
14 } else if (u.equalsIgnoreCase(USER) && p.equals(PASS)) {
15 System.out.println("Welcome, " + u.toLowerCase() + "! You are logged in.");
16 } else {
17 System.out.println("Invalid username or password.");
18 }
19 }
20}
PracticePractice 9 of 10 · Hard

Bus Fare Rules

HardScenario. Jharkhand Travels: Rs 2/km. Under 5 free, 5-12 half, 60+ pay 75%. Night buses (21:00 or later) add Rs 50 unless the fare is 0.
💡 Concept used: Several independent decisions: an else-if ladder for age, then a separate if for the night charge.

Your tasks

  1. Read age, distance and departure hour
  2. Apply the age rules
  3. Add the night charge with a ternary
  4. Print the category and the final fare
🏢 Used in real projects: Railway, bus and airline booking systems combine many rules like these.
BusFare.java  JAVA
1import java.util.Scanner;
2
3public class BusFare {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Age, km, hour (0-23): ");
7 int age = sc.nextInt(), km = sc.nextInt(), hour = sc.nextInt();
8 double fare = km * 2;
9 String category;
10 if (age < 5) {
11 fare = 0;
12 category = "Infant (free)";
13 } else if (age <= 12) {
14 fare = fare / 2;
15 category = "Child (half)";
16 } else if (age >= 60) {
17 fare = fare * 0.75;
18 category = "Senior (25% off)";
19 } else {
20 category = "Adult";
21 }
22 int night = (hour >= 21 && fare > 0) ? 50 : 0;
23 System.out.println("Category : " + category);
24 System.out.printf("Fare : Rs %.2f%n", fare);
25 System.out.println("Night : Rs " + night);
26 System.out.printf("TOTAL : Rs %.2f%n", fare + night);
27 }
28}
PracticePractice 10 of 10 · Hard

Triangle Classifier

HardScenario. A geometry app checks if three sides can form a triangle and classifies it.
💡 Concept used: Validity needs all three conditions (&&); then a ladder decides equilateral / isosceles / scalene; Pythagoras checks right angles.

Your tasks

  1. Read three sides
  2. Check a + b > c for all three pairs
  3. Classify by equal sides
  4. Detect a right-angled triangle (sort sides with Math.max)
Tipreturn; inside main ends the program early.
🏢 Used in real projects: CAD tools and geometry engines validate shapes before drawing them.
Triangle.java  JAVA
1import java.util.Scanner;
2
3public class Triangle {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Three sides: ");
7 int a = sc.nextInt(), b = sc.nextInt(), c = sc.nextInt();
8 if (a + b <= c || a + c <= b || b + c <= a) {
9 System.out.println("Not a valid triangle");
10 return;
11 }
12 String type;
13 if (a == b && b == c) type = "Equilateral";
14 else if (a == b || b == c || a == c) type = "Isosceles";
15 else type = "Scalene";
16 int big = Math.max(a, Math.max(b, c));
17 int sumSq = a * a + b * b + c * c - big * big;
18 boolean right = sumSq == big * big;
19 System.out.println("Type: " + type + (right ? ", right-angled" : ""));
20 }
21}
Module 4Recap

Module 4 Recap & Quiz

What you learned

  • 1if (condition) { ... } else { ... }: exactly one block runs
  • 2else-if ladder: first true condition wins; check highest ranges first
  • 3Combine with && (and), || (or), ! (not)
  • 4Ternary: cond ? a : b chooses a value
  • 5switch with break, or arrow switch expressions case X -> value
  • 6Compare Strings with equals(), not ==

Quick quiz

if (x = 5) in Java...

An int assignment is not a boolean; javac rejects it.

marks = 80. Which runs first? if (m>=60) ... else if (m>=75)

The first true condition wins.

Correct way to compare Strings s and t?

equals compares the text.
MODULE 5

Loops: for, while & do-while

⏱ 4 hours10 practice examplesStep-through animationsCode Lab

You will learn

  • Why loops: repeat without copy-paste
  • for loops: start, condition, update
  • while and do-while loops
  • break, continue and labelled break
  • Nested loops for tables and patterns

You will build

  • A multiplication table
  • A number guessing game
  • An ATM PIN check with 3 tries
for(;;)for (int i = 1; i <= 10; i++)while (pin != ok)
Module 5Real-world use

Where Is This Used in Real Projects?

loopsrepeat work📩Bulk SMSsend to 500 parents📦Ordersprocess each order🎮Game loop60 frames / sec🏧ATM3 PIN attempts📋Reportsone row per student🔄Serverswait for requests

Real projects that use this

  • A school sends fee reminders to every parent with one loop
  • Payment systems process each transaction in a batch with a loop
  • Every game runs a while loop: read input, update, draw, repeat
  • Web servers loop forever, waiting for the next request
Module 5for loop

The for Loop: Repeat a Known Number of Times

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 for (int i = 1; i <= 5; i++) {
4 System.out.println("Welcome, student " + i);
5 }
6 System.out.println("Done!");
7
8 for (int n = 10; n >= 0; n -= 2) {
9 System.out.print(n + " ");
10 }
11 System.out.println();
12 }
13}
Terminal
D:\java-practice> java Main.java
Welcome, student 1
Welcome, student 2
Welcome, student 3
Welcome, student 4
Welcome, student 5
Done!
10 8 6 4 2 0
for (
int i = 11. start
(once)
; i <= 52. condition
(checked each time)
; i++3. update
(after each round)
) { body }repeated code
💡 Concept in shortA for loop has three parts: start (runs once), condition (checked before every round), update (after every round). The body repeats while the condition is true.
Module 5How it flows

The Loop Flowchart

int i = 1 (start)i <= 5 ?trueloop bodyi++ (update)repeatfalseafter loop
💡 Concept in shortWatch the orange dot: start → check → body → update → check again ... until the condition becomes false, then Java continues after the loop.
LoopChecks conditionUse when
forbefore each roundyou know how many times
whilebefore each roundrepeat until something happens
do-whileafter each roundbody must run at least once (menus)
Common mistakeIf the condition never becomes false you get an infinite loop. Press Ctrl+C to stop it.
Module 5Watch the loop

Step Through: Adding Up Monthly Savings

Watch month go 1, 2, 3, 4 and total grow. The running total pattern appears in every billing and report program.

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 int total = 0;
4 for (int month = 1; month <= 4; month++) {
5 int saved = month * 100;
6 total = total + saved;
7 System.out.println("Month " + month + ": total " + total);
8 }
9 System.out.println("Final total: " + total);
10 }
11}
Output
Module 5while

while Loops: Repeat Until Something Happens

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 int countdown = 5;
4 while (countdown > 0) {
5 System.out.print(countdown + "... ");
6 countdown--;
7 }
8 System.out.println("Lift off! Chandrayaan launched!");
9
10 double balance = 10000;
11 int years = 0;
12 while (balance < 20000) {
13 balance = balance * 1.08; // 8% growth per year
14 years++;
15 }
16 System.out.printf("Money doubles in %d years: Rs %.2f%n", years, balance);
17 }
18}
Terminal
D:\java-practice> java Main.java
5... 4... 3... 2... 1... Lift off! Chandrayaan launched!
Money doubles in 10 years: Rs 21589.25
💡 Concept in shortwhile (condition) keeps repeating as long as the condition is true. Use it when you do not know in advance how many rounds are needed.
Common mistakeSomething inside the loop must change the condition (countdown--), otherwise it never stops.
In real projectsBank apps and SIP calculators use "how many years until..." loops like this.
Module 5do-while

do-while: Run at Least Once (Menus)

Main.java  JAVA
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 int balance = 5000, choice;
7 do {
8 System.out.println("1 Balance 2 Withdraw 3 Exit");
9 System.out.print("Choose: ");
10 choice = sc.nextInt();
11 if (choice == 1) {
12 System.out.println("Balance: Rs " + balance);
13 } else if (choice == 2) {
14 System.out.print("Amount: ");
15 int amt = sc.nextInt();
16 if (amt <= balance) { balance -= amt; System.out.println("Collect Rs " + amt); }
17 else System.out.println("Insufficient balance");
18 }
19 } while (choice != 3);
20 System.out.println("Thank you for banking with us!");
21 }
22}
Terminal
D:\java-practice> java Main.java
1 Balance 2 Withdraw 3 Exit
Choose: 1
Balance: Rs 5000
1 Balance 2 Withdraw 3 Exit
Choose: 2
Amount: 1500
Collect Rs 1500
1 Balance 2 Withdraw 3 Exit
Choose: 2
Amount: 9000
Insufficient balance
1 Balance 2 Withdraw 3 Exit
Choose: 3
Thank you for banking with us!
💡 Concept in shortdo { ... } while (condition); runs the body first and checks afterwards, so it always runs at least once. Perfect for menus that must be shown before the user can choose.
In real projectsATMs, ticket machines and console tools all run a menu loop like this.
Module 5break and continue

break, continue and Labelled break

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 for (int roll = 1; roll <= 10; roll++) {
4 if (roll == 4) {
5 System.out.println(roll + " absent - skip");
6 continue; // jump to the next roll
7 }
8 if (roll == 7) {
9 System.out.println("Found topper at roll " + roll);
10 break; // leave the loop
11 }
12 System.out.println("Checked roll " + roll);
13 }
14 outer:
15 for (int row = 1; row <= 3; row++) {
16 for (int seat = 1; seat <= 4; seat++) {
17 if (row == 2 && seat == 3) {
18 System.out.println("Empty seat found at row " + row + " seat " + seat);
19 break outer; // leave BOTH loops
20 }
21 }
22 }
23 }
24}
Terminal
D:\java-practice> java Main.java
Checked roll 1
Checked roll 2
Checked roll 3
4 absent - skip
Checked roll 5
Checked roll 6
Found topper at roll 7
Empty seat found at row 2 seat 3
💡 Concept in shortcontinue skips the rest of this round. break leaves the loop completely. A label like outer: lets break outer; leave nested loops at once.
In real projectsSearch features stop with break as soon as the item is found.
Module 5Nested loops

Nested Loops: Tables and Patterns

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 for (int row = 1; row <= 4; row++) {
4 for (int col = 1; col <= row; col++) {
5 System.out.print("* ");
6 }
7 System.out.println();
8 }
9 System.out.println();
10 for (int t = 2; t <= 3; t++) {
11 for (int i = 1; i <= 5; i++) {
12 System.out.printf("%d x %d = %-3d", t, i, t * i);
13 }
14 System.out.println();
15 }
16 }
17}
Terminal
D:\java-practice> java Main.java
*
* *
* * *
* * * *
 
2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 2 x 4 = 8 2 x 5 = 10
3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 3 x 5 = 15
💡 Concept in shortA loop inside a loop: the inner loop runs completely for each round of the outer loop. Outer = rows, inner = columns.
rowinner loop runsprints
1col = 1*
2col = 1..2* *
3col = 1..3* * *
4col = 1..4* * * *
In real projectsSeating charts, calendars, game boards and spreadsheets are all rows x columns.
Module 5Watch nested loops

Step Through: A 3 x 2 Seating Chart

The inner loop finishes all its rounds (A, B) before the outer loop moves to the next row.

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 for (int row = 1; row <= 3; row++) {
4 for (char seat = 'A'; seat <= 'B'; seat++) {
5 System.out.print(row + "" + seat + " ");
6 }
7 System.out.println();
8 }
9 }
10}
Output
Module 5Hands-on

Code Lab: Try It Yourself

Main.java
Output of the starter code
D:\java-practice> java Main.java
*
* *
* * *
* * * *
* * * * *
Sum 1..100 = 5050
First number whose square > 500: 23
Change the code, then run it on your computer: ⬇ Download → open a terminal in that folder → java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).
Your tasks
  1. Change n to 8
  2. Print only multiples of 3 between 1 and 30
  3. Print a countdown from 10 to 1
  4. Rewrite the sum using a while loop
PracticePractice 1 of 10 · Easy

Multiplication Table

EasyScenario. A primary-school teacher prints any table neatly.
💡 Concept used: A for loop from 1 to 10 with printf alignment.

Your tasks

  1. Read the table number
  2. Loop i = 1 to 10
  3. Print n x i = result aligned
🏢 Used in real projects: Report generators print one row per loop round.
Table.java  JAVA
1import java.util.Scanner;
2
3public class Table {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Which table? ");
7 int n = sc.nextInt();
8 for (int i = 1; i <= 10; i++) {
9 System.out.printf("%3d x %2d = %4d%n", n, i, n * i);
10 }
11 }
12}
PracticePractice 2 of 10 · Easy

Sum and Average of N Marks

EasyScenario. A teacher enters marks for N students; the program shows the total and average.
💡 Concept used: Running total: start at 0 and add inside the loop.

Your tasks

  1. Read N
  2. Loop N times reading marks
  3. Keep a running total
  4. Print total and average
🏢 Used in real projects: Billing, attendance and marks systems all add values in a loop.
SumMarks.java  JAVA
1import java.util.Scanner;
2
3public class SumMarks {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("How many students? ");
7 int n = sc.nextInt();
8 int total = 0;
9 for (int i = 1; i <= n; i++) {
10 System.out.print("Marks of student " + i + ": ");
11 total += sc.nextInt();
12 }
13 System.out.println("Total : " + total);
14 System.out.printf("Average : %.2f%n", (double) total / n);
15 }
16}
PracticePractice 3 of 10 · Easy

Countdown Timer

EasyScenario. An exam hall display counts down the last 10 seconds.
💡 Concept used: A for loop can count backwards with i--.

Your tasks

  1. Loop from 10 down to 1
  2. Print each number on one line
  3. Print "Time up!" after the loop
🏢 Used in real projects: Countdown timers in exams, microwaves and rocket launches.
Countdown.java  JAVA
1public class Countdown {
2 public static void main(String[] args) {
3 for (int s = 10; s >= 1; s--) {
4 System.out.print(s + (s > 1 ? ", " : ""));
5 }
6 System.out.println();
7 System.out.println("Time up! Put your pens down.");
8 }
9}
PracticePractice 4 of 10 · Easy

Digits of a Number

EasyScenario. A bank verifies account numbers by counting digits and adding them.
💡 Concept used: n % 10 gives the last digit; n / 10 removes it. Repeat with while (n > 0).

Your tasks

  1. Read a long number
  2. Count digits and sum them
  3. Build the reversed number
🏢 Used in real projects: Check-digit algorithms for account numbers, ISBNs and Aadhaar-style IDs process digits in loops.
Digits.java  JAVA
1import java.util.Scanner;
2
3public class Digits {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Number: ");
7 long n = sc.nextLong();
8 long original = n, reversed = 0;
9 int count = 0, sum = 0;
10 while (n > 0) {
11 int d = (int) (n % 10);
12 sum += d;
13 count++;
14 reversed = reversed * 10 + d;
15 n /= 10;
16 }
17 System.out.println("Digits : " + count);
18 System.out.println("Sum : " + sum);
19 System.out.println("Reversed: " + reversed);
20 System.out.println("Palindrome? " + (reversed == original));
21 }
22}
PracticePractice 5 of 10 · Easy

Number Guessing Game

EasyScenario. The computer picks a secret number 1-50; the player gets hints until correct.
💡 Concept used: A while loop repeats until the guess equals the secret; a counter tracks attempts.

Your tasks

  1. Pick the secret with new Random(11).nextInt(50) + 1
  2. Loop until correct
  3. Print Too high / Too low
  4. Count attempts
🏢 Used in real projects: Games combine loops and random numbers; OTP retry screens use the same loop.
Guess.java  JAVA
1import java.util.Random;
2import java.util.Scanner;
3
4public class Guess {
5 public static void main(String[] args) {
6 int secret = new Random(11).nextInt(50) + 1;
7 Scanner sc = new Scanner(System.in);
8 int guess = 0, attempts = 0;
9 System.out.println("I am thinking of a number from 1 to 50...");
10 while (guess != secret) {
11 System.out.print("Your guess: ");
12 guess = sc.nextInt();
13 attempts++;
14 if (guess > secret) System.out.println("Too high!");
15 else if (guess < secret) System.out.println("Too low!");
16 }
17 System.out.println("Correct! It was " + secret + ". Attempts: " + attempts);
18 }
19}
PracticePractice 6 of 10 · Medium

ATM PIN with 3 Attempts

MediumScenario. The card is blocked after 3 wrong PINs.
💡 Concept used: A for loop with break on success, plus a boolean flag to know if the loop ended without success.

Your tasks

  1. Loop attempt = 1 to 3
  2. break when the PIN is correct
  3. Show attempts left
  4. After the loop, block the card if never correct
🏢 Used in real projects: ATMs, UPI apps and phone lock screens limit attempts exactly like this.
AtmPin.java  JAVA
1import java.util.Scanner;
2
3public class AtmPin {
4 public static void main(String[] args) {
5 final int PIN = 4826;
6 Scanner sc = new Scanner(System.in);
7 boolean ok = false;
8 for (int attempt = 1; attempt <= 3; attempt++) {
9 System.out.print("Attempt " + attempt + "/3 - PIN: ");
10 if (sc.nextInt() == PIN) {
11 ok = true;
12 break;
13 }
14 System.out.println("Wrong PIN. " + (3 - attempt) + " attempt(s) left.");
15 }
16 System.out.println(ok ? "PIN accepted. Welcome!" : "Card blocked! Contact your branch.");
17 }
18}
PracticePractice 7 of 10 · Medium

Prime Numbers in a Range

MediumScenario. A maths club lists all primes between two numbers.
💡 Concept used: Nested loops: for each number, test divisors up to its square root; break as soon as one divides it.

Your tasks

  1. Read start and end
  2. Outer loop over numbers
  3. Inner loop checks divisors 2..sqrt(n)
  4. Print primes and their count
🏢 Used in real projects: Encryption (RSA) and hashing depend on prime numbers.
Primes.java  JAVA
1import java.util.Scanner;
2
3public class Primes {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Start and end: ");
7 int a = sc.nextInt(), b = sc.nextInt(), count = 0;
8 for (int n = Math.max(2, a); n <= b; n++) {
9 boolean prime = true;
10 for (int d = 2; d * d <= n; d++) {
11 if (n % d == 0) {
12 prime = false;
13 break;
14 }
15 }
16 if (prime) {
17 System.out.print(n + " ");
18 count++;
19 }
20 }
21 System.out.println("\nPrimes found: " + count);
22 }
23}
PracticePractice 8 of 10 · Medium

Pyramid and Diamond Patterns

MediumScenario. Pattern printing trains loop thinking (a favourite in placement tests).
💡 Concept used: Each row prints spaces then stars; the bottom half is the top half in reverse.

Your tasks

  1. Read the height h
  2. Row i: (h - i) spaces and (2i - 1) stars
  3. Loop back down for the diamond
  4. Use " ".repeat(k)
🏢 Used in real projects: Row-by-row thinking draws game boards, progress bars and charts.
Patterns.java  JAVA
1import java.util.Scanner;
2
3public class Patterns {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Height: ");
7 int h = sc.nextInt();
8 for (int i = 1; i <= h; i++) {
9 System.out.println(" ".repeat(h - i) + "*".repeat(2 * i - 1));
10 }
11 for (int i = h - 1; i >= 1; i--) {
12 System.out.println(" ".repeat(h - i) + "*".repeat(2 * i - 1));
13 }
14 }
15}
PracticePractice 9 of 10 · Hard

Savings Goal Simulator

HardScenario. Neha saves for a Rs 15,000 laptop: Rs 1,000 a month, increasing by Rs 200 each month, with 0.5% monthly interest.
💡 Concept used: A while loop simulates month by month until the goal is reached.

Your tasks

  1. Loop while savings < goal
  2. Each month: add interest, then the deposit
  3. Increase the deposit by 200
  4. Print a table and the months needed
🏢 Used in real projects: SIP, recurring-deposit and loan apps simulate month-by-month growth.
SavingsGoal.java  JAVA
1public class SavingsGoal {
2 public static void main(String[] args) {
3 double goal = 15000, savings = 0;
4 int deposit = 1000, month = 0;
5 System.out.printf("%5s %8s %10s%n", "Month", "Deposit", "Savings");
6 while (savings < goal) {
7 month++;
8 savings = savings * 1.005 + deposit;
9 System.out.printf("%5d %8d %,10.2f%n", month, deposit, savings);
10 deposit += 200;
11 }
12 System.out.println("Goal reached in " + month + " months!");
13 }
14}
PracticePractice 10 of 10 · Hard

Simple Interactive Quiz

HardScenario. A 3-question quiz loops through questions, scores answers and lets the user play again.
💡 Concept used: A do-while loop for "play again", a for loop for questions, and a switch to pick each question.

Your tasks

  1. Loop over 3 questions with a switch inside
  2. Compare answers with equalsIgnoreCase
  3. Print the score
  4. Ask "Play again? (y/n)"
🏢 Used in real projects: Quiz apps and online tests loop over questions and keep score.
Quiz.java  JAVA
1import java.util.Scanner;
2
3public class Quiz {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 String again;
7 do {
8 int score = 0;
9 for (int q = 1; q <= 3; q++) {
10 String question = switch (q) {
11 case 1 -> "Capital of Jharkhand?";
12 case 2 -> "Keyword to make a constant in Java?";
13 default -> "Method where a Java program starts?";
14 };
15 String answer = switch (q) {
16 case 1 -> "Ranchi";
17 case 2 -> "final";
18 default -> "main";
19 };
20 System.out.print("Q" + q + ". " + question + " ");
21 if (sc.nextLine().trim().equalsIgnoreCase(answer)) score++;
22 }
23 System.out.println("Score: " + score + "/3");
24 System.out.print("Play again? (y/n) ");
25 again = sc.nextLine();
26 } while (again.equalsIgnoreCase("y"));
27 System.out.println("Thanks for playing!");
28 }
29}
Module 5Recap

Module 5 Recap & Quiz

What you learned

  • 1for (start; condition; update) when you know the count
  • 2while (condition) repeats until something changes; update inside the loop!
  • 3do { } while ( ); runs at least once (menus)
  • 4break leaves, continue skips; labels break outer loops
  • 5Nested loops: inner runs fully for each outer round
  • 6Patterns: running total, counting, searching, digit loops

Quick quiz

How many times does for (int i = 2; i < 8; i++) run?

i = 2..7: six times.

Which loop always runs its body at least once?

do-while checks after the body.

Which keyword skips to the next round?

continue skips the rest of this round.
PART 1 COMPLETE

Well done!

You finished Java Foundations: 5 modules and 50 practice examples.

Before moving on

  • Re-type every practice example yourself without looking
  • Save your work in D:\java-practice\part1
  • Try the quizzes again until you get all of them right
  • Change one thing in each example and predict the output before you run it
  • Solve the Hard examples without looking at the solution first
{ } Java java Main.java main()
☕ Code Lab🌐 Online compiler
Edit the code here. Java runs on your computer (or an online compiler), not in the browser.
Expected output of the original code
Run it on your computer
  1. Install JDK 21 (adoptium.net) and check: java -version
  2. Download .java into D:\java-practice
  3. Open a terminal there and type java Main.java
  4. Or click Copy code and paste it into the online compiler