Java Strings and String Methods
Master text manipulation in Java with Strings and learn powerful built-in methods for common operations.
What is a String?
A String in Java is a sequence of characters used to store and manipulate text. Strings are one of the most commonly used data types in programming.
Unlike primitive data types, String is a class in Java, which means it comes with many built-in methods to perform operations on text.
- Strings are objects, not primitive types
- String values are enclosed in double quotes: "Hello"
- Strings are immutable (cannot be changed after creation)
- Java provides many methods to work with strings
💡 Important: Strings are immutable in Java. Once created, their values cannot be changed. Any modification creates a new String object.
Creating Strings
There are two main ways to create String objects in Java: using string literals and using the new keyword.
Example: Different Ways to Create Strings
public class StringCreation {
public static void main(String[] args) {
// Method 1: String literal (most common)
String name = "John";
// Method 2: Using new keyword
String greeting = new String("Hello");
// Method 3: From character array
char[] letters = {'J', 'a', 'v', 'a'};
String language = new String(letters);
System.out.println(name);
System.out.println(greeting);
System.out.println(language);
}
}
John Hello Java
Explanation:
String name = "John"- Creates a string using literal notation (recommended)new String("Hello")- Creates a string using constructornew String(letters)- Creates a string from a character array
String Concatenation
Concatenation means joining two or more strings together. You can use the + operator or the concat() method.
Example: Joining Strings
public class StringConcat {
public static void main(String[] args) {
String firstName = "John";
String lastName = "Doe";
// Method 1: Using + operator
String fullName1 = firstName + " " + lastName;
System.out.println(fullName1);
// Method 2: Using concat() method
String fullName2 = firstName.concat(" ").concat(lastName);
System.out.println(fullName2);
// Concatenating with numbers
String message = "I am " + 20 + " years old";
System.out.println(message);
}
}
John Doe John Doe I am 20 years old
Explanation:
firstName + " " + lastName- Uses + operator to join stringsconcat()- Built-in method to concatenate strings- Numbers are automatically converted to strings when concatenating
Essential String Methods
1. length() - Get String Length
Returns the number of characters in a string.
Example: "Hello".length() returns 5
2. toUpperCase() and toLowerCase()
Converts all characters to uppercase or lowercase.
Example: "Java".toUpperCase() returns "JAVA"
3. charAt() - Get Character at Index
Returns the character at a specific position (index starts from 0).
Example: "Hello".charAt(0) returns 'H'
4. substring() - Extract Part of String
Returns a portion of the string from start index to end index.
Example: "Hello".substring(1, 4) returns "ell"
5. equals() and equalsIgnoreCase()
Compares two strings for equality (case-sensitive or case-insensitive).
Example: "Java".equals("java") returns false
6. contains() - Check if String Contains Text
Checks if a string contains a specific sequence of characters.
Example: "Hello World".contains("World") returns true
String Methods in Action
Let's see multiple string methods working together in a practical example.
Example: Using Various String Methods
public class StringMethods {
public static void main(String[] args) {
String text = " Java Programming ";
// Length
System.out.println("Length: " + text.length());
// Remove spaces
String trimmed = text.trim();
System.out.println("Trimmed: '" + trimmed + "'");
// Case conversion
System.out.println("Uppercase: " + trimmed.toUpperCase());
System.out.println("Lowercase: " + trimmed.toLowerCase());
// Character at position
System.out.println("Character at index 0: " + trimmed.charAt(0));
// Substring
System.out.println("Substring (0-4): " + trimmed.substring(0, 4));
// Check content
System.out.println("Contains 'Java': " + trimmed.contains("Java"));
// Replace text
System.out.println("Replace: " + trimmed.replace("Java", "Python"));
}
}
Length: 21 Trimmed: 'Java Programming' Uppercase: JAVA PROGRAMMING Lowercase: java programming Character at index 0: J Substring (0-4): Java Contains 'Java': true Replace: Python Programming
Explanation:
trim()- Removes leading and trailing spacessubstring(0, 4)- Extracts characters from index 0 to 3 (end index is exclusive)replace("Java", "Python")- Replaces all occurrences of "Java" with "Python"- Each method returns a new String (original remains unchanged)
String Comparison
Never use == to compare strings! Always use equals() method for proper comparison.
Example: Comparing Strings Correctly
public class StringComparison {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
String s4 = "hello";
// Using equals() - compares content
System.out.println("s1.equals(s2): " + s1.equals(s2));
System.out.println("s1.equals(s3): " + s1.equals(s3));
// Using == - compares reference (not recommended)
System.out.println("s1 == s2: " + (s1 == s2));
System.out.println("s1 == s3: " + (s1 == s3));
// Case-insensitive comparison
System.out.println("s1.equalsIgnoreCase(s4): " + s1.equalsIgnoreCase(s4));
// compareTo() - for alphabetical ordering
System.out.println("s1.compareTo(s4): " + s1.compareTo(s4));
}
}
s1.equals(s2): true s1.equals(s3): true s1 == s2: true s1 == s3: false s1.equalsIgnoreCase(s4): true s1.compareTo(s4): -32
Explanation:
equals()- Compares the actual content of strings (always use this)==- Compares memory references, not content (avoid for strings)equalsIgnoreCase()- Compares content ignoring case differencescompareTo()- Returns negative, zero, or positive for ordering
More Useful String Methods
1. indexOf() and lastIndexOf()
Finds the position of a character or substring. Returns -1 if not found.
Example: "Hello".indexOf('l') returns 2
2. startsWith() and endsWith()
Checks if a string starts or ends with specific characters.
Example: "Java.txt".endsWith(".txt") returns true
3. isEmpty() and isBlank()
isEmpty() checks if length is 0. isBlank() checks if only whitespace (Java 11+).
Example: "".isEmpty() returns true
4. split() - Divide String into Array
Splits a string into an array based on a delimiter.
Example: "a,b,c".split(",") creates array ["a", "b", "c"]
5. trim() - Remove Whitespace
Removes leading and trailing spaces from a string.
Example: " Java ".trim() returns "Java"
6. valueOf() - Convert to String
Converts other data types (int, double, boolean) to String.
Example: String.valueOf(100) returns "100"
Practical String Example
A real-world example combining multiple string methods to process user input.
Example: Email Validation and Processing
public class EmailProcessor {
public static void main(String[] args) {
String email = " John.Doe@Example.COM ";
// Clean the input
email = email.trim().toLowerCase();
System.out.println("Cleaned email: " + email);
// Check if valid format
if (email.contains("@") && email.contains(".")) {
System.out.println("Valid email format!");
// Extract username and domain
int atIndex = email.indexOf("@");
String username = email.substring(0, atIndex);
String domain = email.substring(atIndex + 1);
System.out.println("Username: " + username);
System.out.println("Domain: " + domain);
// Check domain
if (domain.endsWith(".com")) {
System.out.println("Commercial domain");
}
} else {
System.out.println("Invalid email format!");
}
}
}
Cleaned email: john.doe@example.com Valid email format! Username: john.doe Domain: example.com Commercial domain
Explanation:
- Combines
trim()andtoLowerCase()to normalize input - Uses
contains()to validate basic email structure - Employs
indexOf()andsubstring()to extract parts - Applies
endsWith()to check domain extension
Important String Concepts
- Immutability: Every string method creates a new String object rather than modifying the original
- String Pool: Java stores string literals in a special memory area for efficiency
- Always use equals(): Never use == to compare string content, only for reference comparison
- Index starts at 0: First character is at index 0, last is at length-1
- StringBuilder for multiple operations: Use StringBuilder when concatenating many strings in a loop
⚠️ Performance Tip: For frequent string modifications, use StringBuilder instead of String concatenation. It's much faster for multiple operations!