πŸ“š Java Reference
Estimated reading: 4 minutes 363 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 :
Share

Java String Methods

Or Copy Link

CONTENTS
Scroll to Top