String Class

Strings are one of the most commonly used data types. This lesson covers how to use the String class in Java.

Creating Strings

Two Ways to Create

JAVA
// Method 1: String literal (recommended)
String s1 = "Hello";

// Method 2: new keyword
String s2 = new String("Hello");

Difference

JAVA
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");

System.out.println(s1 == s2);      // true (same object)
System.out.println(s1 == s3);      // false (different objects)
System.out.println(s1.equals(s3)); // true (same content)
💡 Recommendation: Use string literals to create strings—they're more efficient. Java caches string literals.

String Characteristics

Immutability

Once a String object is created, its content cannot be changed.

JAVA
String s = "Hello";
s = s + " World";  // Creates a new object, doesn't modify the original

Example: String Immutability

JAVA
public class StringImmutable {
    public static void main(String[] args) {
        String s1 = "Hello";
        String s2 = s1.concat(" World");
        
        System.out.println(s1);  // Hello (original unchanged)
        System.out.println(s2);  // Hello World (new object)
    }
}
▶ Try it Yourself

Common Methods

Length and Checks

Method Description Example
length() String length "Hello".length() → 5
isEmpty() Is empty string "".isEmpty() → true
isBlank() Is blank (whitespace only) " ".isBlank() → true
contains() Contains substring "Hello".contains("ell") → true
startsWith() Starts with "Hello".startsWith("He") → true
endsWith() Ends with "Hello".endsWith("lo") → true

Example: Length and Checks

JAVA
public class StringCheck {
    public static void main(String[] args) {
        String s = "Hello, World!";
        
        System.out.println("Length: " + s.length());          // 13
        System.out.println("Contains World: " + s.contains("World")); // true
        System.out.println("Starts with Hello: " + s.startsWith("Hello")); // true
        System.out.println("Ends with !: " + s.endsWith("!"));       // true
    }
}
▶ Try it Yourself

Searching

Method Description Example
indexOf() First occurrence "Hello".indexOf("l") → 2
lastIndexOf() Last occurrence "Hello".lastIndexOf("l") → 3
charAt() Character at index "Hello".charAt(1) → 'e'

Example: Searching

JAVA
public class StringSearch {
    public static void main(String[] args) {
        String s = "Hello, World!";
        
        System.out.println("indexOf('l'): " + s.indexOf('l'));       // 2
        System.out.println("lastIndexOf('l'): " + s.lastIndexOf('l')); // 10
        System.out.println("charAt(0): " + s.charAt(0));            // H
    }
}
▶ Try it Yourself

Substring

Method Description Example
substring(int begin) From begin to end "Hello".substring(2) → "llo"
substring(int begin, int end) Begin to end (exclusive) "Hello".substring(1,4) → "ell"

Example: Substring

JAVA
public class StringSubstring {
    public static void main(String[] args) {
        String s = "Hello, World!";
        
        System.out.println(s.substring(7));       // World!
        System.out.println(s.substring(0, 5));    // Hello
    }
}
▶ Try it Yourself

Conversion

Method Description Example
toUpperCase() To uppercase "Hello".toUpperCase() → "HELLO"
toLowerCase() To lowercase "Hello".toLowerCase() → "hello"
trim() Remove leading/trailing spaces " Hi ".trim() → "Hi"
strip() Remove spaces (stronger) " Hi ".strip() → "Hi"

Replacement

Method Description Example
replace() Replace all "Hello".replace("l","L") → "HeLLo"
replaceAll() Regex replace "a1b2c".replaceAll("\\d","") → "abc"
replaceFirst() Replace first "a1b1".replaceFirst("1","X") → "aXb1"

Split and Join

Method Description Example
split() Split string "a,b,c".split(",") → ["a","b","c"]
join() Join strings String.join("-","a","b") → "a-b"
concat() Concatenate "Hello".concat(" World") → "Hello World"

Example: Split and Join

JAVA
public class StringSplitJoin {
    public static void main(String[] args) {
        // Split
        String csv = "Alice,Bob,Charlie";
        String[] names = csv.split(",");
        for (String name : names) {
            System.out.println(name);
        }
        
        // Join
        String joined = String.join(" | ", names);
        System.out.println(joined);  // Alice | Bob | Charlie
    }
}
▶ Try it Yourself

String Comparison

== vs equals

JAVA
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");

System.out.println(s1 == s2);      // true (same object)
System.out.println(s1 == s3);      // false (different objects)
System.out.println(s1.equals(s3)); // true (same content)
⚠️ Important: Always use equals() to compare strings, not ==. == compares addresses, equals() compares content.

compareTo()

Compare strings in dictionary order.

JAVA
String a = "apple";
String b = "banana";

System.out.println(a.compareTo(b));  // Negative (a comes before b)
System.out.println(b.compareTo(a));  // Positive (b comes after a)
System.out.println(a.compareTo(a));  // 0 (equal)

equalsIgnoreCase()

Compare ignoring case.

JAVA
String s1 = "Hello";
String s2 = "hello";

System.out.println(s1.equals(s2));            // false
System.out.println(s1.equalsIgnoreCase(s2));   // true

Formatting

String.format()

JAVA
String name = "Alice";
int age = 25;
double score = 95.5;

String info = String.format("Name: %s, Age: %d, Score: %.1f", name, age, score);
System.out.println(info);  // Name: Alice, Age: 25, Score: 95.5

Format Specifiers

Specifier Description Example
%s String %s → "Hello"
%d Integer %d → 42
%f Float %.2f → 3.14
%n Newline

Strings and Arrays

JAVA
// String → char array
String s = "Hello";
char[] chars = s.toCharArray();

// char array → String
String s2 = new String(chars);

// String → byte array
byte[] bytes = s.getBytes();

// byte array → String
String s3 = new String(bytes);

StringBuilder

When you need to modify strings frequently, StringBuilder is more efficient.

JAVA
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
String result = sb.toString();  // "Hello World"
💡 Recommendation: Use + for single concatenations. Use StringBuilder for multiple concatenations.

❓ Frequently Asked Questions

Q How do I choose between String, StringBuilder, and StringBuffer?
A String is immutable, suitable for few operations. StringBuilder is mutable, use in single-threaded contexts. StringBuffer is mutable and thread-safe.
Q Why use equals for string comparison?
A Because == compares object addresses, while equals() compares content.
Q Does substring create a new object?
A Yes. substring returns a new String object.

📖 Summary

📝 Exercises

  1. String operations: Count how many times a specific character appears in a string
  2. Reverse string: Write a method to reverse a string
  3. Word count: Count the number of words in a string (separated by spaces)

Next Lesson

In the next lesson, we'll learn about StringBuilder — using mutable strings.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏