Board Formulas
β˜• JavaπŸ“… Day 11

Strings in Java

Work with text using String methods, compare strings the right way, and build text efficiently with StringBuilder.

🎯

Learning objectives

  • β†’Use common String methods such as length, charAt, substring and indexOf
  • β†’Explain what immutability means and why it matters
  • β†’Compare strings correctly with equals, equalsIgnoreCase and compareTo
  • β†’Build and change text efficiently with StringBuilder

πŸ’‘ Key points

  • A String is an object of the String class, not a primitive. Characters are indexed from 0, like arrays.
  • Strings are immutable: methods like toUpperCase() return a NEW String and leave the original unchanged.
  • == checks whether two references point to the same object. equals() checks whether the characters match.
  • String literals with the same text share one object in the String pool; new String(...) always makes a fresh object.
  • compareTo() returns 0 if equal, a negative number if the first string comes earlier in dictionary order, and a positive number if it comes later.
  • substring(begin, end) includes the begin index but stops before the end index.
  • Use StringBuilder when you change text many times, for example inside a loop.

πŸ’» Code examples(6)

#1Common String methods
java
public class StringBasics {
    public static void main(String[] args) {
        String name = "Priya Sharma";

        System.out.println(name.length());
        System.out.println(name.charAt(0));
        System.out.println(name.toUpperCase());
        System.out.println(name.indexOf("Sharma"));
        System.out.println(name.substring(0, 5));
        System.out.println(name.contains("Sharma"));
        System.out.println(name.replace('a', '@'));
    }
}
Output
12
P
PRIYA SHARMA
6
Priya
true
Priy@ Sh@rm@
Each method returns a value you can print or store. The space counts as a character, so the length is 12. substring(0, 5) takes indexes 0 to 4; the end index is not included.
#2Strings are immutable
java
public class Immutable {
    public static void main(String[] args) {
        String city = "pune";
        city.toUpperCase();          // result thrown away
        System.out.println(city);

        city = city.toUpperCase();   // keep the new String
        System.out.println(city);

        String s = "  Amit  ";
        System.out.println("[" + s.trim() + "]");
        System.out.println("[" + s + "]");
    }
}
Output
pune
PUNE
[Amit]
[  Amit  ]
toUpperCase() does not change city. It returns a new String, and you must assign it back to keep it. trim() works the same way, so s still has its spaces.
#3== vs equals()
java
public class CompareDemo {
    public static void main(String[] args) {
        String a = "Amit";
        String b = "Amit";
        String c = new String("Amit");

        System.out.println(a == b);
        System.out.println(a == c);
        System.out.println(a.equals(c));
        System.out.println("AMIT".equalsIgnoreCase(a));
    }
}
Output
true
false
true
true
a and b point to the same pooled literal, so == is true. c is a separate object, so == is false even though the text is the same. Always use equals() to compare text.
#4compareTo() for dictionary order
java
public class Order {
    public static void main(String[] args) {
        System.out.println("Amit".compareTo("Amit"));
        System.out.println("Amit".compareTo("Priya"));
        System.out.println("Priya".compareTo("Amit"));
        System.out.println("apple".compareTo("Apple"));

        String x = "Ravi", y = "Rohan";
        if (x.compareTo(y) < 0) {
            System.out.println(x + " comes first");
        }
    }
}
Output
0
-15
15
32
Ravi comes first
compareTo() compares character by character using Unicode values. 'A' is 65 and 'P' is 80, so the result is 65 - 80 = -15. Only the sign matters. Uppercase letters (65-90) come before lowercase (97-122).
#5StringBuilder
java
public class Builder {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Java");
        sb.append(" is fun");
        sb.insert(0, "Learning ");
        System.out.println(sb);

        sb.reverse();
        System.out.println(sb);

        StringBuilder nums = new StringBuilder();
        for (int i = 1; i <= 5; i++) {
            nums.append(i).append(" ");
        }
        System.out.println(nums.toString().trim());
    }
}
Output
Learning Java is fun
nuf si avaJ gninraeL
1 2 3 4 5
A StringBuilder is mutable: append, insert and reverse change the same object instead of creating new ones. Call toString() when you need an ordinary String back.
#6Count vowels and check palindromes
java
public class WordCheck {
    static int countVowels(String s) {
        int count = 0;
        for (char ch : s.toLowerCase().toCharArray()) {
            if ("aeiou".indexOf(ch) != -1) {
                count++;
            }
        }
        return count;
    }

    static boolean isPalindrome(String s) {
        String rev = new StringBuilder(s)
            .reverse().toString();
        return s.equalsIgnoreCase(rev);
    }

    public static void main(String[] args) {
        String[] words = {"Madam", "Mumbai", "Level"};
        for (String w : words) {
            System.out.println(w + ": vowels="
                + countVowels(w) + ", palindrome="
                + isPalindrome(w));
        }
    }
}
Output
Madam: vowels=2, palindrome=true
Mumbai: vowels=3, palindrome=false
Level: vowels=2, palindrome=true
toCharArray() lets you walk through the characters with for-each. indexOf(ch) returns -1 when ch is not in "aeiou". Reversing with StringBuilder and comparing with equalsIgnoreCase() gives a palindrome check.

🎯 Practice

Q1. What does this print? String s = "hello"; s.toUpperCase(); System.out.println(s);+

hello. toUpperCase() returns a new String, but the result is not stored, so s is unchanged. Write s = s.toUpperCase(); to keep it.

Q2. What is "Board Formulas".substring(6)?+

"Formulas". With one argument, substring(begin) returns everything from index 6 to the end.

Q3. Two Strings both contain "Amit", but a == b is false. How is that possible?+

== compares references, not text. If one of them was made with new String("Amit") or built while the program runs, it is a different object. Use a.equals(b) to compare the text.

Q4. Reverse the String "Kerala" using StringBuilder.+

String rev = new StringBuilder("Kerala").reverse().toString(); System.out.println(rev); // alareK

Q5. Is "Zebra".compareTo("apple") positive or negative? Why?+

Negative (-7). Uppercase 'Z' is 90 and lowercase 'a' is 97, so "Zebra" counts as earlier. Use compareToIgnoreCase() when you want true alphabetical order.

πŸ“ Notes

Why immutability matters

A String object never changes after it is created. That lets Java safely share a single "Amit" literal between many variables (the String pool), and it means a String you pass to a method cannot be changed behind your back.

The cost: every + on a String creates a brand-new String. In a loop this builds a lot of throwaway objects:

String s = "";
for (int i = 0; i < 1000; i++) {
    s = s + i;      // a new String every time
}

Use a StringBuilder and call append(i) instead. It changes one object in place.

More useful methods

  • split(",") breaks text into an array: "Amit,Priya,Ravi".split(",") gives 3 names.
  • startsWith("Mr"), endsWith(".pdf") and lastIndexOf('a') help when searching.
  • isEmpty() is true only for "" (length 0).
  • String.valueOf(25) turns a number into a String, and Integer.parseInt("25") goes the other way.
String line = "Amit,Priya,Ravi";
String[] names = line.split(",");
System.out.println(names.length);   // 3
System.out.println(names[1]);       // Priya

Common mistakes

  • Using == to compare text. It may work for literals because of the pool, then fail for text typed by the user. Use equals().
  • Forgetting to store the result. name.trim(); on its own does nothing useful.
  • Going past the last index. name.charAt(name.length()) throws StringIndexOutOfBoundsException. The last index is length() - 1.
  • Calling a method on null. If answer might be null, write "yes".equals(answer) rather than answer.equals("yes"). The first version never throws NullPointerException.

Next: Day 12, Constructors. You will see default and parameterised constructors, overloading and constructor chaining.