Java String Functions Tutorial
Chapter 08 · Java Programming Series
PBA Institute 14 min read Beginner to Intermediate 2024

String Functions in Java

Strings are everywhere — names, messages, URLs, file paths. Java's String class is immutable and packed with dozens of useful methods. Mastering them unlocks fast text manipulation for searching, formatting, validation and data extraction.

Key Features

📏

length()

Returns the number of characters in the string.

🔤

charAt(i)

Returns the character at a specific index.

✂️

substring()

Extracts a portion of the string.

🔄

replace()

Replaces characters or substrings with another value.

📤

split()

Splits a string into an array using a delimiter.

🆚

equals()

Compares two strings for equality (case sensitive).

Syntax

  • Create a string: String s = "Hello";
  • Call methods using dot notation: s.length(), s.charAt(0)
  • Strings are immutable — methods return new strings.
  • Use StringBuilder for repeated modifications.

Common String Methods

MethodDescriptionExampleReturns
length()Number of chars"Java".length()4
charAt(i)Char at index"Java".charAt(1)'a'
substring(a,b)Substring"Java".substring(1,3)"av"
toUpperCase()Upper case"java".toUpperCase()"JAVA"
toLowerCase()Lower case"JAVA".toLowerCase()"java"
trim()Strip spaces" hi ".trim()"hi"
replace()Replace chars"abc".replace('a','x')"xbc"
indexOf()Find position"Java".indexOf('v')2
equals()Compare"a".equals("a")true
split()Tokenize"a,b".split(","){a, b}

Detailed Explanation & First Example

Let's start with a hands-on example. The program below shows the core idea behind String Functions in just a few lines of Java. Read it line by line and observe how Java executes each statement in order.

Basic String Methods
class Main
{
    public static void main(String args[])
    {
        String s = "PBA Institute";

        System.out.println("Length: " + s.length());
        System.out.println("Upper:  " + s.toUpperCase());
        System.out.println("Lower:  " + s.toLowerCase());
        System.out.println("Char 4: " + s.charAt(4));
    }
}
Output Length: 13
Upper: PBA INSTITUTE
Lower: pba institute
Char 4: I

Examples — Beginner to Advanced

The following examples progress from simple to more practical patterns. Try each in your IDE, change the inputs and observe the output. This is the fastest way to internalize the concept.

Substring & Index
class Main
{
    public static void main(String args[])
    {
        String s = "Java Programming";

        System.out.println(s.substring(5));
        System.out.println(s.substring(0, 4));
        System.out.println(s.indexOf("Program"));
    }
}
Output Programming
Java
5
Replace & Trim
class Main
{
    public static void main(String args[])
    {
        String s = "   Hello Java   ";

        System.out.println(s.trim());
        System.out.println(s.replace("Java", "World"));
    }
}
Output Hello Java
Hello World
Split a CSV Line
class Main
{
    public static void main(String args[])
    {
        String s = "Apple,Banana,Mango";

        String fruits[] = s.split(",");

        for (String f : fruits)
            System.out.println(f);
    }
}
Output Apple
Banana
Mango
Compare Strings
class Main
{
    public static void main(String args[])
    {
        String a = "hello";
        String b = "HELLO";

        System.out.println(a.equals(b));
        System.out.println(a.equalsIgnoreCase(b));
        System.out.println(a.compareTo(b));
    }
}
Output false
true
32
Reverse a String with StringBuilder
class Main
{
    public static void main(String args[])
    {
        String s = "PBA";

        String rev = new StringBuilder(s).reverse().toString();

        System.out.println(rev);
    }
}
Output ABP

Notes & Tips

  • Strings in Java are immutable — each modification creates a new String object.
  • Use StringBuilder or StringBuffer for heavy modification.
  • Use equals() for content comparison; == compares object references.
  • String constant pool optimizes memory by reusing literal Strings.
  • split() uses regex by default — escape special characters as needed.

Real-World Use Cases

Form Validation

Trim whitespace, check email format, ensure minimum length.

Data Parsing

Split CSV files, parse logs, extract tokens.

Chat / NLP

Lowercase, tokenize and analyze messages.

Searching

Use indexOf, contains to find substrings.

Practice Questions

Reading is not enough — practice solidifies knowledge. Try every question below in your own editor before peeking at any solution.

  • Q1. Count vowels and consonants in a string.
  • Q2. Reverse a string without StringBuilder.
  • Q3. Check if a string is a palindrome.
  • Q4. Count word occurrences in a sentence.
  • Q5. Convert the first letter of each word to uppercase.

Interview Questions

These are the most common questions asked in Java interviews on this topic. Memorize the concept, not just the answer — interviewers often follow up with edge cases.

Q1 Why are Java Strings immutable?
For security, thread safety and to support the String pool optimization.
Q2 Difference between equals() and ==?
== checks reference identity; equals() checks content equality.
Q3 What is the String pool?
A special memory area where Java stores String literals so identical literals share the same object.
Q4 Difference between String, StringBuilder and StringBuffer?
String is immutable; StringBuilder is mutable & not thread-safe; StringBuffer is mutable & synchronized.
Q5 How does String.intern() work?
It adds the String to the pool (if not already there) and returns the pooled reference.

FAQ

FAQ 1 Can a String be null?
Yes — calling methods on a null String throws NullPointerException.
FAQ 2 Is String thread safe?
Strings themselves are immutable and thread-safe; StringBuilder is not but StringBuffer is.
FAQ 3 What does split("\\.") mean?
It splits on a literal dot — the dot is regex special, so it must be escaped.
FAQ 4 Can I concatenate Strings with +?
Yes — but inside loops prefer StringBuilder for performance.
FAQ 5 How do I convert int to String?
Use String.valueOf(n) or Integer.toString(n).

Common Mistakes to Avoid

Even experienced developers slip on the same pitfalls. Watch out for these classic mistakes while working with String Functions in Java:

  • Forgetting the semicolon ; at the end of statements while using String Functions.
  • Mixing up similar method names — read Java docs before using new APIs related to String Functions.
  • Ignoring compiler warnings — they often hint at bugs that will appear later in production.
  • Hard-coding values that should come from configuration files or environment variables.
  • Not handling edge cases: empty inputs, very large inputs, negative numbers and null references.
  • Skipping unit tests — small tests prevent big regressions, especially around control flow.

At-a-Glance

Advantages
Readable Reusable Testable Standardized
Watch Out
Edge Cases Null Safety Performance Memory
Java Version
JDK 8+ JDK 11 JDK 17 LTS JDK 21 LTS
Pair With
Do While Loop Arrays OOP Best Practices

Best Practices

📐

Follow Conventions

Use camelCase for variables, PascalCase for classes, UPPER_SNAKE for constants.

🧪

Write Tests

Cover happy path and edge cases with JUnit before shipping changes to production.

🧹

Keep Methods Short

A method should do one thing and fit on a single screen. Refactor when it grows.

🔍

Validate Inputs

Never trust user input. Validate at the boundary, fail fast and log meaningfully.

📝

Comment the Why

Comments should explain why a decision was made — not what the code does line by line.

♻️

Refactor Often

Small frequent refactors are cheap and safe; big rewrites are risky and expensive.

Pro Tips

TIP 01 Use clear, descriptive identifiers when writing code involving String Functions — your future self will thank you.
TIP 02 Run small experiments in jshell (Java's REPL) to test ideas before committing them to a project.
TIP 03 Read the official java.lang and java.util documentation. The standard library is huge and surprisingly powerful.
TIP 04 Combine this topic with unit testing (JUnit 5) — it forces you to think about edge cases.
TIP 05 Practice with online judges (HackerRank, LeetCode) to internalise the patterns used in real interviews.

Quick Reference

Keyword / ConceptMeaningUsed ForJava Since
String FunctionsString Functions conceptCore Java1.0
classBlueprint of objectsOOP1.0
staticClass-level memberUtilities1.0
finalConstant / no overrideImmutability1.0
publicAccessible everywhereAPI exposure1.0
privateClass-only accessEncapsulation1.0

Related Topics

PREV Do While Loop — strengthens your understanding of the previous building block.
NEXT Arrays — the natural progression after mastering String Functions.
OOP Object Oriented Programming — Class, Object, Inheritance, Polymorphism, Encapsulation, Abstraction.
DSA Data Structures & Algorithms — apply this topic in real coding-interview challenges.
STD LIB Java Standard Library — explore java.util, java.lang and java.io.

Summary

Java's String class is rich in built-in methods for length, slicing, searching, replacing and splitting. Strings are immutable, so use StringBuilder when you need to modify text repeatedly. Use equals() for comparison and split() for tokenization.

Continue Learning