Java Strings

Complete guide to Java Strings with examples. Learn String methods, manipulation, comparison, StringBuilder, StringBuffer, and string formatting.

In Java, strings are objects that represent sequences of characters. The String class is one of the most commonly used classes in Java programming.

1. What is a String in Java?

A string is a sequence of characters. In Java, strings are objects of the String class. Unlike primitive data types, strings are reference types.

// create strings
String type = "Java programming";

Which class is used to create strings in Java?

Here, we have created a string variable named type that holds the value "Hello, World!".

Creating Strings in Java

There are two main ways to create strings in Java:

1. String Literal

String str1 = "Java Programming";
String str2 = "Javaistic";

2. Using new Keyword

String str1 = new String("Java Programming");
String str2 = new String("Javaistic");

Note: String literals are stored in the string pool for memory efficiency, while strings created with new keyword are stored in the heap memory.


2. String Methods

Java provides many useful methods for string manipulation:

1. length() Method

Returns the number of characters in the string.

class Main {
    public static void main(String[] args) {
        String str = "Java";
        System.out.println("Length: " + str.length()); // Output: 4
    }
}

2. charAt() Method

Returns the character at the specified index.

class Main {
    public static void main(String[] args) {
        String str = "Java";
        System.out.println("Character at index 1: " + str.charAt(1)); // Output: a
    }
}

3. substring() Method

Extracts a portion of the string.

class Main {
    public static void main(String[] args) {
        String str = "Java Programming";
        System.out.println("Substring: " + str.substring(5)); // Output: Programming
        System.out.println("Substring: " + str.substring(0, 4)); // Output: Java
    }
}

4. toLowerCase() and toUpperCase()

Convert string to lowercase or uppercase.

class Main {
    public static void main(String[] args) {
        String str = "Java Programming";
        System.out.println("Lowercase: " + str.toLowerCase()); // java programming
        System.out.println("Uppercase: " + str.toUpperCase()); // JAVA PROGRAMMING
    }
}

5. indexOf() Method

Returns the index of the first occurrence of a character or substring.

class Main {
    public static void main(String[] args) {
        String str = "Java Programming";
        System.out.println("Index of 'a': " + str.indexOf('a')); // Output: 1
        System.out.println("Index of 'Programming': " + str.indexOf("Programming")); // Output: 5
    }
}

3. String Comparison

1. Using equals() Method

class Main {
    public static void main(String[] args) {
        String str1 = "Java";
        String str2 = "Java";
        String str3 = new String("Java");

        System.out.println(str1.equals(str2)); // true
        System.out.println(str1.equals(str3)); // true
    }
}

2. Using equalsIgnoreCase() Method

class Main {
    public static void main(String[] args) {
        String str1 = "Java";
        String str2 = "JAVA";

        System.out.println(str1.equalsIgnoreCase(str2)); // true
    }
}

3. Using compareTo() Method

class Main {
    public static void main(String[] args) {
        String str1 = "Apple";
        String str2 = "Banana";

        System.out.println(str1.compareTo(str2)); // negative value (Apple < Banana)
    }
}

Important: Never use == operator to compare strings. It compares references, not content.

What is the output of 'Java'.substring(1, 3)?


4. String Concatenation

1. Using + Operator

class Main {
    public static void main(String[] args) {
        String firstName = "John";
        String lastName = "Doe";
        String fullName = firstName + " " + lastName;
        System.out.println(fullName); // John Doe
    }
}

2. Using concat() Method

class Main {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = " World";
        String result = str1.concat(str2);
        System.out.println(result); // Hello World
    }
}

5. StringBuilder and StringBuffer

When you need to perform many string operations, use StringBuilder or StringBuffer for better performance.

StringBuilder Example

class Main {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("Java");
        sb.append(" ");
        sb.append("Programming");

        System.out.println(sb.toString()); // Java Programming

        // Insert at specific position
        sb.insert(5, "is ");
        System.out.println(sb.toString()); // Java is Programming

        // Delete characters
        sb.delete(5, 8);
        System.out.println(sb.toString()); // Java Programming
    }
}

StringBuffer vs StringBuilder

FeatureStringBuilderStringBuffer
Thread SafetyNot thread-safeThread-safe
PerformanceFasterSlower
UsageSingle-threaded applicationsMulti-threaded applications

6. String Formatting

1. Using printf() Method

class Main {
    public static void main(String[] args) {
        String name = "John";
        int age = 25;
        System.out.printf("Name: %s, Age: %d%n", name, age);
        // Output: Name: John, Age: 25
    }
}

2. Using String.format() Method

class Main {
    public static void main(String[] args) {
        String name = "Alice";
        double score = 95.5;
        String formatted = String.format("Student: %s, Score: %.1f", name, score);
        System.out.println(formatted); // Student: Alice, Score: 95.5
    }
}

Key Takeaways

  • Immutable: Strings cannot be changed. Methods like .toUpperCase() return a new string.
  • Pool: String literals ("Hello") are stored in a special memory pool for efficiency.
  • Comparison: ALWAYS use .equals() to compare values.

Common Pitfalls

[!WARNING] The == Trap: s1 == s2 checks if they are the same object in memory, not if they have the same text. Use s1.equals(s2).

[!WARNING] Concatenation in Loops: Using + in a loop (e.g., s += "a") is very slow because it creates a new String object every time. Use StringBuilder instead.

Challenge

Challenge

Task:

Create a string 'Java Programming' and print its length.