Common String methods

Cleaning a typed email, pulling the domain out of it, splitting a CSV line, building an SMS from a template, aligning a receipt: these are everyday jobs for String methods. You'll learn the methods by family, see exactly how indexes and substring work, avoid the classic split and replace traps, and then practise with 13 problems.

Module 4 · Arrays and Strings⏱ 26 minBeginner13 practice problems
1 The story

The messy sign-up list

The college fest sign-up sheet is a mess. People typed " Riya.Sharma@Gmail.COM ", "kabir@yahoo.co.in", "MEERA@gmail.com". Riya has to clean every email, find who used Gmail, and send each person a message starting with their name.

" Riya@Gmail.COM " .trim().toLowerCase() "riya@gmail.com" 0413 indexOf('@') = 4 substring(0, 4) "riya" substring(5) "gmail.com" Each method returns a new, cleaner String. myphatshala.in
Riya

Sir, do I really have to loop through every character with charAt to find the @ and cut the email?

Arjun Sir

No, String already has methods for that. trim() and toLowerCase() clean it, indexOf('@') finds the position, substring cuts out the parts. One line each.

Riya

Do I need to remember all of them?

Arjun Sir

Remember them in families: inspect, search, extract, transform, build. And remember two traps: substring's end index is not included, and split treats its argument as a pattern, not plain text.

2 Definition

What are String methods?

Formal definition (write this in exams)

String methods are instance methods of java.lang.String that inspect, search, extract or transform the characters of a String. Because String is immutable, every method that produces modified text returns a new String and leaves the original unchanged. Index-based methods use positions from 0 to length() - 1; search methods return -1 when nothing is found.

In simple words

Ready-made tools for text: find something, cut a piece, clean it up, join pieces together. They never damage the original; they hand you a new result.

Words you'll meet in this lesson

Begin / end indexIn substring(begin, end), begin is included, end is excluded.
-1What search methods return when the text isn't found.
RegexA pattern language. split and replaceAll use it.
DelimiterThe separator you split on, like a comma.
WhitespaceSpaces, tabs and newlines.
Method chainings.trim().toLowerCase(): each call works on the previous result.

Rules that apply to every method

OriginalNever changed. Store the result: s = s.trim();
Not foundindexOf and lastIndexOf return -1
Rangessubstring(2, 5) → indexes 2, 3, 4 (length 5 − 2 = 3)
Bad indexStringIndexOutOfBoundsException at run time
Called on nullNullPointerException: check for null first
Regex methodssplit, replaceAll, matches: ., |, * and others have special meanings

Exam tip: "Phatshala".substring(2, 5) is "ats": indexes 2, 3, 4. The length of a substring is always end - begin. Many MCQs test whether you include the end index.

3 Types and ways to use it

The methods, by family

FamilyMethodsExample → result
Inspectlength(), charAt(i), isEmpty(), isBlank()" ".isBlank() → true; " ".isEmpty() → false
SearchindexOf, lastIndexOf, contains, startsWith, endsWith"banana".indexOf("an", 2) → 3
Extractsubstring, split, toCharArray"a,b,,c".split(",") → [a, b, , c]
Transformtrim, strip, toUpperCase, toLowerCase, replace, replaceAll, repeat"ab".repeat(3) → "ababab"
Compareequals, equalsIgnoreCase, compareTo (Lesson 4.4)"java".equalsIgnoreCase("JAVA") → true
Build / convertString.join, String.format, String.valueOf, Integer.parseIntString.format("%05d", 42) → "00042"

The most-used methods, verified

public class Main {
    public static void main(String[] args) {
        String t = "  MyPhatshala Java Course  ".trim();
        System.out.println("[" + t + "] length " + t.length());
        System.out.println(t.indexOf("Java") + " " + t.indexOf('a') + " " + t.lastIndexOf('a') + " " + t.indexOf("Python"));
        System.out.println(t.substring(12) + " | " + t.substring(0, 11) + " | " + t.substring(12, 16));
        System.out.println(t.contains("Java") + " " + t.startsWith("My") + " " + t.endsWith("Course"));
        System.out.println(t.replace("Java", "SQL"));
        System.out.println(String.join(" | ", "Pune", "Delhi", "Agra"));
    }
}
[MyPhatshala Java Course] length 23 12 4 15 -1 Java Course | MyPhatshala | Java true true true MyPhatshala SQL Course Pune | Delhi | Agra

replace vs replaceAll, trim vs strip, isEmpty vs isBlank

replace / replaceAll

replace works on plain text (all occurrences). replaceAll takes a regex: replaceAll("[0-9]", "#") hides every digit.

Plain text vs pattern

trim / strip

Both remove spaces at the ends. strip() (Java 11) also understands Unicode spaces; prefer it in new code.

Ends only

isEmpty / isBlank

isEmpty(): length is 0. isBlank() (Java 11): empty or only spaces. Use isBlank for form fields.

"" vs " "

The split trap: split takes a regular expression. "a.b.c".split(".") returns an empty array, because . means “any character”. Write split("\\."). The same applies to |, *, + and ?. Also, trailing empty pieces are dropped: "a,b,,".split(",") has only 2 elements.

4 Step by step

Cleaning and cutting an email

  1. Clean

    String email = raw.trim().toLowerCase();
    trim() returns a new String without outer spaces; toLowerCase() is called on that result and returns another new String. Two objects created, the original untouched.
  2. Find

    int at = email.indexOf('@');
    indexOf scans from index 0 until it finds the character, returning its position, or -1 if it reaches the end.
  3. Cut

    String user = email.substring(0, at);
    String domain = email.substring(at + 1);
    substring(0, at) stops before the @. substring(at + 1) starts just after it and runs to the end. Each creates a new String with copied characters.
  4. Check

    boolean gmail = domain.equals("gmail.com");
    Compare content with equals (Lesson 4.4). Since we lower-cased earlier, "Gmail.COM" also matches.
  5. Build the message

    String msg = String.format("Hi %s, see you at the fest!", user);
    String.format puts values into a pattern: %s for text, %d for whole numbers, %.2f for 2 decimals.
5 See it happen

Indexes, indexOf and substring: both views

Left: each method call and its result. Right: the characters with their index numbers.

Cutting "riya@mail.com" 6 steps
What you see s = " Riya@Mail.com ".trim(); s = s.toLowerCase(); int at = s.indexOf('@'); s.substring(0, at) s.substring(at + 1) String[] parts = s.split("@"); [Riya@Mail.com] length 13 riya@mail.com at → 4 s.indexOf('#') → -1 "riya" (indexes 0..3) "mail.com" (5..12) parts[0] → riya parts[1] → mail.com Outer spaces gone. One more new String. Position of the first '@'. End index 4 is NOT included. From index 5 to the end. split gives an array of pieces. myphatshala.in
Behind the screen Characters and their indexes Rr iya@ Mm ail.com 0123456789101112 " Riya@Mail.com " (16 chars) → 13 chars end = 4 (stop before) "riya" "mail.com" [0] [1] A new String object with 13 characters. Another new String: only the letters' case differs. Scanning stops at index 4. Begin 0 included, end 4 excluded: 4 − 0 = 4 chars. Copies indexes 5 to 12 into a new String. The '@' itself is dropped; pieces go into an array. myphatshala.in
6 Real-world use

String methods in real systems

Most input arrives as text that must be cleaned, checked and taken apart; most output is text that must be built.

Watch it with an example: reading one line of a bank statement

Banks export statements as CSV text. Watch split, substring, contains and trim turn one line into useful data.

Taking a CSV line apart 6 steps
Animated example "26-01-2025,UPI/ZOMATO/Food, -450.00 " parts[0] "26-01-2025" parts[1] "UPI/ZOMATO/Food" parts[2] " -450.00 " year = "2025" isUpi = true amt = -450.0 line.split(",") → 3 parts parts[0].substring(6) → from index 6 parts[1].contains("UPI") Double.parseDouble(parts[2].trim()) Food spend: Rs 450 via UPI in 2025 One String: date, description, amount each method returns a NEW value; line is unchanged myphatshala.in
ORD1,Riya,3ORD2,Kabir,1ORD3,Meera,2

1. Importing files

CSV exports from banks, shops and spreadsheets are read line by line and split into fields; numbers are converted with parseInt and parseDouble.

"ORD1,Riya,3"→split(",")→Order object

2. Form validation and cleaning

Sign-up forms trim inputs, lower-case emails, check isBlank(), confirm a phone number has 10 digits and that a PAN or IFSC code has the right pattern.

Raw input→strip, isBlank, matches→Clean record
Hi {name},order {id}arrives {date}

3. Templates and messages

Emails, SMS and invoices fill placeholders with replace or String.format, and pad numbers into fixed formats like INV-2026-00042.

Template→format / replace→Message
java tips

4. Search and URLs

Simple search boxes use toLowerCase().contains(…); blog and product pages turn titles into URL slugs with replaceAll; apps read query parameters by splitting on & and =.

"Top 10 Java Tips!"→replaceAll→top-10-java-tips

Examples are simplified. Production code uses libraries for complex formats (CSV, JSON, URLs) because of edge cases like quoted commas and encoded characters.

7 Run the code

The email cleaner

public class Main {
    public static void main(String[] args) {
        String raw = "  Riya.Sharma@Gmail.COM ";
        String email = raw.trim().toLowerCase();
        int at = email.indexOf('@');
        String user = email.substring(0, at);
        String domain = email.substring(at + 1);
        System.out.println("Clean:  " + email);
        System.out.println("User:   " + user);
        System.out.println("Domain: " + domain);
        System.out.println("Gmail?  " + domain.equals("gmail.com"));
        boolean valid = at > 0 && email.indexOf('@', at + 1) == -1 && domain.contains(".");
        System.out.println("Valid?  " + valid);
    }
}
Clean: riya.sharma@gmail.com User: riya.sharma Domain: gmail.com Gmail? true Valid? true
  • raw.trim().toLowerCase()Chained calls; the result is stored in a new variable.
  • email.substring(0, at)Everything before the @ (end excluded).
  • email.indexOf('@', at + 1) == -1Searching again after the first @ checks that there is only one.
  • at > 0The @ isn't the first character (and was found at all).
8 Line by line

Counting with indexOf(ch, from)

Each search starts just after the previous match, until indexOf returns -1.

Worked examples: real problems, solved and traced in memory

Three everyday text-processing jobs solved with String methods. Run each solution, then step through it to see every method call and every new String or array it creates.

Example 1Marketing · email list

Which email provider does each customer use?

Problem statement

The marketing team wants to know the email provider (the domain) of each sign-up. Emails arrive with stray spaces and capitals. Write domainOf(email) that returns the domain in lower case.

Input
emails = {" Riya@Gmail.com", "kabir@YAHOO.co.in "}
Expected output
gmail.com
yahoo.co.in

Approach

  1. Clean first: trim() then toLowerCase(), chained.
  2. Find the position of @ with indexOf.
  3. substring(at + 1) takes everything after it.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

Example 2Online store · order import

Read one order line from a CSV file

Problem statement

Orders arrive as CSV lines: id,customer,quantity,price. Split the line, convert the numbers, and print the order total.

Input
line = "ORD7,Meera,3,249.50"
Expected output
ORD7 for Meera: Rs 748.50

Approach

  1. split(",") returns a new String[] with one element per field.
  2. Numbers are still text, so convert with Integer.parseInt and Double.parseDouble.
  3. Multiply and format the total to 2 decimals.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

Example 3Delivery app · SMS

Fill an SMS template

Problem statement

The delivery SMS template is Hi {name}, order {id} arrives {day}. Replace the placeholders with real values using chained replace calls.

Input
name = "Kabir", id = "ORD-1042", day = "today"
Expected output
Hi Kabir, order ORD-1042 arrives today.
Hi {name}, order {id} arrives {day}.

Approach

  1. replace returns a new String with every occurrence replaced (plain text, no regex).
  2. Chain the calls: each one works on the result of the previous one.
  3. Store the final result; the template itself stays reusable because it never changes.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

9 Quiz and revision

Check yourself

Quick revision

Lesson 4.5 in one screen

  • Families: inspect, search, extract, transform, compare, build.
  • All return new Strings: s = s.trim();
  • indexOf / lastIndexOf → position or -1; indexOf(x, from) continues a search.
  • substring(begin, end): end excluded, length = end − begin; substring(begin) to the end.
  • split and replaceAll take regex: escape . as "\\."; "\\s+" for any spaces.
  • isBlank() for form fields; strip() in new code.
  • String.join, repeat, String.format (%s %d %.2f %-10s %05d) build text.

Interview and viva questions

What's the difference between replace() and replaceAll()?

Both replace every occurrence. replace treats its arguments as plain text (char or CharSequence). replaceAll treats the first argument as a regular expression, so special characters like . or $ have meaning and need escaping.

Why is substring's end index exclusive?

It makes the maths simple: the length is end - begin, and adjacent ranges join without overlap, e.g. s.substring(0, i) + s.substring(i) is always the original string.

What's the difference between trim() and strip()?

trim() removes characters with codes up to 32 (space and control characters). strip(), added in Java 11, removes all Unicode whitespace, including special spaces that come from copy-pasted web text.

How do you split a string on a dot or a pipe?

Escape it, because split takes a regex: split("\\."), split("\\|"), or use split(Pattern.quote(".")).

How do you convert between Strings and numbers?

Text to number: Integer.parseInt("42"), Double.parseDouble("3.5") (throws NumberFormatException for bad text). Number to text: String.valueOf(42), Integer.toString(42) or "" + 42.

Practice problems

Now the built-in methods do the heavy lifting. For each problem, first decide which methods you need (indexOf? substring? split?), then write the code. The last four are real business tasks.

P1Easy

Get the domain from an email

Print the part of an email address after the @.

Input
email = "riya.sharma@myphatshala.in"
Expected output
User: riya.sharma
Domain: myphatshala.in
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        String email = "riya.sharma@myphatshala.in";
        int at = email.indexOf('@');
        String user = email.substring(0, at);
        String domain = email.substring(at + 1);
        System.out.println("User: " + user);
        System.out.println("Domain: " + domain);
    }
}
User: riya.sharma Domain: myphatshala.in

How it works: indexOf('@') finds the position (11). substring(0, at) takes everything before it (end index excluded) and substring(at + 1) everything after it.

P2Easy

Count the words

Count the words in a sentence that may have extra spaces at the ends and between words.

Input
text = "  Java   is  fun to   learn "
Expected output
Words: 5
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        String text = "  Java   is  fun to   learn ";
        String t = text.trim();
        int words = t.isEmpty() ? 0 : t.split("\\s+").length;
        System.out.println("Words: " + words);
    }
}
Words: 5

How it works: trim() removes the outer spaces; split("\\s+") splits on one or more whitespace characters. Splitting on a single " " would create empty pieces for the double spaces. The empty check handles a blank sentence.

P3Easy

Allowed file types

An upload form accepts only PDF, JPG and PNG files, in any letter case. Check some file names.

Input
"Resume.PDF", "photo.jpg", "virus.exe", "notes.pdf.exe"
Expected output
Resume.PDF -> accepted
photo.jpg -> accepted
virus.exe -> rejected
notes.pdf.exe -> rejected
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        String[] files = {"Resume.PDF", "photo.jpg", "virus.exe", "notes.pdf.exe"};
        for (String f : files) {
            String name = f.toLowerCase();
            boolean ok = name.endsWith(".pdf") || name.endsWith(".jpg") || name.endsWith(".png");
            System.out.println(f + " -> " + (ok ? "accepted" : "rejected"));
        }
    }
}
Resume.PDF -> accepted photo.jpg -> accepted virus.exe -> rejected notes.pdf.exe -> rejected

How it works: lower-case once, then check the ending. Using contains(".pdf") would wrongly accept “notes.pdf.exe”. (Real upload checks also inspect the file's content, not just its name.)

P4Easy

Fill in a message template

Replace placeholders in an SMS template with real values.

Input
template = "Hi {name}, your order {id} will arrive on {date}."
Expected output
Hi Riya, your order ORD-1042 will arrive on 18 Oct.
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        String template = "Hi {name}, your order {id} will arrive on {date}.";
        String msg = template.replace("{name}", "Riya")
                             .replace("{id}", "ORD-1042")
                             .replace("{date}", "18 Oct");
        System.out.println(msg);
    }
}
Hi Riya, your order ORD-1042 will arrive on 18 Oct.

How it works: each replace returns a new String, so calls can be chained. replace changes every occurrence and treats the text literally (no regex), which makes it safe for placeholders.

P5Medium

Initials from a full name

Print the initials of a full name in capitals, with dots.

Input
name = "riya kumari sharma"
Expected output
R.K.S.
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        String name = "riya kumari sharma";
        String[] parts = name.trim().split("\\s+");
        String initials = "";
        for (String p : parts) {
            initials += Character.toUpperCase(p.charAt(0)) + ".";
        }
        System.out.println(initials);
    }
}
R.K.S.

How it works: split gives an array of words (Lesson 4.1). For each word, charAt(0) is its first letter. Character.toUpperCase works on a single char.

P6Medium

Count a word inside text

Count how many times “java” appears in a paragraph, ignoring case, including overlapping positions.

Input
text = "Java is great. I use JAVA daily; javascript is different."
Expected output
"java" found 3 times
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        String text = "Java is great. I use JAVA daily; javascript is different.";
        String hay = text.toLowerCase(), needle = "java";
        int count = 0, from = 0;
        while ((from = hay.indexOf(needle, from)) != -1) {
            count++;
            from++;
        }
        System.out.println("\"" + needle + "\" found " + count + " times");
    }
}
"java" found 3 times

How it works: indexOf(needle, from) searches starting at from and returns −1 when nothing is left. Moving from forward by 1 after each hit continues the search. Note that “javascript” also contains “java”: plain text search doesn't know about whole words.

P7Medium

Reverse the word order

Reverse the order of words in a sentence (not the letters).

Input
s = "learn Java the visual way"
Expected output
way visual the Java learn
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        String s = "learn Java the visual way";
        String[] w = s.split(" ");
        String result = "";
        for (int i = w.length - 1; i >= 0; i--) {
            result += w[i];
            if (i > 0) result += " ";
        }
        System.out.println(result);
    }
}
way visual the Java learn

How it works: split into an array, then walk it backwards. The if (i > 0) avoids a trailing space. With Java's collections you could also use Collections.reverse and String.join (Module 11).

P8Medium

Title case with substring

Convert a heading to Title Case: first letter of each word upper case, rest lower case.

Input
h = "the JAVA string GUIDE"
Expected output
The Java String Guide
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        String h = "the JAVA string GUIDE";
        String[] words = h.split(" ");
        for (int i = 0; i < words.length; i++) {
            String w = words[i];
            words[i] = w.substring(0, 1).toUpperCase() + w.substring(1).toLowerCase();
        }
        System.out.println(String.join(" ", words));
    }
}
The Java String Guide

How it works: substring(0, 1) is the first letter as a String; substring(1) is the rest. Each word is replaced in the array, then String.join glues them back with spaces.

P9Medium

Is it a rotation?

Check whether one string is a rotation of another (e.g. “tionrota” is a rotation of “rotation”).

Input
a = "rotation", b = "tionrota"
Expected output
tionrota is a rotation of rotation
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        String a = "rotation", b = "tionrota";
        boolean rotation = a.length() == b.length() && (a + a).contains(b);
        System.out.println(b + (rotation ? " is" : " is not") + " a rotation of " + a);
    }
}
tionrota is a rotation of rotation

How it works: doubling “rotation” gives “rotationrotation”, which contains every rotation of it. The length check stops shorter pieces like “tion” from counting. A classic interview trick.

P10Business problem

Parse an order line from a CSV file

Each line of an orders file looks like ORD101,Riya Sharma,3,249.50 (id, customer, quantity, price). Print a readable summary with the total.

Input
line = "ORD101,Riya Sharma,3,249.50"
Expected output
Order ORD101 for Riya Sharma
3 x Rs 249.50 = Rs 748.50
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        String line = "ORD101,Riya Sharma,3,249.50";
        String[] f = line.split(",");
        String id = f[0];
        String customer = f[1].trim();
        int qty = Integer.parseInt(f[2].trim());
        double price = Double.parseDouble(f[3].trim());
        System.out.println("Order " + id + " for " + customer);
        System.out.println(qty + " x Rs " + String.format("%.2f", price) + " = Rs " + String.format("%.2f", qty * price));
    }
}
Order ORD101 for Riya Sharma 3 x Rs 249.50 = Rs 748.50

How it works: split(",") breaks the line into fields. Numbers arrive as text, so Integer.parseInt and Double.parseDouble convert them. Real CSV files can contain commas inside quotes, so production code uses a CSV library.

P11Business problem

Mask an email for display

Show an email as r*********a@mail.com: keep the first and last letter of the user part, hide the rest.

Input
"riya.sharma@mail.com", "ab@mail.com"
Expected output
r*********a@mail.com
a*@mail.com
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        String[] emails = {"riya.sharma@mail.com", "ab@mail.com"};
        for (String email : emails) {
            int at = email.indexOf('@');
            String user = email.substring(0, at);
            String masked;
            if (user.length() <= 2) {
                masked = user.charAt(0) + "*";
            } else {
                masked = user.charAt(0) + "*".repeat(user.length() - 2) + user.charAt(user.length() - 1);
            }
            System.out.println(masked + email.substring(at));
        }
    }
}
r*********a@mail.com a*@mail.com

How it works: "*".repeat(n) (Java 11+) makes n stars. Very short user names are handled separately so nothing breaks. “Forgot password” pages show masked emails so a stranger can't learn someone's full address.

P12Business problem

Make a URL slug

Blog URLs use a “slug”: lower case, words joined by hyphens, no symbols. Turn titles into slugs.

Input
"Top 10 Java Tips for 2026!", "  String vs StringBuilder: Which?  "
Expected output
top-10-java-tips-for-2026
string-vs-stringbuilder-which
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        String[] titles = {"Top 10 Java Tips for 2026!", "  String vs StringBuilder: Which?  "};
        for (String title : titles) {
            String slug = title.trim().toLowerCase()
                               .replaceAll("[^a-z0-9 ]", "")
                               .replaceAll("\\s+", "-");
            System.out.println(slug);
        }
    }
}
top-10-java-tips-for-2026 string-vs-stringbuilder-which

How it works: replaceAll uses a regular expression. [^a-z0-9 ] means “any character that is not a letter, digit or space”, which we delete; then runs of spaces become one hyphen. Clean, readable URLs are also better for search engines.

P13Business problem

Print an aligned receipt

Print a shop receipt with item names left-aligned and amounts right-aligned with 2 decimals.

Input
items: Notebook 2 x 45.00, Gel pen 5 x 12.50, Geometry box 1 x 120.00
Expected output
Item           Qty    Amount
----------------------------
Notebook         2     90.00
Gel pen          5     62.50
Geometry box     1    120.00
----------------------------
TOTAL                 272.50
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        String[] items = {"Notebook", "Gel pen", "Geometry box"};
        int[] qty = {2, 5, 1};
        double[] price = {45.00, 12.50, 120.00};
        double total = 0;
        System.out.println(String.format("%-14s %3s %9s", "Item", "Qty", "Amount"));
        System.out.println("-".repeat(28));
        for (int i = 0; i < items.length; i++) {
            double amount = qty[i] * price[i];
            total += amount;
            System.out.println(String.format("%-14s %3d %9.2f", items[i], qty[i], amount));
        }
        System.out.println("-".repeat(28));
        System.out.println(String.format("%-18s %9.2f", "TOTAL", total));
    }
}
Item Qty Amount ---------------------------- Notebook 2 90.00 Gel pen 5 62.50 Geometry box 1 120.00 ---------------------------- TOTAL 272.50

How it works: in String.format, %-14s pads text to 14 characters on the right (left-aligned), %3d right-aligns a number in 3 spaces, and %9.2f shows 2 decimals in 9 spaces. Fixed widths line the columns up.

Real-world scenario questions (asked in company interviews)

String methods are easy until real data arrives. Decide your answer first, then open the model answer.

DevOps · versionsFresher

The version check that always says “update required”

An app compares versions like "2.10.3" by doing String[] p = version.split("."); and reading p[0]. It crashes with ArrayIndexOutOfBoundsException. Why?

The interviewer is checking: do you know split takes a regular expression?

Show a strong answer
  • In regex, . means “any character”. Every character is a separator, all pieces are empty, and trailing empty pieces are removed, so the array has length 0.
  • Fix: split("\\.") or split(Pattern.quote(".")).
  • Then compare the parts as numbers with Integer.parseInt; comparing "10" and "9" as text says "10" is smaller.

Avoid: comparing whole version strings with compareTo: "2.10.3" sorts before "2.9.0" as text.

Logistics · addressesFresher

PIN code extraction crashes on short addresses

Code takes the last 6 characters of an address as the PIN: addr.substring(addr.length() - 6). It works for most rows but crashes for an address entered as "Pune", and returns garbage like "Road 5" for others. How do you make it robust?

The interviewer is checking: do you validate before cutting, and think about messy input?

Show a strong answer
  • For "Pune", length() - 6 is negative → StringIndexOutOfBoundsException. Always check the length (or the indexOf result) before substring.
  • Position-based cutting assumes a fixed format. Instead, search for a 6-digit number, e.g. with a regex like \\b\\d{6}\\b, or scan tokens from split("\\s+") for one that's 6 digits.
  • Best: collect the PIN in its own form field and validate it there.

Avoid: catching the exception and returning an empty PIN silently. Flag bad records for review.

Finance · data import1–3 years

The CSV import that shifts columns

A bank-statement import uses line.split(","). Two problems appear: rows like 101,"Sharma, Riya",500 get 4 columns instead of 3, and rows ending with empty fields (102,Kabir,,) have fewer columns than expected. Explain both and what you'd do.

The interviewer is checking: do you know split's limits and when to use a proper parser?

Show a strong answer
  • Split doesn't understand CSV quoting, so the comma inside "Sharma, Riya" is treated as a separator.
  • split(",") drops trailing empty strings; split(",", -1) keeps them so the column count stays correct.
  • For real files use a CSV library (for example Apache Commons CSV or OpenCSV), which handles quotes, escaped quotes and line breaks inside fields.
  • Validate the column count of every row and report bad rows instead of guessing.

Avoid: writing your own quote-handling with more and more indexOf calls. It never covers every case.

Global SaaS · localisation1–3 years

Login works everywhere except Turkey

A permission check does if (role.toLowerCase().equals("admin")). Customers in Turkey report that admins named with the role "ADMIN" lose access. Nothing is wrong with their data. What could be happening?

The interviewer is checking: do you know that case conversion depends on the default locale?

Show a strong answer
  • toLowerCase() without arguments uses the JVM's default locale. In Turkish, upper-case I lowers to a dotless ı, so "ADMIN" becomes "admın", which doesn't equal "admin".
  • For identifiers, codes and keys, use toLowerCase(Locale.ROOT), or simply equalsIgnoreCase.
  • Keep locale-sensitive conversion only for text shown to users.
  • Add a test that runs with a Turkish default locale.

Avoid: “It works on my machine.” Server and user locales differ.