String Methods & Operations

Essential Methods for Working with Strings in Java

CPCS203 - Module 2 | Lesson 3

1 Understanding String Indexing

Before we learn String methods, remember that Strings are indexed starting from 0:

String Index Example: "Hello World"
0
H
1
e
2
l
3
l
4
o
5
6
W
7
o
8
r
9
l
10
d

Length = 11 | Valid indices: 0 to 10

2 Basic String Methods

📜 Basic Information Methods
length()

Returns the number of characters in the String.

"Hello".length()
→ 5
charAt(int index)

Returns the character at the specified index.

"Hello".charAt(1)
→ 'e'
isEmpty()

Returns true if the String has length 0.

"".isEmpty()
→ true
String text = "Hello World"; System.out.println(text.length()); // 11 System.out.println(text.charAt(0)); // H System.out.println(text.charAt(6)); // W System.out.println(text.isEmpty()); // false System.out.println("".isEmpty()); // true

3 String Concatenation

There are multiple ways to combine Strings in Java:

String first = "Hello"; String second = "World"; // Method 1: Using + operator String result1 = first + " " + second; System.out.println(result1); // Hello World // Method 2: Using concat() method String result2 = first.concat(" ").concat(second); System.out.println(result2); // Hello World // Concatenating with other types int number = 42; String message = "The answer is: " + number; System.out.println(message); // The answer is: 42
Remember: Strings are Immutable!

Each concatenation creates a NEW String object. The original Strings are not modified!

4 Extracting Substrings

Substring Methods
substring(int beginIndex)

Returns substring from beginIndex to end.

"Hello World".substring(6)
→ "World"
substring(int begin, int end)

Returns substring from begin to end-1.

"Hello World".substring(0, 5)
→ "Hello"
Visual: substring(2, 7) on "Hello World"
0
H
1
e
2
l
3
l
4
o
5
6
W
7
o
8
r
9
l
10
d

Result: "llo W" (from index 2 up to but NOT including 7)

String text = "Hello World"; System.out.println(text.substring(6)); // World System.out.println(text.substring(0, 5)); // Hello System.out.println(text.substring(2, 7)); // llo W

5 String Comparison

Comparison Methods
Method Description Example Result
equals(String) Case-sensitive comparison "Java".equals("java") false
equalsIgnoreCase(String) Case-insensitive comparison "Java".equalsIgnoreCase("java") true
compareTo(String) Lexicographic comparison "Apple".compareTo("Banana") negative (-1)
startsWith(String) Checks if starts with prefix "Hello".startsWith("He") true
endsWith(String) Checks if ends with suffix "Hello".endsWith("lo") true
contains(CharSequence) Checks if contains substring "Hello".contains("ell") true
String s1 = "Java"; String s2 = "java"; // equals vs equalsIgnoreCase System.out.println(s1.equals(s2)); // false System.out.println(s1.equalsIgnoreCase(s2)); // true // compareTo returns: negative, 0, or positive System.out.println("Apple".compareTo("Banana")); // -1 (A comes before B) System.out.println("Banana".compareTo("Apple")); // 1 (B comes after A) System.out.println("Apple".compareTo("Apple")); // 0 (equal)
Always use .equals() for String comparison!

Never use == to compare String content. Use == only to check if two variables reference the same object.

6 Searching in Strings

Returns first occurrence index, or -1 if not found.

"Hello".indexOf('l')
→ 2

Returns last occurrence index, or -1 if not found.

"Hello".lastIndexOf('l')
→ 3
Visual: indexOf('l') vs lastIndexOf('l') on "Hello"
0
H
1
e
2 ←first
l
3 ←last
l
4
o
String text = "Hello World"; System.out.println(text.indexOf('o')); // 4 (first 'o') System.out.println(text.lastIndexOf('o')); // 7 (last 'o') System.out.println(text.indexOf("World")); // 6 System.out.println(text.indexOf('x')); // -1 (not found) // Search starting from specific index System.out.println(text.indexOf('o', 5)); // 7 (start searching from index 5)

7 String Transformation

🔄 Transformation Methods
toUpperCase()

Converts all characters to uppercase.

"Hello".toUpperCase()
→ "HELLO"
toLowerCase()

Converts all characters to lowercase.

"Hello".toLowerCase()
→ "hello"
trim()

Removes leading and trailing whitespace.

" Hello ".trim()
→ "Hello"
replace(old, new)

Replaces all occurrences of old with new.

"Hello".replace('l', 'p')
→ "Heppo"
String text = " Hello World "; System.out.println(text.toUpperCase()); // " HELLO WORLD " System.out.println(text.toLowerCase()); // " hello world " System.out.println(text.trim()); // "Hello World" System.out.println(text.replace(" ", "-")); // "--Hello-World--" // Remember: Original String is NOT changed! System.out.println(text); // " Hello World " (unchanged)

8 Conversion: String ↔ char[] ↔ Numbers

🔁 Conversion Methods

String to char[]

String text = "Hello"; // Convert String to char array char[] chars = text.toCharArray(); // Now we can modify individual characters chars[0] = 'J'; // Change 'H' to 'J' // Convert back to String String newText = new String(chars); System.out.println(newText); // "Jello"

Numbers to String

int number = 42; double pi = 3.14159; // Method 1: String.valueOf() String s1 = String.valueOf(number); // "42" String s2 = String.valueOf(pi); // "3.14159" // Method 2: Concatenation with empty String String s3 = "" + number; // "42"

String to Numbers

String numStr = "42"; String piStr = "3.14159"; // Parse String to number int num = Integer.parseInt(numStr); // 42 double pi = Double.parseDouble(piStr); // 3.14159 // Be careful with invalid input! // Integer.parseInt("abc") throws NumberFormatException

9 Summary: Quick Reference

Category Methods
Basic length(), charAt(), isEmpty()
Concatenation + operator, concat()
Extraction substring()
Comparison equals(), equalsIgnoreCase(), compareTo(), contains(), startsWith(), endsWith()
Search indexOf(), lastIndexOf()
Transform toUpperCase(), toLowerCase(), trim(), replace()
Conversion toCharArray(), String.valueOf(), Integer.parseInt()

What's Next?

In the next lesson, we'll learn about StringBuilder and StringBuffer - mutable alternatives that are much more efficient for frequent String modifications!