Organise code into methods, store many values in arrays, and master text with String and StringBuilder.
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.addToCart(), applyCoupon(), placeOrder()calculateGst() once and use it on every billprintln(), nextInt(), Math.sqrt(). Now you will write your own.1public class Main {2 static void greet() { // no input, no output3 System.out.println("Namaste! Welcome to BrainBit Infotech.");4 }56 static void greetStudent(String name, String course) {7 System.out.println("Hello " + name + ", welcome to " + course + "!");8 }910 static double gst(double amount, double rate) {11 return amount * rate / 100; // send the answer back12 }1314 public static void main(String[] args) {15 greet();16 greetStudent("Riya", "Core Java");17 double tax = gst(1000, 18);18 System.out.println("GST on 1000 = " + tax);19 System.out.println("GST on 2499 = " + gst(2499, 18));20 }21}
void means the method returns nothing. A non-void method must return a value of its declared type. Arguments are copied into the parameters in order.mainstatic lets main call them directly (objects come in Module 9)gst(1000, 18)Watch the purple "Inside area()" box: each call gets its own fresh variables (a new stack frame) that disappear when the method returns.
1public class Main {2 static int area(int length, int breadth) {3 int a = length * breadth;4 return a;5 }67 public static void main(String[] args) {8 int room = area(12, 10);9 int hall = area(30, 20);10 int total = room + hall;11 System.out.println("Total floor area: " + total + " sq ft");12 }13}
1public class Main {2 static void printTotal(double price, int qty) {3 System.out.println("Total: " + price * qty); // only shows it4 }56 static double total(double price, int qty) {7 return price * qty; // gives it back8 }910 static boolean isAdult(int age) {11 return age >= 18;12 }1314 public static void main(String[] args) {15 printTotal(45.5, 4);16 double bill = total(45.5, 4) + total(120, 2); // can use it in maths17 System.out.println("Bill: " + bill);18 if (isAdult(19)) {19 System.out.println("Can open a bank account alone");20 }21 }22}
return the result, so the caller can store it, add it or use it in an if. Printing inside the method only shows it once.return also ends the method immediately. Code after it in the same block is unreachable.1public class Main {2 static double area(double side) { // square3 return side * side;4 }5 static double area(double length, double breadth) { // rectangle6 return length * breadth;7 }8 static double area(double a, double b, double c) { // triangle (Heron)9 double s = (a + b + c) / 2;10 return Math.sqrt(s * (s - a) * (s - b) * (s - c));11 }1213 public static void main(String[] args) {14 System.out.println("Square : " + area(5));15 System.out.println("Rectangle: " + area(12, 8));16 System.out.println("Triangle : " + area(3, 4, 5));17 }18}
System.out.println is overloaded: one version for int, one for double, one for String, and more.Java always passes a copy. For primitives the copy is the value; for arrays and objects the copy is a reference to the same object.
1public class Main {2 static void addBonus(int marks) {3 marks = marks + 5;4 System.out.println("Inside method: " + marks);5 }67 static void addBonusAll(int[] marks) {8 marks[0] = marks[0] + 5;9 }1011 public static void main(String[] args) {12 int m = 70;13 addBonus(m);14 System.out.println("After call: " + m);15 int[] list = {70, 80};16 addBonusAll(list);17 System.out.println("Array after call: " + list[0]);18 }19}
1public class Main {2 static final double GST = 18; // class-level constant: visible to all methods34 static int sum(int... nums) { // any number of ints5 int total = 0; // local: only inside sum()6 for (int n : nums) {7 total += n;8 }9 return total;10 }1112 public static void main(String[] args) {13 System.out.println(sum(78, 92));14 System.out.println(sum(65, 70, 88, 91, 59));15 System.out.println(sum());16 for (int i = 0; i < 2; i++) {17 int square = i * i; // exists only inside this loop18 }19 // System.out.println(square); // ERROR: square is out of scope20 System.out.println("GST rate: " + GST);21 }22}
{ } where it is declared (its scope). Varargs int... nums accepts any number of arguments as an array.String.format and printf use varargs: that is why they accept any number of values.4! = 4 x 3 x 2 x 1. Watch the waiting frames stack up, then return one by one. Every recursion needs a base case or it never stops (StackOverflowError).
1public class Main {2 static int factorial(int n) {3 if (n <= 1) {4 return 1;5 }6 return n * factorial(n - 1);7 }89 public static void main(String[] args) {10 int f = factorial(4);11 System.out.println("4! = " + f);12 }13}
java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).static boolean isPass(double pct) (true when pct >= 33)percentage(int obtained) that assumes total 500static double average(int... nums)/** ... */ above grade()void method with parameters does a job but returns nothing.static void welcome(String name, String course)1public class Welcome {2 static void welcome(String name, String course) {3 System.out.println("Welcome " + name + "!");4 System.out.println(" Course : " + course);5 System.out.println(" Batch : 10 AM - 12 PM");6 }78 public static void main(String[] args) {9 welcome("Riya", "Core Java");10 welcome("Aman", "Python");11 welcome("Sana", "Web Design");12 }13}
return double can be used directly inside println and calculations.rectangleArea(l, b) and circleArea(r)1public class Areas {2 static double rectangleArea(double l, double b) {3 return l * b;4 }56 static double circleArea(double r) {7 return Math.PI * r * r;8 }910 public static void main(String[] args) {11 double bedroom = rectangleArea(12, 14);12 double hall = rectangleArea(20, 15);13 double tank = circleArea(3.5);14 System.out.printf("Bedroom %.1f, Hall %.1f, Tank %.2f%n", bedroom, hall, tank);15 System.out.printf("Total area: %.2f sq ft%n", bedroom + hall + tank);16 }17}
boolean can be used directly in an if.isEven(int), isPositive(int), inRange(int, int, int)1public class Checks {2 static boolean isEven(int n) { return n % 2 == 0; }3 static boolean isPositive(int n) { return n > 0; }4 static boolean inRange(int n, int lo, int hi) { return n >= lo && n <= hi; }56 public static void main(String[] args) {7 int[] tests = {14, -3, 77};8 for (int t : tests) {9 System.out.println(t + ": even=" + isEven(t) + ", positive=" + isPositive(t) + ", valid marks=" + inRange(t, 0, 100));10 }11 if (isEven(14) && inRange(14, 10, 20)) {12 System.out.println("14 is an even number between 10 and 20");13 }14 }15}
max3 uses Math.max.static double max3(double a, double b, double c)1public class Best {2 static double max3(double a, double b, double c) {3 return Math.max(a, Math.max(b, c));4 }56 public static void main(String[] args) {7 System.out.println("Ankita : " + max3(4.12, 4.35, 4.28) + " m");8 System.out.println("Rohit : " + max3(5.01, 4.97, 5.10) + " m");9 System.out.println("Sana : " + max3(3.88, 4.02, 3.95) + " m");10 }11}
addGst(double price, double rate)addGst(double price) that uses 181public class GstMethods {2 static double addGst(double price, double rate) {3 return Math.round(price * (1 + rate / 100) * 100) / 100.0;4 }56 static double addGst(double price) {7 return addGst(price, 18); // default rate8 }910 public static void main(String[] args) {11 System.out.println("Thali (5%) : " + addGst(150, 5));12 System.out.println("Earphones (18%) : " + addGst(1299));13 System.out.println("Umbrella (12%) : " + addGst(450, 12));14 }15}
return exits early.static boolean isPrime(int n)1public class PrimeMethod {2 static boolean isPrime(int n) {3 if (n < 2) return false;4 for (int d = 2; d * d <= n; d++) {5 if (n % d == 0) return false;6 }7 return true;8 }910 public static void main(String[] args) {11 int twins = 0;12 for (int i = 1; i <= 60; i++) {13 if (isPrime(i)) System.out.print(i + " ");14 if (isPrime(i) && isPrime(i + 2)) twins++;15 }16 System.out.println("\nTwin prime pairs up to 60: " + twins);17 }18}
factLoop(int n) with a for loopfactRec(int n) recursivelylong to avoid overflow1public class Factorial {2 static long factLoop(int n) {3 long f = 1;4 for (int i = 2; i <= n; i++) f *= i;5 return f;6 }78 static long factRec(int n) {9 if (n <= 1) return 1;10 return n * factRec(n - 1);11 }1213 public static void main(String[] args) {14 for (int n : new int[]{1, 5, 10, 20}) {15 System.out.printf("%2d! = %,d (loop) = %,d (recursion)%n", n, factLoop(n), factRec(n));16 }17 }18}
power(base, exp)digitSum(n)fib(n) (Fibonacci)reverse(String) using substring1public class RecursionKit {2 static long power(long base, int exp) {3 if (exp == 0) return 1;4 return base * power(base, exp - 1);5 }6 static int digitSum(int n) {7 if (n < 10) return n;8 return n % 10 + digitSum(n / 10);9 }10 static int fib(int n) {11 if (n <= 1) return n;12 return fib(n - 1) + fib(n - 2);13 }14 static String reverse(String s) {15 if (s.isEmpty()) return s;16 return reverse(s.substring(1)) + s.charAt(0);17 }1819 public static void main(String[] args) {20 System.out.println("2^10 = " + power(2, 10));21 System.out.println("digitSum(834001) = " + digitSum(834001));22 System.out.print("Fibonacci: ");23 for (int i = 0; i < 12; i++) System.out.print(fib(i) + " ");24 System.out.println("\nreverse(\"RANCHI\") = " + reverse("RANCHI"));25 }26}
emi(principal, rate, months) returns the EMIprintPlan(principal, rate, int... years) prints a row per tenure1public class EmiPlanner {2 static double emi(double p, double yearlyRate, int months) {3 double r = yearlyRate / 12 / 100;4 double f = Math.pow(1 + r, months);5 return p * r * f / (f - 1);6 }78 static void printPlan(double p, double rate, int... years) {9 System.out.printf("Loan Rs %,.0f at %.1f%%%n", p, rate);10 for (int y : years) {11 double m = emi(p, rate, y * 12);12 System.out.printf(" %d yr: EMI Rs %,8.0f interest Rs %,8.0f%n", y, m, m * y * 12 - p);13 }14 }1516 public static void main(String[] args) {17 printPlan(85000, 9.5, 1, 2, 3);18 printPlan(85000, 11.0, 2, 3);19 }20}
switch calls the right one.1import java.util.Scanner;23public class MenuCalc {4 static double add(double a, double b) { return a + b; }5 static double sub(double a, double b) { return a - b; }6 static double mul(double a, double b) { return a * b; }7 static String div(double a, double b) { return b == 0 ? "cannot divide by zero" : String.valueOf(a / b); }8 static double pow(double a, double b) { return Math.pow(a, b); }910 public static void main(String[] args) {11 Scanner sc = new Scanner(System.in);12 int ch;13 do {14 System.out.print("1 + 2 - 3 x 4 / 5 ^ 0 exit: ");15 ch = sc.nextInt();16 if (ch < 1 || ch > 5) continue;17 System.out.print(" two numbers: ");18 double a = sc.nextDouble(), b = sc.nextDouble();19 String r = switch (ch) {20 case 1 -> String.valueOf(add(a, b));21 case 2 -> String.valueOf(sub(a, b));22 case 3 -> String.valueOf(mul(a, b));23 case 4 -> div(a, b);24 default -> String.valueOf(pow(a, b));25 };26 System.out.println(" = " + r);27 } while (ch != 0);28 System.out.println("Bye!");29 }30}
static returnType name(params) { ... }void returns nothing; other methods must return a value{ }; varargs int... numsWhat does a void method return?
static int f(int x) and static int f(double x) is called...
A recursive method without a base case causes...
int[]boolean[][]ArrayList is built on an array insidemain(String[] args) itself receives an arraymarks[2], change with marks[2] = 70;.| Code | Means |
|---|---|
int[] a = new int[5]; | 5 boxes, all 0 |
int[] a = {78, 92, 65}; | create + fill |
a[0] | first element |
a.length | how many (no brackets) |
a[a.length - 1] | last element |
ArrayList (Module 15).1public class Main {2 public static void main(String[] args) {3 int[] marks = {78, 92, 65, 88, 71}; // create and fill4 System.out.println("First : " + marks[0]);5 System.out.println("Third : " + marks[2]);6 System.out.println("Count : " + marks.length);7 System.out.println("Last : " + marks[marks.length - 1]);89 marks[2] = 70; // re-test: change a value10 System.out.println("Third after re-test: " + marks[2]);1112 double[] prices = new double[3]; // 3 boxes, default 0.013 prices[0] = 45.5;14 prices[1] = 120;15 System.out.println(prices[0] + ", " + prices[1] + ", " + prices[2]);1617 String[] cities = {"Ranchi", "Jamshedpur", "Dhanbad"};18 System.out.println("Capital: " + cities[0]);19 }20}
new int[3] fills with default values: 0 for numbers, false for boolean, null for String/objects. length is a field, not a method, so no ().marks[2] changes only that one box; the size never changes.Electricity units for 4 months (JBVNL bill). The loop counter i walks from index 0 to length - 1.
1public class Main {2 public static void main(String[] args) {3 int[] units = {120, 95, 140, 110};4 int total = 0;5 for (int i = 0; i < units.length; i++) {6 total += units[i];7 }8 double avg = (double) total / units.length;9 System.out.println("Total units: " + total);10 System.out.println("Average: " + avg);11 }12}
1public class Main {2 public static void main(String[] args) {3 int[] runs = {45, 12, 78, 33, 101, 8};45 int best = runs[0];6 int fifties = 0;7 for (int r : runs) { // "for each r in runs"8 if (r > best) best = r;9 if (r >= 50) fifties++;10 }11 System.out.println("Highest score : " + best);12 System.out.println("50+ scores : " + fifties);1314 String[] players = {"Ishan", "Saurabh", "Varun"};15 for (String p : players) {16 System.out.println("Player: " + p);17 }18 }19}
for (int r : runs) gives you each value in turn, with no index to manage. Use it to read every element. Use a normal for when you need the index or want to change elements.| Need | Use |
|---|---|
| Read every value | for-each |
| Know the position | for (int i...) |
| Change elements | for (int i...) |
| Go backwards | for (int i = n-1; i >= 0; i--) |
int[] b = a; does not copy the array. Both variables point to the same array on the heap, so a change through b is seen through a.int[] c = Arrays.copyOf(a, a.length); or a.clone()== checks same object; Arrays.equals(a, c) checks same values.1import java.util.Arrays;23public class Main {4 public static void main(String[] args) {5 int[] marks = {78, 92, 65, 88, 71};6 System.out.println(Arrays.toString(marks)); // print nicely78 int[] sorted = Arrays.copyOf(marks, marks.length);9 Arrays.sort(sorted);10 System.out.println("Sorted : " + Arrays.toString(sorted));11 System.out.println("Index of 88: " + Arrays.binarySearch(sorted, 88));1213 int[] seats = new int[6];14 Arrays.fill(seats, -1); // -1 = empty seat15 System.out.println("Seats : " + Arrays.toString(seats));1617 String[] names = {"Sneha", "Aman", "Ravi"};18 Arrays.sort(names); // alphabetical19 System.out.println("Names : " + Arrays.toString(names));20 System.out.println("Sum : " + Arrays.stream(marks).sum());21 }22}
java.util.Arrays has static methods for common jobs. Printing an array directly shows a code like [I@1b6d3586; use Arrays.toString() instead.| Method | Does |
|---|---|
toString(a) | text like [1, 2, 3] |
sort(a) | ascending order |
binarySearch(a, x) | find in a SORTED array |
fill(a, v) | set every box |
copyOf(a, n) | new copy |
equals(a, b) | same contents? |
1public class Main {2 public static void main(String[] args) {3 int[] marks = {78, 92, 65};4 for (int i = 0; i <= marks.length; i++) { // BUG: <= should be <5 System.out.println("Subject " + (i + 1) + ": " + marks[i]);6 }7 }8}
0 to length - 1. Asking for marks[3] in a 3-element array crashes the program with ArrayIndexOutOfBoundsException.i <= marks.length. Always write i < marks.length.marks[row][col]. marks.length = rows, marks[0].length = columns.1int[][] marks = {2 {78, 85, 90}, // Aman3 {62, 70, 58}, // Priya4 {95, 88, 92} // Rahul5};6int[][] seats = new int[10][12]; // 10 rows x 12 seats
1public class Main {2 public static void main(String[] args) {3 String[] names = {"Aman", "Priya", "Rahul"};4 int[][] marks = {5 {78, 85, 90},6 {62, 70, 58},7 {95, 88, 92}8 };9 System.out.println("Name Maths Sci Eng Total");10 for (int r = 0; r < marks.length; r++) {11 int total = 0;12 System.out.printf("%-7s", names[r]);13 for (int c = 0; c < marks[r].length; c++) {14 System.out.printf("%6d", marks[r][c]);15 total += marks[r][c];16 }17 System.out.printf("%7d%n", total);18 }19 }20}
1int[] units = {110, 95, 120, 150, 185, 170};2for (int u : units) {3 System.out.println("#".repeat(u / 10) + " " + u);4}
java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).subjects[i] goes with marks[i].1public class MarksCard {2 public static void main(String[] args) {3 String[] subjects = {"Hindi", "English", "Maths", "Science", "SST"};4 int[] marks = {82, 76, 95, 88, 79};5 int total = 0;6 System.out.println("---- Report: Aditi Kumari, Class 9 ----");7 for (int i = 0; i < marks.length; i++) {8 System.out.printf("%-8s : %3d%n", subjects[i], marks[i]);9 total += marks[i];10 }11 System.out.println("Total : " + total + " / 500");12 System.out.printf("Percentage : %.1f%%%n", total * 100.0 / 500);13 }14}
1public class PriceRange {2 public static void main(String[] args) {3 int[] price = {40, 38, 45, 52, 47, 35, 42}; // Rs per kg4 int max = price[0], min = price[0];5 for (int p : price) {6 if (p > max) max = p;7 if (p < min) min = p;8 }9 System.out.println("Highest: Rs " + max);10 System.out.println("Lowest : Rs " + min);11 System.out.println("Range : Rs " + (max - min));12 }13}
1public class PassCount {2 public static void main(String[] args) {3 int[] marks = {45, 28, 67, 90, 31, 55, 12, 78, 33, 60};4 int pass = 0;5 for (int m : marks) {6 if (m >= 33) pass++;7 }8 int fail = marks.length - pass;9 System.out.println("Passed: " + pass + ", Failed: " + fail);10 System.out.printf("Pass rate: %.0f%%%n", pass * 100.0 / marks.length);11 }12}
-1 means "not found".static int find(int[] a, int key)1public class Search {2 static int find(int[] a, int key) {3 for (int i = 0; i < a.length; i++) {4 if (a[i] == key) return i;5 }6 return -1;7 }89 public static void main(String[] args) {10 int[] rolls = {1203, 1187, 1250, 1199, 1222};11 int[] queries = {1199, 1300};12 for (int q : queries) {13 int pos = find(rolls, q);14 System.out.println(q + (pos == -1 ? " not found" : " found at position " + (pos + 1)));15 }16 }17}
1import java.util.Arrays;23public class ReverseRotate {4 public static void main(String[] args) {5 int[] a = {1, 2, 3, 4, 5, 6};6 for (int i = 0, j = a.length - 1; i < j; i++, j--) {7 int t = a[i]; a[i] = a[j]; a[j] = t;8 }9 System.out.println("Reversed : " + Arrays.toString(a));1011 int first = a[0];12 for (int i = 0; i < a.length - 1; i++) a[i] = a[i + 1];13 a[a.length - 1] = first;14 System.out.println("Rotated : " + Arrays.toString(a));15 }16}
1public class BillAnalyser {2 public static void main(String[] args) {3 String[] mon = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};4 int[] units = {110, 95, 120, 150, 185, 170, 160, 155, 140, 125, 105, 115};5 int total = 0, peak = 0;6 for (int i = 0; i < units.length; i++) {7 total += units[i];8 if (units[i] > units[peak]) peak = i;9 }10 double avg = (double) total / units.length;11 System.out.printf("Total %d units, bill Rs %,.2f%n", total, total * 6.30);12 System.out.println("Peak month: " + mon[peak] + " (" + units[peak] + ")");13 System.out.printf("Average: %.1f. Above average: ", avg);14 for (int i = 0; i < units.length; i++) {15 if (units[i] > avg) System.out.print(mon[i] + " ");16 }17 System.out.println();18 }19}
count[face]++. A very common array trick.int[7]1import java.util.Random;23public class DiceCount {4 public static void main(String[] args) {5 Random rnd = new Random(7);6 int[] count = new int[7]; // index 1..6 used7 for (int i = 0; i < 600; i++) {8 count[rnd.nextInt(6) + 1]++;9 }10 for (int f = 1; f <= 6; f++) {11 System.out.printf("%d: %3d %s%n", f, count[f], "*".repeat(count[f] / 5));12 }13 }14}
1import java.util.Arrays;23public class Bubble {4 public static void main(String[] args) {5 int[] a = {64, 25, 12, 22, 11, 90};6 int swaps = 0;7 for (int pass = 1; pass < a.length; pass++) {8 boolean swapped = false;9 for (int i = 0; i < a.length - pass; i++) {10 if (a[i] > a[i + 1]) {11 int t = a[i]; a[i] = a[i + 1]; a[i + 1] = t;12 swapped = true; swaps++;13 }14 }15 System.out.println("Pass " + pass + ": " + Arrays.toString(a));16 if (!swapped) break;17 }18 System.out.println("Total swaps: " + swaps);19 }20}
boolean[][] marks booked seats; a method books a seat and refuses double booking.boolean[][] seats = new boolean[5][8]book(row, seat) returns true/false1public class Cinema {2 static boolean[][] seats = new boolean[5][8];34 static boolean book(char row, int no) {5 int r = row - 'A', c = no - 1;6 if (seats[r][c]) return false;7 seats[r][c] = true;8 return true;9 }1011 public static void main(String[] args) {12 String[] requests = {"C4", "C5", "C4", "E1", "A8"};13 for (String q : requests) {14 boolean ok = book(q.charAt(0), Integer.parseInt(q.substring(1)));15 System.out.println(q + (ok ? " booked" : " already taken!"));16 }17 int free = 0;18 System.out.println(" SCREEN THIS WAY");19 for (int r = 0; r < seats.length; r++) {20 System.out.print((char) ('A' + r) + " ");21 for (boolean b : seats[r]) {22 System.out.print(b ? "[X]" : "[ ]");23 if (!b) free++;24 }25 System.out.println();26 }27 System.out.println("Available seats: " + free);28 }29}
1public class ResultMatrix {2 public static void main(String[] args) {3 String[] st = {"Aman", "Priya", "Rahul", "Sana"};4 String[] sub = {"Maths", "Sci", "Eng", "Comp"};5 int[][] m = {{78, 85, 90, 88}, {92, 70, 58, 95}, {65, 88, 92, 72}, {88, 91, 79, 99}};6 int best = 0, bestTotal = 0;7 for (int r = 0; r < m.length; r++) {8 int t = 0;9 for (int v : m[r]) t += v;10 System.out.printf("%-6s total %3d %.1f%%%n", st[r], t, t / 4.0);11 if (t > bestTotal) { bestTotal = t; best = r; }12 }13 for (int c = 0; c < sub.length; c++) {14 int sum = 0, top = 0;15 for (int r = 0; r < m.length; r++) {16 sum += m[r][c];17 if (m[r][c] > m[top][c]) top = r;18 }19 System.out.printf("%-5s avg %.1f, topper %s (%d)%n", sub[c], sum / 4.0, st[top], m[top][c]);20 }21 System.out.println("Class topper: " + st[best] + " with " + bestTotal);22 }23}
int[] a = {..} or new int[n]; index 0 to length - 1a.length (no brackets); loops: for and for-eachb = a shares, it does not copyArrays.toString / sort / fill / copyOf / equals / binarySearchint[][] m, m[row][col], nested loopsLast index of an array of length 10?
new boolean[3] contains...
After int[] b = a; b[0] = 5; what is a[0]?
String.format for neat columnsStringBuilder for speedsubstring(a, b) gives characters from index a up to (not including) b.| Code | Result |
|---|---|
city.length() | 6 |
city.charAt(0) | 'R' |
city.substring(3) | "CHI" |
city.indexOf("CH") | 3 |
city.toLowerCase() | "ranchi" |
name.trim().toUpperCase().| Method | Use |
|---|---|
trim() / strip() | remove outer spaces |
contains(x) | is x inside? |
startsWith / endsWith | check ends |
indexOf(x) | position, -1 if absent |
replace(a, b) | swap text |
isEmpty / isBlank | empty checks |
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("City: ");7 String city = sc.nextLine();89 System.out.println("== says : " + (city == "Ranchi")); // compares addresses!10 System.out.println("equals says : " + city.equals("Ranchi")); // compares text11 System.out.println("ignoring case : " + city.equalsIgnoreCase("RANCHI"));12 System.out.println("compareTo : " + "Aman".compareTo("Bina")); // negative: Aman first13 }14}
== checks whether two variables point to the same object. equals() checks whether the text is the same. For Strings, always use equals().== gives false even though the text matches. This bug is very common in login code.compareTo returns negative, 0 or positive: used for alphabetical sorting.toUpperCase() builds a new String; to keep it, assign it back: city = city.toUpperCase();"Ranchi" are stored once in a shared pool and reused, saving memory. That is safe only because Strings cannot change.1public class Main {2 public static void main(String[] args) {3 String pass = "Ranchi@2026";4 int upper = 0, lower = 0, digits = 0, special = 0;5 for (int i = 0; i < pass.length(); i++) {6 char ch = pass.charAt(i);7 if (Character.isUpperCase(ch)) upper++;8 else if (Character.isLowerCase(ch)) lower++;9 else if (Character.isDigit(ch)) digits++;10 else special++;11 }12 System.out.println("Upper " + upper + ", lower " + lower + ", digits " + digits + ", special " + special);13 for (char ch : "JAVA".toCharArray()) {14 System.out.print((int) ch + " "); // Unicode numbers15 }16 System.out.println();17 }18}
charAt(i) gives a char. The Character class checks it: isDigit, isLetter, isUpperCase, isWhitespace. toCharArray() gives a char array for for-each.1public class Main {2 public static void main(String[] args) {3 String row = "1203,Aditi Kumari,Ranchi,91.5"; // one line of a CSV file4 String[] parts = row.split(",");5 System.out.println("Roll : " + parts[0]);6 System.out.println("Name : " + parts[1]);7 double pct = Double.parseDouble(parts[3]); // text -> number8 System.out.println("Pct+5: " + (pct + 5));910 String[] tags = {"java", "oop", "beginner"};11 System.out.println(String.join(" #", tags));1213 String line = String.format("%-12s|%8.2f|", "Notebook", 45.5);14 System.out.println(line);15 System.out.println("=".repeat(22));16 }17}
split(",") breaks text into an array at each comma. String.join does the opposite. String.format builds formatted text like printf, but returns it.| Need | Use |
|---|---|
| text -> int | Integer.parseInt("42") |
| text -> double | Double.parseDouble("9.5") |
| number -> text | String.valueOf(42) |
| repeat | "-".repeat(10) |
append adds to the same object instead of creating thousands of new Strings.| Method | Does |
|---|---|
append(x) | add at end |
insert(i, x) | add at index |
deleteCharAt(i) | remove one |
reverse() | reverse |
toString() | get a String |
1public class Main {2 public static void main(String[] args) {3 String[] items = {"Rice 5kg", "Dal 1kg", "Oil 1L"};4 double[] price = {320, 140, 165};5 StringBuilder sb = new StringBuilder();6 sb.append("KUMAR GENERAL STORE, LALPUR\n");7 double total = 0;8 for (int i = 0; i < items.length; i++) {9 sb.append(String.format("%-10s %8.2f%n", items[i], price[i]));10 total += price[i];11 }12 sb.append("-".repeat(19)).append("\n");13 sb.append(String.format("%-10s %8.2f", "TOTAL", total));14 System.out.println(sb);15 long t1 = System.nanoTime();16 String s = "";17 for (int i = 0; i < 20000; i++) s += "x"; // creates 20000 Strings18 long t2 = System.nanoTime();19 StringBuilder b = new StringBuilder();20 for (int i = 0; i < 20000; i++) b.append("x"); // one object21 long t3 = System.nanoTime();22 System.out.println("\nString += was slower: " + ((t2 - t1) > (t3 - t2)));23 }24}
sb.append(a).append(b). In a loop, s += x copies the whole string every time; StringBuilder grows one buffer.java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).1public class NameFormat {2 public static void main(String[] args) {3 String name = " Rohit Kumar Mahto ";4 String clean = name.trim();5 System.out.println("[" + clean + "]");6 System.out.println(clean.toUpperCase());7 System.out.println(clean.toLowerCase());8 String[] w = clean.split(" ");9 String initials = "";10 for (String part : w) initials += part.charAt(0);11 System.out.println("Initials: " + initials);12 System.out.println("Letters : " + clean.replace(" ", "").length());13 }14}
contains, indexOf, lastIndexOf and endsWith combined with &&.1public class EmailCheck {2 public static void main(String[] args) {3 String[] emails = {"neha.k@gmail.com", "rahul@@yahoo.in", "aman.gmail.com", "info@bit.ac.in"};4 for (String e : emails) {5 int at = e.indexOf("@");6 boolean ok = at > 0 && at == e.lastIndexOf("@") && e.indexOf(".", at) > at + 1;7 if (ok) {8 System.out.println(e + " -> valid (user " + e.substring(0, at) + ", domain " + e.substring(at + 1) + ")");9 } else {10 System.out.println(e + " -> INVALID");11 }12 }13 }14}
charAt; use "aeiou".indexOf(ch) to test vowels; split on spaces for words.1public class Counter {2 public static void main(String[] args) {3 String text = "Ranchi is called the City of Waterfalls";4 int v = 0, c = 0, sp = 0;5 for (char ch : text.toLowerCase().toCharArray()) {6 if ("aeiou".indexOf(ch) >= 0) v++;7 else if (Character.isLetter(ch)) c++;8 else if (ch == ' ') sp++;9 }10 System.out.println("Vowels: " + v + ", consonants: " + c + ", spaces: " + sp);11 System.out.println("Words : " + text.split(" ").length);12 }13}
1public class Palindrome {2 static boolean isPal(String s) {3 String clean = s.replaceAll("\\s", "").toLowerCase();4 return clean.equals(new StringBuilder(clean).reverse().toString());5 }67 public static void main(String[] args) {8 String[] tests = {"Malayalam", "12321", "Never odd or even", "Ranchi"};9 for (String t : tests) {10 System.out.printf("%-18s -> %s%n", t, isPal(t) ? "palindrome" : "not palindrome");11 }12 }13}
1public class CsvFees {2 public static void main(String[] args) {3 String[] lines = {"101,Ankit Oraon,Java,4500", "102,Pooja Singh,Python,4000", "103,Md Faiz,Web,3500"};4 int total = 0;5 System.out.println(String.format("%-4s %-14s %-7s %6s", "ID", "Name", "Course", "Fee"));6 for (String ln : lines) {7 String[] f = ln.split(",");8 int fee = Integer.parseInt(f[3]);9 total += fee;10 System.out.println(String.format("%-4s %-14s %-7s %6d", f[0], f[1], f[2], fee));11 }12 System.out.println("Total fees: Rs " + total);13 }14}
1import java.util.Scanner;23public class Strength {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 for (int k = 0; k < 3; k++) {7 System.out.print("Password: ");8 String p = sc.nextLine();9 boolean up = false, low = false, dig = false, sp = false;10 for (char ch : p.toCharArray()) {11 if (Character.isUpperCase(ch)) up = true;12 else if (Character.isLowerCase(ch)) low = true;13 else if (Character.isDigit(ch)) dig = true;14 else sp = true;15 }16 int score = (p.length() >= 8 ? 1 : 0) + (up ? 1 : 0) + (low ? 1 : 0) + (dig ? 1 : 0) + (sp ? 1 : 0);17 String r = score <= 2 ? "Weak" : score <= 4 ? "Medium" : "Strong";18 System.out.println(" score " + score + "/5 -> " + r);19 }20 }21}
1public class VehicleNo {2 static boolean valid(String n) {3 if (n.length() != 10 || !n.startsWith("JH")) return false;4 for (int i = 2; i < 10; i++) {5 char ch = n.charAt(i);6 boolean needDigit = i < 4 || i >= 6;7 if (needDigit && !Character.isDigit(ch)) return false;8 if (!needDigit && !Character.isLetter(ch)) return false;9 }10 return true;11 }1213 public static void main(String[] args) {14 String[] input = {"jh 01 ab 1234", "JH05CK9988", "BR01AB1234", "JH1AB12345"};15 for (String raw : input) {16 String n = raw.replace(" ", "").toUpperCase();17 System.out.print(raw + " -> " + n);18 System.out.println(valid(n) ? " OK, district code " + n.substring(2, 4) : " INVALID");19 }20 }21}
replace, build many messages with StringBuilder, and count SMS parts (160 chars each).1public class SmsTemplate {2 public static void main(String[] args) {3 String tpl = "Dear Parent, fee of Rs {amt} for {name} is due on {date}. Please pay at the school office or online. - DAV Public School, Ranchi";4 String[][] data = {{"Aditi", "4500", "10 Nov"}, {"Rohan", "3800", "10 Nov"}, {"Md Imran", "4500", "15 Nov"}};5 StringBuilder log = new StringBuilder();6 for (String[] d : data) {7 String msg = tpl.replace("{name}", d[0]).replace("{amt}", d[1]).replace("{date}", d[2]);8 int parts = (msg.length() + 159) / 160;9 log.append(d[0]).append(": ").append(msg.length()).append(" chars, ").append(parts).append(" SMS\n");10 System.out.println(msg);11 }12 System.out.print(log);13 }14}
ch - 'a', plus split and StringBuilder.1public class TextAnalyser {2 public static void main(String[] args) {3 String t = "jharkhand is rich in minerals forests and waterfalls like hundru and dassam";4 int[] cnt = new int[26];5 for (char ch : t.toCharArray()) if (Character.isLetter(ch)) cnt[ch - 'a']++;6 for (int k = 0; k < 5; k++) {7 int best = 0;8 for (int i = 1; i < 26; i++) if (cnt[i] > cnt[best]) best = i;9 System.out.printf("%c %2d %s%n", (char) ('a' + best), cnt[best], "#".repeat(cnt[best]));10 cnt[best] = -1;11 }12 String longest = "";13 StringBuilder title = new StringBuilder();14 for (String w : t.split(" ")) {15 if (w.length() > longest.length()) longest = w;16 title.append(Character.toUpperCase(w.charAt(0))).append(w.substring(1)).append(' ');17 }18 System.out.println("Longest word: " + longest);19 System.out.println(title.toString().trim());20 }21}
equals (never ==) for text, equalsIgnoreCase for usernames, and mask the password with repeat.1import java.util.Scanner;23public class Login {4 public static void main(String[] args) {5 final String USER = "librarian", PASS = "Books@123";6 Scanner sc = new Scanner(System.in);7 boolean in = false;8 for (int attempt = 1; attempt <= 3 && !in; attempt++) {9 System.out.print("Username: ");10 String u = sc.nextLine().trim();11 System.out.print("Password: ");12 String p = sc.nextLine();13 System.out.println(" (you typed " + "*".repeat(p.length()) + ")");14 if (u.equalsIgnoreCase(USER) && p.equals(PASS)) {15 in = true;16 System.out.println("Welcome, " + u + "!");17 } else {18 System.out.println("Wrong details. Attempts left: " + (3 - attempt));19 }20 }21 if (!in) System.out.println("Account locked. Contact admin.");22 }23}
length() with bracketscharAt, substring, indexOf, contains, replace, trim, splitequals(), never ==String.format and String.join; parse with Integer.parseIntStringBuilder for building text in loops"Ranchi".substring(1, 4) is...
The right way to compare two Strings' text is...
Which is changeable (mutable)?
You finished Methods, Arrays & Strings: 3 modules and 30 practice examples.
D:\java-practice\part2java -versionD:\java-practicejava Main.java