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

Methods, Arrays & Strings

Organise code into methods, store many values in arrays, and master text with String and StringBuilder.

3 modules~14 hours30 practice examplesNeeds Part 1

By the end of this part you can build

  • Reusable GST, EMI and grade methods
  • A class marks analyser with arrays
  • A seating chart with 2D arrays
  • A username generator and a password checker

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

ROADMAP FOR THIS PART

Module 6Methods: Reusable Blocks of Code4.5 h
Module 7Arrays: Storing Many Values5 h
Module 8Strings and StringBuilder4.5 h
{ } Java java Main.java main()
JavaBefore we begin

How to Use This Part

Suggested teaching hours per module (Part 2)0244.5 hM65 hM74.5 hM8

Every module has

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

Methods: Reusable Blocks of Code

⏱ 4.5 hours10 practice examplesStep-through animationsCode Lab

You will learn

  • Why methods: reuse, organise, test
  • Defining and calling static methods
  • Parameters, arguments and return values
  • Method overloading, varargs and scope
  • Pass-by-value and recursion

You will build

  • Reusable GST, EMI and grade methods
  • A prime-number checker
  • A menu calculator built from methods
void f()static double gst(double a)return total;
Module 6Real-world use

Where Is This Used in Real Projects?

methodswrite once, use everywhere🧾BillingcalculateGst()🔐LogincheckPassword()📧NotificationssendSms()📅DatesdaysBetween()🎮GamesmovePlayer()🌐Web APIsone method per URL

Real projects that use this

  • Every real program is built from methods: an e-commerce backend has addToCart(), applyCoupon(), placeOrder()
  • Write calculateGst() once and use it on every bill
  • Spring Boot web apps map each URL to a Java method
  • Teams divide work by methods and test each one separately (JUnit)
Module 6The idea

A Method Is a Machine: Inputs In, Answer Out

arguments1000, 18gst(amount, rate)does the workreturn180.0
staticno object
needed
doublereturn
type
gstname
(double amount, double rate)parameters
{ ... }body
💡 Concept in shortA method is a named block of code that does one job. You define it once and call it many times. It can take parameters (inputs) and return a result.
♻

Reuse

Write the logic once; call it from anywhere.
📦

Organise

Big programs become small, named pieces.
🔧

Fix once

Change GST from 18% to 12% in one place.
RememberYou already use methods: println(), nextInt(), Math.sqrt(). Now you will write your own.
Module 6Define and call

Defining and Calling Methods

Main.java  JAVA
1public class Main {
2 static void greet() { // no input, no output
3 System.out.println("Namaste! Welcome to BrainBit Infotech.");
4 }
5
6 static void greetStudent(String name, String course) {
7 System.out.println("Hello " + name + ", welcome to " + course + "!");
8 }
9
10 static double gst(double amount, double rate) {
11 return amount * rate / 100; // send the answer back
12 }
13
14 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}
Terminal
D:\java-practice> java Main.java
Namaste! Welcome to BrainBit Infotech.
Hello Riya, welcome to Core Java!
GST on 1000 = 180.0
GST on 2499 = 449.82
💡 Concept in shortvoid 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.
  1. 1
    Methods are written inside the class, outside main
  2. 2
    static lets main call them directly (objects come in Module 9)
  3. 3
    Call with the name and arguments: gst(1000, 18)
  4. 4
    Store or use the returned value
Module 6Watch a call

Step Through: What Happens When a Method Is Called

Watch the purple "Inside area()" box: each call gets its own fresh variables (a new stack frame) that disappear when the method returns.

Main.java  JAVA
1public class Main {
2 static int area(int length, int breadth) {
3 int a = length * breadth;
4 return a;
5 }
6
7 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}
Output
Module 6return vs print

Return a Value vs Print It

Main.java  JAVA
1public class Main {
2 static void printTotal(double price, int qty) {
3 System.out.println("Total: " + price * qty); // only shows it
4 }
5
6 static double total(double price, int qty) {
7 return price * qty; // gives it back
8 }
9
10 static boolean isAdult(int age) {
11 return age >= 18;
12 }
13
14 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 maths
17 System.out.println("Bill: " + bill);
18 if (isAdult(19)) {
19 System.out.println("Can open a bank account alone");
20 }
21 }
22}
Terminal
D:\java-practice> java Main.java
Total: 182.0
Bill: 422.0
Can open a bank account alone
💡 Concept in shortA method that calculates should 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.
Common mistakereturn also ends the method immediately. Code after it in the same block is unreachable.
Module 6Overloading

Method Overloading: Same Name, Different Parameters

Main.java  JAVA
1public class Main {
2 static double area(double side) { // square
3 return side * side;
4 }
5 static double area(double length, double breadth) { // rectangle
6 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 }
12
13 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}
Terminal
D:\java-practice> java Main.java
Square : 25.0
Rectangle: 96.0
Triangle : 6.0
💡 Concept in shortOverloading = several methods with the same name but a different number or type of parameters. Java picks the right one from the arguments you pass.
RememberSystem.out.println is overloaded: one version for int, one for double, one for String, and more.
Module 6Pass by value

Pass-by-Value: The Method Gets a Copy

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.

Main.java  JAVA
1public class Main {
2 static void addBonus(int marks) {
3 marks = marks + 5;
4 System.out.println("Inside method: " + marks);
5 }
6
7 static void addBonusAll(int[] marks) {
8 marks[0] = marks[0] + 5;
9 }
10
11 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}
Output
Module 6Scope and varargs

Variable Scope and Varargs (...)

Main.java  JAVA
1public class Main {
2 static final double GST = 18; // class-level constant: visible to all methods
3
4 static int sum(int... nums) { // any number of ints
5 int total = 0; // local: only inside sum()
6 for (int n : nums) {
7 total += n;
8 }
9 return total;
10 }
11
12 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 loop
18 }
19 // System.out.println(square); // ERROR: square is out of scope
20 System.out.println("GST rate: " + GST);
21 }
22}
Terminal
D:\java-practice> java Main.java
170
373
0
GST rate: 18.0
💡 Concept in shortA variable lives only inside the block { } where it is declared (its scope). Varargs int... nums accepts any number of arguments as an array.
RememberString.format and printf use varargs: that is why they accept any number of values.
Module 6Recursion

Recursion: A Method That Calls Itself

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).

Main.java  JAVA
1public class Main {
2 static int factorial(int n) {
3 if (n <= 1) {
4 return 1;
5 }
6 return n * factorial(n - 1);
7 }
8
9 public static void main(String[] args) {
10 int f = factorial(4);
11 System.out.println("4! = " + f);
12 }
13}
Output
Module 6Hands-on

Code Lab: Try It Yourself

Main.java
Output of the starter code
D:\java-practice> java Main.java
Aman 82.4% A
Priya 93.6% A+
Rahul 60.2% B
Change the code, then run it on your computer: ⬇ Download → open a terminal in that folder → java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).
Your tasks
  1. Add static boolean isPass(double pct) (true when pct >= 33)
  2. Overload percentage(int obtained) that assumes total 500
  3. Write static double average(int... nums)
  4. Add a Javadoc comment /** ... */ above grade()
PracticePractice 1 of 10 · Easy

Greeting Method

EasyScenario. A coaching centre app greets each new student by name and course.
💡 Concept used: A void method with parameters does a job but returns nothing.

Your tasks

  1. Write static void welcome(String name, String course)
  2. Call it for 3 students
  3. Add a line printing the batch time
🏢 Used in real projects: Notification services call one message method for every user.
Welcome.java  JAVA
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 }
7
8 public static void main(String[] args) {
9 welcome("Riya", "Core Java");
10 welcome("Aman", "Python");
11 welcome("Sana", "Web Design");
12 }
13}
PracticePractice 2 of 10 · Easy

Area Methods

EasyScenario. A builder needs areas of rooms and circular tanks many times a day.
💡 Concept used: Methods that return double can be used directly inside println and calculations.

Your tasks

  1. Write rectangleArea(l, b) and circleArea(r)
  2. Use them for 2 rooms and 1 tank
  3. Print the total area
🏢 Used in real projects: Estimation software reuses small calculation methods everywhere.
Areas.java  JAVA
1public class Areas {
2 static double rectangleArea(double l, double b) {
3 return l * b;
4 }
5
6 static double circleArea(double r) {
7 return Math.PI * r * r;
8 }
9
10 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}
PracticePractice 3 of 10 · Easy

Boolean Check Methods

EasyScenario. A form validator needs yes/no checks for numbers.
💡 Concept used: A method returning boolean can be used directly in an if.

Your tasks

  1. Write isEven(int), isPositive(int), inRange(int, int, int)
  2. Test them with a few values
  3. Use them inside if statements
🏢 Used in real projects: Validation libraries are collections of small boolean methods.
Checks.java  JAVA
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; }
5
6 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}
PracticePractice 4 of 10 · Easy

Max of Three with a Method

EasyScenario. A sports app finds the best of three attempts for many athletes.
💡 Concept used: A method can call another method: max3 uses Math.max.

Your tasks

  1. Write static double max3(double a, double b, double c)
  2. Call it for 3 athletes
  3. Print each athlete's best
🏢 Used in real projects: Leaderboards reuse a "best of" method for every player.
Best.java  JAVA
1public class Best {
2 static double max3(double a, double b, double c) {
3 return Math.max(a, Math.max(b, c));
4 }
5
6 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}
PracticePractice 5 of 10 · Easy

GST Method with Default Rate (Overloading)

EasyScenario. A billing app usually charges 18% GST but food items use 5%.
💡 Concept used: Overloading can provide a "default" version that calls the full version.

Your tasks

  1. Write addGst(double price, double rate)
  2. Overload addGst(double price) that uses 18
  3. Print bills for 3 items
🏢 Used in real projects: Tax engines in billing software expose overloaded methods with sensible defaults.
GstMethods.java  JAVA
1public class GstMethods {
2 static double addGst(double price, double rate) {
3 return Math.round(price * (1 + rate / 100) * 100) / 100.0;
4 }
5
6 static double addGst(double price) {
7 return addGst(price, 18); // default rate
8 }
9
10 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}
PracticePractice 6 of 10 · Medium

Prime Checker Used in a Loop

MediumScenario. A maths club lists primes; the check should be a reusable method.
💡 Concept used: Moving logic into a method makes the loop short and readable; return exits early.

Your tasks

  1. Write static boolean isPrime(int n)
  2. Return false as soon as a divisor is found
  3. Use it to print primes from 1 to 60
  4. Count twin primes (p and p+2 both prime)
🏢 Used in real projects: Security code (RSA keys) and hashing use prime checks.
PrimeMethod.java  JAVA
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 }
9
10 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}
PracticePractice 7 of 10 · Medium

Factorial: Loop vs Recursion

MediumScenario. Compare two ways to compute factorials and see where recursion is natural.
💡 Concept used: Iteration uses a loop; recursion calls itself with a smaller problem until the base case.

Your tasks

  1. Write factLoop(int n) with a for loop
  2. Write factRec(int n) recursively
  3. Use long to avoid overflow
  4. Print both for 1, 5, 10, 20
🏢 Used in real projects: Probability, combinations (nCr) and many algorithms use factorials.
Factorial.java  JAVA
1public 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 }
7
8 static long factRec(int n) {
9 if (n <= 1) return 1;
10 return n * factRec(n - 1);
11 }
12
13 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}
PracticePractice 8 of 10 · Medium

Recursion Toolkit

MediumScenario. Practise recursion with three classic interview problems.
💡 Concept used: Each recursive method needs a base case and a smaller sub-problem.

Your tasks

  1. power(base, exp)
  2. digitSum(n)
  3. fib(n) (Fibonacci)
  4. reverse(String) using substring
🏢 Used in real projects: Recursion powers folder scanning, menu trees, JSON parsing and divide-and-conquer algorithms.
RecursionKit.java  JAVA
1public 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 }
18
19 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}
PracticePractice 9 of 10 · Hard

EMI Planner Built from Methods

HardScenario. A showroom compares EMIs for several tenures using small methods.
💡 Concept used: Break a problem into methods: one calculates, one formats, main coordinates. Varargs takes any number of tenures.

Your tasks

  1. emi(principal, rate, months) returns the EMI
  2. printPlan(principal, rate, int... years) prints a row per tenure
  3. Show total interest per row
  4. Call it for two interest rates
🏢 Used in real projects: Loan comparison tools on bank and NBFC websites call one EMI method with many inputs.
EmiPlanner.java  JAVA
1public 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 }
7
8 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 }
15
16 public static void main(String[] args) {
17 printPlan(85000, 9.5, 1, 2, 3);
18 printPlan(85000, 11.0, 2, 3);
19 }
20}
PracticePractice 10 of 10 · Hard

Menu Calculator from Methods

HardScenario. A school calculator offers operations from a menu; each operation is its own method.
💡 Concept used: Main handles the menu loop; each method does one job (single responsibility). switch calls the right one.

Your tasks

  1. Methods: add, subtract, multiply, divide (handles 0), power
  2. A do-while menu loop
  3. Read two numbers per operation
  4. Exit with 0
🏢 Used in real projects: Every real application separates the user interface (menu) from the logic (methods), which makes testing easy.
MenuCalc.java  JAVA
1import java.util.Scanner;
2
3public 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); }
9
10 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}
Module 6Recap

Module 6 Recap & Quiz

What you learned

  • 1A method = named block: static returnType name(params) { ... }
  • 2void returns nothing; other methods must return a value
  • 3Overloading: same name, different parameter lists
  • 4Java passes a copy: primitives are safe; arrays/objects share the same object
  • 5Scope: a variable lives inside its { }; varargs int... nums
  • 6Recursion: a method calling itself with a base case

Quick quiz

What does a void method return?

void means no return value.

static int f(int x) and static int f(double x) is called...

Same name, different parameter types.

A recursive method without a base case causes...

The call stack fills up.
MODULE 7

Arrays: Storing Many Values

⏱ 5 hours10 practice examplesStep-through animationsCode Lab

You will learn

  • Declare, create and initialise arrays
  • Index, length and looping (for and for-each)
  • Arrays live on the heap: references
  • The Arrays utility class: sort, search, copy, fill
  • 2D arrays (tables / matrices)

You will build

  • Class marks analyser
  • Monthly electricity bill chart
  • Cinema seat booking with a 2D array
int[ ]int[] marks = new int[5];Arrays.sort(a)
Module 7Real-world use

Where Is This Used in Real Projects?

arraysone name, many values📊Reportsmarks, sales per month🎬Bookingseat grids🎮Gamesboards, tiles📷Imagespixel grids🎵Audiosample buffers📈Chartsdata points

Real projects that use this

  • A school ERP stores the 5 subject marks of a student in one int[]
  • A cinema app stores seats as a 2D boolean[][]
  • Images are 2D arrays of pixels; Java's ArrayList is built on an array inside
  • main(String[] args) itself receives an array
Module 7The idea

An Array Is a Row of Numbered Boxes

int[] marks = {78, 92, 65, 88, 71};78[0]92[1]65[2]88[3]71[4]index starts at 0 • marks.length = 5 • last index = length - 1 = 4one variable, many values, same type
💡 Concept in shortAn array stores a fixed number of values of the same type under one name. Each box has an index starting from 0. Read with marks[2], change with marks[2] = 70;.
CodeMeans
int[] a = new int[5];5 boxes, all 0
int[] a = {78, 92, 65};create + fill
a[0]first element
a.lengthhow many (no brackets)
a[a.length - 1]last element
RememberSize is fixed once created. Need a list that grows? Use ArrayList (Module 15).
Module 7Create and use

Creating, Reading and Changing an Array

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 int[] marks = {78, 92, 65, 88, 71}; // create and fill
4 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]);
8
9 marks[2] = 70; // re-test: change a value
10 System.out.println("Third after re-test: " + marks[2]);
11
12 double[] prices = new double[3]; // 3 boxes, default 0.0
13 prices[0] = 45.5;
14 prices[1] = 120;
15 System.out.println(prices[0] + ", " + prices[1] + ", " + prices[2]);
16
17 String[] cities = {"Ranchi", "Jamshedpur", "Dhanbad"};
18 System.out.println("Capital: " + cities[0]);
19 }
20}
Terminal
D:\java-practice> java Main.java
First : 78
Third : 65
Count : 5
Last : 71
Third after re-test: 70
45.5, 120.0, 0.0
Capital: Ranchi
💡 Concept in shortnew 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 ().
Module 7Animation

Watch Array Operations Step by Step

int[] marks

0
78
1
92
2
65
3
88
4
71
int[] marks = {78, 92, 65, 88, 71};
Starting value.
💡 Concept in shortEvery operation on an array uses an index. Changing marks[2] changes only that one box; the size never changes.
Common mistakeSwapping two elements always needs a temporary variable, otherwise one value is lost.
Module 7Loop through

Step Through: Sum and Average with a Loop

Electricity units for 4 months (JBVNL bill). The loop counter i walks from index 0 to length - 1.

Main.java  JAVA
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}
Output
Module 7for-each

The Enhanced for (for-each) Loop

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 int[] runs = {45, 12, 78, 33, 101, 8};
4
5 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);
13
14 String[] players = {"Ishan", "Saurabh", "Varun"};
15 for (String p : players) {
16 System.out.println("Player: " + p);
17 }
18 }
19}
Terminal
D:\java-practice> java Main.java
Highest score : 101
50+ scores : 2
Player: Ishan
Player: Saurabh
Player: Varun
💡 Concept in shortfor (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.
NeedUse
Read every valuefor-each
Know the positionfor (int i...)
Change elementsfor (int i...)
Go backwardsfor (int i = n-1; i >= 0; i--)
Module 7Memory

Arrays Live on the Heap: Variables Hold a Reference

STACK (method variables)HEAP (objects)a@ refb@ refn5int[] (on heap)[0]=10 [1]=20 [2]=30
jshell (Java interactive shell)
// jshell: type Java and see the answer at once. Press Next line.
0 / 8
💡 Concept in shortint[] 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.
📋

Need a real copy?

int[] c = Arrays.copyOf(a, a.length); or a.clone()
⚖

Comparing arrays

== checks same object; Arrays.equals(a, c) checks same values.
RememberThis is why a method that receives an array can change it (Module 6, pass-by-value of the reference).
Module 7Arrays class

java.util.Arrays: Ready-Made Tools

Main.java  JAVA
1import java.util.Arrays;
2
3public 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 nicely
7
8 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));
12
13 int[] seats = new int[6];
14 Arrays.fill(seats, -1); // -1 = empty seat
15 System.out.println("Seats : " + Arrays.toString(seats));
16
17 String[] names = {"Sneha", "Aman", "Ravi"};
18 Arrays.sort(names); // alphabetical
19 System.out.println("Names : " + Arrays.toString(names));
20 System.out.println("Sum : " + Arrays.stream(marks).sum());
21 }
22}
Terminal
D:\java-practice> java Main.java
[78, 92, 65, 88, 71]
Sorted : [65, 71, 78, 88, 92]
Index of 88: 3
Seats : [-1, -1, -1, -1, -1, -1]
Names : [Aman, Ravi, Sneha]
Sum : 394
💡 Concept in shortjava.util.Arrays has static methods for common jobs. Printing an array directly shows a code like [I@1b6d3586; use Arrays.toString() instead.
MethodDoes
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?
Module 7Errors

ArrayIndexOutOfBoundsException

Main.java  JAVA
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}
Terminal
D:\java-practice> java Main.java
Subject 1: 78
Subject 2: 92
Subject 3: 65
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at Main.main(Main.java:5)
💡 Concept in shortValid indexes are 0 to length - 1. Asking for marks[3] in a 3-element array crashes the program with ArrayIndexOutOfBoundsException.
Common mistakeThe classic off-by-one bug: i <= marks.length. Always write i < marks.length.
RememberRead the error: it tells you the bad index (3) and the length (3), plus the line number.
Module 72D arrays

2D Arrays: Tables of Rows and Columns

[0] Maths[1] Sci[2] Eng[0] Aman788590[1] Priya627058[2] Rahul958892marks[1][2] = 58 (row 1, column 2)
💡 Concept in shortA 2D array is an array of arrays: like a table. marks[row][col]. marks.length = rows, marks[0].length = columns.
📄 Declare a 2D array (file on disk)TXT
1int[][] marks = {
2 {78, 85, 90}, // Aman
3 {62, 70, 58}, // Priya
4 {95, 88, 92} // Rahul
5};
6int[][] seats = new int[10][12]; // 10 rows x 12 seats
RememberUsed for cinema seats, chess boards, timetables, spreadsheets and image pixels.
Module 7Nested loops

Looping Through a 2D Array: Report Card Totals

Main.java  JAVA
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}
Terminal
D:\java-practice> java Main.java
Name Maths Sci Eng Total
Aman 78 85 90 253
Priya 62 70 58 190
Rahul 95 88 92 275
💡 Concept in shortThe outer loop picks a row; the inner loop visits every column of that row. Reset per-row totals inside the outer loop.
Module 7Chart

From Array to Chart: Monthly Electricity Units

units[] for 6 months (orange = above 130)050100150200110Jan95Feb120Mar150Apr185May170Jun
💡 Concept in shortDashboards and apps keep data in arrays and draw one bar per element. The loop that prints a text chart is the same loop a chart library uses.
📄 Text bar chart in Java (file on disk)TXT
1int[] units = {110, 95, 120, 150, 185, 170};
2for (int u : units) {
3 System.out.println("#".repeat(u / 10) + " " + u);
4}
Module 7Hands-on

Code Lab: Try It Yourself

Main.java
Output of the starter code
D:\java-practice> java Main.java
Mon ** 32
Tue ***** 35
Wed ******** 38
Thu *********** 41
Fri ********* 39
Sat ****** 36
Sun *** 33
Hottest: 41
[32, 35, 38, 41, 39, 36, 33]
Change the code, then run it on your computer: ⬇ Download → open a terminal in that folder → java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).
Your tasks
  1. Also print the day of the hottest temperature
  2. Print the average temperature (2 decimals)
  3. Count days above 35
  4. Print the temperatures in reverse order
PracticePractice 1 of 10 · Easy

Subject Marks Card

EasyScenario. A student's 5 subject marks are stored in one array and printed as a card.
💡 Concept used: Two arrays with matching indexes (parallel arrays): subjects[i] goes with marks[i].

Your tasks

  1. Arrays for subject names and marks
  2. Print each subject with its mark
  3. Print total and percentage
🏢 Used in real projects: School ERP report cards are built from arrays of marks.
MarksCard.java  JAVA
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}
PracticePractice 2 of 10 · Easy

Highest and Lowest Price

EasyScenario. A vegetable vendor at Ranchi's Daily Market tracks tomato prices for a week.
💡 Concept used: Start max/min with the first element, then compare every element in a loop.

Your tasks

  1. Store 7 prices
  2. Find the highest and lowest
  3. Print the difference
🏢 Used in real projects: Price trackers on shopping apps show the highest and lowest price of a product.
PriceRange.java  JAVA
1public class PriceRange {
2 public static void main(String[] args) {
3 int[] price = {40, 38, 45, 52, 47, 35, 42}; // Rs per kg
4 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}
PracticePractice 3 of 10 · Easy

Count Pass and Fail

EasyScenario. A teacher wants to know how many students passed (33 or more).
💡 Concept used: Counting with an if inside a for-each loop.

Your tasks

  1. Store 10 marks
  2. Count pass and fail
  3. Print the pass percentage
🏢 Used in real projects: Result analysis dashboards count values that meet a condition.
PassCount.java  JAVA
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}
PracticePractice 4 of 10 · Easy

Linear Search for a Roll Number

EasyScenario. The office searches a roll number list to find a student's position.
💡 Concept used: Linear search checks each element until it finds the target; -1 means "not found".

Your tasks

  1. Write static int find(int[] a, int key)
  2. Return the index or -1
  3. Search for a present and an absent roll number
🏢 Used in real projects: Every "search" box starts with this idea; databases make it faster with indexes.
Search.java  JAVA
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 }
8
9 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}
PracticePractice 5 of 10 · Easy

Reverse and Rotate

EasyScenario. A digital signboard scrolls a message by rotating an array.
💡 Concept used: Swap from both ends towards the middle to reverse; shift elements to rotate.

Your tasks

  1. Reverse an array in place
  2. Rotate it left by 1
  3. Print after each step with Arrays.toString
🏢 Used in real projects: Carousels, playlists and round-robin schedulers rotate arrays.
ReverseRotate.java  JAVA
1import java.util.Arrays;
2
3public 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));
10
11 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}
PracticePractice 6 of 10 · Medium

Electricity Bill Analyser

MediumScenario. A JBVNL consumer checks 12 months of units: total bill, peak month, months above average.
💡 Concept used: Combining several array passes: sum, max with index, and a second loop compared with the average.

Your tasks

  1. Store 12 monthly units and month names
  2. Total units and bill at Rs 6.30 per unit
  3. Find the peak month
  4. List months above average
🏢 Used in real projects: Utility company apps show exactly this analysis on your bill page.
BillAnalyser.java  JAVA
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}
PracticePractice 7 of 10 · Medium

Frequency Counter (Dice Rolls)

MediumScenario. A board-game app checks whether its dice is fair by counting faces.
💡 Concept used: Use the value itself as an index: count[face]++. A very common array trick.

Your tasks

  1. Roll a dice 600 times with a seeded Random
  2. Count each face in int[7]
  3. Print a star chart
🏢 Used in real projects: Analytics counts events per category (votes per party, orders per hour) with count arrays.
DiceCount.java  JAVA
1import java.util.Random;
2
3public class DiceCount {
4 public static void main(String[] args) {
5 Random rnd = new Random(7);
6 int[] count = new int[7]; // index 1..6 used
7 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}
PracticePractice 8 of 10 · Medium

Bubble Sort with Pass Display

MediumScenario. Understand how sorting works by writing bubble sort and printing every pass.
💡 Concept used: Bubble sort compares neighbours and swaps; after each pass the largest value "bubbles" to the end.

Your tasks

  1. Implement bubble sort on 6 values
  2. Print the array after each pass
  3. Stop early if no swaps happen
  4. Count total swaps
🏢 Used in real projects: Interviews ask for sorting algorithms; in real projects you call Arrays.sort, which uses faster algorithms.
Bubble.java  JAVA
1import java.util.Arrays;
2
3public 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}
PracticePractice 9 of 10 · Hard

Cinema Seat Booking (2D Array)

HardScenario. A Ranchi multiplex screen has 5 rows (A-E) x 8 seats. Book seats and show the map.
💡 Concept used: A 2D boolean[][] marks booked seats; a method books a seat and refuses double booking.

Your tasks

  1. boolean[][] seats = new boolean[5][8]
  2. book(row, seat) returns true/false
  3. Print the seat map with [ ] and [X]
  4. Count available seats
🏢 Used in real projects: BookMyShow-style seat maps are 2D arrays rendered as buttons.
Cinema.java  JAVA
1public class Cinema {
2 static boolean[][] seats = new boolean[5][8];
3
4 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 }
10
11 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}
PracticePractice 10 of 10 · Hard

Class Result Matrix with Toppers

HardScenario. Marks of 4 students in 4 subjects: find each student's total, each subject's average and the subject toppers.
💡 Concept used: Row-wise and column-wise traversal of a 2D array; parallel name arrays.

Your tasks

  1. Row totals and percentage per student
  2. Column averages per subject
  3. Topper in each subject
  4. Overall class topper
🏢 Used in real projects: Exam result portals and spreadsheets do exactly these row and column calculations.
ResultMatrix.java  JAVA
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}
Module 7Recap

Module 7 Recap & Quiz

What you learned

  • 1int[] a = {..} or new int[n]; index 0 to length - 1
  • 2a.length (no brackets); loops: for and for-each
  • 3Array variables hold a reference: b = a shares, it does not copy
  • 4Arrays.toString / sort / fill / copyOf / equals / binarySearch
  • 5Out of range index -> ArrayIndexOutOfBoundsException
  • 62D: int[][] m, m[row][col], nested loops

Quick quiz

Last index of an array of length 10?

Indexes run from 0 to length - 1.

new boolean[3] contains...

Default value for boolean is false.

After int[] b = a; b[0] = 5; what is a[0]?

a and b refer to the same array.
MODULE 8

Strings and StringBuilder

⏱ 4.5 hours10 practice examplesStep-through animationsCode Lab

You will learn

  • String methods: length, charAt, substring, indexOf
  • Comparing strings: equals vs ==
  • Strings are immutable; the String pool
  • split, join, format, char checks
  • StringBuilder for fast building

You will build

  • A username and password validator
  • A PAN / vehicle number checker
  • An SMS bill and receipt builder
"abc"s.substring(0, 3)new StringBuilder()
Module 8Real-world use

Where Is This Used in Real Projects?

Stringstext is everywhere👤Sign-up formsname, email checks🔍Searchcontains, indexOf🧾Receiptsformat, padding📧Emails/SMStemplates📄Files/CSVsplit lines🌐URLs/JSONparsing text

Real projects that use this

  • Almost every input from a user, file, or website arrives as a String
  • Validators check email, mobile and PAN formats with String methods
  • Reports and receipts use String.format for neat columns
  • Log and message builders use StringBuilder for speed
Module 8The idea

A String Is a Sequence of Characters

String city = "RANCHI";   city.length() = 6
0
R
1
A
2
N
3
C
4
H
5
I
city.substring( , )
💡 Concept in shortA String is text inside double quotes. Each character has an index from 0. substring(a, b) gives characters from index a up to (not including) b.
CodeResult
city.length()6
city.charAt(0)'R'
city.substring(3)"CHI"
city.indexOf("CH")3
city.toLowerCase()"ranchi"
RememberChange the numbers or click a preset. Notice the end index is excluded.
Module 8Try methods

Common String Methods in jshell

jshell (Java interactive shell)
// jshell: type Java and see the answer at once. Press Next line.
0 / 13
💡 Concept in shortString methods return a new value; they never change the original string. Chain them: name.trim().toUpperCase().
MethodUse
trim() / strip()remove outer spaces
contains(x)is x inside?
startsWith / endsWithcheck ends
indexOf(x)position, -1 if absent
replace(a, b)swap text
isEmpty / isBlankempty checks
Module 8Compare

Comparing Strings: equals() vs ==

Main.java  JAVA
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("City: ");
7 String city = sc.nextLine();
8
9 System.out.println("== says : " + (city == "Ranchi")); // compares addresses!
10 System.out.println("equals says : " + city.equals("Ranchi")); // compares text
11 System.out.println("ignoring case : " + city.equalsIgnoreCase("RANCHI"));
12 System.out.println("compareTo : " + "Aman".compareTo("Bina")); // negative: Aman first
13 }
14}
Terminal
D:\java-practice> java Main.java
City: Ranchi
== says : false
equals says : true
ignoring case : true
compareTo : -1
💡 Concept in short== checks whether two variables point to the same object. equals() checks whether the text is the same. For Strings, always use equals().
Common mistakeTyped input is a new String object, so == gives false even though the text matches. This bug is very common in login code.
RemembercompareTo returns negative, 0 or positive: used for alphabetical sorting.
Module 8Immutable

Strings Are Immutable: Methods Make New Strings

city"ranchi"old object (unchanged)"RANCHI"new objectcity = city.toUpperCase();
jshell (Java interactive shell)
// jshell: type Java and see the answer at once. Press Next line.
0 / 5
💡 Concept in shortImmutable means a String object can never change. toUpperCase() builds a new String; to keep it, assign it back: city = city.toUpperCase();
🏊

String pool

Literals like "Ranchi" are stored once in a shared pool and reused, saving memory. That is safe only because Strings cannot change.
🔒

Why it matters

Strings are safe to share between methods and threads, and are used as Map keys.
Module 8Characters

Working Character by Character

Main.java  JAVA
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 numbers
15 }
16 System.out.println();
17 }
18}
Terminal
D:\java-practice> java Main.java
Upper 1, lower 5, digits 4, special 1
74 65 86 65
💡 Concept in shortcharAt(i) gives a char. The Character class checks it: isDigit, isLetter, isUpperCase, isWhitespace. toCharArray() gives a char array for for-each.
RememberA password strength meter on a sign-up page counts exactly these four groups.
Module 8split and join

split(), join() and String.format()

Main.java  JAVA
1public class Main {
2 public static void main(String[] args) {
3 String row = "1203,Aditi Kumari,Ranchi,91.5"; // one line of a CSV file
4 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 -> number
8 System.out.println("Pct+5: " + (pct + 5));
9
10 String[] tags = {"java", "oop", "beginner"};
11 System.out.println(String.join(" #", tags));
12
13 String line = String.format("%-12s|%8.2f|", "Notebook", 45.5);
14 System.out.println(line);
15 System.out.println("=".repeat(22));
16 }
17}
Terminal
D:\java-practice> java Main.java
Roll : 1203
Name : Aditi Kumari
Pct+5: 96.5
java #oop #beginner
Notebook | 45.50|
======================
💡 Concept in shortsplit(",") breaks text into an array at each comma. String.join does the opposite. String.format builds formatted text like printf, but returns it.
NeedUse
text -> intInteger.parseInt("42")
text -> doubleDouble.parseDouble("9.5")
number -> textString.valueOf(42)
repeat"-".repeat(10)
Module 8Animation

StringBuilder: Editing Text in Place

StringBuilder sb

0
'J'
1
'a'
2
'v'
3
'a'
StringBuilder sb = new StringBuilder("Java");
Starting value.
💡 Concept in shortStringBuilder is a changeable string. Use it when you build text in a loop: append adds to the same object instead of creating thousands of new Strings.
MethodDoes
append(x)add at end
insert(i, x)add at index
deleteCharAt(i)remove one
reverse()reverse
toString()get a String
Module 8Speed

Why StringBuilder: Building a Long Receipt

Main.java  JAVA
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 Strings
18 long t2 = System.nanoTime();
19 StringBuilder b = new StringBuilder();
20 for (int i = 0; i < 20000; i++) b.append("x"); // one object
21 long t3 = System.nanoTime();
22 System.out.println("\nString += was slower: " + ((t2 - t1) > (t3 - t2)));
23 }
24}
Terminal
D:\java-practice> java Main.java
KUMAR GENERAL STORE, LALPUR
Rice 5kg 320.00
Dal 1kg 140.00
Oil 1L 165.00
-------------------
TOTAL 625.00
 
String += was slower: true
💡 Concept in shortCalls can be chained: sb.append(a).append(b). In a loop, s += x copies the whole string every time; StringBuilder grows one buffer.
Module 8Hands-on

Code Lab: Try It Yourself

Main.java
Output of the starter code
D:\java-practice> java Main.java
Name : Aditi Kumari
Initials : ak
Username : aditi.kumari@school.in
Change the code, then run it on your computer: ⬇ Download → open a terminal in that folder → java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).
Your tasks
  1. Make the initials upper case
  2. Print the name in reverse with StringBuilder
  3. Count the vowels in the name
  4. Check whether the name is a palindrome (ignore case)
PracticePractice 1 of 10 · Easy

Name Formatter

EasyScenario. A school ID card prints names in different styles.
💡 Concept used: Chain String methods: trim, toUpperCase, substring, charAt.

Your tasks

  1. Trim spaces
  2. Print UPPER and lower case
  3. Print the initials and the length
🏢 Used in real projects: ID cards, certificates and email signatures format names like this.
NameFormat.java  JAVA
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}
PracticePractice 2 of 10 · Easy

Email Checker

EasyScenario. A sign-up form does a quick check on email addresses.
💡 Concept used: contains, indexOf, lastIndexOf and endsWith combined with &&.

Your tasks

  1. Must contain exactly one @
  2. Must have a dot after @
  3. Print the username and domain
🏢 Used in real projects: Every registration form validates emails before saving them.
EmailCheck.java  JAVA
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}
PracticePractice 3 of 10 · Easy

Vowel and Word Counter

EasyScenario. A writing app shows word and vowel counts.
💡 Concept used: Loop over characters with charAt; use "aeiou".indexOf(ch) to test vowels; split on spaces for words.

Your tasks

  1. Count vowels and consonants
  2. Count words
  3. Count spaces
🏢 Used in real projects: Word counters in editors and character limits on social media.
Counter.java  JAVA
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}
PracticePractice 4 of 10 · Easy

Palindrome and Reverse

EasyScenario. A word game checks palindromes like "Malayalam" and numbers like 12321.
💡 Concept used: StringBuilder.reverse() plus equalsIgnoreCase; remove spaces with replaceAll.

Your tasks

  1. Reverse with StringBuilder
  2. Check palindrome ignoring case and spaces
  3. Test 4 inputs
🏢 Used in real projects: Interview favourite; real use in data cleaning and string algorithms.
Palindrome.java  JAVA
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 }
6
7 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}
PracticePractice 5 of 10 · Easy

CSV Line Parser

EasyScenario. A coaching centre exports fees as CSV lines. Parse them into a neat table.
💡 Concept used: split + parseInt/parseDouble + String.format for alignment.

Your tasks

  1. Split each line on commas
  2. Convert the fee to a number
  3. Print a formatted table and total
🏢 Used in real projects: Importing Excel/CSV data into an application starts with split.
CsvFees.java  JAVA
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}
PracticePractice 6 of 10 · Medium

Password Strength Meter

MediumScenario. A banking app rates passwords Weak, Medium or Strong.
💡 Concept used: Count character groups with the Character class, then score with if-else.

Your tasks

  1. Check length >= 8
  2. Count upper, lower, digit, special
  3. Score 0-5 and print a rating
  4. Read the password from the keyboard
🏢 Used in real projects: Sign-up pages show this meter as you type.
Strength.java  JAVA
1import java.util.Scanner;
2
3public 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}
PracticePractice 7 of 10 · Medium

Vehicle Number Validator

MediumScenario. A parking app checks Jharkhand registration numbers like JH01AB1234.
💡 Concept used: Check length, prefix and character types at fixed positions; normalise with toUpperCase and replace.

Your tasks

  1. Remove spaces and make upper case
  2. Length must be 10, start with "JH"
  3. Positions 2-3 digits, 4-5 letters, 6-9 digits
  4. Print the district code
🏢 Used in real projects: Toll, parking and traffic apps validate vehicle numbers before searching records.
VehicleNo.java  JAVA
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 }
12
13 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}
PracticePractice 8 of 10 · Medium

SMS Template Filler

MediumScenario. A school sends fee reminder SMS to parents from a template.
💡 Concept used: Replace placeholders with replace, build many messages with StringBuilder, and count SMS parts (160 chars each).

Your tasks

  1. Template with {name}, {amt}, {date}
  2. Fill it for 3 students
  3. Print character count and SMS parts
  4. Collect all messages in one StringBuilder log
🏢 Used in real projects: Bulk SMS and email systems fill templates exactly like this.
SmsTemplate.java  JAVA
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}
PracticePractice 9 of 10 · Hard

Text Analyser: Most Frequent Letter

HardScenario. Analyse a paragraph: letter frequency, longest word, title case.
💡 Concept used: A count array indexed by ch - 'a', plus split and StringBuilder.

Your tasks

  1. Count each letter a-z
  2. Print the top letter and a bar chart of the top 5
  3. Find the longest word
  4. Convert to Title Case
🏢 Used in real projects: Search engines, spell checkers and plagiarism tools start with letter and word statistics.
TextAnalyser.java  JAVA
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}
PracticePractice 10 of 10 · Hard

Simple Login System

HardScenario. A library kiosk allows 3 login attempts with a username and password.
💡 Concept used: Use equals (never ==) for text, equalsIgnoreCase for usernames, and mask the password with repeat.

Your tasks

  1. Stored username/password
  2. Up to 3 attempts in a loop
  3. Username case-insensitive, password case-sensitive
  4. Show a masked password and lock after 3 failures
🏢 Used in real projects: Every login screen compares strings; real systems compare password hashes instead of plain text.
Login.java  JAVA
1import java.util.Scanner;
2
3public 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}
Module 8Recap

Module 8 Recap & Quiz

What you learned

  • 1Strings are objects; index from 0; length() with brackets
  • 2charAt, substring, indexOf, contains, replace, trim, split
  • 3Compare text with equals(), never ==
  • 4Strings are immutable: methods return NEW strings
  • 5String.format and String.join; parse with Integer.parseInt
  • 6StringBuilder for building text in loops

Quick quiz

"Ranchi".substring(1, 4) is...

From index 1 up to (not including) 4.

The right way to compare two Strings' text is...

== compares references.

Which is changeable (mutable)?

String is immutable.
PART 2 COMPLETE

Well done!

You finished Methods, Arrays & Strings: 3 modules and 30 practice examples.

Before moving on

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