Java Programming
Strings Tutorial
Study Guide
Java Strings - Complete Tutorial
Master Java Strings: Learn String class fundamentals, 50+ built-in methods, string manipulation, comparison, formatting, StringBuilder, StringBuffer with practical examples.
What are Strings?
In Java, a String is a sequence of characters. Unlike primitive data types, String is a class in Java. Strings are immutable — once created, they cannot be changed.
String is a reference type
// String is a reference type
String message = "Hello World";
Creating Strings
1. String Literal (Recommended)
String literal
String str1 = "Hello";
String str2 = "Hello"; // Points to same object as str1 (String Pool)
2. Using new Keyword
new String()
String str3 = new String("Hello"); // Creates new object in heap
String str4 = new String("Hello"); // Different object
3. Character Array
From char array
char[] chars = {'J', 'a', 'v', 'a'};
String str5 = new String(chars); // "Java"
4. Empty String
Empty string
String empty1 = "";
String empty2 = new String();
String Methods
Important String Methods
| Method | Description | Example |
|---|---|---|
length() | Returns length | "Hello".length() → 5 |
charAt() | Gets character at index | "Java".charAt(1) → 'a' |
toUpperCase() | Converts to uppercase | "hi".toUpperCase() → "HI" |
toLowerCase() | Converts to lowercase | "HELLO".toLowerCase() → "hello" |
trim() | Removes leading/trailing spaces | " hi ".trim() → "hi" |
substring() | Extracts part of string | "Hello".substring(1,4) → "ell" |
replace() | Replaces characters | "Java".replace('J','K') → "Kava" |
contains() | Checks if contains sequence | "Hello".contains("ell") → true |
startsWith() | Checks prefix | "Java".startsWith("Ja") → true |
endsWith() | Checks suffix | "Java".endsWith("va") → true |
isEmpty() | Checks if empty | "".isEmpty() → true |
isBlank() (Java 11+) | Checks if blank | " ".isBlank() → true |
Code Examples
StringMethodsDemo
public class StringMethodsDemo {
public static void main(String[] args) {
String str = " Java Programming ";
System.out.println("Length: " + str.length()); // 20
String trimmed = str.trim();
System.out.println("Trimmed: '" + trimmed + "'"); // 'Java Programming'
System.out.println("Uppercase: " + trimmed.toUpperCase()); // JAVA PROGRAMMING
System.out.println("First char: " + trimmed.charAt(0)); // J
System.out.println("Last char: " + trimmed.charAt(trimmed.length() - 1)); // g
System.out.println("First 4 chars: " + trimmed.substring(0, 4)); // Java
System.out.println("From index 5: " + trimmed.substring(5)); // Programming
System.out.println("Contains 'Java': " + trimmed.contains("Java")); // true
System.out.println("Starts with 'Java': " + trimmed.startsWith("Java")); // true
System.out.println("Ends with 'ing': " + trimmed.endsWith("ing")); // true
}
}
String Concatenation
1. Using + Operator
+ operator
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName; // "John Doe"
2. Using concat() Method
concat()
String str1 = "Hello";
String str2 = "World";
String result = str1.concat(" ").concat(str2); // "Hello World"
3. Mixed Types
Mixed types
int age = 25;
String message = "Age: " + age; // "Age: 25"
Performance Consideration
StringBuilder in loops
// Inefficient (creates many intermediate strings)
String bad = "";
for (int i = 0; i < 1000; i++) {
bad += i; // Bad!
}
// Efficient (use StringBuilder)
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i);
}
String good = sb.toString();
String Comparison
equals() vs ==
StringComparison
public class StringComparison {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
System.out.println(s1 == s2); // true (same object in String Pool)
System.out.println(s1 == s3); // false (different objects)
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // true
String s4 = "hello";
System.out.println(s1.equalsIgnoreCase(s4)); // true
System.out.println("Apple".compareTo("Banana")); // negative
System.out.println("Banana".compareTo("Apple")); // positive
System.out.println("Java".compareTo("Java")); // 0
}
}
Searching in Strings
StringSearch
public class StringSearch {
public static void main(String[] args) {
String text = "The quick brown fox jumps over the lazy dog";
System.out.println("Index of 'quick': " + text.indexOf("quick")); // 4
System.out.println("Index of 'o': " + text.indexOf('o')); // 12
System.out.println("Index of 'zebra': " + text.indexOf("zebra")); // -1
System.out.println("Last index of 'o': " + text.lastIndexOf('o')); // 38
System.out.println("Last index of 'the': " + text.lastIndexOf("the")); // 31
System.out.println("Find 'o' after index 20: " + text.indexOf('o', 20)); // 38
System.out.println("Contains 'fox': " + text.contains("fox")); // true
System.out.println("Matches word 'brown': " + text.matches(".*brown.*")); // true
}
}
Modifying Strings (Creating New Strings)
Remember: Strings are immutable — these methods return new strings.
StringModification
public class StringModification {
public static void main(String[] args) {
String original = "Hello World";
String replaced = original.replace('o', 'a'); // "Hella Warld"
String replacedAll = original.replaceAll("World", "Java"); // "Hello Java"
String sub = original.substring(6); // "World"
String upper = original.toUpperCase(); // "HELLO WORLD"
String lower = original.toLowerCase(); // "hello world"
String spaced = " Hi ";
String trimmed = spaced.trim(); // "Hi"
String[] words = original.split(" "); // ["Hello", "World"]
String joined = String.join("-", "2024", "01", "15"); // "2024-01-15"
String repeated = "Hi".repeat(3); // "HiHiHi"
System.out.println("Original unchanged: " + original); // Still "Hello World"
}
}
StringBuilder and StringBuffer
For mutable strings (when you need to modify frequently):
| Feature | StringBuilder | StringBuffer |
|---|---|---|
| Thread-safe | No | Yes |
| Performance | Faster | Slower |
| Use case | Single thread | Multi-thread |
StringBuilder Examples
StringBuilderDemo
public class StringBuilderDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuilder("Hello");
StringBuilder sb3 = new StringBuilder(50);
sb.append("Java").append(" ").append("Programming");
System.out.println(sb); // "Java Programming"
sb.insert(5, "is ");
System.out.println(sb); // "Java is Programming"
sb.replace(8, 10, "the");
System.out.println(sb); // "Java is the Programming"
sb.delete(8, 12);
System.out.println(sb); // "Java is Programming"
sb.reverse();
System.out.println(sb); // "gnimmargorP si avaJ"
String result = sb.toString();
StringBuilder numbers = new StringBuilder();
for (int i = 1; i <= 10; i++) {
numbers.append(i);
if (i < 10) numbers.append(", ");
}
System.out.println(numbers); // "1, 2, 3, 4, 5, 6, 7, 8, 9, 10"
}
}
Practical Examples
Example 1: Password Validator
PasswordValidator
public class PasswordValidator {
public static void main(String[] args) {
String password = "Pass123!";
boolean isValid = validatePassword(password);
System.out.println("Password valid: " + isValid);
}
static boolean validatePassword(String pwd) {
if (pwd == null || pwd.length() < 8) {
System.out.println("Password must be at least 8 characters");
return false;
}
boolean hasUpper = false, hasLower = false, hasDigit = false, hasSpecial = false;
for (char c : pwd.toCharArray()) {
if (Character.isUpperCase(c)) hasUpper = true;
else if (Character.isLowerCase(c)) hasLower = true;
else if (Character.isDigit(c)) hasDigit = true;
else hasSpecial = true;
}
if (!hasUpper) System.out.println("Need uppercase letter");
if (!hasLower) System.out.println("Need lowercase letter");
if (!hasDigit) System.out.println("Need digit");
if (!hasSpecial) System.out.println("Need special character");
return hasUpper && hasLower && hasDigit && hasSpecial;
}
}
Example 2: Email Extractor
EmailExtractor
public class EmailExtractor {
public static void main(String[] args) {
String text = "Contact us at support@example.com or sales@company.org";
extractEmails(text);
}
static void extractEmails(String text) {
String[] words = text.split(" ");
for (String word : words) {
if (word.contains("@") && word.contains(".")) {
System.out.println("Found email: " + word);
}
}
}
}
Example 3: Text Formatter
TextFormatter
public class TextFormatter {
public static void main(String[] args) {
String text = " java PROGRAMMING is FUN ";
System.out.println("Original: '" + text + "'");
System.out.println("After clean: '" + cleanText(text) + "'");
System.out.println("Capitalized: '" + capitalizeWords(text) + "'");
}
static String cleanText(String text) {
return text.trim().toLowerCase();
}
static String capitalizeWords(String text) {
String cleaned = text.trim().toLowerCase();
String[] words = cleaned.split(" ");
StringBuilder result = new StringBuilder();
for (String word : words) {
if (word.length() > 0) {
result.append(word.substring(0, 1).toUpperCase())
.append(word.substring(1)).append(" ");
}
}
return result.toString().trim();
}
}
Common Pitfalls
1. Null vs Empty String
Null-safe checks
String str1 = null;
String str2 = "";
// if (str1.isEmpty()) { } // NullPointerException
if (str1 != null && !str1.isEmpty()) {
// Process
}
if (str1 == null || str1.isBlank()) {
System.out.println("String is null or blank");
}
2. Comparing Strings
Use equals(), not ==
String s1 = new String("Hello");
String s2 = new String("Hello");
if (s1 == s2) { } // false - different objects
if (s1.equals(s2)) { // true
System.out.println("Equal");
}
if ("Hello".equals(s1)) { // null-safe
System.out.println("Equal");
}
3. Performance in Loops
StringBuilder in loops
// BAD
String result = "";
for (int i = 0; i < 1000; i++) {
result += "x";
}
// GOOD
StringBuilder result = new StringBuilder();
for (int i = 0; i < 1000; i++) {
result.append("x");
}
4. IndexOutOfBoundsException
Safe indices
String str = "Java";
// charAt(str.length()) // Error! last index is length-1
char last = str.charAt(str.length() - 1); // Correct
if (str.length() > 5) {
String sub = str.substring(5);
}
Quick Reference Card
Quick reference
// Creation
String s = "text";
String s2 = new String("text");
// Common operations
int len = s.length();
char c = s.charAt(0);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
String trimmed = s.trim();
String sub = s.substring(1, 4);
boolean eq = s1.equals(s2);
boolean eqIgnore = s1.equalsIgnoreCase(s2);
int compare = s1.compareTo(s2);
int index = s.indexOf("find");
boolean contains = s.contains("sub");
String replaced = s.replace('a', 'b');
String[] parts = s.split(",");
String joined = String.join("-", arr);
// StringBuilder
StringBuilder sb = new StringBuilder();
sb.append("text");
sb.insert(0, "start");
sb.replace(0, 3, "new");
sb.delete(0, 2);
sb.reverse();
String result = sb.toString();
// Null-safe
if (s == null || s.isEmpty()) { }
if (s == null || s.isBlank()) { } // Java 11+
Key Takeaways
- Strings are immutable — any modification creates a new
String - Use
equals()for content comparison, not== - String literals are stored in the String Pool for memory efficiency
- Use
StringBuilderfor frequent modifications in single-threaded code - Use
StringBufferfor thread-safe modifications - Check for
nullbefore calling string methods - Indices start at
0; last index islength - 1 trim()removes whitespace from both endssplit()uses regular expressions — escape special characters if needed- Performance matters — use
StringBuilderin loops
Summary
Master string literals vs new String(), common methods, safe comparison with equals(), and StringBuilder for efficient building. Avoid == for content, null-pointer traps, and += in tight loops.