Skip to Content
bytegarden

Strings

Creating Strings

Strings are immutable in Java example of creating strings of different types (String1.java, below)

String1.java
// Using String Literals, Character Array, and new keyword to create a string
public class String1 {
    public static void main(String[] args) {
        
        // Using String Literal
        String str1 = "Java program";
        System.out.println(str1);

        // From Character Array
        char[] c = {'A', 'B', 'C', 'D'};
        String str2 = new String(c);
        // Starting from index 2, take 2 characters
        String str3 = new String(c, 2, 2); // Results in "CD"
        System.out.println(str2);
        System.out.println(str3);

        // using new keyword
        String str4 = new String("Java");
        System.out.println(str4);
    }
}
Runs in your browser with Java 21. Ctrl/⌘ + Enter to run.Built with CheerpJ
  1. Using String Literal (Simplest Method)
  2. Using Constructors
    • From Character Array
    • From Byte Array
    • From String Literal with new

Memory Management

  • String variables are references that hold/point to string objects
  • References store the address of objects (though Java doesn’t expose addresses)
  • Same literals are reused from String pool for memory efficiency

String Constant Pool

Java maintains a pool of string constants. When using string literals, objects are created in the pool. Identical literals reuse the same object in the pool.

Heap Memory

Using the new keyword creates objects in the heap. This can result in two objects:

  • One in the heap (new object)

  • One in the string constant pool (if the literal is new)

  • String Literal version exists in String Pool

    String str1 = "Java";  // Creates object in pool
    String str2 = "Java";  // Points to same object in pool i.e to "Java"
    String str3 = new String("Java");  // Creates new object in heap
    System.out.println(str1 == str2);  // true
    System.out.println(str1 == str3);  // false

String Methods

Basic Methods

length()              → int  // "Hello" → 5
charAt(i)             → char // "Hello".charAt(0) → 'H'
indexOf(String s)     → int  // "Hello".indexOf('e') → 1 (if not found then -1)
lastIndexOf(String s) → int  // "Hello".lastIndexOf('l') → 3 (if not found then -1)

Case Methods

toLowerCase() → String  // "Hello" → "hello"
toUpperCase() → String  // "hello" → "HELLO"

Substring Methods

substring(int start)     → String  // "Hello".substring(2) → "llo"
substring(int start,end) → String  // "Hello".substring(1,4) → "ell"

Modification Methods

trim()                          → String  // "  Hi  ".trim() → "Hi"
replace(char old, char new)     → String  // "Hello".replace('l','w') → "Hewwo"

Comparison Methods

equals(String str)           → boolean  // Case-sensitive comparison
equalsIgnoreCase(String str) → boolean  // "Hello".equalsIgnoreCase("hello") → true
startsWith(String prefix)    → boolean  // "Hello".startsWith("He") → true
endsWith(String suffix)      → boolean  // "Hello".endsWith("lo") → true
contains(CharSequence s)     → boolean  // "Hello".contains("el") → true
compareTo(String s)          → int      // "abc".compareTo("abc") → 0, "abc".compareTo("abd") → -1, "abc".compareTo("abb") → 1

Conversion Methods

valueOf(int i)       → String  // String.valueOf(123) → "123"
valueOf(double d)    → String  // String.valueOf(123.45) → "123.45"
valueOf(boolean b)   → String  // String.valueOf(true) → "true"
valueOf(char c)      → String  // String.valueOf('c') → "c"

Common Pitfalls

  • Use equals() not == for comparison
    • equals() - Compares string contents (for string comparison)
    • == Compares reference addresses (not for string comparison)
  • Check for null before method calls
  • String methods create new strings (immutable)

Practice: interview questions on Strings