In Java, Strings are reference types, meaning they are stored in memory as objects, unlike primitive types like int or char. This has an important impact on how memory is managed, particularly with the String Pool (also called String Interning).
- The String Pool is a special area in memory where string literals are stored. When you create a string with a literal, like
"java", Java checks if the string already exists in the pool. If it does, it uses the existing reference; if not, it adds it to the pool. - The same string object can be referenced by different variables, like in the example with a and b below.
Example:
String a = "java";
String b = "java"; // Same object in the pool
System.out.println(System.identityHashCode(a)); // 713338599
System.out.println(System.identityHashCode(b)); // 713338599
But when you create a string with new String(), both a and b are different objects with different memory references.
String a = new String("java");
String b = new String("java"); // Two separate objects
System.out.println(System.identityHashCode(a)); // 317983781
System.out.println(System.identityHashCode(b)); // 1555845260
Immutability
Strings are immutable in Java. Once a string is created, its value cannot be changed. Any operation that seems to change a string (like appending text) actually creates a new string object.
Example:
String message = "hello";
message = message + " world"; // New String object is created
System.out.println(message); // "hello world"
Why is this important?
- Security: Immutable strings prevent accidental or malicious changes (like modifying a password or file path).
- Memory Efficiency: The same string object can be reused across the program without duplicating it.
- Thread Safety: Multiple threads can safely use the same string since it’s immutable.
Useful String Methods
Check / Validate Strings
isEmpty(): Returns true if the string has no characters (i.e., length is 0).
System.out.println("".isEmpty()); // true
System.out.println(" ".isEmpty()); // false
isBlank(): (Java 11+) Returns true if the string is empty or contains only whitespace.
System.out.println(" ".isBlank()); // true
System.out.println("abc".isBlank()); // false
matches(String regex): Checks if the string matches a regular expression.
String email = "user@example.com";
System.out.println(email.matches("[A-Za-z0-9]+@[A-Za-z]+\\.com")); // true
"one".matches("one") // true
Compare Strings
equals(String): Compares two strings for equality (case-sensitive).
System.out.println("java".equals("java")); // true
System.out.println("Java".equals("java")); // false
equalsIgnoreCase(String): Compares two strings for equality, ignoring case differences.
System.out.println("java".equalsIgnoreCase("JAVA")); // true
contains(String): Checks if a string contains a specific sequence of characters.
System.out.println("hello world".contains("world")); // true
startsWith(String): Checks if a string starts with the specified prefix.
endsWith(String): Checks if a string ends with the specified suffix.
System.out.println("hello".startsWith("he")); // true
System.out.println("hello".endsWith("lo")); // true
Working with indexes
length(): Returns the number of characters in the string.
System.out.println("hello".length()); // 5
indexOf(String): Returns the index of the first occurrence of the specified substring. Returns -1 if not found.
System.out.println("hello".indexOf("e")); // 1
System.out.println("hello".indexOf("z")); // -1
lastIndexOf(String): Returns the index of the last occurrence of the specified substring.
System.out.println("hello".lastIndexOf("l")); // 3
charAt(index): Returns the character at the specified index.
System.out.println("hello".charAt(2)); // 'l'
Modifications / Extractions
trim(): Removes any leading and trailing spaces.
String input = " hello ";
System.out.println(input.trim()); // "hello"
toUpperCase(): Converts all characters to uppercase.
toLowerCase(): Converts all characters to lowercase.
String input = "hello";
System.out.println(input.toUpperCase()); // "HELLO"
String input2 = "HELLO";
System.out.println(input2.toLowerCase()); // "hello"
substring(start): Returns a substring from the specified start index to the end of the string.
String str = "hello world";
System.out.println(str.substring(6)); // "world"
substring(start, end): Returns a substring from the start index to the end index minus 1.
String str = "hello world";
System.out.println(str.substring(0, 5)); // "hello"
replace(old, new): Replaces all occurrences of a specified substring with another substring.
String str = "hello world";
System.out.println(str.replace("world", "Java")); // "hello Java"
Other Helpful String Methods
concat(String): Appends one string to another.
String str = "hello";
System.out.println(str.concat(" world")); // "hello world"
valueOf(): Converts other types (e.g., int, float, boolean) into a string.
int num = 123;
System.out.println(String.valueOf(num)); // "123"
Summary
- Strings in Java are reference types, immutable, and widely used for text manipulation.
- Key methods like
equals(),length(),substring(),replace(), andtrim()are frequently used for comparing, extracting, and modifying strings. - Java’s string methods also help with validation (e.g.,
isEmpty(),matches()) and case conversion (toUpperCase(),toLowerCase()).
Leave a Reply