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
| Method | Description | Example | Returns |
|---|---|---|---|
| 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.
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));
}
}
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.
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"));
}
}
Java
5
class Main
{
public static void main(String args[])
{
String s = " Hello Java ";
System.out.println(s.trim());
System.out.println(s.replace("Java", "World"));
}
}
Hello World
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);
}
}
Banana
Mango
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));
}
}
true
32
class Main
{
public static void main(String args[])
{
String s = "PBA";
String rev = new StringBuilder(s).reverse().toString();
System.out.println(rev);
}
}
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.
For security, thread safety and to support the String pool optimization.
== checks reference identity; equals() checks content equality.
A special memory area where Java stores String literals so identical literals share the same object.
String is immutable; StringBuilder is mutable & not thread-safe; StringBuffer is mutable & synchronized.
String.intern() work?It adds the String to the pool (if not already there) and returns the pooled reference.
FAQ
Yes — calling methods on a null String throws
NullPointerException.
Strings themselves are immutable and thread-safe; StringBuilder is not but StringBuffer is.
split("\\.") mean?It splits on a literal dot — the dot is regex special, so it must be escaped.
Yes — but inside loops prefer StringBuilder for performance.
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
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
Quick Reference
| Keyword / Concept | Meaning | Used For | Java Since |
|---|---|---|---|
| String Functions | String Functions concept | Core Java | 1.0 |
| class | Blueprint of objects | OOP | 1.0 |
| static | Class-level member | Utilities | 1.0 |
| final | Constant / no override | Immutability | 1.0 |
| public | Accessible everywhere | API exposure | 1.0 |
| private | Class-only access | Encapsulation | 1.0 |
Related Topics
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.