Write your first Java programs: output, variables, data types, operators, input, decisions and loops.
Every code example has a ▶ Run button. Click ✎ Edit, or press L, to open the Code Lab.
java Main.javajava Main.java in the folder D:\java-practice..java file, the javac compiler turns them into bytecode, and the JVM runs that bytecode on any computer.| Tool | Who needs it | Contains |
|---|---|---|
| JDK | programmers (you!) | javac, java, jshell + JRE |
| JRE | users who only run apps | JVM + libraries |
| JVM | part of every JRE | bytecode runner, garbage collector |
java -version and javac -versionD:\java-practice for all programs1public class Main {2 public static void main(String[] args) {3 System.out.println("Namaste, Ranchi!");4 System.out.println("Welcome to Java.");5 }6}
main method. Each statement ends with a semicolon ;.Main.java (file name = class name)Main{ } braces mark where blocks start and endpublic, static and void fully in Modules 6 and 10. For now: copy this line exactly.| Rule | Example |
|---|---|
| Java is case-sensitive | System works, system does not |
| File name = public class name | Main.java holds public class Main |
| Statements end with ; | System.out.println("Hi"); |
| Blocks use { } | class body, method body |
javac Main.java creates Main.class (bytecode). java Main starts the JVM and runs it. For a single file, java Main.java does both steps in memory.1public class Main {2 public static void main(String[] args) {3 System.out.println("BrainBit Infotech"); // prints, then new line4 System.out.print("Ranchi, "); // stays on the same line5 System.out.print("Jharkhand");6 System.out.println(); // just a new line7 System.out.println("Marks: " + 92); // join text and a number8 System.out.println(10 + 5); // maths first: 159 System.out.println("10 + 5 = " + 10 + 5); // careful! text joining10 System.out.printf("Fee: Rs %d, GST: %.2f%n", 4500, 810.0);11 }12}
println prints and moves to a new line; print stays on the same line; printf prints with a format: %d whole number, %.2f decimal, %s text, %n new line.+ joins text. Use brackets: "10 + 5 = " + (10 + 5).1/*2 * Program : Fee notice3 * Author : Your Name4 */5public class Main {6 public static void main(String[] args) {7 // single-line comment: Java ignores this8 System.out.println("Name:\tAman"); // \t = tab9 System.out.println("Line 1\nLine 2"); // \n = new line10 System.out.println("She said \"Hello\""); // \" = quote11 System.out.println("Path: D:\\java-practice"); // \\ = one backslash12 }13}
// for one line, /* ... */ for many lines. Escape sequences start with a backslash and put special characters inside text.| Escape | Means |
|---|---|
\n | new line |
\t | tab |
\" | double quote |
\\ | backslash |
/** ... */ is a Javadoc comment. Tools turn it into HTML documentation, like the official Java docs.Press Next step. The JVM runs the statements in main one by one, from top to bottom.
1public class Main {2 public static void main(String[] args) {3 System.out.println("Good morning, students!");4 System.out.println("Today: Java class at 10 AM");5 // this comment is skipped6 System.out.print("Lab ");7 System.out.println(2);8 System.out.println("Have a great day!");9 }10}
1public class Main {2 public static void main(String[] args) {3 System.out.println("Fee is due on 10th")4 System.out.println("Pay at the office");5 }6}
1public class Main {2 public static void main(String[] args) {3 System.out.println("Total students: 40");4 System.out.println("Per group: " + 40 / 0);5 }6}
;, wrong spelling); nothing runs. Run-time errors (exceptions) happen while running, like dividing by zero. Read the line number and the message.| Thing | Convention | Example |
|---|---|---|
| Class | PascalCase (each word capital) | StudentReport |
| Method / variable | camelCase | totalMarks, printBill() |
| Constant | UPPER_SNAKE_CASE | GST_RATE |
| Package | all lowercase | com.brainbit.billing |
_ and $, cannot start with a digit, and cannot be a keyword like class or int. Following the conventions makes your code look professional.Some Java keywords: classpublicstaticvoidintdoubleifelseforwhilereturnnewthistruefalsenull
java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).printf("%02d-%02d-%d%n", 8, 10, 2026)System.out.println() prints a line of text and moves to the next line.* symbolsSystem.out.println()1public class Banner {2 public static void main(String[] args) {3 System.out.println("****************************************");4 System.out.println(" BRAINBIT INFOTECH COMPUTER CENTRE");5 System.out.println();6 System.out.println(" Main Road, Ranchi, Jharkhand");7 System.out.println(" Phone: 98765 43210");8 System.out.println("****************************************");9 System.out.println(" Welcome! Please mark attendance.");10 }11}
\t = tab, \n = new line inside a String.\t to line up the values\n to print several lines from one statement1public class IdCard {2 public static void main(String[] args) {3 System.out.println("+-------------------------------+");4 System.out.println("| DAV PUBLIC SCHOOL, RANCHI |");5 System.out.println("+-------------------------------+");6 System.out.println("Name\t: Ananya Kumari\nClass\t: 8 B\nRoll\t: 17\nBlood\t: B+");7 System.out.println("+-------------------------------+");8 }9}
print stays on the same line, println ends the line; + joins text with numbers.print + println to build the route line+1public class BusTicket {2 public static void main(String[] args) {3 System.out.println("----------------------------------");4 System.out.println(" JHARKHAND TRAVELS");5 System.out.println("----------------------------------");6 System.out.print("Route : Ranchi");7 System.out.println(" -> Jamshedpur");8 System.out.println("Date : 08-10-2026");9 System.out.println("Seat : " + 14);10 System.out.println("Fare : Rs " + (280 + 20));11 System.out.println("----------------------------------");12 System.out.println("Happy journey!");13 }14}
Notice.java, but it does not compile. Find and fix 4 mistakes.;, Strings need closing quotes, and the public class name must match the file name.1public class notice {2 public static void main(String[] args) {3 System.out.println("Exam Notice")4 system.out.println("Class 10 maths exam on Monday");5 System.out.println("Bring your admit card);6 }7}
1public class Notice {2 public static void main(String[] args) {3 System.out.println("Exam Notice");4 System.out.println("Class 10 maths exam on Monday");5 System.out.println("Bring your admit card");6 }7}
println. Brackets make Java calculate before joining text.(78 + 85 + 92)(78 + 85 + 92) / 3.0/ 3.0 gives decimals1public class Marks {2 public static void main(String[] args) {3 System.out.println("Maths : 78");4 System.out.println("Science : 85");5 System.out.println("English : 92");6 System.out.println("Total : " + (78 + 85 + 92));7 System.out.println("Average : " + (78 + 85 + 92) / 3.0);8 System.out.println("Whole-number average: " + (78 + 85 + 92) / 3);9 }10}
printf uses format codes: %-10s = text left-aligned in 10 spaces, %5s = right-aligned in 5.printf%n for new lines1public class Timetable {2 public static void main(String[] args) {3 System.out.println("CLASS 8 B - MONDAY");4 System.out.printf("%-8s %-7s %-18s%n", "Period", "Time", "Subject");5 System.out.println("----------------------------------");6 System.out.printf("%-8d %-7s %-18s%n", 1, "09:00", "Mathematics");7 System.out.printf("%-8d %-7s %-18s%n", 2, "09:45", "Science");8 System.out.printf("%-8d %-7s %-18s%n", 3, "10:30", "Computer (Java)");9 System.out.printf("%-8d %-7s %-18s%n", 4, "11:15", "English");10 System.out.printf("%-8d %-7s %-18s%n", 5, "12:00", "Hindi");11 System.out.println("----------------------------------");12 System.out.println("Lunch break: 12:45 to 1:15");13 }14}
println prints one row. Backslashes must be written as \\ inside a String.1public class Cup {2 public static void main(String[] args) {3 System.out.println(" ( ) ( ) )");4 System.out.println(" ) ( ) ( (");5 System.out.println(" ( ) ( ) )");6 System.out.println(" _____________");7 System.out.println(" <_____________> ___");8 System.out.println(" | |/ _ \\");9 System.out.println(" | J A V A | | |");10 System.out.println(" | |_| |");11 System.out.println("___| |\\___/");12 System.out.println("\\ \\___________/ /");13 System.out.println(" \\_________________/");14 }15}
%,d adds thousand commas, %.2f shows 2 decimals, %10.2f right-aligns in 10 spaces.printf, write %%.1public class FeeReceipt {2 public static void main(String[] args) {3 System.out.println("======== FEE RECEIPT ========");4 System.out.printf("Student : %s%n", "Ravi Mahto");5 System.out.printf("Course : %s%n", "Core Java (3 months)");6 System.out.println("-----------------------------");7 System.out.printf("Fee : Rs %10.2f%n", 12500.0);8 System.out.printf("GST 18%% : Rs %10.2f%n", 12500 * 0.18);9 System.out.printf("Total : Rs %10.2f%n", 12500 * 1.18);10 System.out.println("-----------------------------");11 System.out.printf("Amount in figures: Rs %,d%n", 14750);12 System.out.println("Thank you! BrainBit Infotech");13 }14}
public). main can call a static method of another class: Printer.line().Printer with static methods line() and title(String)main1class Printer {2 static void line() {3 System.out.println("=================================");4 }56 static void title(String text) {7 line();8 System.out.println(" " + text);9 line();10 }11}1213public class Report {14 public static void main(String[] args) {15 Printer.title("MONTHLY TEST - CLASS 9A");16 System.out.println("Highest: Priya (96)");17 System.out.println("Average: 71.4");18 Printer.line();19 }20}
printf widths, calculations in arguments and %n to build a professional report.%5.1f%% for the percentage1public class ReportCard {2 public static void main(String[] args) {3 System.out.println("+---------------------------+");4 System.out.println("| REPORT CARD - TERM 1 |");5 System.out.println("+---------------------------+");6 System.out.printf("| %-12s %5s |%n", "Subject", "Marks");7 System.out.printf("| %-12s %5d |%n", "Mathematics", 88);8 System.out.printf("| %-12s %5d |%n", "Science", 79);9 System.out.printf("| %-12s %5d |%n", "English", 91);10 System.out.printf("| %-12s %5d |%n", "Computer", 97);11 System.out.println("+---------------------------+");12 System.out.printf("| %-12s %5d |%n", "Total", 88 + 79 + 91 + 97);13 System.out.printf("| %-12s %5.1f%% |%n", "Percentage", (88 + 79 + 91 + 97) / 4.0);14 System.out.println("+---------------------------+");15 }16}
.java files; javac makes bytecode; the JVM runs it anywherejava -versionpublic static void main(String[] args);; Java is case-sensitive; file name = public class nameprintln, print, printf with %d %.2f %s %nWhich tool turns Main.java into bytecode?
System.out.println("5 + 5 = " + 5 + 5); prints?
Where does a Java program start running?
int qty and double price to make your billlong accountNo, double balance, boolean isActiveint loses paise; huge numbers in int overflowint for whole numbers, double for decimals, String for text. The type cannot change later.int marks; (make the box)marks = 92; (put a value in)int marks = 92;marks = 95; (old value is replaced)int age = "fourteen"; will not even compile. This catches many bugs early.| Type | Holds | Example | Size |
|---|---|---|---|
byte | small whole number | byte b = 100; | 1 byte |
short | whole number | short s = 30000; | 2 bytes |
int | whole number (default) | int marks = 92; | 4 bytes |
long | very big whole number | long phone = 9835011111L; | 8 bytes |
float | decimal (less precise) | float t = 36.6f; | 4 bytes |
double | decimal (default) | double price = 499.99; | 8 bytes |
char | one character | char grade = 'A'; | 2 bytes |
boolean | true / false | boolean paid = true; | JVM decides (usually 1 byte) |
String (capital S) is a class: it stores text like "Ranchi". Use int and double most of the time.L after big long numbers and f after float numbers. char uses single quotes, String uses double quotes.1public class Main {2 public static void main(String[] args) {3 String name = "Priya Kumari";4 int age = 14;5 double marks = 92.5;6 char grade = 'A';7 boolean passed = true;8 long mobile = 9835011111L;910 System.out.println(name + " is " + age + " years old");11 System.out.println("Marks: " + marks + ", grade " + grade);12 System.out.println("Passed? " + passed);13 System.out.println("Mobile: " + mobile);1415 age = age + 1; // birthday!16 System.out.println("Next year: " + age);17 }18}
+ is a String, Java joins text: "Age " + 14 becomes "Age 14".int mobile = 9835011111; fails: the number is too big for int (max about 2.1 billion). Use long.(int) and drops the decimal part. It does not round.| Code | Result | Why |
|---|---|---|
(int) 99.99 | 99 | decimals cut off |
Math.round(99.5) | 100 | proper rounding |
(double) 7 / 2 | 3.5 | cast first, then divide |
'A' + 1 | 66 | char used as a number |
1public class Main {2 public static void main(String[] args) {3 final double GST_RATE = 18.0; // cannot change later4 final int MAX_STUDENTS = 40;5 var city = "Ranchi"; // Java infers String6 var fee = 4500; // Java infers int78 double gst = fee * GST_RATE / 100;9 System.out.println("City: " + city);10 System.out.println("GST on Rs " + fee + " = " + gst);11 System.out.println("Seats: " + MAX_STUDENTS);12 // GST_RATE = 12; // ERROR: cannot assign a value to final variable13 }14}
final makes a constant: a value that must never change, like a tax rate. Constants use UPPER_CASE names. var (Java 10+) lets Java work out the type from the value, but the type is still fixed.1public class Main {2 public static void main(String[] args) {3 int a = 17, b = 5;4 System.out.println("a + b = " + (a + b));5 System.out.println("a - b = " + (a - b));6 System.out.println("a * b = " + (a * b));7 System.out.println("a / b = " + (a / b)); // 3, not 3.4!8 System.out.println("a % b = " + (a % b)); // remainder 29 System.out.println("a / 5.0 = " + (a / 5.0)); // 3.410 System.out.println("Is 17 even? " + (a % 2 == 0));11 System.out.println("Math.pow(2, 10) = " + Math.pow(2, 10));12 }13}
+ - * / work like maths, but int / int gives an int (decimals are dropped). % (modulus) gives the remainder: great for even/odd checks, last digits and "every n-th item".| Expression | Result |
|---|---|
17 / 5 | 3 |
17 % 5 | 2 |
17 / 5.0 | 3.4 |
-17 % 5 | -2 |
Math.pow(x, y), which returns a double.Shortcut operators update a variable using its own value. Watch the difference between count++ and ++count.
1public class Main {2 public static void main(String[] args) {3 int wallet = 500;4 wallet += 200;5 wallet -= 150;6 wallet *= 2;7 wallet /= 3;8 int count = 5;9 int a = count++;10 int b = ++count;11 count--;12 System.out.println(wallet + " " + a + " " + b + " " + count);13 }14}
== != > < >= <=) compare values and give a boolean. Logical operators combine booleans: && (AND: both true), || (OR: at least one), ! (NOT).| A | B | A && B | A || B |
|---|---|---|---|
| true | true | true | true |
| true | false | false | true |
| false | true | false | true |
| false | false | false | false |
= assigns, == compares. And && / || are short-circuit: if the left side already decides the answer, the right side is not checked.10 + 2 * (6 - 3) / 3 % 2| Priority | Operators |
|---|---|
| 1 | ( ) |
| 2 | ++ -- ! (unary) |
| 3 | * / % |
| 4 | + - |
| 5 | < <= > >= |
| 6 | == != |
| 7 | && |
| 8 | || |
| 9 | = += -= ... |
java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).total > 5000 to see if free delivery appliesint and compare with Math.round(total)String for text, int for whole numbers, char for one letter, boolean for yes/no.1public class Profile {2 public static void main(String[] args) {3 String name = "Ankit Oraon";4 int studentClass = 9;5 char section = 'A';6 int roll = 21;7 boolean isMember = true;89 System.out.println("==== LIBRARY CARD ====");10 System.out.println("Name : " + name);11 System.out.println("Class : " + studentClass + section);12 System.out.println("Roll : " + roll);13 System.out.println("Member : " + isMember);14 roll = 22;15 System.out.println("New roll after re-shuffle: " + roll);16 }17}
double so decimals are kept.1public class Temperature {2 public static void main(String[] args) {3 double celsius = 31.5;4 double fahrenheit = celsius * 9 / 5 + 32;5 System.out.printf("Ranchi today: %.1f C = %.1f F%n", celsius, fahrenheit);67 double bodyF = 98.6;8 double bodyC = (bodyF - 32) * 5 / 9;9 System.out.printf("Body temperature: %.1f F = %.1f C%n", bodyF, bodyC);10 }11}
double for money.1public class SimpleInterest {2 public static void main(String[] args) {3 double principal = 25000;4 double rate = 7.5; // percent per year5 int years = 3;67 double interest = principal * rate * years / 100;8 double amount = principal + interest;9 System.out.printf("Principal : Rs %.2f%n", principal);10 System.out.printf("Interest : Rs %.2f%n", interest);11 System.out.printf("Amount : Rs %.2f%n", amount);12 }13}
Math.PI is a ready-made constant; r * r squares a number.1public class Shapes {2 public static void main(String[] args) {3 double length = 14.5, breadth = 10.0;4 double radius = 3.5;56 double roomArea = length * breadth;7 double roomPerimeter = 2 * (length + breadth);8 double tankArea = Math.PI * radius * radius;9 double tankCircumference = 2 * Math.PI * radius;1011 System.out.printf("Room : area %.2f sq ft, perimeter %.2f ft%n", roomArea, roomPerimeter);12 System.out.printf("Tank : area %.2f sq ft, circumference %.2f ft%n", tankArea, tankCircumference);13 }14}
1public class Swap {2 public static void main(String[] args) {3 int seatA = 12, seatB = 27;4 System.out.println("Before: A=" + seatA + " B=" + seatB);56 int temp = seatA;7 seatA = seatB;8 seatB = temp;9 System.out.println("After : A=" + seatA + " B=" + seatB);1011 seatA = seatA + seatB; // 3912 seatB = seatA - seatB; // 27 -> old A13 seatA = seatA - seatB; // 1214 System.out.println("Back : A=" + seatA + " B=" + seatB);15 }16}
/ gives the whole part; % gives what is left over.%02d1public class Duration {2 public static void main(String[] args) {3 int total = 8125;4 int hours = total / 3600;5 int minutes = (total % 3600) / 60;6 int seconds = total % 60;7 System.out.println(total + " seconds = " + hours + "h " + minutes + "m " + seconds + "s");8 System.out.printf("Display: %02d:%02d:%02d%n", hours, minutes, seconds);9 }10}
double, show 2 decimals with printf, and use Math.round (not a cast) for the final rupee amount.1public class GstBill {2 public static void main(String[] args) {3 final double GST_RATE = 18;4 double price = 749.50;5 int qty = 3;67 double subtotal = price * qty;8 double gst = subtotal * GST_RATE / 100;9 double total = subtotal + gst;1011 System.out.printf("Subtotal : %10.2f%n", subtotal);12 System.out.printf("GST 18%% : %10.2f%n", gst);13 System.out.printf("Total : %10.2f%n", total);14 System.out.println("Cast (int) : " + (int) total);15 System.out.println("Math.round() : " + Math.round(total));16 }17}
char values are numbers underneath (Unicode). Adding to a char and casting back gives the next letters.1public class CharCodes {2 public static void main(String[] args) {3 char upper = 'A', lower = 'a', digit = '0';4 System.out.println("A=" + (int) upper + " a=" + (int) lower + " 0=" + (int) digit);56 char letter = 'R';7 char shifted = (char) (letter + 3);8 System.out.println(letter + " shifted by 3 -> " + shifted);910 char small = 'j';11 char big = (char) (small - 32);12 System.out.println(small + " -> " + big);1314 char c = '7';15 boolean isDigit = c >= '0' && c <= '9';16 System.out.println(c + " is a digit? " + isDigit + ", value " + (c - '0'));17 }18}
Math.pow(a, b) computes a to the power b.1public class Emi {2 public static void main(String[] args) {3 double principal = 90000;4 double yearlyRate = 10.5;5 int years = 2;67 double r = yearlyRate / 12 / 100;8 int n = years * 12;9 double factor = Math.pow(1 + r, n);10 double emi = principal * r * factor / (factor - 1);1112 System.out.printf("Monthly EMI : Rs %,.2f%n", emi);13 System.out.printf("Total paid : Rs %,.2f%n", emi * n);14 System.out.printf("Total interest : Rs %,.2f%n", emi * n - principal);15 }16}
int overflows and how long fixes it.int holds up to 2,147,483,647. Going past it wraps around to a negative number with no error. long holds much bigger values.Integer.MAX_VALUE and add 1Long.MAX_VALUEMath.addExact to make overflow throw an error1public class Overflow {2 public static void main(String[] args) {3 int big = Integer.MAX_VALUE;4 System.out.println("int max : " + big);5 System.out.println("int max + 1 : " + (big + 1));67 int wrong = 5 * 1024 * 1024 * 1024;8 long right = 5L * 1024 * 1024 * 1024;9 System.out.println("5 GB as int : " + wrong);10 System.out.println("5 GB as long: " + right);11 System.out.println("long max : " + Long.MAX_VALUE);12 System.out.println("Safe add : " + Math.addExact(big, 1));13 }14}
int marks = 92;String(int) and drops decimalsfinal makes constants; var infers the type% gives the remainder; Math.pow for powers++x changes first, x++ uses the old value first; && || ! combine booleansSystem.out.println(7 / 2); prints?
Best type for a bank balance like 1520.75?
int a = 5; int b = a++; b is?
1import java.util.Scanner; // 1. import23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in); // 2. create6 System.out.print("Your name: ");7 String name = sc.nextLine(); // 3. read a whole line8 System.out.print("Your age: ");9 int age = sc.nextInt(); // read a whole number10 System.out.print("Height in metres: ");11 double h = sc.nextDouble(); // read a decimal12 System.out.println("Hello " + name + "! Next year you will be " + (age + 1));13 System.out.println("Height in cm: " + h * 100);14 sc.close();15 }16}
Scanner reads what the user types. Three steps: import it, create it with new Scanner(System.in), then call a method for the type you want.| Method | Reads |
|---|---|
nextLine() | the whole line (text with spaces) |
next() | one word |
nextInt() | a whole number |
nextDouble() | a decimal number |
nextBoolean() | true / false |
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Roll number: ");7 int roll = sc.nextInt();8 System.out.print("Full name: ");9 String name = sc.nextLine(); // BUG: reads the leftover Enter10 System.out.println("Roll " + roll + ", name = [" + name + "]");11 }12}
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Roll number: ");7 int roll = sc.nextInt();8 sc.nextLine(); // FIX: eat the leftover Enter9 System.out.print("Full name: ");10 String name = sc.nextLine();11 System.out.println("Roll " + roll + ", name = [" + name + "]");12 }13}
nextInt() reads the number but leaves the Enter key in the input. The next nextLine() reads that empty line. Call an extra sc.nextLine() to clear it.1public class Main {2 public static void main(String[] args) {3 String item = "Notebook";4 int qty = 12;5 double price = 45.5;6 System.out.printf("%s x %d = Rs %.2f%n", item, qty, qty * price);7 System.out.printf("[%10s]%n", "right"); // right-align in 108 System.out.printf("[%-10s]%n", "left"); // left-align in 109 System.out.printf("[%05d]%n", 42); // pad with zeros10 System.out.printf("%,d students%n", 125000); // thousand commas11 System.out.printf("%.1f%%%n", 87.456); // percent sign12 String line = String.format("Roll %03d | %-8s | %6.2f", 7, "Riya", 91.5);13 System.out.println(line);14 }15}
printf = print with a template. Each % code is replaced by the next value. String.format builds the same text but returns it instead of printing.| Code | For | Example result |
|---|---|---|
%d | int / long | 42 |
%.2f | double, 2 decimals | 45.50 |
%s | String / anything | Riya |
%c | char | A |
%10s / %-10s | width right / left | [ right] |
%05d | zero padding | 00042 |
%,d | commas | 125,000 |
%n | new line |
1public class Main {2 public static void main(String[] args) {3 System.out.println("sqrt(625) = " + Math.sqrt(625));4 System.out.println("pow(2, 10) = " + Math.pow(2, 10));5 System.out.println("abs(-7) = " + Math.abs(-7));6 System.out.println("max(45, 78) = " + Math.max(45, 78));7 System.out.println("min(45, 78) = " + Math.min(45, 78));8 System.out.println("round(7.5) = " + Math.round(7.5));9 System.out.println("ceil(7.1) = " + Math.ceil(7.1));10 System.out.println("floor(7.9) = " + Math.floor(7.9));11 System.out.println("PI = " + Math.PI);12 int students = 130, perBus = 40;13 System.out.println("Buses needed: " + (int) Math.ceil((double) students / perBus));14 }15}
Math is a built-in class full of static methods: you call them with Math.name(...), no object or import needed.Math.ceil gives 4 buses. A cast would wrongly give 3.Math every day.1import java.util.Random;23public class Main {4 public static void main(String[] args) {5 Random rnd = new Random(42); // 42 = seed (same numbers each run)6 int dice = rnd.nextInt(6) + 1; // 1 to 67 int otp = rnd.nextInt(900000) + 100000; // 6-digit OTP8 double chance = rnd.nextDouble(); // 0.0 to 1.09 boolean heads = rnd.nextBoolean();10 System.out.println("Dice: " + dice);11 System.out.println("OTP: " + otp);12 System.out.printf("Chance: %.3f%n", chance);13 System.out.println("Toss: " + (heads ? "Heads" : "Tails"));14 int lucky = (int) (Math.random() * 100) + 1; // 1 to 100, different each run15 System.out.println("Lucky number is between 1 and 100: " + (lucky >= 1 && lucky <= 100));16 }17}
rnd.nextInt(n) gives a random int from 0 to n-1; add 1 for "1 to n". A seed like new Random(42) repeats the same sequence, which is useful for testing.java.security.SecureRandom. Normal Random is predictable.The program pauses at each nextInt() until the user types a value and presses Enter.
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Cups of tea: ");7 int teas = sc.nextInt();8 System.out.print("Samosas: ");9 int samosas = sc.nextInt();10 int bill = teas * 12 + samosas * 15;11 System.out.println("Total: Rs " + bill);12 }13}
java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).nextLine() (remember the Enter-key trap!)nextLine() reads a whole line of text including spaces.1import java.util.Scanner;23public class Greeting {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Your name: ");7 String name = sc.nextLine();8 System.out.print("Your city: ");9 String city = sc.nextLine();10 System.out.println("*******************************");11 System.out.println(" Welcome, " + name + "!");12 System.out.println(" Greetings from " + city + ".");13 System.out.println("*******************************");14 }15}
nextInt() reads whole numbers; multiply by prices and add.1import java.util.Scanner;23public class TeaBill {4 public static void main(String[] args) {5 final int TEA = 12, SAMOSA = 15;6 Scanner sc = new Scanner(System.in);7 System.out.print("Cups of tea: ");8 int teas = sc.nextInt();9 System.out.print("Samosas: ");10 int samosas = sc.nextInt();11 System.out.println("---------------------------");12 System.out.printf("Tea x %2d = Rs %4d%n", teas, teas * TEA);13 System.out.printf("Samosa x %2d = Rs %4d%n", samosas, samosas * SAMOSA);14 System.out.println("---------------------------");15 System.out.printf("TOTAL = Rs %4d%n", teas * TEA + samosas * SAMOSA);16 }17}
nextDouble() reads decimals; Math.PI and Math.pow(r, 2) help with the formula.1import java.util.Scanner;23public class Circle {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Radius (cm): ");7 double r = sc.nextDouble();8 double area = Math.PI * Math.pow(r, 2);9 double circumference = 2 * Math.PI * r;10 System.out.printf("Area : %.2f sq cm%n", area);11 System.out.printf("Circumference : %.2f cm%n", circumference);12 }13}
printf("%.2f") shows money with 2 decimals; %,.2f adds commas.1import java.util.Scanner;23public class Currency {4 public static void main(String[] args) {5 final double RATE = 84.0; // example rate6 Scanner sc = new Scanner(System.in);7 System.out.print("Amount in rupees: ");8 double rupees = sc.nextDouble();9 double dollars = rupees / RATE;10 System.out.printf("Rs %,.2f = $ %,.2f%n", rupees, dollars);11 System.out.printf("Check: $ %,.2f x %.0f = Rs %,.2f%n", dollars, RATE, dollars * RATE);12 }13}
rnd.nextInt(6) + 1 gives 1 to 6. A seed makes the result repeatable for testing.new Random(7)1import java.util.Random;23public class Dice {4 public static void main(String[] args) {5 Random rnd = new Random(7);6 int d1 = rnd.nextInt(6) + 1;7 int d2 = rnd.nextInt(6) + 1;8 System.out.println("Die 1: " + d1);9 System.out.println("Die 2: " + d2);10 System.out.println("Total: " + (d1 + d2));11 System.out.println("Doubles? " + (d1 == d2));12 }13}
nextDouble(), Math.pow and printf.1import java.util.Scanner;23public class Bmi {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Name: ");7 String name = sc.nextLine();8 System.out.print("Weight (kg): ");9 double w = sc.nextDouble();10 System.out.print("Height (m): ");11 double h = sc.nextDouble();12 double bmi = w / Math.pow(h, 2);13 System.out.printf("%s, your BMI is %.1f%n", name, bmi);14 System.out.printf("Healthy weight for %.2f m: %.1f kg to %.1f kg%n", h, 18.5 * h * h, 24.9 * h * h);15 }16}
nextInt(900000) + 100000 always gives 6 digits. Compare ints with ==.new Random(2026)1import java.util.Random;2import java.util.Scanner;34public class Otp {5 public static void main(String[] args) {6 Random rnd = new Random(2026);7 int otp = rnd.nextInt(900000) + 100000;8 System.out.println("SMS: Your BrainBit Infotech login OTP is " + otp);9 Scanner sc = new Scanner(System.in);10 System.out.print("Enter OTP: ");11 int typed = sc.nextInt();12 System.out.println("Verified? " + (typed == otp));13 }14}
Math.ceil so the restaurant never gets less; integer % tells how much extra is collected.1import java.util.Scanner;23public class SplitBill {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Bill amount: ");7 double bill = sc.nextDouble();8 System.out.print("Tip percent: ");9 double tip = sc.nextDouble();10 System.out.print("Friends: ");11 int friends = sc.nextInt();12 double total = bill + bill * tip / 100;13 int share = (int) Math.ceil(total / friends);14 System.out.printf("Total with tip : Rs %.2f%n", total);15 System.out.printf("Each pays : Rs %d%n", share);16 System.out.printf("Extra collected: Rs %.2f%n", share * friends - total);17 }18}
Math.min / Math.max repeatedly; the average is the sum divided by 5.0; spread = max - min.1import java.util.Scanner;23public class Stats {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Enter 5 times: ");7 double a = sc.nextDouble(), b = sc.nextDouble(), c = sc.nextDouble(), d = sc.nextDouble(), e = sc.nextDouble();8 double min = Math.min(Math.min(Math.min(a, b), Math.min(c, d)), e);9 double max = Math.max(Math.max(Math.max(a, b), Math.max(c, d)), e);10 double avg = (a + b + c + d + e) / 5.0;11 System.out.printf("Fastest : %.2f s%n", min);12 System.out.printf("Slowest : %.2f s%n", max);13 System.out.printf("Average : %.2f s%n", avg);14 System.out.printf("Spread : %.2f s%n", max - min);15 }16}
Math methods with printf widths to build a neat table.1import java.util.Scanner;23public class SciCalc {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Enter a number: ");7 double x = sc.nextDouble();8 System.out.printf("%-12s %12s%n", "Function", "Result");9 System.out.printf("%-12s %12.3f%n", "square", Math.pow(x, 2));10 System.out.printf("%-12s %12.3f%n", "cube", Math.pow(x, 3));11 System.out.printf("%-12s %12.3f%n", "sqrt", Math.sqrt(x));12 System.out.printf("%-12s %12.3f%n", "cbrt", Math.cbrt(x));13 System.out.printf("%-12s %12.3f%n", "log10", Math.log10(x));14 System.out.printf("%-12s %12d%n", "round", Math.round(x));15 System.out.printf("%-12s %12.0f%n", "ceil", Math.ceil(x));16 System.out.printf("%-12s %12.0f%n", "floor", Math.floor(x));17 }18}
import java.util.Scanner; then new Scanner(System.in)nextLine() line, next() word, nextInt(), nextDouble()nextInt(), call an extra nextLine() before reading textprintf codes: %d %.2f %s %10s %-10s %,d %nMath: sqrt, pow, abs, max, min, round, ceil, floor, PIRandom: nextInt(n) gives 0..n-1; use SecureRandom for securityWhich reads a full name with spaces?
rnd.nextInt(6) + 1 gives?
printf("%.1f", 3.456) prints?
1int marks = 72;2if (marks >= 33) {3 System.out.println("Pass");4 System.out.println("Well done!");5} else {6 System.out.println("Fail");7}8System.out.println("Result checked");
if runs its block only when the condition is true. else runs when it is false. Exactly one of the two blocks runs.1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Enter your age: ");7 int age = sc.nextInt();8 if (age >= 18) {9 System.out.println("You can vote in the Jharkhand elections.");10 System.out.println("Carry your Voter ID card.");11 } else {12 int years = 18 - age;13 System.out.println("You can vote after " + years + " year(s).");14 }15 System.out.println("Thank you for using Voter Help.");16 }17}
if (age >= 18); with a semicolon ends the if immediately, so the block below ALWAYS runs. A classic bug!1int marks = sc.nextInt();2String grade;3if (marks >= 90) {4 grade = "A+";5} else if (marks >= 75) {6 grade = "A";7} else if (marks >= 60) {8 grade = "B";9} else if (marks >= 33) {10 grade = "C";11} else {12 grade = "F";13}14System.out.println("Grade: " + grade);
Notice how Java skips the lines it does not need.
1public class Main {2 public static void main(String[] args) {3 int marks = 81;4 String grade;5 if (marks >= 90) {6 grade = "A+";7 } else if (marks >= 75) {8 grade = "A";9 } else if (marks >= 60) {10 grade = "B";11 } else {12 grade = "F";13 }14 System.out.println("Grade: " + grade);15 boolean merit = grade.equals("A+") || grade.equals("A");16 System.out.println("Merit certificate? " + merit);17 }18}
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Username: ");7 String user = sc.nextLine().trim();8 System.out.print("Password: ");9 String pass = sc.nextLine();1011 if (user.equalsIgnoreCase("admin")) {12 if (pass.equals("Ranchi@2026")) {13 System.out.println("Login successful");14 } else {15 System.out.println("Wrong password");16 }17 } else {18 System.out.println("No such user");19 }20 int age = 25;21 boolean adultWorker = age >= 18 && age <= 60;22 System.out.println("Working age? " + adultWorker);23 }24}
&& and || to combine conditions into one..equals(), never ==. == checks if they are the same object in memory, which can be false even for equal text.1public class Main {2 public static void main(String[] args) {3 int marks = 47;4 String result = marks >= 33 ? "Pass" : "Fail";5 System.out.println(result);67 double cartTotal = 850;8 int delivery = cartTotal >= 499 ? 0 : 40;9 System.out.println("Delivery charge: Rs " + delivery);1011 int n = 7;12 System.out.println(n + " is " + (n % 2 == 0 ? "even" : "odd"));13 int a = 45, b = 78;14 System.out.println("Bigger: " + (a > b ? a : b));15 }16}
condition ? a : b gives a when the condition is true, otherwise b. Use it to choose between two values. For actions or longer logic, use a normal if-else.1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.println("1 Litti Chokha 2 Dhuska 3 Pitha 4 Rugra curry");7 System.out.print("Choice: ");8 int choice = sc.nextInt();9 switch (choice) {10 case 1:11 System.out.println("Litti Chokha: Rs 60");12 break;13 case 2:14 System.out.println("Dhuska with aloo: Rs 40");15 break;16 case 3:17 case 4:18 System.out.println("Seasonal special, ask the counter");19 break;20 default:21 System.out.println("Invalid choice");22 }23 }24}
switch compares one value with many case labels and jumps to the match. break stops it. default runs when nothing matches. Works with int, char, String and enums.break causes fall-through: the next case also runs. Sometimes useful (cases 3 and 4 above), usually a bug.1public class Main {2 public static void main(String[] args) {3 String day = "SAT";4 String type = switch (day) {5 case "SAT", "SUN" -> "Weekend";6 case "MON", "TUE", "WED", "THU", "FRI" -> "Weekday";7 default -> "Unknown";8 };9 System.out.println(day + " is a " + type);1011 int month = 7;12 int days = switch (month) {13 case 2 -> 28;14 case 4, 6, 9, 11 -> 30;15 default -> 31;16 };17 System.out.println("Month " + month + " has " + days + " days");18 }19}
case X -> value needs no break (no fall-through) and the whole switch can return a value. Several labels can share one arm: case 4, 6, 9, 11.if (marks = 33)if (marks >= 33);if (name == "Riya")if (0 < x < 10)case 1: ... (no break)if (marks == 33)if (marks >= 33) { ... }if (name.equals("Riya"))if (x > 0 && x < 10)case 1 -> ... or add breakequals() / equalsIgnoreCase()&&java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).n % 2 == 0.1import java.util.Scanner;23public class EvenOdd {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Enter a number: ");7 int n = sc.nextInt();8 if (n % 2 == 0) {9 System.out.println(n + " is EVEN");10 } else {11 System.out.println(n + " is ODD");12 }13 if (n % 5 == 0) {14 System.out.println(n + " is also a multiple of 5");15 }16 }17}
1import java.util.Scanner;23public class PassFail {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Marks (0-100): ");7 int marks = sc.nextInt();8 if (marks < 0 || marks > 100) {9 System.out.println("Invalid marks!");10 } else if (marks >= 33) {11 System.out.println("PASS with " + marks + " marks");12 } else {13 System.out.println("FAIL: needs " + (33 - marks) + " more marks");14 }15 }16}
&&, or keep a running maximum.Math.max1import java.util.Scanner;23public class Largest {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Three jumps (m): ");7 double a = sc.nextDouble(), b = sc.nextDouble(), c = sc.nextDouble();8 double best;9 if (a >= b && a >= c) {10 best = a;11 } else if (b >= c) {12 best = b;13 } else {14 best = c;15 }16 System.out.println("Best jump: " + best + " m");17 System.out.println("Check with Math.max: " + Math.max(a, Math.max(b, c)));18 }19}
&& and ||.1import java.util.Scanner;23public class LeapYear {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Year: ");7 int y = sc.nextInt();8 boolean leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;9 System.out.println(y + (leap ? " is a leap year" : " is not a leap year"));10 System.out.println("February has " + (leap ? 29 : 28) + " days");11 }12}
1import java.util.Scanner;23public class DayName {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Day number (1-7): ");7 int d = sc.nextInt();8 String name = switch (d) {9 case 1 -> "Monday";10 case 2 -> "Tuesday";11 case 3 -> "Wednesday";12 case 4 -> "Thursday";13 case 5 -> "Friday";14 case 6 -> "Saturday";15 case 7 -> "Sunday";16 default -> "Invalid";17 };18 System.out.println("Day: " + name);19 System.out.println(d == 7 ? "Holiday!" : "School day");20 }21}
1import java.util.Scanner;23public class Grade {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Marks obtained: ");7 int got = sc.nextInt();8 System.out.print("Total marks: ");9 int total = sc.nextInt();10 double pct = got * 100.0 / total;11 String grade;12 if (pct >= 90) grade = "A+";13 else if (pct >= 75) grade = "A";14 else if (pct >= 60) grade = "B";15 else if (pct >= 45) grade = "C";16 else if (pct >= 33) grade = "D";17 else grade = "F";18 String remark = switch (grade) {19 case "A+", "A" -> "Excellent";20 case "B", "C" -> "Good";21 case "D" -> "Needs improvement";22 default -> "Please meet the teacher";23 };24 System.out.printf("Percentage: %.2f%% Grade: %s (%s)%n", pct, grade, remark);25 }26}
1import java.util.Scanner;23public class ElectricityBill {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Units consumed: ");7 int u = sc.nextInt();8 double energy;9 if (u <= 100) {10 energy = u * 6.30;11 } else if (u <= 200) {12 energy = 100 * 6.30 + (u - 100) * 6.70;13 } else {14 energy = 100 * 6.30 + 100 * 6.70 + (u - 200) * 7.40;15 }16 double total = energy + 75;17 System.out.printf("Energy charge : Rs %,.2f%n", energy);18 System.out.printf("Fixed charge : Rs %,.2f%n", 75.0);19 System.out.printf("Total bill : Rs %,.2f%n", total);20 System.out.printf("Average/unit : Rs %.2f%n", total / u);21 }22}
equalsIgnoreCase for the username, length() and equals for the password, and order the checks well.1import java.util.Scanner;23public class Login {4 public static void main(String[] args) {5 final String USER = "teacher01";6 final String PASS = "Dav#Ranchi9";7 Scanner sc = new Scanner(System.in);8 System.out.print("Username: ");9 String u = sc.nextLine().trim();10 System.out.print("Password: ");11 String p = sc.nextLine();12 if (p.length() < 8) {13 System.out.println("Password must have at least 8 characters.");14 } else if (u.equalsIgnoreCase(USER) && p.equals(PASS)) {15 System.out.println("Welcome, " + u.toLowerCase() + "! You are logged in.");16 } else {17 System.out.println("Invalid username or password.");18 }19 }20}
1import java.util.Scanner;23public class BusFare {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Age, km, hour (0-23): ");7 int age = sc.nextInt(), km = sc.nextInt(), hour = sc.nextInt();8 double fare = km * 2;9 String category;10 if (age < 5) {11 fare = 0;12 category = "Infant (free)";13 } else if (age <= 12) {14 fare = fare / 2;15 category = "Child (half)";16 } else if (age >= 60) {17 fare = fare * 0.75;18 category = "Senior (25% off)";19 } else {20 category = "Adult";21 }22 int night = (hour >= 21 && fare > 0) ? 50 : 0;23 System.out.println("Category : " + category);24 System.out.printf("Fare : Rs %.2f%n", fare);25 System.out.println("Night : Rs " + night);26 System.out.printf("TOTAL : Rs %.2f%n", fare + night);27 }28}
&&); then a ladder decides equilateral / isosceles / scalene; Pythagoras checks right angles.return; inside main ends the program early.1import java.util.Scanner;23public class Triangle {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Three sides: ");7 int a = sc.nextInt(), b = sc.nextInt(), c = sc.nextInt();8 if (a + b <= c || a + c <= b || b + c <= a) {9 System.out.println("Not a valid triangle");10 return;11 }12 String type;13 if (a == b && b == c) type = "Equilateral";14 else if (a == b || b == c || a == c) type = "Isosceles";15 else type = "Scalene";16 int big = Math.max(a, Math.max(b, c));17 int sumSq = a * a + b * b + c * c - big * big;18 boolean right = sumSq == big * big;19 System.out.println("Type: " + type + (right ? ", right-angled" : ""));20 }21}
if (condition) { ... } else { ... }: exactly one block runs&& (and), || (or), ! (not)cond ? a : b chooses a valuebreak, or arrow switch expressions case X -> valueequals(), not ==if (x = 5) in Java...
marks = 80. Which runs first? if (m>=60) ... else if (m>=75)
Correct way to compare Strings s and t?
1public class Main {2 public static void main(String[] args) {3 for (int i = 1; i <= 5; i++) {4 System.out.println("Welcome, student " + i);5 }6 System.out.println("Done!");78 for (int n = 10; n >= 0; n -= 2) {9 System.out.print(n + " ");10 }11 System.out.println();12 }13}
for loop has three parts: start (runs once), condition (checked before every round), update (after every round). The body repeats while the condition is true.| Loop | Checks condition | Use when |
|---|---|---|
for | before each round | you know how many times |
while | before each round | repeat until something happens |
do-while | after each round | body must run at least once (menus) |
Watch month go 1, 2, 3, 4 and total grow. The running total pattern appears in every billing and report program.
1public class Main {2 public static void main(String[] args) {3 int total = 0;4 for (int month = 1; month <= 4; month++) {5 int saved = month * 100;6 total = total + saved;7 System.out.println("Month " + month + ": total " + total);8 }9 System.out.println("Final total: " + total);10 }11}
1public class Main {2 public static void main(String[] args) {3 int countdown = 5;4 while (countdown > 0) {5 System.out.print(countdown + "... ");6 countdown--;7 }8 System.out.println("Lift off! Chandrayaan launched!");910 double balance = 10000;11 int years = 0;12 while (balance < 20000) {13 balance = balance * 1.08; // 8% growth per year14 years++;15 }16 System.out.printf("Money doubles in %d years: Rs %.2f%n", years, balance);17 }18}
while (condition) keeps repeating as long as the condition is true. Use it when you do not know in advance how many rounds are needed.countdown--), otherwise it never stops.1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 int balance = 5000, choice;7 do {8 System.out.println("1 Balance 2 Withdraw 3 Exit");9 System.out.print("Choose: ");10 choice = sc.nextInt();11 if (choice == 1) {12 System.out.println("Balance: Rs " + balance);13 } else if (choice == 2) {14 System.out.print("Amount: ");15 int amt = sc.nextInt();16 if (amt <= balance) { balance -= amt; System.out.println("Collect Rs " + amt); }17 else System.out.println("Insufficient balance");18 }19 } while (choice != 3);20 System.out.println("Thank you for banking with us!");21 }22}
do { ... } while (condition); runs the body first and checks afterwards, so it always runs at least once. Perfect for menus that must be shown before the user can choose.1public class Main {2 public static void main(String[] args) {3 for (int roll = 1; roll <= 10; roll++) {4 if (roll == 4) {5 System.out.println(roll + " absent - skip");6 continue; // jump to the next roll7 }8 if (roll == 7) {9 System.out.println("Found topper at roll " + roll);10 break; // leave the loop11 }12 System.out.println("Checked roll " + roll);13 }14 outer:15 for (int row = 1; row <= 3; row++) {16 for (int seat = 1; seat <= 4; seat++) {17 if (row == 2 && seat == 3) {18 System.out.println("Empty seat found at row " + row + " seat " + seat);19 break outer; // leave BOTH loops20 }21 }22 }23 }24}
continue skips the rest of this round. break leaves the loop completely. A label like outer: lets break outer; leave nested loops at once.1public class Main {2 public static void main(String[] args) {3 for (int row = 1; row <= 4; row++) {4 for (int col = 1; col <= row; col++) {5 System.out.print("* ");6 }7 System.out.println();8 }9 System.out.println();10 for (int t = 2; t <= 3; t++) {11 for (int i = 1; i <= 5; i++) {12 System.out.printf("%d x %d = %-3d", t, i, t * i);13 }14 System.out.println();15 }16 }17}
| row | inner loop runs | prints |
|---|---|---|
| 1 | col = 1 | * |
| 2 | col = 1..2 | * * |
| 3 | col = 1..3 | * * * |
| 4 | col = 1..4 | * * * * |
The inner loop finishes all its rounds (A, B) before the outer loop moves to the next row.
1public class Main {2 public static void main(String[] args) {3 for (int row = 1; row <= 3; row++) {4 for (char seat = 'A'; seat <= 'B'; seat++) {5 System.out.print(row + "" + seat + " ");6 }7 System.out.println();8 }9 }10}
java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).for loop from 1 to 10 with printf alignment.1import java.util.Scanner;23public class Table {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Which table? ");7 int n = sc.nextInt();8 for (int i = 1; i <= 10; i++) {9 System.out.printf("%3d x %2d = %4d%n", n, i, n * i);10 }11 }12}
1import java.util.Scanner;23public class SumMarks {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("How many students? ");7 int n = sc.nextInt();8 int total = 0;9 for (int i = 1; i <= n; i++) {10 System.out.print("Marks of student " + i + ": ");11 total += sc.nextInt();12 }13 System.out.println("Total : " + total);14 System.out.printf("Average : %.2f%n", (double) total / n);15 }16}
for loop can count backwards with i--.1public class Countdown {2 public static void main(String[] args) {3 for (int s = 10; s >= 1; s--) {4 System.out.print(s + (s > 1 ? ", " : ""));5 }6 System.out.println();7 System.out.println("Time up! Put your pens down.");8 }9}
n % 10 gives the last digit; n / 10 removes it. Repeat with while (n > 0).1import java.util.Scanner;23public class Digits {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Number: ");7 long n = sc.nextLong();8 long original = n, reversed = 0;9 int count = 0, sum = 0;10 while (n > 0) {11 int d = (int) (n % 10);12 sum += d;13 count++;14 reversed = reversed * 10 + d;15 n /= 10;16 }17 System.out.println("Digits : " + count);18 System.out.println("Sum : " + sum);19 System.out.println("Reversed: " + reversed);20 System.out.println("Palindrome? " + (reversed == original));21 }22}
while loop repeats until the guess equals the secret; a counter tracks attempts.new Random(11).nextInt(50) + 11import java.util.Random;2import java.util.Scanner;34public class Guess {5 public static void main(String[] args) {6 int secret = new Random(11).nextInt(50) + 1;7 Scanner sc = new Scanner(System.in);8 int guess = 0, attempts = 0;9 System.out.println("I am thinking of a number from 1 to 50...");10 while (guess != secret) {11 System.out.print("Your guess: ");12 guess = sc.nextInt();13 attempts++;14 if (guess > secret) System.out.println("Too high!");15 else if (guess < secret) System.out.println("Too low!");16 }17 System.out.println("Correct! It was " + secret + ". Attempts: " + attempts);18 }19}
for loop with break on success, plus a boolean flag to know if the loop ended without success.1import java.util.Scanner;23public class AtmPin {4 public static void main(String[] args) {5 final int PIN = 4826;6 Scanner sc = new Scanner(System.in);7 boolean ok = false;8 for (int attempt = 1; attempt <= 3; attempt++) {9 System.out.print("Attempt " + attempt + "/3 - PIN: ");10 if (sc.nextInt() == PIN) {11 ok = true;12 break;13 }14 System.out.println("Wrong PIN. " + (3 - attempt) + " attempt(s) left.");15 }16 System.out.println(ok ? "PIN accepted. Welcome!" : "Card blocked! Contact your branch.");17 }18}
break as soon as one divides it.1import java.util.Scanner;23public class Primes {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Start and end: ");7 int a = sc.nextInt(), b = sc.nextInt(), count = 0;8 for (int n = Math.max(2, a); n <= b; n++) {9 boolean prime = true;10 for (int d = 2; d * d <= n; d++) {11 if (n % d == 0) {12 prime = false;13 break;14 }15 }16 if (prime) {17 System.out.print(n + " ");18 count++;19 }20 }21 System.out.println("\nPrimes found: " + count);22 }23}
" ".repeat(k)1import java.util.Scanner;23public class Patterns {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Height: ");7 int h = sc.nextInt();8 for (int i = 1; i <= h; i++) {9 System.out.println(" ".repeat(h - i) + "*".repeat(2 * i - 1));10 }11 for (int i = h - 1; i >= 1; i--) {12 System.out.println(" ".repeat(h - i) + "*".repeat(2 * i - 1));13 }14 }15}
while loop simulates month by month until the goal is reached.1public class SavingsGoal {2 public static void main(String[] args) {3 double goal = 15000, savings = 0;4 int deposit = 1000, month = 0;5 System.out.printf("%5s %8s %10s%n", "Month", "Deposit", "Savings");6 while (savings < goal) {7 month++;8 savings = savings * 1.005 + deposit;9 System.out.printf("%5d %8d %,10.2f%n", month, deposit, savings);10 deposit += 200;11 }12 System.out.println("Goal reached in " + month + " months!");13 }14}
do-while loop for "play again", a for loop for questions, and a switch to pick each question.1import java.util.Scanner;23public class Quiz {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 String again;7 do {8 int score = 0;9 for (int q = 1; q <= 3; q++) {10 String question = switch (q) {11 case 1 -> "Capital of Jharkhand?";12 case 2 -> "Keyword to make a constant in Java?";13 default -> "Method where a Java program starts?";14 };15 String answer = switch (q) {16 case 1 -> "Ranchi";17 case 2 -> "final";18 default -> "main";19 };20 System.out.print("Q" + q + ". " + question + " ");21 if (sc.nextLine().trim().equalsIgnoreCase(answer)) score++;22 }23 System.out.println("Score: " + score + "/3");24 System.out.print("Play again? (y/n) ");25 again = sc.nextLine();26 } while (again.equalsIgnoreCase("y"));27 System.out.println("Thanks for playing!");28 }29}
for (start; condition; update) when you know the countwhile (condition) repeats until something changes; update inside the loop!do { } while ( ); runs at least once (menus)break leaves, continue skips; labels break outer loopsHow many times does for (int i = 2; i < 8; i++) run?
Which loop always runs its body at least once?
Which keyword skips to the next round?
You finished Java Foundations: 5 modules and 50 practice examples.
D:\java-practice\part1java -versionD:\java-practicejava Main.java