← Back to Chapters

Java String Methods

? Java String Methods

? Quick Overview

In Java, String is an immutable class used to represent sequences of characters. Java provides a rich set of built-in methods (around 65+) to manipulate, compare, search, split, and transform strings efficiently.

? Key Concepts

  • Strings are immutable (cannot be changed once created)
  • Methods return new String objects
  • Stored in the String Constant Pool
  • Belongs to java.lang package

? Syntax / Theory

A string method is always called using a string object.

? View Code Example
// Creating a String object in Java
String name = "Java Programming";

? Commonly Used String Methods

? View Code Example
// Demonstration of multiple String methods
String text = " Hello Java World ";

System.out.println(text.length());
System.out.println(text.trim());
System.out.println(text.toUpperCase());
System.out.println(text.toLowerCase());
System.out.println(text.charAt(1));
System.out.println(text.substring(1, 6));
System.out.println(text.contains("Java"));
System.out.println(text.replace("Java", "Python"));
System.out.println(text.startsWith(" Hello"));
System.out.println(text.endsWith("World "));

? Live Output / Explanation

  • length() → Total characters including spaces
  • trim() → Removes leading and trailing spaces
  • toUpperCase() → Converts to uppercase
  • substring() → Extracts part of string
  • contains() → Checks substring existence

? Live String Playground

Type in the box below to see how Java String methods change your text in real-time:

length()
toUpperCase()
toLowerCase()
trim()
charAt(0)
startsWith("Java")

? Tips & Best Practices

  • Use equals() instead of == for comparison
  • Use StringBuilder for frequent modifications
  • Avoid unnecessary string concatenation in loops
  • Prefer isEmpty() over length() == 0

? Try It Yourself

  • Write a program to count vowels in a string
  • Reverse a string without using built-in reverse
  • Check if a string is a palindrome
  • Count words in a sentence