🔧 [5] Operators & Control Flow — Decision Making in Java!
✨ Introduction
Ready to make your code a little smarter? 🚀 Once you've got a handle on variables and data types, the next big leap is teaching your program how to think, decide, and act.
That's where operators and control flow come in. Whether it's doing some quick math 🧮, checking conditions 🤔, or repeating tasks 🔁 — these tools help your program react to the world like a mini decision-maker.
In this guide, you'll explore Java's powerful tools like arithmetic, logical, and comparison operators. Then we'll
dive into decision-making structures like if and switch, and loop through tasks using
for, while, and do-while loops.
By the end, you'll have the building blocks to control your program's flow and bring logic to life! 💡
➕ Java Operators Overview
🧮 Arithmetic Operators
These perform basic math operations.
| Operator | Description | Example |
|---|---|---|
| + | Addition | a + b |
| - | Subtraction | a - b |
| * | Multiplication | a * b |
| / | Division | a / b |
| % | Remainder (Modulus) | a % b |
🔎 Relational (Comparison) Operators
These operators are used in conditions to compare values.
| Operator | Description | Example |
|---|---|---|
| == | Equal to | a == b |
| != | Not equal to | a != b |
| > | Greater than | a > b |
| < | Less than | a < b |
| >= | Greater than or equal to | a >= b |
| <= | Less than or equal to | a <= b |
🧠 Logical Operators
These operators combine multiple conditions together.
| Operator | Description | Example |
|---|---|---|
| && | AND (both conditions must be true) | a > 5 && b < 10 |
| || | OR (at least one condition is true) | a > 5 || b < 10 |
| ! | NOT (reverses the condition) | !isReady |
🧪 Examples of Operators — Building Logic
🧮 Arithmetic Operators
int a = 12, b = 4;
System.out.println(a + b); // ➕ 16 (Addition)
System.out.println(a - b); // ➖ 8 (Subtraction)
System.out.println(a * b); // ✖️ 48 (Multiplication)
System.out.println(a / b); // ➗ 3 (Division)
System.out.println(a % b); // 🔁 0 (Remainder)
🔎 Relational (Comparison) Operators
int x = 7, y = 10;
System.out.println(x == y); // ❓ false (7 is not equal to 10)
System.out.println(x != y); // ✅ true (7 is not equal to 10)
System.out.println(x > y); // ❌ false (7 is not greater than 10)
System.out.println(x < y); // ✅ true (7 is less than 10)
System.out.println(x <= 7); // ✅ true (7 is less than or equal to 7)
🧠 Logical Operators
boolean isAdult = true;
boolean hasTicket = false;
int score = 85;
System.out.println(isAdult && hasTicket); // ❌ false (only one is true)
System.out.println(isAdult || hasTicket); // ✅ true (at least one is true)
System.out.println(!(score > 50)); // ❌ false (score is greater than 50, negated)
System.out.println(score > 80 && score < 100); // ✅ true (both conditions met)
System.out.println(score < 50 || score > 90); // ❌ false (neither condition is true)
🧩 Practice Questions — Try It Yourself
🧮 Arithmetic Operator Questions
// Q1: Add two numbers: 12 and 8
// Q2: Subtract 5 from 20
// Q3: Multiply 7 and 6
// Q4: Divide 100 by 25
// Q5: Find the remainder when 22 is divided by 7
// Hint: Use +, -, *, /, % operators respectively
🔎 Relational Operator Questions
// Q1: Check if 10 is equal to 10
// Q2: Check if 15 is not equal to 20
// Q3: Is 100 greater than 99?
// Q4: Is 25 less than 15?
// Q5: Is 30 greater than or equal to 30?
// Hint: Use ==, !=, >, <, >=, <=
🧠 Logical Operator Questions
// Q1: Check if a person is an adult (age >= 18) AND has a valid ID
// Q2: Check if a student passed (marks > 40) OR has grace marks
// Q3: Reverse the condition: "isRaining"
// Q4: Check if temperature > 20 AND < 35
// Q5: Check if a number is either less than 0 OR greater than 100
// Hint: Use &&, ||, ! for combining conditions
📝 Answers with Explanations
🧮 Arithmetic Operator Answers
// Q1
System.out.println(12 + 8); // ➕ 20
// ✅ Explanation: Adds two integers.
// ❌ Common Mistake: Using strings instead: "12" + "8" gives "128"
// Q2
System.out.println(20 - 5); // ➖ 15
// ✅ Explanation: Subtracts 5 from 20.
// ❌ Common Mistake: Reversing the operands: 5 - 20 = -15
// Q3
System.out.println(7 * 6); // ✖️ 42
// ✅ Explanation: Multiplies 7 and 6.
// ❌ Common Mistake: Typing x instead of *
// Q4
System.out.println(100 / 25); // ➗ 4
// ✅ Explanation: Integer division; no decimals here.
// ❌ Common Mistake: Using 0 as divisor (runtime error)
// Q5
System.out.println(22 % 7); // 🔁 1
// ✅ Explanation: 7 fits in 22 three times (21), remainder is 1.
// ❌ Common Mistake: Confusing modulus with division
🔎 Relational Operator Answers
// Q1
System.out.println(10 == 10); // ✅ true
// ✅ Explanation: Both sides are equal.
// ❌ Common Mistake: Using = instead of ==
// Q2
System.out.println(15 != 20); // ✅ true
// ✅ Explanation: 15 is not equal to 20.
// ❌ Common Mistake: Reversing != to == by habit
// Q3
System.out.println(100 > 99); // ✅ true
// ✅ Explanation: 100 is greater than 99.
// ❌ Common Mistake: Using < accidentally
// Q4
System.out.println(25 < 15); // ✅ false
// ✅ Explanation: 25 is not less than 15.
// ❌ Common Mistake: Reading it backwards
// Q5
System.out.println(30 >= 30); // ✅ true
// ✅ Explanation: 30 is equal to 30, so ≥ is true.
// ❌ Common Mistake: Confusing >= with >
🧠 Logical Operator Answers
// Q1
int age = 20;
boolean hasID = true;
System.out.println(age >= 18 && hasID); // ✅ true
// ✅ Explanation: Both conditions are true
// ❌ Common Mistake: Using & instead of &&
// Q2
int marks = 35;
boolean grace = true;
System.out.println(marks > 40 || grace); // ✅ true
// ✅ Explanation: One condition is true (grace)
// ❌ Common Mistake: Using && instead of ||
// Q3
boolean isRaining = true;
System.out.println(!isRaining); // ✅ false
// ✅ Explanation: ! reverses true to false
// ❌ Common Mistake: Writing ! without parentheses or variable
// Q4
int temp = 25;
System.out.println(temp > 20 && temp < 35); // ✅ true
// ✅ Explanation: 25 is in the range 21-34
// ❌ Common Mistake: Using || instead of &&
// Q5
int number = -5;
System.out.println(number < 0 || number > 100); // ✅ true
// ✅ Explanation: One condition is true (number < 0)
// ❌ Common Mistake: Not grouping conditions properly
💡 Tip: Practice modifying the values above and observe how the output changes — this is the best way to master logic!
🧩 Word Problems: Build DSA Thinking Using Java Operators
🧮 Arithmetic Operators — 5 Problems
- Shopping Cart Total: You bought 3 notebooks for ₹40 each and 2 pens for ₹15 each. Find the total bill amount.
- Average Marks: Your scores in 3 subjects are 78, 85, and 92. Find the average score.
- Area of Rectangle: Given length = 15 units and width = 8 units, calculate the area.
- Splitting Bill: You have ₹1,000 and want to divide it equally among 4 friends. How much will each get?
- Leftover Chocolates: You bought 53 chocolates. If each kid gets 6, how many are left after distribution?
🔎 Relational Operators — 5 Problems
- Age Eligibility: Check if a person aged 17 is eligible to vote (must be 18 or older).
- Exam Pass Check: A student scores 43 marks. Pass mark is 40. Did they pass?
- Speeding Fine: A car is going at 95 km/h in a 90 km/h zone. Should it get fined?
- Same Numbers: Check if two entered numbers are exactly the same.
- Budget Check: You want to buy a phone for ₹25,000. Your budget is ₹20,000. Is it affordable?
🧠 Logical Operators — 5 Problems
- Exam Criteria: You passed both theory (≥40) and practical (≥35). Check if you passed overall.
- Discount Eligibility: You're eligible for a discount if you're a student or a senior citizen. Write logic for that.
- Temperature Range: Check if temperature is between 20°C and 30°C (inclusive).
- Weekend Checker: Today is Saturday. Write a condition that checks if today is Saturday or Sunday.
- Security Check: You're not allowed if you're on the banned list. Write a NOT condition to allow entry if not banned.
✅ Answers: Word Problems on Operators
🧮 Arithmetic Operator Answers
// Q1
int total = (3 * 40) + (2 * 15);
System.out.println("Total Bill: ₹" + total); // ₹150
// Q2
int avg = (78 + 85 + 92) / 3;
System.out.println("Average Marks: " + avg); // 85
// Q3
int area = 15 * 8;
System.out.println("Area: " + area); // 120
// Q4
int eachGets = 1000 / 4;
System.out.println("Each gets: ₹" + eachGets); // ₹250
// Q5
int leftover = 53 % 6;
System.out.println("Leftover chocolates: " + leftover); // 5
🔎 Relational Operator Answers
// Q1
int age = 17;
System.out.println(age >= 18); // false
// Q2
int marks = 43;
System.out.println(marks >= 40); // true
// Q3
int speed = 95;
System.out.println(speed > 90); // true
// Q4
int a = 10, b = 10;
System.out.println(a == b); // true
// Q5
int price = 25000, budget = 20000;
System.out.println(price <= budget); // false
🧠 Logical Operator Answers
// Q1
int theory = 45, practical = 37;
System.out.println(theory >= 40 && practical >= 35); // true
// Q2
boolean isStudent = true;
boolean isSenior = false;
System.out.println(isStudent || isSenior); // true
// Q3
int temp = 25;
System.out.println(temp >= 20 && temp <= 30); // true
// Q4
String day = "Saturday";
System.out.println(day.equals("Saturday") || day.equals("Sunday")); // true
// Q5
boolean isBanned = false;
System.out.println(!isBanned); // true (entry allowed)
🧠 15 Arithmetic Challenger Problems
- Train Distance: A train travels at 60 km/h. How far will it go in 5.5 hours?
- Currency Converter: Convert ₹500 to USD (Assume 1 USD = ₹82).
- Square Perimeter: Find the perimeter of a square with side length 19 cm.
- Apple Distribution: You have 365 apples. Distribute equally among 12 baskets. How many does each get?
- Mobile Data Usage: You have 1.5GB per day for 30 days. What's the total monthly data?
- Library Fine: ₹2 fine/day. You returned a book 18 days late. Total fine?
- Bill Split with Tip: Your total bill is ₹750. Tip is 10%. Split among 5 friends.
- Simple Interest: ₹1000 at 5% annual interest for 2 years.
- Discount Price: Original price is ₹800. Discount = 15%. What's the new price?
- Circle Area: Radius is 7 cm. Use 3.14 as π.
- Temperature Convert: Convert 100°C to Fahrenheit (F = C × 9/5 + 32).
- Electricity Bill: Unit rate = ₹6.5. Total units = 175. Total bill?
- Marks Percentage: You scored 540/600. What's your percentage?
- Speed Calculation: You ran 400m in 50 seconds. What's the speed in m/s?
- Time Taken: Distance = 900 km, Speed = 60 km/h. Time taken?
🧮 Arithmetic Operator Answers
public class ArithmeticChallengerAnswers {
public static void main(String[] args) {
// Q1: Train Distance
double distance = 60 * 5.5;
System.out.println("Q1 - Distance Travelled: " + distance + " km"); // 330.0 km
// Q2: Currency Converter
double usd = 500.0 / 82;
System.out.println("Q2 - USD Amount: $" + usd); // ~$6.10
// Q3: Square Perimeter
int perimeter = 4 * 19;
System.out.println("Q3 - Perimeter: " + perimeter + " cm"); // 76 cm
// Q4: Apple Distribution
int applesEach = 365 / 12;
System.out.println("Q4 - Apples per basket: " + applesEach); // 30
// Q5: Mobile Data Usage
double totalData = 1.5 * 30;
System.out.println("Q5 - Total Monthly Data: " + totalData + " GB"); // 45.0 GB
// Q6: Library Fine
int fine = 2 * 18;
System.out.println("Q6 - Total Fine: ₹" + fine); // ₹36
// Q7: Bill Split with Tip
double totalWithTip = 750 + (0.10 * 750);
double perPerson = totalWithTip / 5;
System.out.println("Q7 - Each Pays: ₹" + perPerson); // ₹165.0
// Q8: Simple Interest
// Formula:
// SI = (P × R × T) / 100
// Where:
// P = Principal amount
// R = Rate of interest (annual)
// T = Time in years
double si = (1000 * 5 * 2) / 100.0;
System.out.println("Q8 - Simple Interest: ₹" + si); // ₹100.0
// Q9: Discount Price
double discount = 0.15 * 800;
double newPrice = 800 - discount;
System.out.println("Q9 - Discounted Price: ₹" + newPrice); // ₹680.0
// Q10: Circle Area
// Formula:
// A = π × r²
// Where:
// A = Area of the circle
// π = Pi (approximately 3.1416)
// r = Radius of the circle
double area = 3.14 * 7 * 7;
System.out.println("Q10 - Circle Area: " + area + " cm²"); // 153.86 cm²
// Q11: Temperature Convert
// Temperature Conversion: Celsius to Fahrenheit
// Formula:
// F = (C × 9/5) + 32
// Where:
// C = Temperature in Celsius
// F = Temperature in Fahrenheit
double fahrenheit = (100 * 9.0/5.0) + 32;
System.out.println("Q11 - Fahrenheit: " + fahrenheit + "°F"); // 212.0°F
// Q12: Electricity Bill
double bill = 6.5 * 175;
System.out.println("Q12 - Electricity Bill: ₹" + bill); // ₹1137.5
// Q13: Marks Percentage
double percent = (540.0 / 600.0) * 100;
System.out.println("Q13 - Percentage: " + percent + "%"); // 90.0%
// Q14: Speed Calculation
double speed = 400.0 / 50.0;
System.out.println("Q14 - Speed: " + speed + " m/s"); // 8.0 m/s
// Q15: Time Taken
double time = 900.0 / 60.0;
System.out.println("Q15 - Time Taken: " + time + " hours"); // 15.0 hours
}
}
🔎 15 Relational Challenger Problems
- Eligibility Check: Check if someone who is 12 is a teenager (13-19).
- Perfect Score: Check if a student's score is exactly 100.
- Profit or Loss: Selling price = ₹950, cost price = ₹1000. Was it a loss?
- Equal Sides: Check if a triangle with sides 5, 5, 5 is equilateral.
- Even Age: Check if an age is even (divisible by 2).
- Greater Amount: Compare two bank balances: ₹15,400 and ₹16,000.
- Top Rank: A student scores the highest in class. Check if score equals max score.
- Loan Limit: User requests ₹50,000. Max allowed is ₹40,000. Approve?
- Rectangle or Square: Check if length and breadth are equal.
- Temperature Comparison: Is today hotter than yesterday?
- Speed Violation: Check if car exceeds 80 km/h speed limit.
- Correct Pin: Verify if entered PIN matches the correct one.
- Attendance Requirement: Is 72% attendance enough for required 75%?
- Minimum Age: Check if user is at least 21 to rent a car.
- Three Equal Numbers: Are all 3 entered numbers the same?
🔎 Relational Operator Answers
public class RelationalChallengerAnswers {
public static void main(String[] args) {
// Q1: Eligibility Check (Teenager: age 13-19)
int age = 12;
boolean isTeenager = age >= 13 && age <= 19;
System.out.println("Q1 - Is Teenager? " + isTeenager); // false
// Q2: Perfect Score
int score = 100;
boolean isPerfect = score == 100;
System.out.println("Q2 - Is Perfect Score? " + isPerfect); // true
// Q3: Profit or Loss
int sp = 950, cp = 1000;
boolean isLoss = sp < cp;
System.out.println("Q3 - Was it a Loss? " + isLoss); // true
// Q4: Equal Sides
int s1 = 5, s2 = 5, s3 = 5;
boolean isEquilateral = (s1 == s2) && (s2 == s3);
System.out.println("Q4 - Is Equilateral? " + isEquilateral); // true
// Q5: Even Age
int ageCheck = 24;
boolean isEven = ageCheck % 2 == 0;
System.out.println("Q5 - Is Even Age? " + isEven); // true
// Q6: Greater Amount
int balance1 = 15400, balance2 = 16000;
boolean isSecondGreater = balance2 > balance1;
System.out.println("Q6 - Is ₹16000 greater than ₹15400? " + isSecondGreater); // true
// Q7: Top Rank
int studentScore = 98, maxScore = 98;
boolean isTopRanker = studentScore == maxScore;
System.out.println("Q7 - Is Top Ranker? " + isTopRanker); // true
// Q8: Loan Limit
int requested = 50000, maxAllowed = 40000;
boolean isApproved = requested <= maxAllowed;
System.out.println("Q8 - Loan Approved? " + isApproved); // false
// Q9: Rectangle or Square
int length = 10, breadth = 10;
boolean isSquare = length == breadth;
System.out.println("Q9 - Is Square? " + isSquare); // true
// Q10: Temperature Comparison
int todayTemp = 37, yesterdayTemp = 35;
boolean isHotter = todayTemp > yesterdayTemp;
System.out.println("Q10 - Is Today Hotter? " + isHotter); // true
// Q11: Speed Violation
int speed = 85;
boolean isOverSpeeding = speed > 80;
System.out.println("Q11 - Speeding Violation? " + isOverSpeeding); // true
// Q12: Correct Pin
int enteredPin = 1234, correctPin = 1234;
boolean isPinCorrect = enteredPin == correctPin;
System.out.println("Q12 - Is Pin Correct? " + isPinCorrect); // true
// Q13: Attendance Requirement
double attendance = 72.0, required = 75.0;
boolean meetsRequirement = attendance >= required;
System.out.println("Q13 - Meets Attendance Requirement? " + meetsRequirement); // false
// Q14: Minimum Age
int userAge = 21;
boolean canRentCar = userAge >= 21;
System.out.println("Q14 - Can Rent Car? " + canRentCar); // true
// Q15: Three Equal Numbers
int a = 7, b = 7, c = 7;
boolean allEqual = (a == b) && (b == c);
System.out.println("Q15 - Are All Numbers Equal? " + allEqual); // true
}
}
🧠 15 Logical Challenger Problems
- Voter Eligibility: Check if person is Indian and 18+ to vote.
- Scholarship Criteria: Marks ≥ 90 or family income < ₹2,00,000.
- Loan Approval: Age ≥ 25 and salary ≥ ₹30,000.
- Attendance Alert: Attendance < 75% or marks < 40 → Show warning?
- Exam Cheating Detector: isCheating = true → Block exam using
!. - Working Hours: Check if employee worked between 9AM and 6PM.
- Valid User: User must have username and password to log in.
- Age or Membership: Entry allowed if age ≥ 60 or isPremiumMember.
- Not Empty String: isEmpty = false → Allow form submit?
- Account Active: Active user and email verified → Allow access.
- Shopping Deal: Add to cart if product in stock and discount ≥ 10%.
- Logical Puzzle: (a > b) and (b > c) → is a > c?
- Event Entry: Age ≥ 18 and hasTicket or isGuest.
- Security Alert: !isVerified → Show warning popup.
- Salary Range: Is salary between ₹25,000 and ₹50,000?
🧠 Logical Operator Answers
public class LogicalChallengerAnswers {
public static void main(String[] args) {
// Q1: Voter Eligibility
boolean isIndian = true;
int age = 20;
boolean canVote = isIndian && age >= 18;
System.out.println("Q1 - Can Vote? " + canVote); // true
// Q2: Scholarship Criteria
int marks = 85;
int income = 180000;
boolean getsScholarship = marks >= 90 || income < 200000;
System.out.println("Q2 - Eligible for Scholarship? " + getsScholarship); // true
// Q3: Loan Approval
int personAge = 28;
int salary = 32000;
boolean loanApproved = personAge >= 25 && salary >= 30000;
System.out.println("Q3 - Loan Approved? " + loanApproved); // true
// Q4: Attendance Alert
double attendance = 70.0;
double testMarks = 38.0;
boolean showWarning = attendance < 75 || testMarks < 40;
System.out.println("Q4 - Show Warning? " + showWarning); // true
// Q5: Exam Cheating Detector
boolean isCheating = true;
boolean allowExam = !isCheating;
System.out.println("Q5 - Allow Exam? " + allowExam); // false
// Q6: Working Hours
// Define the hour someone checks in
int checkInHour = 10; // This means the person checked in at 10 AM
// Define the working hours using a logical AND (&&) condition
// Check if the check-in time is between 9 AM and 6 PM (inclusive)
// This means the time must be greater than or equal to 9 AND less than or equal to 18
boolean isWorkingHours = checkInHour >= 9 && checkInHour <= 18;
// Explanation:
// - checkInHour >= 9 → Is 10 greater than or equal to 9? ✅ Yes
// - checkInHour <= 18 → Is 10 less than or equal to 18? ✅ Yes
// - Since both conditions are true, the result is true
System.out.println("Q6 - Within Working Hours? " + isWorkingHours); // Output: true
// Q7: Valid User
boolean hasUsername = true;
boolean hasPassword = true;
boolean canLogin = hasUsername && hasPassword;
System.out.println("Q7 - Can Login? " + canLogin); // true
// Q8: Age or Membership
int userAge = 45;
boolean isPremiumMember = true;
boolean allowEntry = userAge >= 60 || isPremiumMember;
System.out.println("Q8 - Entry Allowed? " + allowEntry); // true
// Q9: Not Empty String
boolean isEmpty = false;
boolean canSubmit = !isEmpty;
System.out.println("Q9 - Allow Form Submit? " + canSubmit); // true
// Q10: Account Active
boolean isActive = true;
boolean isEmailVerified = true;
boolean allowAccess = isActive && isEmailVerified;
System.out.println("Q10 - Access Granted? " + allowAccess); // true
// Q11: Shopping Deal
boolean inStock = true;
int discount = 15;
boolean addToCart = inStock && discount >= 10;
System.out.println("Q11 - Add to Cart? " + addToCart); // true
// Q12: Logical Puzzle
int a = 10, b = 8, c = 5;
// We are checking three comparisons:
// 1. a > b → Is 'a' greater than 'b'? → true
// 2. b > c → Is 'b' greater than 'c'? → true
// 3. a > c → Is 'a' greater than 'c'? → true
// ✅ In mathematics, if (a > b) and (b > c), we can conclude (a > c).
// This is called a *transitive relation*.
// ✅ So in theory, we don't need to check (a > c) separately —
// it will always be true if the first two are true.
// 🛡️ BUT in real-world code, values may change,
// and logic may evolve — so including (a > c) as an explicit condition:
// - Makes your logic clearer to other programmers
// - Acts as a safety check in case 'b' gets changed unexpectedly
// - Helps avoid bugs from assuming transitivity in changing contexts
boolean isAGreaterThanC = (a > b) && (b > c) && (a > c);
System.out.println("Q12 - Is a > c? " + isAGreaterThanC); // Output: true
// Q13: Event Entry
int guestAge = 17;
boolean hasTicket = false;
boolean isGuest = true;
boolean canEnter = (guestAge >= 18 && hasTicket) || isGuest;
System.out.println("Q13 - Can Enter Event? " + canEnter); // true
// Q14: Security Alert
boolean isVerified = false;
boolean showPopup = !isVerified;
System.out.println("Q14 - Show Security Alert? " + showPopup); // true
// Q15: Salary Range
int empSalary = 42000;
boolean isInRange = empSalary >= 25000 && empSalary <= 50000;
System.out.println("Q15 - Salary in Range? " + isInRange); // true
}
}
🔀 Control Flow Statements
✅ if / else if / else
Use this when you want your program to make decisions based on certain conditions.
int number = 7;
if (number > 0) {
System.out.println("Positive");
} else if (number < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
✅ Explanation: The program checks if the number is positive, negative, or zero and prints the appropriate result.
❌ Expected Mistake: Writing if (number = 0) instead of if (number == 0).
The first one assigns 0 instead of comparing it.
🌀 switch Statement
Use switch when you have multiple exact values to check against a single variable.
int day = 3;
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
default: System.out.println("Invalid Day");
}
✅ Explanation: This prints the day name based on the number. The break is important
to stop the flow after each match.
❌ Expected Mistake: Omitting break will cause multiple cases to execute (called
"fall-through").
🔁 Loops — Repeat Until You're Done
➡️ for Loop
Best when you know how many times to repeat something. It has three parts: initialization, condition, and update.
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
✅ Explanation: This prints numbers 1 to 5. Loop starts at 1 and runs while i <= 5.
❌ Expected Mistake: Accidentally putting i++ in the condition (like
i++ <= 5), which changes value before the check.
🔁 while Loop
Use when you don't know how many times the loop should run — the condition is checked before each run.
int i = 1;
while (i <= 3) {
System.out.println("Looping: " + i);
i++;
}
✅ Explanation: Repeats the loop until i becomes greater than 3.
❌ Expected Mistake: Forgetting i++ causes an infinite loop.
🔂 do-while Loop
This loop runs at least once, even if the condition is false.
int i = 1;
do {
System.out.println("Running: " + i);
i++;
} while (i <= 3);
✅ Explanation: The code inside do runs once before the condition is even checked.
❌ Expected Mistake (Misunderstanding): A beginner might think: "If the condition is false from the beginning, the code inside should never run."
🔴 But that would be true for a while loop — not for a do-while. In a
do-while loop, the block of code runs at least once before the condition is checked.
So even if the condition is false initially, the code still executes once.
🚫 Common Mistake in Loop Understanding:
| Concept | Mistake |
|---|---|
| do-while | Assuming the condition is checked before running the loop |
| Truth | The loop body always runs at least once, no matter the condition |
| Common Error | Thinking it behaves like a while loop (which
doesn't run at all if false) |
🎯 15 Best if, else if, and else Concept Challenges
- Grade Checker: Write a program that takes student marks as input and prints:
- "A" for marks ≥ 90
- "B" for marks between 80 and 89
- "C" for marks between 70 and 79
- Else, print "Fail"
- Temperature Advice: Given a temperature value, print:
- "Too Cold" if temperature < 10
- "Moderate" if between 10 and 25
- "Hot" if above 25
- Even/Odd Check: Given a number, check whether it's even or odd and print "Even" or "Odd".
- Age Category: Given a person's age, print:
- "Child" for ages 0–12
- "Teen" for 13–19
- "Adult" for 20–59
- "Senior" for 60 and above
- Login Status: If a user is not logged in, print "Login Required"; else, print "Welcome back".
- Number Sign: Given a number, print:
- "Positive" if the number is greater than 0
- "Zero" if the number is 0
- "Negative" if less than 0
- Day Checker: Given a number (1–7), print the corresponding weekday:
- 1 = Monday, 2 = Tuesday, ..., 7 = Sunday
- Any other number should print "Not a valid day"
- BMI Category: Given the BMI value, print:
- "Underweight" if BMI < 18.5
- "Normal" if between 18.5 and 24.9
- "Overweight" if between 25 and 29.9
- "Obese" if BMI ≥ 30
- Exam Result: Based on marks:
- ≥90 → "Distinction"
- 60–89 → "Passed"
- <60 → "Failed"
- Traffic Light: Based on traffic signal color (red/yellow/green), print:
- "Stop" for "red"
- "Ready" for "yellow"
- "Go" for "green"
- Any other value → "Invalid Signal"
- Movie Rating: Based on rating:
- ≥4.5 → "Excellent"
- 3.5–4.4 → "Good"
- 2.5–3.4 → "Average"
- Else → "Poor"
- Password Strength: Based on password length:
- ≥12 characters → "Strong"
- 8–11 characters → "Moderate"
- <8 characters → "Weak"
- Bill Discount: Based on total bill:
- ≥5000 → "20% Discount"
- 3000–4999 → "10% Discount"
- Else → "No Discount"
- Voting Zone: Based on city:
- "Delhi" → "Zone A"
- "Mumbai" → "Zone B"
- Else → "Zone C"
- Student Category: Based on age:
- 0–5 → "Toddler"
- 6–12 → "School"
- 13–18 → "High School"
- 19+ → "College Student"
🔀 if, else if, and else Challenge Solutions
public class IfElseChallengerAnswers {
public static void main(String[] args) {
// Q1: Grade Checker
int marks = 85;
if (marks >= 90) {
System.out.println("Q1 - Grade: A");
} else if (marks >= 80) {
System.out.println("Q1 - Grade: B");
} else if (marks >= 70) {
System.out.println("Q1 - Grade: C");
} else {
System.out.println("Q1 - Grade: Fail");
}
// Q2: Temperature Advice
int temp = 15;
if (temp < 10) {
System.out.println("Q2 - Too Cold");
} else if (temp <= 25) {
System.out.println("Q2 - Moderate");
} else {
System.out.println("Q2 - Hot");
}
// Q3: Even/Odd Check
int num = 13;
if (num % 2 == 0) {
System.out.println("Q3 - Even");
} else {
System.out.println("Q3 - Odd");
}
// Q4: Age Category
int age = 65;
if (age <= 12) {
System.out.println("Q4 - Child");
} else if (age <= 19) {
System.out.println("Q4 - Teen");
} else if (age <= 59) {
System.out.println("Q4 - Adult");
} else {
System.out.println("Q4 - Senior");
}
// Q5: Login Status
boolean isLoggedIn = false;
if (!isLoggedIn) {
System.out.println("Q5 - Login Required");
} else {
System.out.println("Q5 - Welcome back");
}
// Q6: Number Sign
int value = 0;
if (value > 0) {
System.out.println("Q6 - Positive");
} else if (value == 0) {
System.out.println("Q6 - Zero");
} else {
System.out.println("Q6 - Negative");
}
// Q7: Day Checker
int day = 3;
if (day == 1) {
System.out.println("Q7 - Monday");
} else if (day == 2) {
System.out.println("Q7 - Tuesday");
} else if (day == 3) {
System.out.println("Q7 - Wednesday");
} else if (day == 4) {
System.out.println("Q7 - Thursday");
} else if (day == 5) {
System.out.println("Q7 - Friday");
} else if (day == 6) {
System.out.println("Q7 - Saturday");
} else if (day == 7) {
System.out.println("Q7 - Sunday");
} else {
System.out.println("Q7 - Not a valid day");
}
// Q8: BMI Category
double bmi = 27.5;
if (bmi < 18.5) {
System.out.println("Q8 - Underweight");
} else if (bmi < 25) {
System.out.println("Q8 - Normal");
} else if (bmi < 30) {
System.out.println("Q8 - Overweight");
} else {
System.out.println("Q8 - Obese");
}
// Q9: Exam Result
int studentMarks = 68;
if (studentMarks >= 90) {
System.out.println("Q9 - Distinction");
} else if (studentMarks >= 60) {
System.out.println("Q9 - Passed");
} else {
System.out.println("Q9 - Failed");
}
// Q10: Traffic Light
String light = "yellow";
if (light.equals("red")) {
System.out.println("Q10 - Stop");
} else if (light.equals("yellow")) {
System.out.println("Q10 - Ready");
} else if (light.equals("green")) {
System.out.println("Q10 - Go");
} else {
System.out.println("Q10 - Invalid Signal");
}
// Q11: Movie Rating
double rating = 4.7;
if (rating >= 4.5) {
System.out.println("Q11 - Excellent");
} else if (rating >= 3.5) {
System.out.println("Q11 - Good");
} else if (rating >= 2.5) {
System.out.println("Q11 - Average");
} else {
System.out.println("Q11 - Poor");
}
// Q12: Password Strength
String password = "hello123";
if (password.length() >= 12) {
System.out.println("Q12 - Strong Password");
} else if (password.length() >= 8) {
System.out.println("Q12 - Moderate Password");
} else {
System.out.println("Q12 - Weak Password");
}
// Q13: Bill Discount
int totalBill = 4500;
if (totalBill >= 5000) {
System.out.println("Q13 - 20% Discount");
} else if (totalBill >= 3000) {
System.out.println("Q13 - 10% Discount");
} else {
System.out.println("Q13 - No Discount");
}
// Q14: Voting Zone
String state = "Delhi";
if (state.equals("Delhi")) {
System.out.println("Q14 - Vote in Zone A");
} else if (state.equals("Mumbai")) {
System.out.println("Q14 - Vote in Zone B");
} else {
System.out.println("Q14 - Vote in Zone C");
}
// Q15: Student Category by Age
int studentAge = 21;
if (studentAge <= 5) {
System.out.println("Q15 - Toddler");
} else if (studentAge <= 12) {
System.out.println("Q15 - School Student");
} else if (studentAge <= 18) {
System.out.println("Q15 - High School");
} else {
System.out.println("Q15 - College Student");
}
}
}
import java.util.Scanner;
public class IfElseChallengerAnswersInteractive {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Q1: Grade Checker
System.out.print("Q1 - Enter marks: ");
int marks = sc.nextInt();
if (marks >= 90) {
System.out.println("Grade: A");
} else if (marks >= 80) {
System.out.println("Grade: B");
} else if (marks >= 70) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: Fail");
}
// Q2: Temperature Advice
System.out.print("Q2 - Enter temperature: ");
int temp = sc.nextInt();
if (temp < 10) {
System.out.println("Too Cold");
} else if (temp <= 25) {
System.out.println("Moderate");
} else {
System.out.println("Hot");
}
// Q3: Even/Odd Check
System.out.print("Q3 - Enter a number: ");
int num = sc.nextInt();
if (num % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
// Q4: Age Category
System.out.print("Q4 - Enter age: ");
int age = sc.nextInt();
if (age <= 12) {
System.out.println("Child");
} else if (age <= 19) {
System.out.println("Teen");
} else if (age <= 59) {
System.out.println("Adult");
} else {
System.out.println("Senior");
}
// Q5: Login Status
System.out.print("Q5 - Are you logged in? (true/false): ");
boolean isLoggedIn = sc.nextBoolean();
if (!isLoggedIn) {
System.out.println("Login Required");
} else {
System.out.println("Welcome back");
}
// Q6: Number Sign
System.out.print("Q6 - Enter a number: ");
int value = sc.nextInt();
if (value > 0) {
System.out.println("Positive");
} else if (value == 0) {
System.out.println("Zero");
} else {
System.out.println("Negative");
}
// Q7: Day Checker
System.out.print("Q7 - Enter day number (1-7): ");
int day = sc.nextInt();
if (day == 1) {
System.out.println("Monday");
} else if (day == 2) {
System.out.println("Tuesday");
} else if (day == 3) {
System.out.println("Wednesday");
} else if (day == 4) {
System.out.println("Thursday");
} else if (day == 5) {
System.out.println("Friday");
} else if (day == 6) {
System.out.println("Saturday");
} else if (day == 7) {
System.out.println("Sunday");
} else {
System.out.println("Not a valid day");
}
// Q8: BMI Category
System.out.print("Q8 - Enter your BMI: ");
double bmi = sc.nextDouble();
if (bmi < 18.5) {
System.out.println("Underweight");
} else if (bmi < 25) {
System.out.println("Normal");
} else if (bmi < 30) {
System.out.println("Overweight");
} else {
System.out.println("Obese");
}
// Q9: Exam Result
System.out.print("Q9 - Enter exam marks: ");
int studentMarks = sc.nextInt();
if (studentMarks >= 90) {
System.out.println("Distinction");
} else if (studentMarks >= 60) {
System.out.println("Passed");
} else {
System.out.println("Failed");
}
// Q10: Traffic Light
System.out.print("Q10 - Enter signal (red/yellow/green): ");
sc.nextLine(); // consume leftover newline
String light = sc.nextLine();
if (light.equalsIgnoreCase("red")) {
System.out.println("Stop");
} else if (light.equalsIgnoreCase("yellow")) {
System.out.println("Ready");
} else if (light.equalsIgnoreCase("green")) {
System.out.println("Go");
} else {
System.out.println("Invalid Signal");
}
// Q11: Movie Rating
System.out.print("Q11 - Enter movie rating (0.0 - 5.0): ");
double rating = sc.nextDouble();
if (rating >= 4.5) {
System.out.println("Excellent");
} else if (rating >= 3.5) {
System.out.println("Good");
} else if (rating >= 2.5) {
System.out.println("Average");
} else {
System.out.println("Poor");
}
// Q12: Password Strength
System.out.print("Q12 - Enter your password: ");
sc.nextLine(); // consume newline
String password = sc.nextLine();
if (password.length() >= 12) {
System.out.println("Strong Password");
} else if (password.length() >= 8) {
System.out.println("Moderate Password");
} else {
System.out.println("Weak Password");
}
// Q13: Bill Discount
System.out.print("Q13 - Enter total bill amount: ");
int totalBill = sc.nextInt();
if (totalBill >= 5000) {
System.out.println("20% Discount");
} else if (totalBill >= 3000) {
System.out.println("10% Discount");
} else {
System.out.println("No Discount");
}
// Q14: Voting Zone
System.out.print("Q14 - Enter your city (Delhi/Mumbai/etc): ");
sc.nextLine(); // consume newline
String state = sc.nextLine();
if (state.equalsIgnoreCase("Delhi")) {
System.out.println("Vote in Zone A");
} else if (state.equalsIgnoreCase("Mumbai")) {
System.out.println("Vote in Zone B");
} else {
System.out.println("Vote in Zone C");
}
// Q15: Student Category by Age
System.out.print("Q15 - Enter student age: ");
int studentAge = sc.nextInt();
if (studentAge <= 5) {
System.out.println("Toddler");
} else if (studentAge <= 12) {
System.out.println("School Student");
} else if (studentAge <= 18) {
System.out.println("High School");
} else {
System.out.println("College Student");
}
sc.close();
}
}
🎯 15 Best Switch-Case Concept Challenges
- Day of the Week: Given an integer from 1 to 7, print the name of the corresponding day (e.g., 1 = Monday, 2 = Tuesday, ..., 7 = Sunday). If the number is outside this range, print "Invalid day".
- Grade Evaluator: Given a character representing a grade ('A', 'B', 'C', 'D', 'F'), print the corresponding performance (e.g., 'A' = Excellent). If it's any other character, print "Invalid grade".
- Month Name: Given a number from 1 to 12, print the name of the corresponding month. For any number outside this range, print "Invalid month".
- Traffic Signal: Given a traffic signal color ("red", "yellow", "green"), print its corresponding action ("Stop", "Wait", "Go"). If the input doesn't match any of these, print "Invalid signal".
- Calculator Operation: Given two integers and a character representing an operator ('+', '-', '*', '/'), perform the corresponding arithmetic operation. If the operator is invalid, print "Invalid operator". Handle division by zero.
- Browser Detection: Given a browser name ("Chrome", "Firefox", "Safari"), print "Supported". For any other browser name, print "Not supported".
- Vowel or Consonant: Given a character (either uppercase or lowercase), check whether it's a vowel ('a', 'e', 'i', 'o', 'u'). If so, print "Vowel". Otherwise, print "Consonant".
- Level Description: Given a level number (1, 2, or 3), print the difficulty description: 1 = Easy, 2 = Medium, 3 = Hard. If the input is not 1-3, print "Unknown Level".
- Shape Sides: Given a shape name ("Triangle", "Square", "Pentagon"), print the number of sides. For any other shape, print "Unknown shape".
- Currency Symbol: Given a currency code ("USD", "EUR", "JPY"), print the corresponding symbol ("$", "€", "¥"). If the code is not recognized, print "Unknown currency".
- Season Finder: Given a short month name ("Jan", "Feb", ..., "Dec"), print the corresponding
season:
- Winter: "Dec", "Jan", "Feb"
- Spring: "Mar", "Apr", "May"
- Summer: "Jun", "Jul", "Aug"
- Autumn: "Sep", "Oct", "Nov"
- Language Greeting: Given a language name ("English", "Spanish", "French"), print a greeting in that language. If it's not one of these, print "Language not supported".
- Menu Selection: Given a menu option number (1, 2, or 3), print the corresponding label: 1 = Start, 2 = Settings, 3 = Exit. If the option is not in the range, print "Invalid Option".
- Planet Order: Given a number from 1 to 8, print the corresponding planet's name in order from the Sun: 1 = Mercury, 2 = Venus, ..., 8 = Neptune. If the number is outside 1–8, print "Invalid planet number".
- File Extension: Given a file extension:
- If it's ".jpg", ".png", or ".gif", print "Image File"
- If it's ".mp4" or ".mkv", print "Video File"
- If it's ".pdf", print "Document File"
- Otherwise, print "Unknown File Type"
🧠 Switch-Case Challenge Solutions
public class SwitchCaseChallengerAnswers {
public static void main(String[] args) {
// Q1: Day of the Week
int day = 3;
switch (day) {
case 1: System.out.println("Q1 - Monday"); break;
case 2: System.out.println("Q1 - Tuesday"); break;
case 3: System.out.println("Q1 - Wednesday"); break;
case 4: System.out.println("Q1 - Thursday"); break;
case 5: System.out.println("Q1 - Friday"); break;
case 6: System.out.println("Q1 - Saturday"); break;
case 7: System.out.println("Q1 - Sunday"); break;
default: System.out.println("Q1 - Invalid day");
}
// Q2: Grade Evaluator
char grade = 'B';
switch (grade) {
case 'A': System.out.println("Q2 - Excellent"); break;
case 'B': System.out.println("Q2 - Good"); break;
case 'C': System.out.println("Q2 - Average"); break;
case 'D': System.out.println("Q2 - Below Average"); break;
case 'F': System.out.println("Q2 - Fail"); break;
default: System.out.println("Q2 - Invalid grade");
}
// Q3: Month Name
int month = 8;
switch (month) {
case 1: System.out.println("Q3 - January"); break;
case 2: System.out.println("Q3 - February"); break;
case 3: System.out.println("Q3 - March"); break;
case 4: System.out.println("Q3 - April"); break;
case 5: System.out.println("Q3 - May"); break;
case 6: System.out.println("Q3 - June"); break;
case 7: System.out.println("Q3 - July"); break;
case 8: System.out.println("Q3 - August"); break;
case 9: System.out.println("Q3 - September"); break;
case 10: System.out.println("Q3 - October"); break;
case 11: System.out.println("Q3 - November"); break;
case 12: System.out.println("Q3 - December"); break;
default: System.out.println("Q3 - Invalid month");
}
// Q4: Traffic Signal
String signal = "green";
switch (signal) {
case "red": System.out.println("Q4 - Stop"); break;
case "yellow": System.out.println("Q4 - Wait"); break;
case "green": System.out.println("Q4 - Go"); break;
default: System.out.println("Q4 - Invalid signal");
}
// Q5: Calculator Operation
int a = 12, b = 4;
char operator = '/';
switch (operator) {
case '+': System.out.println("Q5 - " + (a + b)); break;
case '-': System.out.println("Q5 - " + (a - b)); break;
case '*': System.out.println("Q5 - " + (a * b)); break;
case '/': System.out.println("Q5 - " + (b != 0 ? (a / b) : "Cannot divide by zero")); break;
default: System.out.println("Q5 - Invalid operator");
}
// Q6: Browser Detection
String browser = "Safari";
switch (browser) {
case "Chrome":
case "Firefox":
case "Safari":
System.out.println("Q6 - Supported");
break;
default:
System.out.println("Q6 - Not supported");
}
// Q7: Vowel or Consonant
char ch = 'O';
switch (Character.toLowerCase(ch)) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
System.out.println("Q7 - Vowel");
break;
default:
System.out.println("Q7 - Consonant");
}
// Q8: Level Description
int level = 2;
switch (level) {
case 1: System.out.println("Q8 - Easy"); break;
case 2: System.out.println("Q8 - Medium"); break;
case 3: System.out.println("Q8 - Hard"); break;
default: System.out.println("Q8 - Unknown Level");
}
// Q9: Shape Sides
String shape = "Square";
switch (shape) {
case "Triangle": System.out.println("Q9 - 3 sides"); break;
case "Square": System.out.println("Q9 - 4 sides"); break;
case "Pentagon": System.out.println("Q9 - 5 sides"); break;
default: System.out.println("Q9 - Unknown shape");
}
// Q10: Currency Symbol
String currency = "JPY";
switch (currency) {
case "USD": System.out.println("Q10 - $ (USD)"); break;
case "EUR": System.out.println("Q10 - € (EUR)"); break;
case "JPY": System.out.println("Q10 - ¥ (JPY)"); break;
default: System.out.println("Q10 - Unknown currency");
}
// Q11: Season Finder
String monthName = "Jan";
switch (monthName) {
case "Dec":
case "Jan":
case "Feb":
System.out.println("Q11 - Winter"); break;
case "Mar":
case "Apr":
case "May":
System.out.println("Q11 - Spring"); break;
case "Jun":
case "Jul":
case "Aug":
System.out.println("Q11 - Summer"); break;
case "Sep":
case "Oct":
case "Nov":
System.out.println("Q11 - Autumn"); break;
default:
System.out.println("Q11 - Invalid month");
}
// Q12: Language Greeting
String language = "Spanish";
switch (language) {
case "English": System.out.println("Q12 - Hello"); break;
case "Spanish": System.out.println("Q12 - Hola"); break;
case "French": System.out.println("Q12 - Bonjour"); break;
default: System.out.println("Q12 - Language not supported");
}
// Q13: Menu Selection
int option = 2;
switch (option) {
case 1: System.out.println("Q13 - Start"); break;
case 2: System.out.println("Q13 - Settings"); break;
case 3: System.out.println("Q13 - Exit"); break;
default: System.out.println("Q13 - Invalid Option");
}
// Q14: Planet Order
int planetNumber = 4;
switch (planetNumber) {
case 1: System.out.println("Q14 - Mercury"); break;
case 2: System.out.println("Q14 - Venus"); break;
case 3: System.out.println("Q14 - Earth"); break;
case 4: System.out.println("Q14 - Mars"); break;
case 5: System.out.println("Q14 - Jupiter"); break;
case 6: System.out.println("Q14 - Saturn"); break;
case 7: System.out.println("Q14 - Uranus"); break;
case 8: System.out.println("Q14 - Neptune"); break;
default: System.out.println("Q14 - Invalid planet number");
}
// Q15: File Type Detector
String fileExt = ".pdf";
switch (fileExt) {
case ".jpg":
case ".png":
case ".gif":
System.out.println("Q15 - Image File"); break;
case ".mp4":
case ".mkv":
System.out.println("Q15 - Video File"); break;
case ".pdf":
System.out.println("Q15 - Document File"); break;
default:
System.out.println("Q15 - Unknown File Type");
}
}
}
import java.util.Scanner;
public class SwitchCaseChallengerUserInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Q1: Day of the Week
System.out.print("Q1 - Enter a number (1-7) for day of the week: ");
int day = sc.nextInt();
switch (day) {
case 1: System.out.println("Q1 - Monday"); break;
case 2: System.out.println("Q1 - Tuesday"); break;
case 3: System.out.println("Q1 - Wednesday"); break;
case 4: System.out.println("Q1 - Thursday"); break;
case 5: System.out.println("Q1 - Friday"); break;
case 6: System.out.println("Q1 - Saturday"); break;
case 7: System.out.println("Q1 - Sunday"); break;
default: System.out.println("Q1 - Invalid day");
}
// Q2: Grade Evaluator
System.out.print("Q2 - Enter a grade (A/B/C/D/F): ");
char grade = sc.next().toUpperCase().charAt(0);
switch (grade) {
case 'A': System.out.println("Q2 - Excellent"); break;
case 'B': System.out.println("Q2 - Good"); break;
case 'C': System.out.println("Q2 - Average"); break;
case 'D': System.out.println("Q2 - Below Average"); break;
case 'F': System.out.println("Q2 - Fail"); break;
default: System.out.println("Q2 - Invalid grade");
}
// Q3: Month Name
System.out.print("Q3 - Enter a number (1-12) for month: ");
int month = sc.nextInt();
switch (month) {
case 1: System.out.println("Q3 - January"); break;
case 2: System.out.println("Q3 - February"); break;
case 3: System.out.println("Q3 - March"); break;
case 4: System.out.println("Q3 - April"); break;
case 5: System.out.println("Q3 - May"); break;
case 6: System.out.println("Q3 - June"); break;
case 7: System.out.println("Q3 - July"); break;
case 8: System.out.println("Q3 - August"); break;
case 9: System.out.println("Q3 - September"); break;
case 10: System.out.println("Q3 - October"); break;
case 11: System.out.println("Q3 - November"); break;
case 12: System.out.println("Q3 - December"); break;
default: System.out.println("Q3 - Invalid month");
}
// Q4: Traffic Signal
System.out.print("Q4 - Enter traffic signal color (red/yellow/green): ");
String signal = sc.next().toLowerCase();
switch (signal) {
case "red": System.out.println("Q4 - Stop"); break;
case "yellow": System.out.println("Q4 - Wait"); break;
case "green": System.out.println("Q4 - Go"); break;
default: System.out.println("Q4 - Invalid signal");
}
// Q5: Calculator Operation
System.out.print("Q5 - Enter two integers: ");
int a = sc.nextInt();
int b = sc.nextInt();
System.out.print("Q5 - Enter an operator (+, -, *, /): ");
char operator = sc.next().charAt(0);
switch (operator) {
case '+': System.out.println("Q5 - " + (a + b)); break;
case '-': System.out.println("Q5 - " + (a - b)); break;
case '*': System.out.println("Q5 - " + (a * b)); break;
case '/':
if (b != 0) System.out.println("Q5 - " + (a / b));
else System.out.println("Q5 - Cannot divide by zero");
break;
default: System.out.println("Q5 - Invalid operator");
}
// Q6: Browser Detection
System.out.print("Q6 - Enter a browser name (Chrome/Firefox/Safari): ");
String browser = sc.next();
switch (browser) {
case "Chrome":
case "Firefox":
case "Safari":
System.out.println("Q6 - Supported"); break;
default:
System.out.println("Q6 - Not supported");
}
// Q7: Vowel or Consonant
System.out.print("Q7 - Enter an alphabet character: ");
char ch = sc.next().toLowerCase().charAt(0);
switch (ch) {
case 'a': case 'e': case 'i': case 'o': case 'u':
System.out.println("Q7 - Vowel"); break;
default:
System.out.println("Q7 - Consonant");
}
// Q8: Level Description
System.out.print("Q8 - Enter a level (1-3): ");
int level = sc.nextInt();
switch (level) {
case 1: System.out.println("Q8 - Easy"); break;
case 2: System.out.println("Q8 - Medium"); break;
case 3: System.out.println("Q8 - Hard"); break;
default: System.out.println("Q8 - Unknown Level");
}
// Q9: Shape Sides
System.out.print("Q9 - Enter a shape (Triangle/Square/Pentagon): ");
String shape = sc.next();
switch (shape) {
case "Triangle": System.out.println("Q9 - 3 sides"); break;
case "Square": System.out.println("Q9 - 4 sides"); break;
case "Pentagon": System.out.println("Q9 - 5 sides"); break;
default: System.out.println("Q9 - Unknown shape");
}
// Q10: Currency Symbol
System.out.print("Q10 - Enter a currency code (USD/EUR/JPY): ");
String currency = sc.next();
switch (currency) {
case "USD": System.out.println("Q10 - $ (USD)"); break;
case "EUR": System.out.println("Q10 - € (EUR)"); break;
case "JPY": System.out.println("Q10 - ¥ (JPY)"); break;
default: System.out.println("Q10 - Unknown currency");
}
// Q11: Season Finder
System.out.print("Q11 - Enter month short name (Jan-Dec): ");
String monthName = sc.next();
switch (monthName) {
case "Dec": case "Jan": case "Feb":
System.out.println("Q11 - Winter"); break;
case "Mar": case "Apr": case "May":
System.out.println("Q11 - Spring"); break;
case "Jun": case "Jul": case "Aug":
System.out.println("Q11 - Summer"); break;
case "Sep": case "Oct": case "Nov":
System.out.println("Q11 - Autumn"); break;
default:
System.out.println("Q11 - Invalid month");
}
// Q12: Language Greeting
System.out.print("Q12 - Enter a language (English/Spanish/French): ");
String language = sc.next();
switch (language) {
case "English": System.out.println("Q12 - Hello"); break;
case "Spanish": System.out.println("Q12 - Hola"); break;
case "French": System.out.println("Q12 - Bonjour"); break;
default: System.out.println("Q12 - Language not supported");
}
// Q13: Menu Selection
System.out.print("Q13 - Enter menu option (1-3): ");
int option = sc.nextInt();
switch (option) {
case 1: System.out.println("Q13 - Start"); break;
case 2: System.out.println("Q13 - Settings"); break;
case 3: System.out.println("Q13 - Exit"); break;
default: System.out.println("Q13 - Invalid Option");
}
// Q14: Planet Order
System.out.print("Q14 - Enter planet number (1-8): ");
int planetNumber = sc.nextInt();
switch (planetNumber) {
case 1: System.out.println("Q14 - Mercury"); break;
case 2: System.out.println("Q14 - Venus"); break;
case 3: System.out.println("Q14 - Earth"); break;
case 4: System.out.println("Q14 - Mars"); break;
case 5: System.out.println("Q14 - Jupiter"); break;
case 6: System.out.println("Q14 - Saturn"); break;
case 7: System.out.println("Q14 - Uranus"); break;
case 8: System.out.println("Q14 - Neptune"); break;
default: System.out.println("Q14 - Invalid planet number");
}
// Q15: File Type Detector
System.out.print("Q15 - Enter a file extension (e.g., .jpg, .pdf): ");
String fileExt = sc.next();
switch (fileExt) {
case ".jpg": case ".png": case ".gif":
System.out.println("Q15 - Image File"); break;
case ".mp4": case ".mkv":
System.out.println("Q15 - Video File"); break;
case ".pdf":
System.out.println("Q15 - Document File"); break;
default:
System.out.println("Q15 - Unknown File Type");
}
sc.close();
}
}
🔁 15 Best for Loop Concept Challenges
- Print Numbers from 1 to 10: Write a program using a
forloop that prints all numbers starting from 1 up to 10, each on a new line. - Sum of First N Natural Numbers: Ask the user to enter a number
N. Use a loop to calculate and print the sum of numbers from 1 toN. - Print Even Numbers from 1 to 50: Use a
forloop to print all even numbers between 1 and 50 (inclusive), separated by spaces. - Multiplication Table Generator: Prompt the user to enter a number, then print its
multiplication table from 1 to 10 using a
forloop. - Factorial Calculator: Ask the user to enter a number
N. Use a loop to compute the factorial ofN(i.e.,N!) and display the result. - Print Numbers in Reverse: Write a loop that prints numbers from 10 down to 1 in descending order, all on one line separated by spaces.
- Square of Numbers from 1 to 10: Use a loop to print each number from 1 to 10 along with its
square in the format:
number^2 = result. - Count Multiples of 3 Between 1 and 100: Use a loop to count how many numbers from 1 to 100 are divisible by 3 and print that count.
- Sum of Odd Numbers up to N: Ask the user to enter a number
N, then use a loop to calculate and print the sum of all odd numbers from 1 toN. - Pattern Printing - Star Triangle: Use nested
forloops to print a right-angled triangle of asterisks (*) with 5 rows. - Pattern Printing - Number Triangle: Use nested loops to print a triangle with numbers starting from 1 and increasing consecutively across 5 rows.
- Skip Multiples of 4: Use a loop to print numbers from 1 to 20, but skip (do not print) numbers that are divisible by 4.
- Stop Loop on Specific Match: Print numbers from 1 to 100 using a loop, but stop the loop (use
break) when the number 42 is reached. - Sum of Digits of a Number: Ask the user to input a number. Use a loop to compute and print the sum of its individual digits.
- Fibonacci Series Generator: Prompt the user to enter how many terms of the Fibonacci sequence
to print. Then use a loop to display the first
Nterms of the sequence.
🧮 Java for Loop Challenge Solutions
public class ForLoopChallengerAnswers {
public static void main(String[] args) {
// 1. Print 1 to 10
for (int i = 1; i <= 10; i++) {
System.out.println("Q1 - " + i);
}
// 2. Sum of First N Numbers
int n = 10, sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
System.out.println("Q2 - Sum: " + sum);
// 3. Even Numbers from 1 to 50
System.out.print("Q3 - Even Numbers: ");
for (int i = 2; i <= 50; i += 2) {
System.out.print(i + " ");
}
System.out.println();
// 4. Multiplication Table
int num = 7;
for (int i = 1; i <= 10; i++) {
System.out.println("Q4 - " + num + " x " + i + " = " + (num * i));
}
// 5. Factorial Calculator
int fact = 1, x = 5;
for (int i = 1; i <= x; i++) {
fact *= i;
}
System.out.println("Q5 - Factorial: " + fact);
// 6. Reverse Print
System.out.print("Q6 - Reverse: ");
for (int i = 10; i >= 1; i--) {
System.out.print(i + " ");
}
System.out.println();
// 7. Square of Numbers 1-10
for (int i = 1; i <= 10; i++) {
System.out.println("Q7 - " + i + "^2 = " + (i * i));
}
// 8. Count Multiples of 3 (1 to 100)
int count = 0;
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0) count++;
}
System.out.println("Q8 - Multiples of 3: " + count);
// 9. Sum of Odd Numbers up to N
int oddSum = 0;
for (int i = 1; i <= n; i += 2) {
oddSum += i;
}
System.out.println("Q9 - Sum of odd numbers: " + oddSum);
// 10. Pattern: Stars Triangle (5 rows)
System.out.println("Q10 - Star Triangle:");
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
// 11. Pattern: Numbers Triangle (5 rows)
System.out.println("Q11 - Number Triangle:");
int number = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(number++ + " ");
}
System.out.println();
}
// 12. Skip Multiples of 4
System.out.print("Q12 - Skipping multiples of 4: ");
for (int i = 1; i <= 20; i++) {
if (i % 4 == 0) continue;
System.out.print(i + " ");
}
System.out.println();
// 13. Break on Match
System.out.print("Q13 - Break at 42: ");
for (int i = 1; i <= 100; i++) {
if (i == 42) break;
System.out.print(i + " ");
}
System.out.println();
// 14. Sum of Digits
int numToSum = 1234;
int digitSum = 0;
for (; numToSum > 0; numToSum /= 10) {
digitSum += numToSum % 10;
}
System.out.println("Q14 - Digit Sum: " + digitSum);
// 15. Fibonacci Series (first N terms)
System.out.print("Q15 - Fibonacci Series: ");
int terms = 10, a = 0, b = 1;
for (int i = 1; i <= terms; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
System.out.println();
}
}
import java.util.Scanner;
public class ForLoopChallengerUserInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 1. Print 1 to 10
System.out.println("Q1 - Numbers from 1 to 10:");
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
// 2. Sum of First N Numbers
System.out.print("Q2 - Enter N for sum from 1 to N: ");
int n = sc.nextInt();
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
System.out.println("Sum = " + sum);
// 3. Even Numbers from 1 to 50
System.out.print("Q3 - Even Numbers from 1 to 50: ");
for (int i = 2; i <= 50; i += 2) {
System.out.print(i + " ");
}
System.out.println();
// 4. Multiplication Table
System.out.print("Q4 - Enter a number for multiplication table: ");
int num = sc.nextInt();
for (int i = 1; i <= 10; i++) {
System.out.println(num + " x " + i + " = " + (num * i));
}
// 5. Factorial Calculator
System.out.print("Q5 - Enter a number to calculate factorial: ");
int x = sc.nextInt();
int fact = 1;
for (int i = 1; i <= x; i++) {
fact *= i;
}
System.out.println("Factorial = " + fact);
// 6. Reverse Print
System.out.print("Q6 - Numbers from 10 to 1: ");
for (int i = 10; i >= 1; i--) {
System.out.print(i + " ");
}
System.out.println();
// 7. Square of Numbers from 1 to 10
System.out.println("Q7 - Squares of numbers 1 to 10:");
for (int i = 1; i <= 10; i++) {
System.out.println(i + "^2 = " + (i * i));
}
// 8. Count Multiples of 3 (1 to 100)
int count = 0;
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0) count++;
}
System.out.println("Q8 - Count of multiples of 3 from 1 to 100: " + count);
// 9. Sum of Odd Numbers up to N
System.out.print("Q9 - Enter N to find sum of odd numbers up to N: ");
int oddN = sc.nextInt();
int oddSum = 0;
for (int i = 1; i <= oddN; i += 2) {
oddSum += i;
}
System.out.println("Sum of odd numbers = " + oddSum);
// 10. Pattern: Stars Triangle
System.out.println("Q10 - Star Triangle (5 rows):");
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
// 11. Pattern: Numbers Triangle
System.out.println("Q11 - Number Triangle (5 rows):");
int number = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(number++ + " ");
}
System.out.println();
}
// 12. Skip Multiples of 4
System.out.print("Q12 - Numbers from 1 to 20 (skipping multiples of 4): ");
for (int i = 1; i <= 20; i++) {
if (i % 4 == 0) continue;
System.out.print(i + " ");
}
System.out.println();
// 13. Break on Match
System.out.print("Q13 - Numbers from 1 to 100 (stop at 42): ");
for (int i = 1; i <= 100; i++) {
if (i == 42) break;
System.out.print(i + " ");
}
System.out.println();
// 14. Sum of Digits
System.out.print("Q14 - Enter a number to sum its digits: ");
int numToSum = sc.nextInt();
int digitSum = 0;
for (; numToSum > 0; numToSum /= 10) {
digitSum += numToSum % 10;
}
System.out.println("Digit sum = " + digitSum);
// 15. Fibonacci Series
System.out.print("Q15 - Enter N to print first N Fibonacci numbers: ");
int terms = sc.nextInt();
int a = 0, b = 1;
System.out.print("Fibonacci Series: ");
for (int i = 1; i <= terms; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
System.out.println();
sc.close();
}
}
🔁 15 Best while Loop Concept Challenges
- Print Numbers 1 to 10: Write a program that uses a
whileloop to print numbers from 1 to 10. - Countdown from 10 to 1: Use a
whileloop to print a countdown from 10 down to 1. - Add Until Total Reaches 100: Keep asking the user to input numbers and keep adding them until the total is 100 or more.
- Reverse the Digits of a Number: Input a number and reverse its digits using a
whileloop. - Count the Number of Digits: Write a program that counts how many digits are in a given integer
using a
whileloop. - Check if a Number is a Palindrome: Check whether a given number reads the same backward as forward (e.g., 1221).
- Sum the Digits of a Number: Calculate and print the sum of all digits in a number using a
whileloop. - Multiplication Table Until Exit: Continuously print the multiplication table for user input
until the user enters
-1to exit. - Guess the Secret Number: Let the user guess a secret number until they guess it correctly.
- Print Powers of Two up to 1024: Use a
whileloop to print powers of 2 starting from 1 up to 1024. - Generate Fibonacci Numbers Until a Limit: Print all Fibonacci numbers less than a given limit
(e.g., 100) using a
whileloop. - Check if a Number is an Armstrong Number: Determine whether a 3-digit number is an Armstrong number (e.g., 153 → 1³ + 5³ + 3³ = 153).
- Sum of Even Numbers from 1 to 100: Use a
whileloop to calculate the sum of all even numbers from 1 to 100. - Find All Factors of a Number: Print all positive integers that divide a given number exactly
using a
whileloop. - User Login with 3 Attempts: Allow the user up to 3 attempts to enter the correct password. If incorrect after 3 tries, lock the account.
🧮 Java while Loop Challenge Solutions
import java.util.Scanner;
public class WhileLoopChallengerAnswers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Q1: Print 1 to 10
System.out.println("Q1 - Printing numbers from 1 to 10:");
int i = 1;
while (i <= 10) {
System.out.println(i);
i++;
}
// Q2: Countdown
System.out.println("\nQ2 - Countdown from 10 to 1:");
int n = 10;
while (n >= 1) {
System.out.println(n);
n--;
}
// Q3: Sum Until 100
System.out.println("\nQ3 - Keep entering numbers to reach or exceed a sum of 100:");
int sum = 0;
while (sum < 100) {
System.out.print("Enter number: ");
int input = sc.nextInt();
sum += input;
}
System.out.println("Total sum: " + sum);
// Q4: Reverse Digits
System.out.print("\nQ4 - Enter a number to reverse its digits: ");
int num = sc.nextInt();
int rev = 0;
while (num != 0) {
int digit = num % 10;
rev = rev * 10 + digit;
num /= 10;
}
System.out.println("Reversed number: " + rev);
// Q5: Count Digits
System.out.print("\nQ5 - Enter a number to count its digits: ");
int countNum = sc.nextInt();
int count = 0;
while (countNum != 0) {
countNum /= 10;
count++;
}
System.out.println("Number of digits: " + count);
// Q6: Check Palindrome
System.out.print("\nQ6 - Enter a number to check if it's a palindrome: ");
int original = sc.nextInt();
int temp = original;
int reversed = 0;
while (temp != 0) {
int digit = temp % 10;
reversed = reversed * 10 + digit;
temp /= 10;
}
System.out.println(original == reversed ? "Palindrome" : "Not Palindrome");
// Q7: Sum of Digits
System.out.print("\nQ7 - Enter a number to find sum of its digits: ");
int digitSumNum = sc.nextInt();
int digitSum = 0;
while (digitSumNum != 0) {
digitSum += digitSumNum % 10;
digitSumNum /= 10;
}
System.out.println("Sum of digits: " + digitSum);
// Q8: Table Until Exit
System.out.println("\nQ8 - Enter numbers to print their multiplication table (-1 to exit):");
int tableInput;
do {
System.out.print("Enter number: ");
tableInput = sc.nextInt();
int t = 1;
while (tableInput != -1 && t <= 10) {
System.out.println(tableInput + " x " + t + " = " + (tableInput * t));
t++;
}
} while (tableInput != -1);
// Q9: Guess the Number
System.out.println("\nQ9 - Guess the secret number between 1 and 10:");
int secret = 7;
int guess;
do {
System.out.print("Your guess: ");
guess = sc.nextInt();
} while (guess != secret);
System.out.println("Correct!");
// Q10: Power of Two
System.out.println("\nQ10 - Powers of 2 up to 1024:");
int power = 1;
while (power <= 1024) {
System.out.println(power);
power *= 2;
}
// Q11: Fibonacci Until Limit
System.out.print("\nQ11 - Enter a limit to generate Fibonacci numbers: ");
int limit = sc.nextInt();
int a = 0, b = 1;
System.out.print("Fibonacci series: ");
while (a < limit) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
System.out.println();
// Q12: Check Armstrong Number
System.out.print("\nQ12 - Enter a 3-digit number to check if it's an Armstrong number: ");
int arm = sc.nextInt();
int originalArm = arm;
int result = 0;
while (arm != 0) {
int digit = arm % 10;
result += digit * digit * digit;
arm /= 10;
}
System.out.println(result == originalArm ? "Armstrong number" : "Not Armstrong");
// Q13: Even Sum
System.out.println("\nQ13 - Sum of even numbers from 1 to 100:");
int even = 1;
int evenSum = 0;
while (even <= 100) {
if (even % 2 == 0)
evenSum += even;
even++;
}
System.out.println("Sum of even numbers: " + evenSum);
// Q14: Factor Finder
System.out.print("\nQ14 - Enter a number to find its factors: ");
int factNum = sc.nextInt();
int f = 1;
System.out.println("Factors of " + factNum + ":");
while (f <= factNum) {
if (factNum % f == 0)
System.out.println(f);
f++;
}
// Q15: User Login Attempts
String correctPass = "admin123";
int attempts = 0;
System.out.println("\nQ15 - Login system (3 attempts):");
while (attempts < 3) {
System.out.print("Enter password: ");
String input = sc.next();
if (input.equals(correctPass)) {
System.out.println("Access Granted");
break;
}
attempts++;
}
if (attempts == 3) {
System.out.println("Account Locked");
}
sc.close();
}
}
🔁 15 Best do-while Concept Challenges
- Print numbers from 1 to 10: Use a
do-whileloop to print numbers from 1 to 10. No user input is required. - Sum of first N numbers: Prompt the user to enter a number
N. Use ado-whileloop to find and print the sum of numbers from 1 toN. - Multiplication table: Ask the user to enter a number. Use a
do-whileloop to print its multiplication table up to 10. - Reverse a number: Prompt the user to enter a number. Use a
do-whileloop to reverse the digits of that number (e.g., input: 1234 → output: 4321). - Palindrome check: Ask the user to input a number. Use a
do-whileloop to check whether the number is a palindrome (reads the same forwards and backwards). - Digit count: Prompt the user to enter a number. Use a
do-whileloop to count how many digits the number has. - Even numbers from 1 to 50: Use a
do-whileloop to print all even numbers between 1 and 50 (inclusive). No user input required. - Factorial: Ask the user to enter a number. Use a
do-whileloop to calculate and print its factorial (e.g., 5 → 120). - Sum of digits: Prompt the user to enter a number. Use a
do-whileloop to compute and display the sum of its digits. - Positive input prompt: Use a
do-whileloop to repeatedly ask the user to enter a number until they provide a positive number. - Decimal to binary conversion: Ask the user to enter a decimal number. Use a
do-whileloop to convert and display its binary representation (as an integer). - Star pattern: Prompt the user to enter the number of rows. Use nested
do-whileloops to print a right-angled triangle pattern of stars (*) up to that number of rows. - Countdown: Use a
do-whileloop to print a countdown from 10 to 1. No user input is required. - Fibonacci series: Ask the user how many terms of the Fibonacci series to print. Use a
do-whileloop to generate and display that many terms. - Sum of odd numbers: Prompt the user to enter a number
N. Use ado-whileloop to calculate and print the sum of all odd numbers from 1 toN.
🧮 Java do-while Challenge Solutions
import java.util.Scanner;
public class DoWhileChallengerUserInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Q1: Print 1 to 10
System.out.println("Q1 - Printing numbers from 1 to 10:");
int i = 1;
do {
System.out.print(i + " ");
i++;
} while (i <= 10);
System.out.println("\n");
// Q2: Sum of first N numbers
System.out.print("Q2 - Enter N to find sum from 1 to N: ");
int n = sc.nextInt();
int sum = 0, j = 1;
do {
sum += j;
j++;
} while (j <= n);
System.out.println("Sum: " + sum + "\n");
// Q3: Multiplication table
System.out.print("Q3 - Enter a number for its multiplication table: ");
int num = sc.nextInt(), k = 1;
do {
System.out.println(num + " x " + k + " = " + (num * k));
k++;
} while (k <= 10);
System.out.println();
// Q4: Reverse a number
System.out.print("Q4 - Enter a number to reverse: ");
int number = sc.nextInt(), reversed = 0, temp = number;
do {
reversed = reversed * 10 + temp % 10;
temp /= 10;
} while (temp != 0);
System.out.println("Reversed: " + reversed + "\n");
// Q5: Palindrome check
System.out.print("Q5 - Enter a number to check palindrome: ");
int original = sc.nextInt(), rev = 0, copy = original;
do {
rev = rev * 10 + copy % 10;
copy /= 10;
} while (copy != 0);
System.out.println(original == rev ? "Palindrome\n" : "Not a palindrome\n");
// Q6: Digit count
System.out.print("Q6 - Enter a number to count digits: ");
int digitNum = sc.nextInt(), count = 0;
do {
count++;
digitNum /= 10;
} while (digitNum != 0);
System.out.println("Digit count: " + count + "\n");
// Q7: Even numbers from 1 to 50
System.out.println("Q7 - Even numbers from 1 to 50:");
int ev = 2;
do {
System.out.print(ev + " ");
ev += 2;
} while (ev <= 50);
System.out.println("\n");
// Q8: Factorial
System.out.print("Q8 - Enter a number to find factorial: ");
int x = sc.nextInt(), fact = 1, f = 1;
do {
fact *= f;
f++;
} while (f <= x);
System.out.println("Factorial: " + fact + "\n");
// Q9: Sum of digits
System.out.print("Q9 - Enter a number to sum its digits: ");
int numToSum = sc.nextInt(), digitSum = 0;
do {
digitSum += numToSum % 10;
numToSum /= 10;
} while (numToSum != 0);
System.out.println("Digit sum: " + digitSum + "\n");
// Q10: Positive input prompt simulation
int input;
do {
System.out.print("Q10 - Enter a positive number: ");
input = sc.nextInt();
} while (input <= 0);
System.out.println("Positive input accepted: " + input + "\n");
// Q11: Decimal (Integer) to Binary
System.out.print("Q11 - Enter a whole number (integer): ");
if (sc.hasNextInt()) {
int dec = sc.nextInt();
int binary = 0, place = 1;
int originalDec = dec;
if (dec == 0) {
binary = 0;
} else {
do {
int rem = dec % 2;
binary += rem * place;
place *= 10;
dec /= 2;
} while (dec != 0);
}
System.out.println("Binary of " + originalDec + " is: " + binary + "\n");
} else {
System.out.println("Invalid input! Please enter a whole number (no decimal part).\n");
sc.next(); // clear the invalid input
}
// Q11: Decimal (Floating-Point) to Binary
System.out.print("Q11 - Enter a decimal number (e.g., 5.75): ");
if (sc.hasNextDouble()) {
double decimalInput = sc.nextDouble();
int intPart = (int) decimalInput;
double fracPart = decimalInput - intPart;
// Convert integer part using do-while
String intBinary = "";
if (intPart == 0) {
intBinary = "0";
} else {
do {
intBinary = (intPart % 2) + intBinary;
intPart /= 2;
} while (intPart > 0);
}
// Convert fractional part using do-while
String fracBinary = "";
int limit = 10; // max digits after point
int fracCount = 0;
if (fracPart > 0) {
do {
fracPart *= 2;
if (fracPart >= 1) {
fracBinary += "1";
fracPart -= 1;
} else {
fracBinary += "0";
}
fracCount++;
} while (fracPart > 0 && fracCount < limit);
}
System.out.println("Binary of " + decimalInput + " is: " + intBinary +
(fracBinary.isEmpty() ? "" : "." + fracBinary) + "\n");
} else {
System.out.println("Invalid input! Please enter a numeric value.\n");
sc.next(); // clear invalid input
}
// Q12: Star pattern
System.out.print("Q12 - Enter number of rows for star pattern: ");
int rows = sc.nextInt(), row = 1;
do {
int star = 1;
do {
System.out.print("* ");
star++;
} while (star <= row);
System.out.println();
row++;
} while (row <= rows);
System.out.println();
// Q13: Countdown
System.out.println("Q13 - Countdown from 10:");
int down = 10;
do {
System.out.print(down + " ");
down--;
} while (down >= 1);
System.out.println("\n");
// Q14: Fibonacci series
System.out.print("Q14 - Enter number of Fibonacci terms: ");
int terms = sc.nextInt(), a = 0, b = 1, fib = 1;
System.out.print("Fibonacci series: ");
do {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
fib++;
} while (fib <= terms);
System.out.println("\n");
// Q15: Sum of odd numbers
System.out.print("Q15 - Enter a number to sum all odd numbers up to it: ");
int limit = sc.nextInt(), odd = 1, oddSum = 0;
do {
oddSum += odd;
odd += 2;
} while (odd <= limit);
System.out.println("Sum of odd numbers: " + oddSum);
sc.close();
}
}
🔢 Decimal to Binary Converter
🧠 Logic (Simple Explanation)
- We ask the user for a number.
- If it's a whole number (like 5 or 10), we use math to turn it into binary.
- If it's a number with a decimal (like 5.75), we split it into two parts and convert both separately.
🔁 Integer to Binary using do-while loop
// 🟢 Q11: Decimal (Integer) to Binary using do-while
System.out.print("Q11 - Enter a whole number (integer): "); // Ask the user for an integer input
if (sc.hasNextInt()) { // Check if the input is a valid whole number (integer)
int dec = sc.nextInt(); // Read and store the input number
int binary = 0, place = 1; // Initialize binary result and place value (1s, 10s, 100s...)
int originalDec = dec; // Save original number for display later
if (dec == 0) { // Special case: if the number is 0, binary is also 0
binary = 0;
} else {
do { // Start do-while loop for conversion (runs at least once)
int rem = dec % 2; // Get remainder when dividing by 2 (either 0 or 1)
binary += rem * place; // Add the bit in the correct place value (units, tens, etc.)
place *= 10; // Move to the next binary digit's place (like shifting left)
dec /= 2; // Divide number by 2 for next iteration (integer division)
} while (dec != 0); // Repeat until the number becomes 0
}
// Print the original number and its binary form
System.out.println("Binary of " + originalDec + " is: " + binary + "\n");
} else {
// If user entered an invalid input (like a string or decimal), show message
System.out.println("Invalid input! Please enter a whole number (no decimal part).\n");
sc.next(); // Clear the invalid input from the scanner buffer
}
📘 Easy Explanation:
- We keep dividing the number by 2 using a
do-whileloop. - Each time, we get a remainder — either 0 or 1.
- We build the binary number by combining these remainders from right to left.
placehelps put binary digits in the right place: units, tens, hundreds.
🔁 Floating-Point (Decimal) to Binary using do-while loop
// 🟢 Q11: Decimal (Floating-Point) to Binary using do-while
System.out.print("Q11 - Enter a decimal number (e.g., 5.75): "); // Prompt user for decimal input
if (sc.hasNextDouble()) { // Check if the input is a valid decimal (integers are valid too)
double decimalInput = sc.nextDouble(); // Read the input number
int intPart = (int) decimalInput; // Extract the integer part
double fracPart = decimalInput - intPart; // Extract the fractional part
// --- Convert integer part using do-while ---
String intBinary = ""; // To store binary of the integer part
if (intPart == 0) {
intBinary = "0"; // If 0, set binary as "0"
} else {
do {
intBinary = (intPart % 2) + intBinary; // Add remainder to binary string
intPart /= 2; // Move to next bit
} while (intPart > 0); // Repeat until integer part becomes 0
}
// --- Convert fractional part using do-while ---
String fracBinary = ""; // To store binary of fractional part
int limit = 10; // Limit to max 10 fractional digits
int fracCount = 0; // Counter for fractional digits
if (fracPart > 0) {
do {
fracPart *= 2; // Multiply fraction by 2
if (fracPart >= 1) {
fracBinary += "1"; // Add 1 and subtract
fracPart -= 1;
} else {
fracBinary += "0"; // Add 0
}
fracCount++; // Increase counter
} while (fracPart > 0 && fracCount < limit); // Stop if fraction becomes 0 or limit reached
}
// Display final binary representation
System.out.println("Binary of " + decimalInput + " is: " + intBinary +
(fracBinary.isEmpty() ? "" : "." + fracBinary) + "\n");
} else {
// If invalid input entered
System.out.println("Invalid input! Please enter a numeric value.\n");
sc.next(); // Clear invalid token
}
📘 Easy Explanation:
- We break the number into two parts: before and after the decimal point.
- For the integer part, we use
do-whileand divide repeatedly by 2 (same as above). - For the fractional part:
- Multiply by 2.
- If the result is 1 or more, record a
1and subtract 1. - If it's less than 1, record a
0. - Repeat (using
do-while) up to 10 times or until the fraction becomes 0.
- The final binary is a combination of the two parts with a
.in the middle.
✅ Sample Output:
Integer Input: 13 Binary: 1101 Decimal Input: 5.75 Integer part: 5 → 101 Fraction part: .75 → .11 Binary: 101.11
🔁 Integer to Binary using while loop
// Q11: Decimal (Integer) to Binary
System.out.print("Q11 - Enter a whole number (integer): "); // Ask user to type a whole number (no decimals)
if (sc.hasNextInt()) { // Check if the user typed a valid whole number
int dec = sc.nextInt(); // Store the number in 'dec'
int binary = 0, place = 1; // 'binary' will hold our answer, 'place' tracks the position (1s, 10s, 100s)
int originalDec = dec; // Save the original number to show in the end
while (dec != 0) { // Keep going until the number becomes 0
int rem = dec % 2; // Divide by 2, get the remainder (this is one binary digit)
binary += rem * place; // Put the digit in the right position (units, tens, etc.)
place *= 10; // Move to the next place (e.g., 1 → 10 → 100)
dec /= 2; // Cut the number in half (integer division)
}
// Show the original and the result
System.out.println("Binary of " + originalDec + " is: " + binary + "\n");
} else {
// If they typed something wrong (like 5.2 or letters)
System.out.println("Invalid input! Please enter a whole number (no decimal part).\n");
sc.next(); // Clear the bad input
}
📘 Easy Explanation:
- We keep dividing the number by 2.
- Each time, we write down the remainder (0 or 1).
- We build the binary number by putting these remainders in reverse order.
- We use
placeto multiply the bits into correct position: 1s, 10s, 100s, etc. - This is for **integers only**, not decimals like 5.1 or 7.75.
🔁 Floating-Point (Decimal) to Binary
// Q11: Decimal (Floating-Point) to Binary
System.out.print("Q11 - Enter a decimal number (e.g., 5.75): "); // Ask user to enter a decimal number
if (sc.hasNextDouble()) { // Check if they entered a valid decimal
double decimalInput = sc.nextDouble(); // Read it
int intPart = (int) decimalInput; // Get the whole number part (e.g., from 5.75 → 5)
double fracPart = decimalInput - intPart; // Get the decimal part (e.g., from 5.75 → 0.75)
// --- Convert the integer part to binary ---
String intBinary = ""; // Store the binary result as text
if (intPart == 0) {
intBinary = "0"; // If the whole part is 0, just write 0
} else {
while (intPart > 0) {
intBinary = (intPart % 2) + intBinary; // Add remainder in front each time
intPart /= 2;
}
}
// --- Convert the fractional part to binary ---
String fracBinary = "";
int limit = 10; // Only go 10 digits after decimal point to avoid infinite loops
while (fracPart > 0 && fracBinary.length() < limit) {
fracPart *= 2; // Multiply the fraction by 2
if (fracPart >= 1) {
fracBinary += "1"; // If it's 1 or more, add a 1
fracPart -= 1; // Remove the 1
} else {
fracBinary += "0"; // If less than 1, just add 0
}
}
// Join the two parts together and print
System.out.println("Binary of " + decimalInput + " is: " + intBinary +
(fracBinary.isEmpty() ? "" : "." + fracBinary) + "\n");
} else {
System.out.println("Invalid input! Please enter a numeric value.\n");
sc.next(); // clear invalid input
}
📘 Easy Explanation:
- We split the number into two parts: before and after the dot.
- Example: 5.75 →
intPart = 5,fracPart = 0.75 - Convert the whole number (5) like before (5 → 101)
- To convert the decimal part (0.75):
- Multiply it by 2 → 0.75 * 2 = 1.5 → record 1
- Take the .5 → 0.5 * 2 = 1.0 → record 1
- Done! → 0.75 → 11 in binary
- Final answer: 5.75 → 101.11
✅ Sample Output:
Integer Input: 13 Binary: 1101 Decimal Input: 5.75 Integer part: 5 → 101 Fraction part: .75 → .11 Binary: 101.11
🧪 Summary of Key Concepts:
| Part | What It Does |
|---|---|
% 2 |
Gets binary digit (remainder) — either 0 or 1 |
/ 2 |
Divides the number by 2 to move to the next binary digit (integer part) |
* 2 |
Used to convert fractional part — shift left in binary terms |
do-while |
Loop runs at least once even if the condition is false initially — great for guaranteed input processing |
while |
Loop checks the condition first — safer when input may already be invalid |
| place | Tracks binary digit positions (1s, 10s, 100s...) — only used for integer-to-binary when storing result as a number |
| String | Used to build binary values with leading zeros or decimal points (especially for floating-point numbers) |
🤔 Which is better: do-while or while?
- Use
do-whilewhen you want the loop to run at least once no matter what. Example: converting a number that could be zero. - Use
whilewhen the condition must be true before running even the first time. It's slightly safer in input-sensitive scenarios. - In binary conversion: both can work, but
do-whileis a better fit when converting 0 or small numbers (guarantees 1 run).
🧮 Factorial Calculator Using All Loop Types in Java
The factorial of a number n is the product of all positive integers from
1 to n.
🧠 Step-by-Step Explanation
- Input a number (e.g., 5).
- Initialize a variable
fact = 1. - Loop from 1 to that number and multiply
factby each value. - Print the final value of
factafter the loop ends.
🔁 Using for Loop
import java.util.Scanner;
public class FactorialFor {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
System.out.println("Factorial of " + num + " is: " + fact);
}
}
🔁 Using while Loop
import java.util.Scanner;
public class FactorialWhile {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int fact = 1, i = 1;
while (i <= num) {
fact *= i;
i++;
}
System.out.println("Factorial of " + num + " is: " + fact);
}
}
🔁 Using do-while Loop
import java.util.Scanner;
public class FactorialDoWhile {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int fact = 1, i = 1;
do {
fact *= i;
i++;
} while (i <= num);
System.out.println("Factorial of " + num + " is: " + fact);
}
}
✅ Summary
- Factorial is computed by multiplying a series of integers from 1 to n.
- Use any loop type depending on control and preference.
foris best for fixed iterations;whileanddo-whileare useful for variable conditions.
🔢 Fibonacci Series in Java
This section demonstrates how to print the Fibonacci Series using for, while, and
do-while loops in Java. It also includes detailed step-by-step explanations inside the code as
comments.
✅ 1. Using for loop
public class FibonacciFor {
public static void main(String[] args) {
int n = 10; // Total number of terms
int a = 0, b = 1;
System.out.print("Fibonacci Series using for loop: ");
// Step 1: Print first two terms
System.out.print(a + " " + b + " ");
// Step 2: Loop from 2 to n-1
for (int i = 2; i < n; i++) {
int c = a + b; // Next term is sum of previous two
System.out.print(c + " ");
a = b; // Move b to a
b = c; // Move c to b
}
}
}
✅ 2. Using while loop
public class FibonacciWhile {
public static void main(String[] args) {
int n = 10;
int a = 0, b = 1;
int i = 2;
System.out.print("Fibonacci Series using while loop: ");
// Step 1: Print the first two terms
System.out.print(a + " " + b + " ");
// Step 2: Continue loop while i < n
while (i < n) {
int c = a + b;
System.out.print(c + " ");
a = b;
b = c;
i++; // Increment counter
}
}
}
✅ 3. Using do-while loop
public class FibonacciDoWhile {
public static void main(String[] args) {
int n = 10;
int a = 0, b = 1;
int i = 2;
System.out.print("Fibonacci Series using do-while loop: ");
// Step 1: Print the first two terms
System.out.print(a + " " + b + " ");
// Step 2: Use do-while to continue until n terms
do {
int c = a + b;
System.out.print(c + " ");
a = b;
b = c;
i++;
} while (i < n);
}
}
📌 Step-by-Step Logic
- Start with two variables:
a = 0,b = 1 - Print the first two terms:
0 1 - Loop from 2 to n:
- Calculate
c = a + b - Print
c - Update
a = b,b = c
- Calculate
- Repeat until all
nterms are printed
📈 Fibonacci Series Until a Given Limit
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. The sequence starts from 0 and 1. Unlike the version with a fixed number of terms, here we stop when the next number would exceed a user-defined limit.
🔁 Using for Loop
// Step-by-step for-loop Fibonacci until a limit
int limit = 100;
int a = 0, b = 1;
System.out.print("Fibonacci series up to " + limit + ": ");
System.out.print(a + " " + b + " ");
for (int next = a + b; next <= limit; next = a + b) {
System.out.print(next + " ");
a = b;
b = next;
}
- Start with two base numbers: 0 and 1.
- Print both starting numbers.
- Loop to calculate the next Fibonacci number until it exceeds the given
limit. - Update
aandbaccordingly in each iteration.
🔄 Using while Loop
// Step-by-step while-loop Fibonacci until a limit
int limit = 100;
int a = 0, b = 1;
System.out.print("Fibonacci series up to " + limit + ": ");
System.out.print(a + " " + b + " ");
int next = a + b;
while (next <= limit) {
System.out.print(next + " ");
a = b;
b = next;
next = a + b;
}
🔂 Using do-while Loop
// Step-by-step do-while-loop Fibonacci until a limit
int limit = 100;
int a = 0, b = 1;
System.out.print("Fibonacci series up to " + limit + ": ");
System.out.print(a + " " + b + " ");
int next = a + b;
do {
System.out.print(next + " ");
a = b;
b = next;
next = a + b;
} while (next <= limit);
This version ensures that at least one iteration happens even if the limit is small. Ideal when initial values must be printed regardless of conditions.
🧮 Factor Finder: Using All Loops
🔹 What Are Factors?
A factor of a number is any number that divides it exactly without leaving a remainder.
Example: Factors of 12 are 1, 2, 3, 4, 6, and 12.
🔁 Using for Loop
int num = 12;
System.out.println("Factors of " + num + " using for loop:");
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
System.out.print(i + " ");
}
}
✅ Explanation:
- Start loop from 1 to num
- Check if
num % i == 0 - If yes, print
ias a factor
🔁 Using while Loop
int num = 12;
int i = 1;
System.out.println("\nFactors of " + num + " using while loop:");
while (i <= num) {
if (num % i == 0) {
System.out.print(i + " ");
}
i++;
}
✅ Explanation:
- Initialize counter
i = 1 - Repeat while
i <= num - Check divisibility and print factor
- Increment
i
🔁 Using do-while Loop
int num = 12;
int i = 1;
System.out.println("\nFactors of " + num + " using do-while loop:");
do {
if (num % i == 0) {
System.out.print(i + " ");
}
i++;
} while (i <= num);
✅ Explanation:
- Start with
i = 1 - Use
do-whileto ensure the loop runs at least once - Check divisibility and print factor
- Increment
iuntili > num
✅ Output Example for num = 12:
Factors of 12 using for loop:
1 2 3 4 6 12
Factors of 12 using while loop:
1 2 3 4 6 12
Factors of 12 using do-while loop:
1 2 3 4 6 12
🔢 Digit Counter in Java
📝 Objective:
Count the number of digits in an integer using for, while, and do-while
loops.
💡 Logic:
- Divide the number by 10 repeatedly until it becomes 0.
- Each division removes the last digit.
- Count how many times this happens.
📘 Example:
If the number is 4567, it has 4 digits.
✅ Using for Loop
int num = 4567;
int count = 0;
for (int temp = num; temp != 0; temp /= 10) {
count++;
}
System.out.println("Digit Count: " + count);
🔍 Step-by-Step:
- Initialize
temp = num. - Loop:
temp != 0. - On each iteration, remove the last digit using
temp /= 10. - Increment
countuntiltempbecomes 0.
✅ Using while Loop
int num = 4567;
int count = 0;
int temp = num;
while (temp != 0) {
count++;
temp /= 10;
}
System.out.println("Digit Count: " + count);
🔍 Step-by-Step:
- Copy
numtotemp. - Continue while
temp != 0. - Each time: divide
tempby 10 and incrementcount.
✅ Using do-while Loop
int num = 4567;
int count = 0;
int temp = num;
do {
count++;
temp /= 10;
} while (temp != 0);
System.out.println("Digit Count: " + count);
🔍 Step-by-Step:
- This loop runs at least once, even if the number is 0.
- Each loop: count++, then divide
tempby 10. - Loop continues while
temp != 0.
📌 Special Case:
- If
num = 0, all loops must still return 1 digit. - Fix: Add a condition to check
if (num == 0), return 1 directly or handle it indo-while.
✅ Output:
Digit Count: 4
🔢 Digit Analysis
Below we calculate:
- Total number of digits
- Sum of digits
- Count of even and odd digits
🧮 Using for loop
int number = 4623;
int original = number;
int count = 0, even = 0, odd = 0, sum = 0;
for (; number > 0; number /= 10) {
int digit = number % 10;
count++;
sum += digit;
if (digit % 2 == 0) even++;
else odd++;
}
System.out.println("Digits: " + count);
System.out.println("Sum: " + sum);
System.out.println("Even digits: " + even);
System.out.println("Odd digits: " + odd);
🔍 Step-by-step:
% 10extracts the last digit/= 10removes the last digitif (digit % 2 == 0)checks for even
🔁 Using while loop
int number = 4623;
int original = number;
int count = 0, even = 0, odd = 0, sum = 0;
while (number > 0) {
int digit = number % 10;
count++;
sum += digit;
if (digit % 2 == 0) even++;
else odd++;
number /= 10;
}
System.out.println("Digits: " + count);
System.out.println("Sum: " + sum);
System.out.println("Even digits: " + even);
System.out.println("Odd digits: " + odd);
🔂 Using do-while loop
int number = 4623;
int original = number;
int count = 0, even = 0, odd = 0, sum = 0;
do {
int digit = number % 10;
count++;
sum += digit;
if (digit % 2 == 0) even++;
else odd++;
number /= 10;
} while (number > 0);
System.out.println("Digits: " + count);
System.out.println("Sum: " + sum);
System.out.println("Even digits: " + even);
System.out.println("Odd digits: " + odd);
✅ Sample Output
Digits: 4
Sum: 15
Even digits: 3
Odd digits: 1
🧠 Which loop is best?
| Loop | Best When... |
|---|---|
for |
You know all parts: start, end, and update |
while |
You only need to repeat based on a condition |
do-while |
You want the loop to run at least once |
💡 Armstrong Number Logic in Java
An Armstrong number is a number that is equal to the sum of the cubes of its digits. For example,
153 is an Armstrong number because:
1³ + 5³ + 3³ = 1 + 125 + 27 = 153
✅ Java Code Example
public class ArmstrongCheck {
public static void main(String[] args) {
int number = 153;
int originalNumber = number;
int sum = 0;
while (number > 0) {
int digit = number % 10;
sum += digit * digit * digit;
number /= 10;
}
if (sum == originalNumber) {
System.out.println(originalNumber + " is an Armstrong number.");
} else {
System.out.println(originalNumber + " is not an Armstrong number.");
}
}
}
🔍 Key Concepts
number % 10: Extracts the last digit.digit * digit * digit: Cubes the digit.number /= 10: Removes the last digit (integer division).
❓ Why Use while (number > 0) Instead of while (number != 0)?
- ✔️ Clarity: Clearly expresses intent to process positive digits only.
- ✔️ Safety: Prevents infinite loops if a negative number is entered.
- ❌ Risk with
!= 0: If number is negative, it never becomes 0 — leads to infinite loop.
📊 Comparison
| Condition | Works for Positive? | Works for Zero? | Works for Negative? | Issue |
|---|---|---|---|---|
while (number > 0) |
✅ Yes | ✅ Yes (loop doesn't run) | ✅ Yes (loop doesn't run) | None |
while (number != 0) |
✅ Yes | ✅ Yes (loop doesn't run) | ❌ No | Infinite loop for negative input |
📝 Final Tip
Use the while (number > 0) condition when processing digits of a number. It ensures your loop is
safe, predictable, and avoids edge-case bugs from negative inputs.
🔁 Palindrome Number Check in Java
A palindrome number is a number that remains the same when its digits are reversed. For example,
121, 1331, and 454 are palindromes.
✅ Java Code Example
public class PalindromeCheck {
public static void main(String[] args) {
int number = 121;
int originalNumber = number;
int reversed = 0;
while (number > 0) {
int digit = number % 10;
reversed = reversed * 10 + digit;
number /= 10;
}
if (reversed == originalNumber) {
System.out.println(originalNumber + " is a palindrome.");
} else {
System.out.println(originalNumber + " is not a palindrome.");
}
}
}
🔍 How It Works
number % 10: Extracts the last digit.reversed = reversed * 10 + digit: Builds the reversed number.number /= 10: Removes the last digit.
❓ Why Use while (number > 0) and Not while (number != 0)?
- ✔️ Prevents infinite loop:
number != 0can cause infinite loop for negative input. - ✔️ Palindromes are non-negative by definition: So
number > 0safely skips negatives. - ✔️ Better readability: Shows intention to loop through digits until the number is 0.
📊 Condition Comparison
| Condition | Positive Input | Zero Input | Negative Input | Potential Issue |
|---|---|---|---|---|
while (number > 0) |
✅ Yes | ✅ Yes (loop doesn't run) | ✅ Yes (loop doesn't run) | None |
while (number != 0) |
✅ Yes | ✅ Yes (loop doesn't run) | ❌ No | Infinite loop for negative input |
📝 Final Tip
Use while (number > 0) to safely reverse digits when checking for palindromes. It's more robust and
avoids accidental infinite loops from negative numbers.
⭐ Right-angled triangle Star Pattern in Java Using All Loop Types
Let's print a right-angled triangle star pattern using for, while, and
do-while loops in Java. Each loop gives the same output but works differently in structure.
✅ 1. Using for Loop
public class StarPatternFor {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
✅ 2. Using while Loop
public class StarPatternWhile {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
int j = 1;
while (j <= i) {
System.out.print("* ");
j++;
}
System.out.println();
i++;
}
}
}
✅ 3. Using do-while Loop
public class StarPatternDoWhile {
public static void main(String[] args) {
int i = 1;
do {
int j = 1;
do {
System.out.print("* ");
j++;
} while (j <= i);
System.out.println();
i++;
} while (i <= 5);
}
}
🧠 Pattern Logic
- Each row
ihasistars. - Outer loop tracks the row number (1 to 5).
- Inner loop prints stars based on the current row.
🔄 Loop Comparison
| Loop Type | Entry Check? | Common Usage |
|---|---|---|
for |
✅ Condition checked before loop | Best when number of iterations is known |
while |
✅ Condition checked before loop | Use when you may not know iterations in advance |
do-while |
✅ Condition checked after loop | Ensures loop runs at least once |
📌 Output
* * * * * * * * * * * * * * *
📝 Final Tip
Use for loop when the size of the pattern is fixed. Use while or do-while
for more dynamic or user-driven patterns, especially when input is taken at runtime.
🌟 Star Patterns in Java (All Loops)
📐 Pattern 1: Right-Angled Triangle
*
* *
* * *
* * * *
* * * * *
✅ For Loop
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
✅ While Loop
int i = 1;
while (i <= 5) {
int j = 1;
while (j <= i) {
System.out.print("* ");
j++;
}
System.out.println();
i++;
}
✅ Do-While Loop
int i = 1;
do {
int j = 1;
do {
System.out.print("* ");
j++;
} while (j <= i);
System.out.println();
i++;
} while (i <= 5);
📐 Pattern 2: Inverted Triangle
* * * * *
* * * *
* * *
* *
*
✅ For Loop
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
✅ While Loop
int i = 5;
while (i >= 1) {
int j = 1;
while (j <= i) {
System.out.print("* ");
j++;
}
System.out.println();
i--;
}
✅ Do-While Loop
int i = 5;
do {
int j = 1;
do {
System.out.print("* ");
j++;
} while (j <= i);
System.out.println();
i--;
} while (i >= 1);
📐 Pattern 3: Pyramid
*
* *
* * *
* * * *
* * * * *
✅ For Loop
for (int i = 1; i <= 5; i++) {
for (int space = 1; space <= 5 - i; space++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
📐 Pattern 4: Inverted Pyramid
* * * * *
* * * *
* * *
* *
*
✅ For Loop
for (int i = 5; i >= 1; i--) {
for (int space = 1; space <= 5 - i; space++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
📐 Pattern 5: Diamond
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
✅ For Loop (Full Diamond)
// Upper Half
for (int i = 1; i <= 5; i++) {
for (int space = 1; space <= 5 - i; space++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
// Lower Half
for (int i = 4; i >= 1; i--) {
for (int space = 1; space <= 5 - i; space++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
📌 Tip:
- Use nested loops: outer for rows, inner for spaces or stars.
- Play with spacing to align the patterns correctly.
- Pattern size can be user input (e.g., replace 5 with
n).
📐 Number Patterns in Java with Explanations
1️⃣ Right-Angled Number Triangle (For Loop)
Print numbers in a right-angled triangle using nested for loops.
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
- Outer loop (
i) runs from 1 ton→ number of rows. - Inner loop (
j) runs from 1 toi→ print increasing numbers per row.
2️⃣ Inverted Number Triangle (For Loop)
Print decreasing sequences in each row.
int n = 5;
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
- Outer loop runs from
nto 1. - Inner loop prints from 1 to current row limit.
3️⃣ Number Pyramid (For Loop)
Create a centered pyramid and its inverted version using numbers.
🔼 Number Pyramid
int n = 5;
for (int i = 1; i <= n; i++) {
// Print leading spaces
for (int s = 1; s <= n - i; s++) {
System.out.print(" ");
}
// Print numbers with space
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
🔹 Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
🔻 Inverted Number Pyramid
int n = 5;
for (int i = n; i >= 1; i--) {
// Print leading spaces
for (int s = 1; s <= n - i; s++) {
System.out.print(" ");
}
// Print numbers with space
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
🔹 Output:
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
💡 Notes:
- Leading spaces align the numbers in a triangle shape.
System.out.print(j + " ");adds a number and a space for proper width.- The structure is built using nested loops: outer loop for rows, inner loops for spaces and numbers.
4️⃣ Diamond Number Pattern (For Loop)
Upper and lower pyramid combined to form a diamond with numbers.
int n = 5;
// Upper half
for (int i = 1; i <= n; i++) {
for (int s = 1; s <= n - i; s++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
// Lower half
for (int i = n - 1; i >= 1; i--) {
for (int s = 1; s <= n - i; s++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
- Two parts: upper pyramid and inverted pyramid.
- Each line starts with spaces to center the numbers.
- Numbers increase from 1 to i on each line.
📌 Output for n = 5:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
5️⃣ Floyd's Triangle
Numbers increase sequentially row by row.
int n = 5;
int num = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(num + " ");
num++;
}
System.out.println();
}
numstarts at 1 and increases with each printed number.- Each row
icontains exactlyinumbers. - Forms a triangular pattern from top to bottom.
📌 Output for n = 5:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
📘 Non-Primitive Data Type: String
In Java, a String is a non-primitive data type that represents a sequence of characters. It is an
object of the String class and provides various useful methods for manipulation.
🔹 String Basics
// Declaration
String name = "Aelify";
// Common operations
System.out.println(name.length()); // 6
System.out.println(name.charAt(0)); // 'A'
System.out.println(name.toUpperCase()); // "AELIFY"
System.out.println(name.substring(1)); // "elify"
🧠 Concept: Loop Through a String
Let's print each character in a string using all 3 loops.
▶️ Using for loop
String str = "Java";
for (int i = 0; i < str.length(); i++) {
System.out.println(str.charAt(i));
}
▶️ Using while loop
String str = "Java";
int i = 0;
while (i < str.length()) {
System.out.println(str.charAt(i));
i++;
}
▶️ Using do-while loop
String str = "Java";
int i = 0;
do {
System.out.println(str.charAt(i));
i++;
} while (i < str.length());
🔍 Step-by-Step Explanation
- Declare a
Stringvariable with a value, e.g.,"Java". - Use a loop to access each index of the string using
charAt(i). - Print each character on a new line.
📌 Output for all loops (str = "Java")
J
a
v
a
✅ Recap
Stringis an object that represents character sequences.- It is immutable - once created, it cannot be changed.
- You can use
for,while, ordo-whileto iterate over each character.
📦 Java Classes — Non-Primitive Data Type
In Java, a class is a blueprint for creating objects. It encapsulates data for the object and methods
to manipulate that data. Let's understand how classes work with a step-by-step explanation and looping usage.
🧒 Simple Explanation: What Is a Class in Java?
Think of a class like a blueprint or a template for something real — like a Student, Car, or Animal.
- 🧱 A
classtells Java what things (data) an object should have, and what it can do (methods). - 👶 An object is made from a class — like creating a real student from the student template.
- 🚪 A
constructoris like a door that lets you create objects with specific values. - 🗣 A
methodis like a behavior — it tells the object what to do (like speak or display info).
📦 In Simple Words:
Imagine you're making a toy using a mold (class). Every time you pour plastic into the mold (create an object), you get a new toy with the shape and features you designed.
🔄 Steps to Create and Use a Class in Java
- Create the class: Define the data (like
nameandage). - Add a constructor: This helps you set values when the object is created.
- Add methods: These perform actions, like showing the info.
- Use the class in
main(): Make real students usingnewkeyword. - Use loops: If you have many students, use
for,while, ordo-whileto show all their info.
✅ Example in Real Life:
A class is like a cookie-cutter 🍪. You design it once, and then make many cookies (objects) from it. Each cookie can have different flavors (data).
🧠 Tip:
Always start by asking: "What do I want to model?" — That will become your class.
✅ Basic Class Structure
class Student {
String name;
int age;
// Constructor
Student(String name, int age) {
this.name = name;
this.age = age;
}
// Method
void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
🧪 Example: Using Class in Main Method
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Aelify", 20);
Student s2 = new Student("Bob", 22);
s1.displayInfo();
s2.displayInfo();
}
}
🔁 Looping Over Class Objects (Array of Objects)
You can use loops to handle multiple class objects efficiently.
📌 Using for loop
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student[] students = {
new Student("Aelify", 20),
new Student("Bob", 21),
new Student("Charlie", 22)
};
for (int i = 0; i < students.length; i++) {
students[i].displayInfo();
}
}
}
📌 Using while loop
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student[] students = {
new Student("Aelify", 20),
new Student("Bob", 21),
new Student("Charlie", 22)
};
int i = 0;
while (i < students.length) {
students[i].displayInfo();
i++;
}
}
}
📌 Using do-while loop
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student[] students = {
new Student("Aelify", 20),
new Student("Bob", 21),
new Student("Charlie", 22)
};
int i = 0;
do {
students[i].displayInfo();
i++;
} while (i < students.length);
}
}
🔍 Step-by-Step Breakdown
- ✅ Create a class — Define attributes and behaviors using variables and methods.
- ✅ Constructor — Used to initialize objects with specific values.
- ✅ Object creation — Use
newkeyword to instantiate the class. - ✅ Looping — Store objects in an array and loop through them for bulk operations.
📌 Output Example
Name: Aelify, Age: 20
Name: Bob, Age: 21
Name: Charlie, Age: 22
✅ Arrays in Java
Arrays are non-primitive data structures that store multiple values of the same type in a single variable. They are indexed starting from 0.
An array is like a row of boxes 🧱. Each box stores a value, and we can find any value by its box
number (called an index). Indexes start from 0.
📦 Array Declaration & Initialization
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
🔁 Loop using while
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int i = 0;
while (i < numbers.length) {
System.out.println("Element at index " + i + ": " + numbers[i]);
i++;
}
}
}
🔂 Loop using do-while
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int j = 0;
do {
System.out.println("Element at index " + j + ": " + numbers[j]);
j++;
} while (j < numbers.length);
}
}
➕ Sum of Array Elements
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println("Sum of elements: " + sum);
}
}
🧠 Multi-dimensional Array (2D)
public class Main {
public static void main(String[] args) {
int[][] matrix = {
{1, 2},
{3, 4},
{5, 6}
};
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
}
}
📘 Simple Explanation (for beginners)
Imagine an array like a row of mailboxes 📬. Each one holds a number and has a label: 0, 1, 2... etc.
- Declare: Tell Java "I'm making an array of numbers" →
int[] numbers; - Initialize: Fill it with values →
{10, 20, 30, 40, 50} - Access: Use
numbers[0]to see what’s inside the first box - Loop: Let Java open all boxes one by one using a
fororwhileloop - Sum: Add up all numbers using a loop
🎒 Real-Life Analogy
Think of an array like a row of school bags. Each bag has a number tag (index) and holds a book (value). You can loop through the bags to find what’s inside!
An array is like a train 🚆 with multiple coaches. Each coach carries a passenger (number). You can walk through the coaches one by one to check who’s sitting where!
✅ Output Example
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
Sum of elements: 150
🧠 Java Matrices (Multi-dimensional Arrays)
A matrix in Java is essentially a 2D array — an array of arrays. Think of it like a table with rows and columns, where each cell holds a value.
🔹 Declaring a 2D Array (Matrix)
int[][] matrix = new int[3][2]; // 3 rows, 2 columns
This creates a matrix like:
[0][0] [0][1] [1][0] [1][1] [2][0] [2][1]
public class Main {
public static void main(String[] args) {
// Declares a 2D array (matrix) with 3 rows and 2 columns
int[][] matrix = new int[3][2];
// Outer loop iterates over each row
for (int i = 0; i < matrix.length; i++) {
// Inner loop iterates over each column in the current row
for (int j = 0; j < matrix[i].length; j++) {
// Assigns the value i + j to each element in the matrix
matrix[i][j] = i + j;
// Prints the current element followed by a space
System.out.print(matrix[i][j] + " ");
}
// Moves to the next line after printing one row
System.out.println();
}
}
}
🔹 Initializing a Matrix Directly
public class Main {
public static void main(String[] args) {
// Declares and initializes a 2D array with 3 rows and 2 columns
int[][] matrix = {
{1, 2},
{3, 4},
{5, 6}
};
// Traverses and prints each element using nested loops
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
// Prints each element followed by a space
System.out.print(matrix[i][j] + " ");
}
// Moves to the next line after each row
System.out.println();
}
}
}
🔍 Accessing Elements
public class Main {
public static void main(String[] args) {
// Initializes a 2D array with fixed values
int[][] matrix = {
{1, 2},
{3, 4},
{5, 6}
};
// Accesses and prints the element in the first row, second column
System.out.println("Element at [0][1]: " + matrix[0][1]); // prints 2
}
}
🔁 Traversing a Matrix with Nested Loops
public class Main {
public static void main(String[] args) {
// Initializes a 2D array with 3 rows and 2 columns
int[][] matrix = {
{1, 2},
{3, 4},
{5, 6}
};
// Outer loop goes through each row
for (int row = 0; row < matrix.length; row++) {
// Inner loop goes through each column in the current row
for (int col = 0; col < matrix[row].length; col++) {
// Prints each element followed by a space
System.out.print(matrix[row][col] + " ");
}
// Moves to next line after printing a full row
System.out.println();
}
}
}
🌟 Enhanced For Loop (for-each)
public class Main {
public static void main(String[] args) {
// Initializes a 2D array
int[][] matrix = {
{1, 2},
{3, 4},
{5, 6}
};
// For-each loop to go through each row (which is a 1D array)
for (int[] row : matrix) {
// For-each loop to go through each element in the current row
for (int num : row) {
// Prints each number with a space
System.out.print(num + " ");
}
// Moves to the next line after printing a row
System.out.println();
}
}
}
➕ Matrix Addition
public class Main {
public static void main(String[] args) {
// Declares and initializes two 2x2 matrices A and B
int[][] A = {
{1, 2},
{3, 4}
};
int[][] B = {
{5, 6},
{7, 8}
};
// Creates a result matrix to store the sum, same size as A and B
int[][] result = new int[2][2];
// Loops over each element to add corresponding elements of A and B
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A[0].length; j++) {
result[i][j] = A[i][j] + B[i][j];
}
}
// Prints the resulting matrix
for (int[] row : result) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
}
✖️ Matrix Multiplication
public class Main {
public static void main(String[] args) {
// Declares and initializes matrices A and B
int[][] A = {
{1, 2},
{3, 4}
};
int[][] B = {
{2, 0},
{1, 2}
};
// Resultant matrix for storing multiplication results
int[][] product = new int[2][2];
// Triple nested loop to perform matrix multiplication
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
// Initialize current cell to 0
product[i][j] = 0;
// Perform the dot product of row of A and column of B
for (int k = 0; k < 2; k++) {
product[i][j] += A[i][k] * B[k][j];
}
}
}
// Prints the product matrix
for (int[] row : product) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
}
📏 Transpose of a Matrix
public class Main {
public static void main(String[] args) {
// Original matrix with 3 rows and 2 columns
int[][] original = {
{1, 2},
{3, 4},
{5, 6}
};
// Transpose matrix will have 2 rows and 3 columns
int[][] transpose = new int[2][3];
// Loops through each element and swaps rows with columns
for (int i = 0; i < original.length; i++) {
for (int j = 0; j < original[0].length; j++) {
transpose[j][i] = original[i][j];
}
}
// Prints the transposed matrix
for (int[] row : transpose) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
}
🧠 Advanced: Jagged Arrays
These are arrays where each row can have a different number of columns:
public class Main {
public static void main(String[] args) {
// Declares a jagged array with 3 rows and unspecified column sizes
int[][] jagged = new int[3][];
// First row has 2 elements
jagged[0] = new int[]{1, 2};
// Second row has 3 elements
jagged[1] = new int[]{3, 4, 5};
// Third row has 1 element
jagged[2] = new int[]{6};
// Loops through each row
for (int i = 0; i < jagged.length; i++) {
// Loops through each column in current row
for (int j = 0; j < jagged[i].length; j++) {
// Prints each element followed by space
System.out.print(jagged[i][j] + " ");
}
// New line after each row
System.out.println();
}
}
}
✅ Recap:
- 2D Arrays = Tables of data (rows & columns)
- Access using
matrix[i][j] - Use nested loops to traverse
- Common tasks: Addition, Multiplication, Transpose
- Jagged arrays allow flexible row sizes
✅ With these tools, you can now build anything from a spreadsheet to a tic-tac-toe game using matrices!
🧠 Java Matrices (2D Arrays)
Matrices (2D arrays) are like tables in Java — rows and columns of data. They're used in everything from spreadsheets to games like tic-tac-toe.
🎮 Project 1: Tic-Tac-Toe Game
import java.util.Scanner;
public class TicTacToe {
public static void main(String[] args) {
// Initialize the board with 3x3 empty spaces
char[][] board = {
{' ', ' ', ' '},
{' ', ' ', ' '},
{' ', ' ', ' '}
};
Scanner sc = new Scanner(System.in);
char currentPlayer = 'X';
for (int moves = 0; moves < 9; moves++) {
// Print current board
System.out.println("\nCurrent Board:");
for (char[] row : board) {
for (char cell : row) {
System.out.print("|" + cell);
}
System.out.println("|");
}
System.out.println("Player " + currentPlayer + ", enter row and column (0-2):");
int row = sc.nextInt();
int col = sc.nextInt();
// ✅ Check for invalid input range
if (row < 0 || row > 2 || col < 0 || col > 2) {
System.out.println("❌ Invalid input! Row and column must be between 0 and 2. Try again.");
moves--; // Don't count this as a valid move
continue; // Ask again
}
// ✅ Check if cell is already occupied
if (board[row][col] == ' ') {
board[row][col] = currentPlayer;
// ✅ Check for winning conditions
if ((board[row][0] == currentPlayer && board[row][1] == currentPlayer && board[row][2] == currentPlayer) ||
(board[0][col] == currentPlayer && board[1][col] == currentPlayer && board[2][col] == currentPlayer) ||
(board[0][0] == currentPlayer && board[1][1] == currentPlayer && board[2][2] == currentPlayer) ||
(board[0][2] == currentPlayer && board[1][1] == currentPlayer && board[2][0] == currentPlayer)) {
System.out.println("🎉 Player " + currentPlayer + " wins!");
return;
}
// Switch player
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
} else {
System.out.println("❌ Cell already taken! Try again.");
moves--; // Don't count this move
}
}
System.out.println("🤝 It's a draw!");
}
}
📊 Project 2: Simple Spreadsheet
import java.util.Scanner;
public class Spreadsheet {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Ask user for number of rows and columns
System.out.print("Enter number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter number of columns: ");
int cols = scanner.nextInt();
// Create a 2D array with user-defined size
int[][] data = new int[rows][cols];
// 🔹 Input Spreadsheet Data
System.out.println("\nEnter values for the spreadsheet:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print("Enter value for cell [" + i + "][" + j + "]: ");
data[i][j] = scanner.nextInt();
}
}
System.out.println();
// 🔹 Sum of Each Row
System.out.println("📌 Sum of Each Row:");
for (int i = 0; i < rows; i++) {
int rowSum = 0;
for (int j = 0; j < cols; j++) {
rowSum += data[i][j];
}
System.out.println("Sum of row " + i + ": " + rowSum);
}
System.out.println();
// 🔹 Sum of Each Column
System.out.println("📌 Sum of Each Column:");
for (int col = 0; col < cols; col++) {
int colSum = 0;
for (int row = 0; row < rows; row++) {
colSum += data[row][col];
}
System.out.println("Sum of column " + col + ": " + colSum);
}
System.out.println();
// 🔹 Total Sum of All Elements
int totalSum = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
totalSum += data[i][j];
}
}
System.out.println("🧮 Total sum of all elements: " + totalSum);
System.out.println();
// 🔹 Display Spreadsheet
System.out.println("📋 Spreadsheet View:");
for (int[] row : data) {
for (int val : row) {
System.out.print(val + "\t");
}
System.out.println();
}
scanner.close(); // Clean up
}
}
🐍 Snake Game in Java (Console-based)
🐍 This is a simple console-based Snake Game in Java designed for absolute beginners! It uses a 2D
array (matrix) to simulate a game board where a snake ('S') moves using WASD keys and tries to eat food
('F') randomly placed on the grid.
Each time the snake eats the food, your score increases, and new food appears elsewhere on the board. The game ends
if you hit the wall or choose to quit. 🚧
🎯 What You'll Learn:
- How to use 2D arrays (matrices) in Java
- How to take keyboard input using
Scanner - How to generate random positions with
Random - Basic game loop structure and state handling
- How to check for collisions (like wall boundaries)
- How to update a visual game board in the console
🧩 Concept
- Matrix size: 10x10
- Snake: represented by 'S'
- Food: represented by 'F'
- Empty cell: '.'
🧠 Logic
- Create a
10x102D array to represent the game board. - Initialize all cells to
'.'(empty space). - Place the snake's starting position at the center using
'S'. - Randomly place food on an empty cell using
'F'. - Start a game loop that runs while the game is active.
- Use
Scannerto read player input:W(up),A(left),S(down),D(right),Q(quit). - Before moving, clear the snake's previous cell by setting it back to
'.'. - Update the snake’s position based on the input direction.
- Check for wall collisions: if the snake moves outside the board, end the game.
- If the snake moves onto a cell with food, increase the score and generate new food in a random empty cell.
- Update the new snake position on the board with
'S'.
🔤 Code (SnakeGame.java)
// 📦 Importing utility classes needed for random number generation and user input
import java.util.Random; // 🎲 Used to generate random positions for food on the board
import java.util.Scanner; // ⌨️ Used to read user keyboard input (W, A, S, D, Q)
public class SnakeGame {
public static void main(String[] args) {
// 🎯 Set dimensions for the game board (10 rows x 10 columns)
int rows = 10;
int cols = 10;
// 🧱 Create a 2D array (matrix) to represent the board
// Each cell can be: '.' (empty), 'S' (snake), or 'F' (food)
char[][] board = new char[rows][cols];
// 🐍 Initialize snake's starting position at the center of the board
int snakeRow = rows / 2; // Row index for snake's position
int snakeCol = cols / 2; // Column index for snake's position
// 🍎 Variables to hold the food's position
int foodRow, foodCol;
// 🎮 Game tracking variables
int score = 0; // Keeps track of how much food the snake eats
boolean isRunning = true; // Controls whether the game loop keeps running
// ⌨️ Create a Scanner object to read keyboard input from the user
Scanner scanner = new Scanner(System.in);
// 🎲 Create a Random object to generate random food positions
Random random = new Random();
// 🔁 Fill the entire board with '.' to represent empty spaces
for (int i = 0; i < rows; i++) { // Loop through each row
for (int j = 0; j < cols; j++) { // Loop through each column in the current row
board[i][j] = '.'; // Set cell to empty
}
}
// 🐍 Place the snake's starting position on the board
board[snakeRow][snakeCol] = 'S';
// 🍎 Place the food at a random position that is NOT on the snake
do {
foodRow = random.nextInt(rows); // Random row between 0 and rows-1
foodCol = random.nextInt(cols); // Random column between 0 and cols-1
} while (board[foodRow][foodCol] == 'S'); // Repeat if it lands on the snake
// 🧃 Place the food symbol on the board
board[foodRow][foodCol] = 'F';
// 🕹️ Main game loop — runs until player quits or hits a wall
while (isRunning) {
// 💬 Display the current score to the player
System.out.println("\nScore: " + score);
// 🖨️ Print column numbers at the top of the board
System.out.print(" "); // Extra spaces to align columns with row numbers
for (int j = 0; j < cols; j++) {
System.out.print(j + " "); // Print column index
}
System.out.println(); // Move to next line
// 🖨️ Print the board row by row with row numbers on the left
for (int i = 0; i < rows; i++) {
System.out.print(i + " "); // Print row index with spacing
for (int j = 0; j < cols; j++) {
System.out.print(board[i][j] + " "); // Print cell content
}
System.out.println(); // Move to next row
}
// ⌨️ Ask player for movement input
System.out.print("Move (WASD to move, Q to quit): ");
String input = scanner.nextLine().toUpperCase(); // Read and convert to uppercase
// ✅ Prepare to check the move
boolean validMove = true; // Tracks if input is a valid direction
int newRow = snakeRow; // Temporary new row position for snake
int newCol = snakeCol; // Temporary new column position for snake
// 🧭 Decide the direction based on input
switch (input) {
case "W": newRow--; break; // Move up
case "A": newCol--; break; // Move left
case "S": newRow++; break; // Move down
case "D": newCol++; break; // Move right
case "Q": // Quit the game
isRunning = false; // Stop game loop
continue; // Skip rest of this loop iteration
default:
// ❌ Invalid input — warn player and keep snake where it is
System.out.println("Invalid input! Use W, A, S, D to move.");
validMove = false; // Mark the move as invalid
break;
}
// 🚫 If invalid move, skip updating the snake and redraw the board
if (!validMove) {
continue; // Go back to top of loop
}
// 🚧 Check if new position is outside the board (wall collision)
if (newRow < 0 || newRow >= rows || newCol < 0 || newCol >= cols) {
System.out.println("💥 Game Over! You hit the wall.");
break; // End the game loop
}
// 🧽 Clear the snake's old position (replace with '.')
board[snakeRow][snakeCol] = '.';
// 🔄 Update snake position to new coordinates
snakeRow = newRow;
snakeCol = newCol;
// 🍽️ Check if snake moved into the food's position
if (snakeRow == foodRow && snakeCol == foodCol) {
score++; // Increase score
// 🍎 Place new food somewhere not on the snake
do {
foodRow = random.nextInt(rows); // Random new food row
foodCol = random.nextInt(cols); // Random new food col
} while (board[foodRow][foodCol] == 'S'); // Avoid snake position
// 🧃 Place new food on the board
board[foodRow][foodCol] = 'F';
}
// 🐍 Place snake's new position on the board
board[snakeRow][snakeCol] = 'S';
}
// 🧹 Close scanner to release system resources
scanner.close();
// 🎉 Show the player's final score after game ends
System.out.println("👋 Game Ended. Final Score: " + score);
}
}
📌 Output Sample
Score: 2
0 1 2 3 4 5 6 7 8 9
0 . . . . . . . . . .
1 . . . . . . . . . .
2 . S . . . . . . . .
3 . . . . . . . F . .
4 . . . . . . . . . .
5 . . . . . . . . . .
6 . . . . . . . . . .
7 . . . . . . . . . .
8 . . . . . . . . . .
9 . . . . . . . . . .
Move (WASD to move, Q to quit):
🧠 Key Changes & Explanation:
| Feature | Explanation |
|---|---|
| Food (F) | Randomly placed on any empty cell on the board. If snake eats it, score increases. |
| Score | An integer that increases each time food is eaten. |
| Game End | If snake moves out of bounds or player quits (Q). |
| Random Food | Re-positioned after each eating, not allowed on the snake cell. |
🧠 Concepts Used in This Game:
| Concept | Explanation |
|---|---|
| 2D Arrays | Used to represent the game board
(char[][] board) as a grid. |
| Scanner | Reads user input from the keyboard. |
| Random | Picks random positions to place the food. |
| Loops | Used to fill and print the board, and repeat the game until quitting. |
| Conditions | Used to check user input and whether the snake hits the wall or eats the food. |
| Switch | Clean way to handle movement options. |
| Functions | Main logic is inside main, split with comments
into logical steps. |
🧯 Common Mistakes to Avoid
-
Forgetting to import required classes:
If you forgetimport java.util.Random;orimport java.util.Scanner;, your program won’t compile. Java won’t recognizeRandomorScannerwithout these imports. -
Not closing the Scanner:
Always close theScannerobject withscanner.close()at the end of the program to free system resources. -
Creating multiple Scanner instances for the same input stream:
Using more than oneScannerforSystem.incan cause unexpected behavior or skipped inputs. Reuse the same instance throughout the program. -
Using Random incorrectly:
Callingrandom.nextInt()without an argument will throw an error. Always specify the bound, e.g.,random.nextInt(rows)to stay within the board range. -
Hardcoding positions instead of using variables:
Avoid using fixed numbers for board positions. Always calculate positions dynamically usingrows,cols,snakeRow, andsnakeCol.
✅ What You Learned
- How to import and use Java utility classes like
Random(for random numbers) andScanner(for user input) - How to set up and manage game variables (board size, score, and a boolean to control the game loop)
- How to create and work with a 2D array to represent a game board
- How to generate random positions within the board’s boundaries using
Random - How to place game elements (snake and food) at their starting positions
🧠 Exercises — Practice Time!
💡 Beginner
- Write a program to check if a number is positive, negative, or zero using
if. - Print numbers from 1 to 10 using a
forloop. - Check if a number is divisible by 2 and 3 using
&&.
🧪 Intermediate
- Use a
switchto print weekday names from number (1-7). - Use
whileloop to print first 5 even numbers. - Use ternary operator to print “Even” or “Odd”.
🔥 Challenge
- Build a simple calculator that takes two numbers and an operator (+, -, *, /) and returns the result.
- Write a program to reverse digits of an integer using loop.
- Print a pattern using nested loops (like triangle or square of *).
⚠️ Common Mistakes in Operators & Control Flow (Java)
💡 Operators
- ❌ Confusing
=(assignment) with==(equality) - ❌ Using
==for comparing strings instead of.equals() - ❌ Forgetting parentheses in complex arithmetic expressions
- ❌ Dividing integers and expecting a float result (e.g.,
5/2gives 2) - ❌ Misusing increment/decrement operators inside conditions
- ❌ Using
!without proper parentheses (e.g.,!a == b) - ❌ Writing
a && b || cwithout understanding operator precedence - ❌ Confusing
&and&&or|and|| - ❌ Using
a = b = cwithout realizing assignment returns a value - ❌ Forgetting to cast during mixed-type arithmetic (e.g.,
int + double)
💡 if / else if / else
- ❌ Using
if (condition);with an unintended semicolon - ❌ Omitting
{ }for multiple statements in anifblock - ❌ Placing
elsewithout a precedingif - ❌ Not covering all conditions in
if / else ifladders - ❌ Using assignment in conditions (
if (a = 5)instead of==) - ❌ Confusing nested
ifstatements without clear indentation - ❌ Misunderstanding short-circuit logic in conditions (e.g.,
if (x != 0 && y/x > 1)) - ❌ Overcomplicating conditions instead of breaking them into steps
- ❌ Using
ifwhere aswitchwould be cleaner - ❌ Forgetting the default
elseto handle unanticipated cases
💡 Switch-Case
- ❌ Omitting
breakinswitchcases, causing fall-through - ❌ Using non-constant expressions in
caselabels - ❌ Forgetting the
defaultcase inswitchstatement - ❌ Using incompatible types (e.g.,
float) inswitchexpressions - ❌ Duplicating
casevalues, causing compile errors -
❌ Using
==for string matching inswitchinstead of Java 7+ string switch-
eg.
// ❌ Incorrect way: using '==' for string comparison String fruit = "apple"; if (fruit == "apple") { System.out.println("Fruit is apple"); } // ✅ Better: using switch with String (Java 7+) switch (fruit) { case "apple": System.out.println("Fruit is apple"); break; case "banana": System.out.println("Fruit is banana"); break; default: System.out.println("Unknown fruit"); }
-
eg.
- ❌ Using code after a
breakthat is never reached - ❌ Nesting
switchstatements without braces or clarity - ❌ Including unreachable
caseblocks (e.g., duplicate constants) - ❌ Not realizing
switchsupports only specific types (e.g.,int,char,String)
💡 for loop
- ❌ Creating infinite loops with missing increment/decrement logic
- ❌ Off-by-one errors (e.g., using
i <= ninstead of<) - ❌ Declaring loop variables outside unnecessarily
- ❌ Modifying loop counter inside the loop body incorrectly
- ❌ Nested loops using the same loop variable (e.g.,
iinsidei) - ❌ Using wrong data type for loop variable in large ranges
- ❌ Logic depends on side effects within loop headers
- ❌ Forgetting braces for nested loops
- ❌ Not initializing loop variable, leading to garbage values
- ❌ Confusing increment direction in
forloops (e.g.,i--instead ofi++)
💡 while loop
- ❌ Not updating loop control variable inside
while(infinite loop) - ❌ Checking an always-false condition causing loop to never run
- ❌ Using
whileinstead ofdo-whilewhen at least one execution is required - ❌ Altering loop variables unintentionally inside the loop
- ❌ Not handling user input that causes
whileto repeat forever
💡 do-while loop
- ❌ Using
do-whilewithout understanding it runs at least once - ❌ Adding semicolon after
doincorrectly (do; { ... }) - ❌ Forgetting semicolon at the end of
while(condition); - ❌ Using
breakandcontinuepoorly insidedo-while - ❌ Misplacing loop control variables outside of the loop body
✅ Operators & Control Flow (Java): Recap
- Use arithmetic operators (
+,-,*,/,%) for calculations - Use relational operators (
==,!=,>,<,>=,<=) to compare values - Logical operators (
&&,||,!) combine or invert conditions - Use
if,else if,elseto handle conditional branching switchis useful for multi-way branching with fixed valuesforloops are ideal when the number of iterations is knownwhileloops are used when the condition must be true before entering the loopdo-whileloops run the block at least once before checking the condition- Ternary operator (
condition ? trueValue : falseValue) offers a concise alternative to simple if-else - Always initialize and update loop control variables to avoid infinite loops
🧠 Answers — With Explanations & Common Mistakes
💡 Beginner
-
Check if a number is positive, negative, or zero
public class PositiveNegativeZero { public static void main(String[] args) { int number = -5; // Change this to test different numbers if (number > 0) { System.out.println("Positive"); } else if (number < 0) { System.out.println("Negative"); } else { System.out.println("Zero"); } } }✅ Explanation:
if (number > 0)→ Runs when the number is greater than zero.else if (number < 0)→ Runs when the number is less than zero.else→ Runs when the number is exactly zero.
❌ Common Mistakes:
- Using
=instead of==for equality (causes assignment, not comparison). - Using multiple
ifstatements instead ofelse if, which may cause multiple outputs.
-
Print numbers from 1 to 10 using a
forlooppublic class PrintOneToTen { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { System.out.println(i); } } }✅ Explanation:
- The loop starts at
i = 1. - The condition
i <= 10ensures it runs untilireaches 10. i++increasesiby 1 each time.
❌ Common Mistakes:
- Using
i < 10instead ofi <= 10, which prints only 1–9. - Resetting
iinside the loop (e.g.,i = 1;), causing an infinite loop. - Forgetting
i++, which also causes an infinite loop.
- The loop starts at
-
Check if a number is divisible by 2 and 3
public class DivisibleByTwoAndThree { public static void main(String[] args) { int number = 12; // Change this to test if (number % 2 == 0 && number % 3 == 0) { System.out.println("Divisible by both 2 and 3"); } else { System.out.println("Not divisible by both"); } } }✅ Explanation:
%(modulus) finds the remainder.number % 2 == 0→ divisible by 2.number % 3 == 0→ divisible by 3.&&means both conditions must be true.
❌ Common Mistakes:
- Using
||instead of&&— checks if divisible by 2 or 3, not both. - Writing
number % 2 = 0— assignment instead of comparison, causing a compilation error. - Forgetting parentheses in complex conditions, leading to wrong results.
🧪 Intermediate
-
Use a
switchto print weekday names from number (1-7)public class WeekdaySwitch { public static void main(String[] args) { int day = 3; // Change to test different days (1-7) switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; case 7: System.out.println("Sunday"); break; default: System.out.println("Invalid day"); } } }✅ Explanation: The
switchstatement checks the value ofdayagainst eachcase. When a match is found, the corresponding block runs.breakstops the execution from continuing into the next case. Thedefaultcase runs when none of the cases match.❌ Common Mistakes:
- Forgetting
break, which causes the program to execute all following cases ("fall-through"). - Not including a
defaultcase — this means invalid inputs won't be handled. - Using numbers outside the range 1–7 without realizing they'll go to
default.
- Forgetting
-
Use
whileloop to print first 5 even numberspublic class FirstFiveEvens { public static void main(String[] args) { int count = 0; // How many even numbers printed int number = 2; // Start from the first even number while (count < 5) { System.out.println(number); number += 2; // Jump to the next even number count++; // Keep track of how many printed } } }✅ Explanation: The
whileloop runs as long ascount < 5. Each time it prints the current even number, increases it by 2, and incrementscountto eventually stop the loop.❌ Common Mistakes:
- Forgetting to increment
countornumber— causes an infinite loop. - Starting
numberat 0 if you want numbers from 2 — leads to wrong sequence. - Using
<= 5instead of< 5withcount— prints 6 numbers instead of 5.
- Forgetting to increment
-
Use ternary operator to print “Even” or “Odd”
public class EvenOddTernary { public static void main(String[] args) { int num = 7; // Change this to test String result = (num % 2 == 0) ? "Even" : "Odd"; System.out.println(result); } }✅ Explanation: The ternary operator
?:is a shorthand forif-else. Here,(num % 2 == 0)checks if the number is divisible by 2. If true, it assigns"Even"toresult, otherwise"Odd".❌ Common Mistakes:
- Forgetting parentheses around the condition, making it harder to read or leading to precedence issues.
- Using
=instead of==in the condition — causes unintended assignment. - Placing a semicolon
;inside the ternary — breaks the expression.
🔥 Challenge
-
Build a simple calculator (fixed values)
public class SimpleCalculator { public static void main(String[] args) { int a = 10, b = 5; char op = '*'; switch (op) { case '+': System.out.println(a + b); break; case '-': System.out.println(a - b); break; case '*': System.out.println(a * b); break; case '/': if (b != 0) { System.out.println(a / b); } else { System.out.println("Cannot divide by zero"); } break; default: System.out.println("Invalid operator"); } } }✅ Explanation: The
switchchecks the value ofopand performs the corresponding arithmetic operation. For division, we checkb != 0to prevent division by zero.❌ Common Mistakes:
- Forgetting
break— leads to executing multiple cases unintentionally. - Using
"+"(String) instead of'+'(char) forop. - Not checking for division by zero — causes runtime exception.
- Forgetting
-
Reverse digits of an integer
public class ReverseNumber { public static void main(String[] args) { int num = 1234; int reversed = 0; while (num != 0) { int digit = num % 10; reversed = reversed * 10 + digit; num /= 10; } System.out.println("Reversed: " + reversed); } }✅ Explanation: We extract the last digit with
num % 10, multiply the reversed number by 10 to shift digits, then add the extracted digit. We remove the last digit fromnumusing integer division.❌ Common Mistakes:
- Forgetting
num /= 10— causes an infinite loop. - Mixing up
%and/— leads to incorrect results. - Not handling negative numbers if required.
- Forgetting
-
Print patterns using nested loops (triangle & square)
public class TrianglePattern { public static void main(String[] args) { int rows = 5; // Triangle pattern for (int i = 1; i <= rows; i++) { for (int j = 1; j <= i; j++) { System.out.print("* "); } System.out.println(); } } }public class SquarePattern { public static void main(String[] args) { int size = 5; // Square pattern for (int i = 1; i <= size; i++) { for (int j = 1; j <= size; j++) { System.out.print("* "); } System.out.println(); } } }✅ Explanation:
- Triangle: Outer loop controls the number of rows, inner loop prints stars equal to the current row number.
- Square: Both outer and inner loops run
sizetimes, so each row has the same number of stars. System.out.printkeeps printing on the same line, whileSystem.out.println()moves to the next line after each row.
❌ Common Mistakes:
- Swapping
printandprintln— breaks the pattern layout. - Using
<instead of<=in loops — causes missing stars or rows. - Accidentally reusing the same loop variable in both loops — leads to incorrect output.
-
Calculator with user input (handles invalid input)
import java.util.Scanner; public class CalculatorUserInput { public static void main(String[] args) { Scanner sc = new Scanner(System.in); try { System.out.print("Enter first number: "); if (!sc.hasNextDouble()) { System.out.println("Invalid number! Please restart the program."); return; } double a = sc.nextDouble(); System.out.print("Enter operator (+, -, *, /): "); String opInput = sc.next(); if (opInput.length() != 1 || "+-*/".indexOf(opInput.charAt(0)) == -1) { System.out.println("Invalid operator! Please restart the program."); return; } char op = opInput.charAt(0); System.out.print("Enter second number: "); if (!sc.hasNextDouble()) { System.out.println("Invalid number! Please restart the program."); return; } double b = sc.nextDouble(); switch (op) { case '+': System.out.println("Result: " + (a + b)); break; case '-': System.out.println("Result: " + (a - b)); break; case '*': System.out.println("Result: " + (a * b)); break; case '/': if (b != 0) { System.out.println("Result: " + (a / b)); } else { System.out.println("Cannot divide by zero"); } break; } } finally { sc.close(); } } }✅ Explanation: This version checks for invalid numbers using
hasNextDouble()and validates the operator string before performing the calculation.❌ Common Mistakes:
- Not checking
hasNextDouble()before reading numbers — causes program crash if letters are entered. - Accepting multi-character operators like
++— this code prevents that. - Skipping
finallyorclose()— leads to resource leaks.
- Not checking
-
Complex calculator with multiple operations (handles invalid input)
import java.util.Scanner; public class ComplexCalculator { public static void main(String[] args) { Scanner sc = new Scanner(System.in); boolean running = true; while (running) { try { System.out.print("Enter first number: "); if (!sc.hasNextDouble()) { System.out.println("Invalid number! Please try again."); sc.next(); // clear wrong input continue; } double a = sc.nextDouble(); System.out.print("Enter operator (+, -, *, /, %): "); String opInput = sc.next(); if (opInput.length() != 1 || "+-*/%".indexOf(opInput.charAt(0)) == -1) { System.out.println("Invalid operator! Please try again."); continue; } char op = opInput.charAt(0); System.out.print("Enter second number: "); if (!sc.hasNextDouble()) { System.out.println("Invalid number! Please try again."); sc.next(); // clear wrong input continue; } double b = sc.nextDouble(); switch (op) { case '+': System.out.println("Result: " + (a + b)); break; case '-': System.out.println("Result: " + (a - b)); break; case '*': System.out.println("Result: " + (a * b)); break; case '/': if (b != 0) { System.out.println("Result: " + (a / b)); } else { System.out.println("Cannot divide by zero"); } break; case '%': if (b != 0) { System.out.println("Result: " + (a % b)); } else { System.out.println("Cannot perform modulo by zero"); } break; } System.out.print("Do you want to calculate again? (yes/no): "); String choice = sc.next(); if (!choice.equalsIgnoreCase("yes")) { running = false; } } catch (Exception e) { System.out.println("Unexpected error: " + e.getMessage()); sc.next(); // clear bad input } } sc.close(); System.out.println("Calculator closed."); } }✅ Explanation: This version uses
hasNextDouble()and operator validation to prevent crashes. It runs in a loop and keeps asking until the user chooses to exit.❌ Common Mistakes:
- Not clearing invalid input with
sc.next()— without this, the loop keeps reading the same bad input forever. - Using
==for strings instead ofequalsIgnoreCase()— this breaks string comparison. - Forgetting to validate division and modulus by zero.
- Not clearing invalid input with
🧪 Modulus with Smaller Dividend
-
Example:
public class ModulusDemo { public static void main(String[] args) { System.out.println(2 % 3); // integer modulus System.out.println(2 % 3.0); // double modulus double result = 5.5 % 2.2; // raw double result System.out.println(Math.round(result * 100.0) / 100.0); // rounded to 2 decimals } } -
Output:
2 2.0 1.1 -
✅ Explanation: The modulus operator (
%) returns the remainder after division.2 % 3→ Since 2 is smaller than 3, the quotient is 0 and the remainder is 2 (integer).2 % 3.0→ One operand is adouble, so Java promotes the result todouble, giving 2.0.5.5 % 2.2→ The quotient is 2 (truncated), raw result is1.0999999999999996due to floating-point precision. Using rounding:Math.round(result * 100.0) / 100.0→1.1.
remainder = dividend - (divisor × truncatedQuotient)- Dividend: 2
- Divisor: 3
- Integer division: 2 / 3 = 0 (since 2 is smaller than 3, the quotient is zero)
- Remainder: 2 - (3 × 0) = 2
-
❌ Common Mistakes:
- Thinking modulus only works for integers — it also works with floating-point numbers.
- Confusing modulus with division — modulus gives the remainder, not the quotient.
- Forgetting type promotion — when one operand is
double, the result is alsodouble. - Not accounting for floating-point precision — use rounding for cleaner results.
🎉 That's it! You've now solved all practice questions from basic checks to loops and logic!
Now you can create decisions, loops, and intelligent logic inside your Java code. This is the step where code becomes powerful!
— Blog by Aelify (ML2AI.com)