ItTechGenie-Subject - Java Strings (Warm-up + 10 Questions)

Java Question Bank

Java Strings | Q0 Warm‑up (Show/Hide Answer) + Q1–Q10 Scenario Questions (5 Moderate + 5 Complex) — With Answers

Instruction: Boilerplate is visible by default. Students implement ONLY methods marked // ✅ TODO.
Answers: Available via Show/Hide Answer.
Warm‑up: 1 (Q0) Moderate: 5 (Q1–Q5) Complex: 5 (Q6–Q10) Inputs: spaces + quotes + unicode α/β + emoji ✅ + special chars
0

Warm‑up: String immutability + == vs equals() + intern() (with answer)

Immutability== vs equalsintern()Warm-up

Warm‑up: You have two strings created in different ways (literal and new String()). Task: 1) Print whether '==' is true/false 2) Print whether equals() is true/false 3) Use intern() and check '==' again Implement ONLY: warmUp() to print 3 lines.

✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Strings scenario (students implement ONLY // ✅ TODO)Ctrl+C
public class Main {
    // ✅ TODO: Student must implement only this method
    static void warmUp() {
        // TODO:
        // - create a as literal, b as new String(...)
        // - print: (a==b), a.equals(b)
        // - intern b and print: (a==bInterned)
        throw new UnsupportedOperationException("TODO");
    }

    public static void main(String[] args) {
        warmUp();
    }
}

Answer (Logic + Code)

Logic: - '==' compares references, not content. - equals() compares content. - intern() returns pooled reference for same content, so '==' can become true.

String a = "Hello α/β ✅";
String b = new String("Hello α/β ✅");

System.out.println("a==b : " + (a == b));
System.out.println("a.equals(b) : " + a.equals(b));

String bi = b.intern();
System.out.println("a==b.intern() : " + (a == bi));
1

Normalize User Input — trim + remove quotes + collapse spaces

trimreplaceregexModerate

Scenario: Your signup form sends messy fullName. Normalize it: - trim - remove wrapping double quotes (if present) - collapse multiple spaces/tabs into one space - keep unicode (α/β) and emoji ✅ as-is Implement ONLY: TextUtil.normalizeName(raw).

✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Strings scenario (students implement ONLY // ✅ TODO)Ctrl+C
class TextUtil {
    // ✅ TODO: Student must implement only this method
    static String normalizeName(String raw) {
        // TODO: null safe + trim + remove surrounding quotes + collapse whitespace
        throw new UnsupportedOperationException("TODO");
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.println(TextUtil.normalizeName("   \"  Gopi   Suresh   α/β ✅  \"    "));
    }
}

Answer (Logic + Code)

Trim, remove outer quotes, collapse whitespace using replaceAll("\\s+", " ").

static String normalizeName(String raw) {
    if (raw == null) return "";
    String s = raw.trim();
    if (s.startsWith(""") && s.endsWith(""") && s.length() >= 2) {
        s = s.substring(1, s.length() - 1).trim();
    }
    s = s.replaceAll("\\s+", " ");
    return s;
}
2

Mask Sensitive Token — keep last 4, mask rest

substringrepeatvalidationModerate

Scenario: Mask a token before logging. Rules: - If length <= 4 => return "****" - Else => "*" repeated (len-4) + last4 - Preserve special chars in last4 (like ✅) Implement ONLY: Masker.maskToken(token).

✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Strings scenario (students implement ONLY // ✅ TODO)Ctrl+C
class Masker {
    // ✅ TODO: Student must implement only this method
    static String maskToken(String token) {
        // TODO: normalize + apply rules
        throw new UnsupportedOperationException("TODO");
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.println(Masker.maskToken("  ORD-αβ-1234✅  "));
    }
}

Answer (Logic + Code)

Use trim; build mask prefix via "*".repeat(n) (Java 11+).

static String maskToken(String token) {
    String t = (token == null ? "" : token.trim());
    if (t.length() <= 4) return "****";
    String last4 = t.substring(t.length() - 4);
    return "*".repeat(t.length() - 4) + last4;
}
3

CSV Builder — Build a line with StringBuilder (avoid + in loop)

StringBuilderCSVescapingModerate

Scenario: Export order item to one CSV line: id,name,qty Rules: - Escape commas by wrapping name in quotes - Escape quotes inside name by doubling them (" -> "") - Use StringBuilder (no string concatenation in loops) Implement ONLY: CsvLine.build(id,name,qty).

✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Strings scenario (students implement ONLY // ✅ TODO)Ctrl+C
class CsvLine {
    // ✅ TODO: Student must implement only this method
    static String build(String id, String name, int qty) {
        // TODO: StringBuilder + escape CSV fields
        throw new UnsupportedOperationException("TODO");
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.println(CsvLine.build("P-α1", "Phone, 6.5\" ✅", 2));
    }
}

Answer (Logic + Code)

StringBuilder avoids many temporary strings; escape inner quotes and quote field when needed.

static String build(String id, String name, int qty) {
    String safeId = (id == null ? "" : id.trim());
    String n = (name == null ? "" : name.trim());

    boolean needsQuotes = n.contains(",") || n.contains(""");
    if (n.contains(""")) n = n.replace(""", """");

    StringBuilder sb = new StringBuilder();
    sb.append(safeId).append(",");
    if (needsQuotes) sb.append(""").append(n).append(""");
    else sb.append(n);
    sb.append(",").append(qty);
    return sb.toString();
}
4

Parse Command Params — Extract key=value pairs (quoted values supported)

scansubstringMapModerate

Scenario: Command string: PAY amount="1200" currency=INR note="alpha β ✅" ref=TXN-001!@# Extract into Map for keys: amount,currency,note,ref. Rules: - Values may be quoted and contain spaces - Keep unicode and special chars Implement ONLY: CommandParser.parse(cmd).

✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Strings scenario (students implement ONLY // ✅ TODO)Ctrl+C
import java.util.*;

class CommandParser {
    // ✅ TODO: Student must implement only this method
    static Map<String,String> parse(String cmd) {
        // TODO: scan string, read key=value, handle quoted values
        throw new UnsupportedOperationException("TODO");
    }
}
public class Main {
    public static void main(String[] args) {
        String cmd = " PAY amount=\"1200\" currency=INR note=\"alpha β ✅\" ref=TXN-001!@# ";
        System.out.println(CommandParser.parse(cmd));
    }
}

Answer (Logic + Code)

Scan key=value; for quoted values read until next quote; for plain values read until whitespace.

static Map<String,String> parse(String cmd) {
    Map<String,String> m = new LinkedHashMap<>();
    String s = (cmd == null ? "" : cmd.trim());

    int i = 0;
    while (i < s.length()) {
        while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;
        int eq = s.indexOf('=', i);
        if (eq < 0) break;

        String key = s.substring(i, eq).trim();
        i = eq + 1;

        String val;
        if (i < s.length() && s.charAt(i) == '"') {
            i++;
            int end = s.indexOf('"', i);
            if (end < 0) end = s.length();
            val = s.substring(i, end);
            i = Math.min(end + 1, s.length());
        } else {
            int end = i;
            while (end < s.length() && !Character.isWhitespace(s.charAt(end))) end++;
            val = s.substring(i, end);
            i = end;
        }
        if (!key.isEmpty()) m.put(key, val);
    }
    return m;
}
5

Keyword Detector — case-insensitive + whole word only

regexword boundarycase-insensitiveModerate

Scenario: Detect keyword "refund" as a whole word in customer chat. Rules: - case-insensitive - whole word only ("refund" => yes; "refunded" => no) Implement ONLY: Detector.hasRefundKeyword(msg).

✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Strings scenario (students implement ONLY // ✅ TODO)Ctrl+C
import java.util.regex.*;

class Detector {
    // ✅ TODO: Student must implement only this method
    static boolean hasRefundKeyword(String msg) {
        // TODO: Pattern \brefund\b with CASE_INSENSITIVE
        throw new UnsupportedOperationException("TODO");
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.println(Detector.hasRefundKeyword("  Need a \"REFUND\" ✅ now! not refunded yet...  "));
    }
}

Answer (Logic + Code)

Pattern.compile("\\brefund\\b", CASE_INSENSITIVE).matcher(msg).find()

static boolean hasRefundKeyword(String msg) {
    if (msg == null) return false;
    Pattern p = Pattern.compile("\\brefund\\b", Pattern.CASE_INSENSITIVE);
    return p.matcher(msg).find();
}
6

Search Normalizer — Unicode normalize + remove diacritics

NormalizerdiacriticssearchComplex

Scenario: Accent-insensitive search: "café" should match "cafe". Rules: - Normalize to NFD - Remove diacritic marks (\p{M}) - Lowercase Implement ONLY: SearchKey.toKey(text).

✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Strings scenario (students implement ONLY // ✅ TODO)Ctrl+C
import java.text.Normalizer;

class SearchKey {
    // ✅ TODO: Student must implement only this method
    static String toKey(String text) {
        // TODO: NFD normalize + remove diacritics + lowercase
        throw new UnsupportedOperationException("TODO");
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.println(SearchKey.toKey("  Café α/β ✅  "));
    }
}

Answer (Logic + Code)

Use Normalizer.normalize(text, Form.NFD) then replaceAll("\\p{M}+",""), then lowercase.

static String toKey(String text) {
    if (text == null) return "";
    String s = text.trim();
    String n = Normalizer.normalize(s, Normalizer.Form.NFD);
    n = n.replaceAll("\\p{M}+", "");
    return n.toLowerCase();
}
7

Log Sanitizer — remove control chars + limit length safely

sanitizationcontrol charssafetyComplex

Scenario: Sanitize incoming log message: - Replace tabs/newlines with a single space - Remove other control chars (bell, etc.) - Collapse whitespace - Trim - Max length = 80 Implement ONLY: LogSanitizer.clean(msg).

✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Strings scenario (students implement ONLY // ✅ TODO)Ctrl+C
class LogSanitizer {
    // ✅ TODO: Student must implement only this method
    static String clean(String msg) {
        // TODO: replace \t\n\r -> space; remove control chars; collapse whitespace; cut to 80
        throw new UnsupportedOperationException("TODO");
    }
}
public class Main {
    public static void main(String[] args) {
        String cleaned = LogSanitizer.clean("  USER\tName=\"Gopi\"\nAction=LOGIN ✅ α/β \u0007 !@#  ");
        System.out.println(cleaned);
        System.out.println(cleaned.length());
    }
}

Answer (Logic + Code)

Replace whitespace controls, strip remaining control chars using \p{Cntrl}, then enforce max length.

static String clean(String msg) {
    if (msg == null) return "";
    String s = msg.replace("\t", " ").replace("\n", " ").replace("\r", " ");
    s = s.replaceAll("\\p{Cntrl}+", "");        // remove remaining control chars (bell etc.)
    s = s.replaceAll("\\s+", " ").trim();      // collapse whitespace
    if (s.length() > 80) s = s.substring(0, 80);
    return s;
}
8

Mini JSON Extractor — parse simple JSON without library

parsingescape handlingrobustnessComplex

Scenario: Legacy JSON-like string (no nested objects): {"id":"U-α1","name":"Gopi ✅","city":"Bengaluru","note":"He said: \"Hi!\" !@#"} Extract values for given key. Rules: - Value is inside quotes - Value may contain escaped quotes (\") Implement ONLY: MiniJson.get(json, key) Print id,name,city,note.

✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Strings scenario (students implement ONLY // ✅ TODO)Ctrl+C
class MiniJson {
    // ✅ TODO: Student must implement only this method
    static String get(String json, String key) {
        // TODO:
        // - find: "key":"  (with escaped quotes)
        // - read until closing quote that is NOT escaped
        // - unescape \" -> "
        throw new UnsupportedOperationException("TODO");
    }
}
public class Main {
    public static void main(String[] args) {
        String json = "{\"id\":\"U-α1\",\"name\":\"Gopi ✅\",\"city\":\"Bengaluru\",\"note\":\"He said: \\\"Hi!\\\" !@#\"}";
        System.out.println(MiniJson.get(json, "id"));
        System.out.println(MiniJson.get(json, "name"));
        System.out.println(MiniJson.get(json, "city"));
        System.out.println(MiniJson.get(json, "note"));
    }
}

Answer (Logic + Code)

Scan from the value start; treat backslash as escape; stop at first unescaped quote; then unescape.

static String get(String json, String key) {
    if (json == null || key == null) return "";
    String needle = "\"" + key + "\":\"";           // "key":"
    int start = json.indexOf(needle);
    if (start < 0) return "";
    int i = start + needle.length();

    StringBuilder sb = new StringBuilder();
    boolean escaped = false;

    while (i < json.length()) {
        char c = json.charAt(i);
        if (escaped) {                                    // previous char was backslash
            sb.append(c);                                 // keep escaped char as-is
            escaped = false;
        } else {
            if (c == '\\') escaped = true;              // begin escape
            else if (c == '"') break;                    // end quote (not escaped)
            else sb.append(c);                            // regular char
        }
        i++;
    }

    // Unescape: turn \" into " in output (simple case)
    return sb.toString().replace("\\"", """).replace("\\\\", "\\");
}
9

Template Engine — replace ${placeholders} safely

StringBuilderreplacevalidationComplex

Scenario: You send SMS/email templates: "Hi ${name}, your order ${orderId} is ready ✅. City=${city}" Replace placeholders from a Map. Rules: - Unknown placeholders stay as-is - Null values become empty - Avoid repeated String.replace calls inside loops (use StringBuilder scan) Implement ONLY: TemplateEngine.render(template, values) Print rendered string.

✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Strings scenario (students implement ONLY // ✅ TODO)Ctrl+C
import java.util.*;

class TemplateEngine {
    // ✅ TODO: Student must implement only this method
    static String render(String template, Map<String,String> values) {
        // TODO:
        // - scan template and replace ${key}
        // - if key not found => keep ${key}
        throw new UnsupportedOperationException("TODO");
    }
}
public class Main {
    public static void main(String[] args) {
        String tpl = "Hi ${name}, your order ${orderId} is ready ✅. City=${city} | Note=${note}";
        Map<String,String> m = new HashMap<>();
        m.put("name", "Gopi Suresh");
        m.put("orderId", "ORD-α1!@#");
        m.put("city", "Bengaluru");
        m.put("note", "He said: \"OK\"");
        System.out.println(TemplateEngine.render(tpl, m));
    }
}

Answer (Logic + Code)

Scan for ${ ... } segments; append literal parts and substituted values into StringBuilder.

static String render(String template, Map<String,String> values) {
    if (template == null) return "";
    Map<String,String> v = (values == null ? java.util.Collections.emptyMap() : values);

    StringBuilder out = new StringBuilder();
    int i = 0;
    while (i < template.length()) {
        int start = template.indexOf("${", i);
        if (start < 0) {
            out.append(template.substring(i));
            break;
        }
        out.append(template.substring(i, start));
        int end = template.indexOf("}", start + 2);
        if (end < 0) {                                    // no closing }, append rest
            out.append(template.substring(start));
            break;
        }
        String key = template.substring(start + 2, end);
        if (v.containsKey(key)) out.append(v.get(key) == null ? "" : v.get(key));
        else out.append("${").append(key).append("}");
        i = end + 1;
    }
    return out.toString();
}
10

URL Query Encoder — encode + decode (spaces, unicode, special chars)

URLEncoderURLDecoderUTF-8Complex

Scenario: You build a URL query string from parameters and also decode it back. Rules: - Use UTF-8 - Encode keys and values - Keep ordering stable (LinkedHashMap) Implement ONLY: - QueryString.build(params) - QueryString.parse(query) Print built query and parsed map.

✅ Includes spaces + quotes + unicode α/β + emoji ✅ + special chars.
Java Strings scenario (students implement ONLY // ✅ TODO)Ctrl+C
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

class QueryString {
    // ✅ TODO: Student must implement only this method
    static String build(Map<String,String> params) {
        // TODO: URLEncoder.encode(key,value,"UTF-8") and join with &
        throw new UnsupportedOperationException("TODO");
    }

    // ✅ TODO: Student must implement only this method
    static Map<String,String> parse(String query) {
        // TODO: split by & and decode key/value
        throw new UnsupportedOperationException("TODO");
    }
}
public class Main {
    public static void main(String[] args) {
        Map<String,String> p = new LinkedHashMap<>();
        p.put("name", "Gopi Suresh ✅");
        p.put("note", "alpha β + quotes \"Hi\" !@#");
        p.put("city", "Bengaluru");
        p.put("id", "U-α1");

        String q = QueryString.build(p);
        System.out.println(q);
        System.out.println(QueryString.parse(q));
    }
}

Answer (Logic + Code)

Use URLEncoder/URLDecoder with UTF-8; handle missing '=' safely; preserve order with LinkedHashMap.

static String build(Map<String,String> params) {
    if (params == null || params.isEmpty()) return "";
    StringBuilder sb = new StringBuilder();
    boolean first = true;

    for (Map.Entry<String,String> e : params.entrySet()) {
        if (!first) sb.append("&");
        first = false;

        String k = e.getKey() == null ? "" : e.getKey();
        String v = e.getValue() == null ? "" : e.getValue();

        sb.append(URLEncoder.encode(k, StandardCharsets.UTF_8));
        sb.append("=");
        sb.append(URLEncoder.encode(v, StandardCharsets.UTF_8));
    }
    return sb.toString();
}

static Map<String,String> parse(String query) {
    Map<String,String> out = new LinkedHashMap<>();
    if (query == null || query.isBlank()) return out;

    String[] parts = query.split("&");
    for (String p : parts) {
        if (p.isEmpty()) continue;
        int eq = p.indexOf('=');
        String k = (eq >= 0) ? p.substring(0, eq) : p;
        String v = (eq >= 0) ? p.substring(eq + 1) : "";
        k = URLDecoder.decode(k, StandardCharsets.UTF_8);
        v = URLDecoder.decode(v, StandardCharsets.UTF_8);
        out.put(k, v);
    }
    return out;
}