Strings, String Buffer and String Reader

Immutable String, mutable StringBuilder/StringBuffer, string methods, constant pool and StringReader.


Session 1 covers string creation via literals and the new keyword, the string constant pool, and immutability. Key String methods include charAt, indexOf, contains, concat, equals, trim, substring, toLowerCase, matches and startsWith. Session 2 covers StringBuilder and StringBuffer, mutable character sequences; StringBuilder is not synchronized, so faster. Methods include append, insert, replace, delete, reverse, capacity and ensureCapacity.

Example
StringBuilder sb = new StringBuilder("Hello ");
sb.append("Java");
System.out.println(sb);
Code Snippets 5
Creating strings - literal vs new keyword
Basic

Creating strings - literal vs new keyword

// ------------------------------------------------------------------
// 1. Creating strings - literal vs new keyword
// ------------------------------------------------------------------
class StringExample {
  public static void main(String[] args) {
    String s1 = "java";
    // literal -> pool
    char ch[] = {
      's', 't', 'r', 'i', 'n', 'g', 's'
    }
    ;
    String s2 = new String(ch);
    // from char array
    String s3 = new String("example");
    // new keyword -> heap
    System.out.println(s1);
    System.out.println(s2);
    System.out.println(s3);
  }
}

String interning - literal reuses the pooled instance
Basic

String interning - literal reuses the pooled instance

// ------------------------------------------------------------------
// 2. String interning - literal reuses the pooled instance
// ------------------------------------------------------------------
class StringPoolDemo {
  public static void main(String[] args) {
    String s1 = "Welcome";
    String s2 = "Welcome";
    // reuse pooled instance
    String s3 = new String("Welcome");
    System.out.println("s1 == s2       : " +(s1 == s2));
    // true
    System.out.println("s1 == s3       : " +(s1 == s3));
    // false
    System.out.println("s1.equals(s3)  : " + s1.equals(s3));
    // true
  }
}

Strings are immutable
Basic

Strings are immutable

// ------------------------------------------------------------------
// 3. Strings are immutable
// ------------------------------------------------------------------
class ImmutableDemo {
  public static void main(String[] args) {
    String example = "Hello! ";
    example = example.concat(" World");
    System.out.println(example);
    // "Hello! World"
    // The original "Hello! " string was NOT modified -
    // a new string was created and assigned to the variable.
  }
}

contains() method
Basic

contains() method

// ------------------------------------------------------------------
// 4. contains() method
// ------------------------------------------------------------------
class ContainsDemo {
  public static void main(String[] args) {
    String str1 = "Java String contains()";
    boolean result = str1.contains("Java");
    System.out.println("contains('Java') = " + result);
    String s2 = "Learn Java";
    String s3 = "Java";
    String s4 = "java";
    if(s2.contains(s3)) System.out.println(s2 + " contains " + s3);
    else System.out.println(s2 + " doesn't contain " + s3);
    if(s2.contains(s4)) System.out.println(s2 + " contains " + s4);
    else System.out.println(s2 + " doesn't contain " + s4);
    // case sensitive
  }
}

indexOf(), trim(), charAt(), toLowerCase(), concat(), matches(), startsWith(),replace()
Basic

indexOf(), trim(), charAt(), toLowerCase(), concat(), matches(), startsWith(),replace()

// ------------------------------------------------------------------
// 5. indexOf() - first occurrence + fromIndex variant
// ------------------------------------------------------------------
class IndexOfDemo {
  public static void main(String[] args) {
    String str1 = "Learn Java";
    System.out.println("indexOf('J')   = " + str1.indexOf('J'));
    // 6
    System.out.println("indexOf('a')   = " + str1.indexOf('a'));
    // 1
    System.out.println("indexOf('j')   = " + str1.indexOf('j'));
    // -1
    System.out.println("indexOf(\"ava\") = " + str1.indexOf("ava"));
    // 7
    System.out.println("indexOf(\"java\")= " + str1.indexOf("java"));
    // -1
    System.out.println("indexOf(\"\")   = " + str1.indexOf(""));
    // 0
    // fromIndex parameter
    String str2 = "Learn Java programming";
    System.out.println("indexOf('a', 4)       = " + str2.indexOf('a', 4));
    // 6
    System.out.println("indexOf(\"Java\", 8)  = " + str2.indexOf("Java", 8));
    // -1
    System.out.println("lastIndexOf('a')      = " + str2.lastIndexOf('a'));
  }
}
// ------------------------------------------------------------------
// 6. trim() - remove leading/trailing whitespace
// ------------------------------------------------------------------
class TrimDemo {
  public static void main(String[] args) {
    String str1 = "   Learn Java Programming      ";
    System.out.println("[" + str1 + "]");
    System.out.println("[" + str1.trim() + "]");
    // remove ALL whitespace with replaceAll
    String str2 = "Learn\nJava \n\n   ";
    String result = str2.replaceAll("\\s", "");
    System.out.println("[" + result + "]");
  }
}
// ------------------------------------------------------------------
// 7. charAt()
// ------------------------------------------------------------------
class CharAtDemo {
  public static void main(String[] args) {
    String str1 = "Java Programming";
    System.out.println(str1.charAt(2));
    // 'v'
  }
}
// ------------------------------------------------------------------
// 8. toLowerCase() / toUpperCase()
// ------------------------------------------------------------------
class CaseDemo {
  public static void main(String[] args) {
    String str1 = "JAVA PROGRAMMING";
    System.out.println(str1.toLowerCase());
    System.out.println(str1.toUpperCase());
  }
}
// ------------------------------------------------------------------
// 9. concat() and + operator
// ------------------------------------------------------------------
class ConcatDemo {
  public static void main(String[] args) {
    String str1 = "Learn ";
    String str2 = "Java";
    System.out.println(str1.concat(str2));
    // Learn Java
    System.out.println(str2.concat(str1));
    // JavaLearn
    System.out.println(str1 + str2);
    // Learn Java
    // + operator: non-string operands are converted to strings
    String s = "Java";
    System.out.println(s + 5);
    // Java5
    System.out.println(s + true);
    // Javatrue
  }
}
// ------------------------------------------------------------------
// 10. matches() - regular expression
// ------------------------------------------------------------------
class MatchesDemo {
  public static void main(String[] args) {
    String regex = "^J..a$";
    System.out.println("Java".matches(regex));
    // true (J a v a)
    System.out.println("jAva".matches(regex));
    // false
  }
}
// ------------------------------------------------------------------
// 11. startsWith() with and without offset
// ------------------------------------------------------------------
class StartsWithDemo {
  public static void main(String[] args) {
    String str = "JavaScript";
    System.out.println(str.startsWith("Java"));
    // true
    String str2 = "Java Programming";
    System.out.println(str2.startsWith("Java", 3));
    // false
    System.out.println(str2.startsWith("a Pr", 3));
    // true
  }
}
// ------------------------------------------------------------------
// 12. More String methods - substring, join, endsWith, isEmpty, toString
// ------------------------------------------------------------------
class MoreStringMethods {
  public static void main(String[] args) {
    String str = "Hello World";
    System.out.println("substring(6)     = " + str.substring(6));
    // World
    System.out.println("substring(0,5)   = " + str.substring(0, 5));
    // Hello
    System.out.println("endsWith('rld')  = " + str.endsWith("rld"));
    // true
    System.out.println("isEmpty          = " + str.isEmpty());
    // false
    String joined = String.join("-", "2026", "09", "06");
    System.out.println("join: " + joined);
    String s = new String("test");
    System.out.println("toString: " + s.toString());
    System.out.println("hashCode: " + s.hashCode());
    System.out.println("equalsIgnoreCase = " + "HELLO".equalsIgnoreCase("hello"));
    // true
  }
}
// ------------------------------------------------------------------
// 13. Practice problem - replace a specified character
// ------------------------------------------------------------------
class ReplaceDemo {
  public static void main(String[] args) {
    String str = "Java Programming";
    String replaced = str.replace('a', 'X');
    System.out.println(replaced);
    // JXvX ProgrXmming
  }
}
Video Lesson Open in new tab
Quiz
1. In Java, strings are objects of which class?
2. What makes Java Strings immutable?
3. What is the String Constant Pool?
4. What is the difference between == and .equals() when comparing Strings?
5. Which class should be used when we need a mutable string in Java?
6. What is the output of: String s = "Hello"; s.concat(" World"); System.out.println(s);
7. Which method is used to convert a String to a character array?
8. What is the difference between StringBuffer and StringBuilder?
9. What does the following code return? "Java".substring(1, 3)
10. Which of the following creates a new String object?
Coding Problems
1. Write a Java program to reverse the string using StringBuilder.
Discussion

Login to join the discussion.


No comments yet.