JAVA - Zero to Hero / Arrays and Strings

String Methods in JAVA

🔧 Why Use String Methods?

Java treats every string like an object, so instead of writing extra logic to manipulate text manually, you can just call these ready-made methods.

1️⃣ length()

Function:

Returns the number of characters in the string.

String s = "Hello";
System.out.println(s.length());
5

2️⃣ charAt(int index)

Function:

Returns the character at the specified index (starts from 0).

String s = "Hello";
System.out.println(s.charAt(1));
e

3️⃣ substring(int start, int end)

Function:

Returns part of the string from start index to (end - 1).

String s = "Hello";
System.out.println(s.substring(1, 4));
ell

4️⃣ toUpperCase()

Function:

Converts all characters in the string to uppercase.

String s = "Hello";
System.out.println(s.toUpperCase());
HELLO

5️⃣ toLowerCase()

Function:

Converts all characters in the string to lowercase.

String s = "Hello";
System.out.println(s.toLowerCase());
hello

6️⃣ equals(String another)

Function:

Checks if two strings are exactly equal (case-sensitive).

String s = "Hello";
System.out.println(s.equals("Hello"));
true

7️⃣ contains(CharSequence seq)

Function:

Checks whether the string contains the given sequence of characters.

String s = "Hello";
System.out.println(s.contains("ll"));
true

8️⃣ replace(char oldChar, char newChar)

Function:

Replaces all occurrences of one character with another.

String s = "Hello";
System.out.println(s.replace('l', 'x'));
Hexxo

9️⃣ trim()

Function:

Removes leading and trailing spaces from the string.

String s = "  Hello  ";
System.out.println(s.trim());
Hello