πŸ“š Java Reference
Estimated reading: 4 minutes 47 views

🧡 Java String Methods: Complete Guide with Examples, Syntax & Explanations


🧲 Introduction – Why Java String Methods Matter

In Java, String is one of the most widely used classes. Whether you’re handling user input, displaying messages, or parsing files β€” strings are everywhere. But raw strings are just data β€” string methods give them power. πŸ’‘

By mastering Java String methods, you’ll be able to:

  • βœ… Manipulate text efficiently
  • βœ… Search, compare, and extract substrings
  • βœ… Format and clean input data

πŸ“˜ Java String is immutable, meaning every modification creates a new object.


πŸ”‘ What is a Java String?

A String in Java is a sequence of characters, treated as an object. You create strings using:

String message = "Hello, Java!";

πŸ“‹ Common Java String Methods

Below is a categorized table of popular String methods:

🧩 MethodπŸ“˜ Purpose
length()Returns the number of characters
charAt(int index)Returns the character at a given index
substring(int begin, int end)Extracts a portion of the string
toLowerCase() / toUpperCase()Converts case
trim()Removes whitespace
replace(old, new)Replaces characters
equals(str) / equalsIgnoreCase(str)Compares strings
contains(str)Checks if substring exists
startsWith() / endsWith()Checks prefix/suffix
split(regex)Splits string based on regex
indexOf() / lastIndexOf()Finds character/index
isEmpty()Checks if string is empty
concat(str)Concatenates two strings

πŸ”Ž Examples of Java String Methods


βœ… 1. length() – Find the String Length

String text = "Java";
System.out.println(text.length());

Output:

4

βœ… Explanation: Returns the number of characters in "Java".


βœ… 2. charAt(int index) – Access Character by Index

String name = "Developer";
System.out.println(name.charAt(0));

Output:

D

βœ… Explanation: Indexing starts at 0, so this prints the first character.


βœ… 3. substring(int begin, int end)

String title = "Full Stack Developer";
System.out.println(title.substring(0, 4));

Output:

Full

βœ… Explanation: Extracts characters from index 0 to 3 (excluding index 4).


βœ… 4. toLowerCase() and toUpperCase()

String lang = "Java Programming";
System.out.println(lang.toLowerCase());
System.out.println(lang.toUpperCase());

Output:

java programming
JAVA PROGRAMMING

βœ… Explanation: Converts the string to lower and upper case.


βœ… 5. trim() – Remove Leading/Trailing Whitespaces

String input = "   Hello World!   ";
System.out.println(input.trim());

Output:

Hello World!

βœ… Explanation: Removes extra spaces from start and end.


βœ… 6. replace() – Replace Characters/Substrings

String sentence = "Java is awesome!";
System.out.println(sentence.replace("awesome", "powerful"));

Output:

Java is powerful!

βœ… Explanation: Replaces awesome with powerful.


βœ… 7. equals() and equalsIgnoreCase()

String a = "Java";
String b = "java";
System.out.println(a.equals(b));             // false
System.out.println(a.equalsIgnoreCase(b));   // true

βœ… Explanation: equals() is case-sensitive, equalsIgnoreCase() is not.


βœ… 8. contains() – Search for Substring

String text = "Java Backend Developer";
System.out.println(text.contains("Backend"));

Output:

true

βœ… Explanation: Confirms if “Backend” exists in the string.


βœ… 9. startsWith() and endsWith()

String url = "https://openai.com";
System.out.println(url.startsWith("https"));
System.out.println(url.endsWith(".org"));

Output:

true
false

βœ… Explanation: Validates the beginning and end of a string.


βœ… 10. split() – Break String into Parts

String data = "apple,banana,grape";
String[] fruits = data.split(",");
for (String fruit : fruits) {
    System.out.println(fruit);
}

Output:

apple
banana
grape

βœ… Explanation: Splits the string into an array using , as the delimiter.


βœ… 11. indexOf() and lastIndexOf()

String quote = "Think Twice, Code Once";
System.out.println(quote.indexOf("e"));       // 11
System.out.println(quote.lastIndexOf("e"));   // 18

βœ… Explanation: Finds the first and last position of a character.


βœ… 12. isEmpty()

String emptyStr = "";
System.out.println(emptyStr.isEmpty());

Output:

true

βœ… Explanation: Checks if the string is empty (length is 0).


βœ… 13. concat() – Append Strings

String first = "Hello";
String second = " World";
System.out.println(first.concat(second));

Output:

Hello World

βœ… Explanation: Appends two strings.


πŸ’‘ Java String Method Tips

  • βœ… Use equals() instead of == for string comparison.
  • βœ… Chain methods like str.trim().toLowerCase() for better readability.
  • ⚠️ Avoid modifying large strings repeatedly β€” use StringBuilder for better performance.
  • πŸ“˜ Strings are immutable. Each method returns a new String, not modifying the original.

🧠 Summary – Java String Methods at a Glance

Java String methods provide powerful tools to manipulate, format, analyze, and transform text data in your applications. Since strings are immutable, each method returns a new string, ensuring thread-safety and data integrity.

Here’s what you’ve learned:

  • βœ… String Basics: Strings are objects and created using String class.
  • βœ… Key Methods Covered: length(), charAt(), substring(), toUpperCase(), trim(), replace(), equals(), split(), indexOf(), and many more.
  • βœ… Real-World Examples: Each method included syntax, output, and detailed explanation.
  • ⚠️ Best Practices: Use equals() for comparison, avoid == for content check, and prefer StringBuilder for heavy string manipulation.

Mastering these methods equips you to handle text data efficiently β€” an essential skill for any Java developer.


❓ FAQs on Java String Methods

❓ What is the difference between equals() and ==?

equals() compares content, while == compares memory addresses (references).

❓ Can we modify a String in Java?

No, Strings are immutable. Any modification returns a new string.

❓ Which is better: + operator or concat()?

Both work similarly. However, for multiple concatenations, prefer StringBuilder.

❓ What happens if charAt() index is out of bounds?

It throws a StringIndexOutOfBoundsException.

❓ How do I remove all spaces from a string?

Use: str.replace(" ", "") – it removes all spaces.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Java String Methods

Or Copy Link

CONTENTS
Scroll to Top