Course Content
Core Java
About Lesson

The String class in Java is a fundamental class used for representing and manipulating sequences of characters. It is one of the most commonly used classes in Java.

Creating Strings

String str1 = "Hello, World!"; // Using string literal
String str2 = new String("Hello, World!"); // Using constructor

String Literals

A string literal is a sequence of characters enclosed in double quotes ("). String literals are used to create String objects in Java.

String str1 = "Hello, World!";
String str2 = "Java Programming";

When a string literal is created, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string does not exist, it is added to the pool.

This mechanism helps in saving memory and improving performance by reusing existing string instances.

String str1 = "Hello";
String str2 = "Hello"; // str2 references the same object as str1
String str3 = new String("Hello"); // str3 references a new object

boolean isSameReference1 = (str1 == str2); // true, as str1 and str2 reference the same object in the pool
boolean isSameReference2 = (str1 == str3); // false, as str3 is a new object

String Immutability

String literals in Java are immutable, meaning once a string literal is created, it cannot be changed. Any operation that seems to modify a string actually creates a new string object.

String str = "Hello";
str = str.concat(" World"); // "Hello" is unchanged, a new string "Hello World" is created

String Constant Pool

The String Constant Pool (also known as the interned string pool) is a special memory region in the Java Virtual Machine (JVM) that is used to store string literals.

The String Constant Pool (also known as the interned string pool) is a special memory region in the Java Virtual Machine (JVM) that is used to store string literals. When you create a string literal in Java, the JVM automatically places it in the String Constant Pool.

When you create a string using the new keyword, a new String object is created on the heap, even if an identical string exists in the pool.

The intern() method can be used to add a string to the String Constant Pool or get a reference to an existing string in the pool. If the string already exists in the pool, intern() returns a reference to the pooled instance. If it does not, it adds the string to the pool and returns the reference.

String str1 = new String("Hello");
String str2 = str1.intern(); // str2 references the string in the pool
String str3 = "Hello";

boolean isSameReference = (str2 == str3); // true

Advantages

  • Memory Efficiency: By storing identical strings only once, the pool reduces memory usage.
  • Performance Improvement: String comparisons using == are faster because they compare references, not the content.

Common Methods

length() Returns the length of the string.

String str = "Hello, World!";
int length = str.length(); // 13
System.out.println("Length: " + length);

charAt(int index) Returns the character at the specified index.

String str = "Hello";
char ch = str.charAt(1); // 'e'
System.out.println("Character at index 1: " + ch);

substring(int beginIndex) : Returns a new string that is a substring of this string starting from the specified index.

String str = "Hello, World!";
String substr = str.substring(7); // "World!"
System.out.println("Substring from index 7: " + substr);

substring(int beginIndex, int endIndex) : Returns a new string that is a substring of this string starting from beginIndex to endIndex.

String str = "Hello, World!";
String substr = str.substring(7, 12); // "World"
System.out.println("Substring from index 7 to 12: " + substr);

indexOf(String str) : Returns the index of the first occurrence of the specified substring.

String str = "Hello, World!";
int index = str.indexOf("World"); // 7
System.out.println("Index of 'World': " + index);

lastIndexOf(String str) : Returns the index of the last occurrence of the specified substring.

String str = "Hello, World! Hello, Universe!";
int index = str.lastIndexOf("Hello"); // 14
System.out.println("Last index of 'Hello': " + index);

 

equals(Object anObject) : Compares this string to the specified object for equality.

String str1 = "Hello";
String str2 = "Hello";
boolean isEqual = str1.equals(str2); // true
System.out.println("Strings are equal: " + isEqual);

equalsIgnoreCase(String anotherString) : Compares this string to another string, ignoring case considerations.

String str1 = "hello";
String str2 = "HELLO";
boolean isEqual = str1.equalsIgnoreCase(str2); // true
System.out.println("Strings are equal ignoring case: " + isEqual);

compareTo(String anotherString) : Compares two strings lexicographically.

String str1 = "Hello";
String str2 = "World";
int comparison = str1.compareTo(str2); // negative because "Hello" is lexicographically less than "World"
System.out.println("Comparison result: " + comparison);

toLowerCase() : Converts all characters in the string to lower case.

String str = "Hello, World!";
String lowerStr = str.toLowerCase(); // "hello, world!"
System.out.println("Lower case: " + lowerStr);

toUpperCase() : Converts all characters in the string to upper case.

String str = "Hello, World!";
String upperStr = str.toUpperCase(); // "HELLO, WORLD!"
System.out.println("Upper case: " + upperStr);

trim() : Removes leading and trailing whitespace

String str = "   Hello, World!   ";
String trimmedStr = str.trim(); // "Hello, World!"
System.out.println("Trimmed string: " + trimmedStr);

replace(char oldChar, char newChar) : Returns a new string resulting from replacing all occurrences of oldChar with newChar.

String str = "Hello, World!";
String newStr = str.replace('o', 'a'); // "Hella, Warld!"
System.out.println("Replaced string: " + newStr);

split(String regex) : Splits this string around matches of the given regular expression.

String str = "apple,banana,orange";
String[] fruits = str.split(",");
System.out.println("Fruits: " + Arrays.toString(fruits)); // [apple, banana, orange]

contains(CharSequence s) : Returns true if and only if this string contains the specified sequence of char values.

String str = "Hello, World!";
boolean contains = str.contains("World"); // true
System.out.println("Contains 'World': " + contains);

startsWith(String prefix) : Tests if this string starts with the specified prefix.

String str = "Hello, World!";
boolean startsWith = str.startsWith("Hello"); // true
System.out.println("Starts with 'Hello': " + startsWith);

endsWith(String suffix) : Tests if this string ends with the specified suffix.

String str = "Hello, World!";
boolean endsWith = str.endsWith("World!"); // true
System.out.println("Ends with 'World!': " + endsWith);

valueOf() : Returns the string representation of the passed argument. It can be a primitive data type, an object, etc.

int num = 123;
String str = String.valueOf(num); // "123"
System.out.println("String value of num: " + str);

matches(String regex) : Tells whether or not this string matches the given regular expression.

String str = "12345";
boolean matches = str.matches("\\d+"); // true, checks if the string contains only digits
System.out.println("Matches regex \\d+: " + matches);

join(CharSequence delimiter, CharSequence... elements) : Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.

String joinedString = String.join(", ", "apple", "banana", "orange");
System.out.println("Joined string: " + joinedString); // "apple, banana, orange"

Scroll to Top