Java Programming Common String Manipulations Complete Guide
Understanding the Core Concepts of Java Programming Common String Manipulations
Java Programming Common String Manipulations
1. Creating Strings
Strings can be created in various ways in Java, using either object literal syntax or the new
keyword. Here’s an example:
- Object Literal:
String str1 = "Hello";
- Using
new
:String str2 = new String("World");
Important Info:
- Object literals are interned by default. This means that if two string literals have the same sequence of characters, they actually refer to the same memory location.
- Using the
new
keyword explicitly creates a new string object in heap memory, which can be useful if you need a mutable string.
2. Concatenation
Concatenating strings combines two or more strings into one. This can be done using the +
operator or the concat()
method.
String str1 = "Hello";
String str2 = "World";
String result = str1 + " " + str2; // Result: Hello World
String resultConcat = str1.concat(str2); // Result: HelloWorld (no space)
Important Info:
- The
+
operator is generally more readable and easier to use. concat()
does not accept null values and will throw aNullPointerException
. Always ensure all concatenated strings are non-null.
3. Substring Extraction
Extracting substrings from within a string is achieved using the substring()
method. It comes in two forms: substring(int beginIndex)
and substring(int beginIndex, int endIndex)
.
String message = "Hello World";
String subMessage1 = message.substring(6); // Result: World
String subMessage2 = message.substring(0, 5); // Result: Hello
Important Info:
- The
endIndex
parameter is exclusive.message.substring(beginIndex, endIndex)
captures characters frombeginIndex
toendIndex - 1
. - Index values should not exceed the length of the string to prevent
StringIndexOutOfBoundsException
.
4. Length Calculation
The length()
method returns the number of characters in the string.
String message = "Hello World";
int length = message.length(); // Result: 11
Important Info:
length()
method returns a primitiveint
, notInteger
. Avoid unnecessary autoboxing for performance.
5. Case Conversion
Java provides toLowerCase()
and toUpperCase()
methods to convert the case of strings.
String message = "Hello World";
String lowerCase = message.toLowerCase(); // Result: hello world
String upperCase = message.toUpperCase(); // Result: HELLO WORLD
Important Info:
- Consider locale when performing case conversions with special characters or accented letters, e.g.,
str.toLowerCase(Locale.ENGLISH)
.
6. Trim Whitespace
The trim()
method removes leading and trailing white spaces (spaces, tabs, newlines).
String messageWithPadding = " Hello World ";
String trimmedMessage = messageWithPadding.trim(); // Result: Hello World
Important Info:
trim()
does not affect internal white spaces. Use regex-based manipulation for such cases, e.g.,str.replaceAll("\\s+", "")
to remove all whitespaces.
7. Comparison
Strings can be compared lexicographically using the equals()
, equalsIgnoreCase()
, compareTo()
, and compareToIgnoreCase()
methods.
String str1 = "Hello";
String str2 = "hello";
boolean equalsCase = str1.equals(str2); // Result: false
boolean equalsNoCase = str1.equalsIgnoreCase(str2); // Result: true
int compare = str1.compareTo(str2); // Result: -32 (negative because H < h in ASCII)
int compareCaseInsensitive = str1.compareToIgnoreCase(str2); // Result: 0
Important Info:
equals()
considers case.compareTo()
andcompareToIgnoreCase()
return an integer indicating the relationship between the compared strings.
8. Replacement
Replacing parts of a string is handled by the replace()
, replaceAll()
, and replaceFirst()
methods. replaceAll()
and replaceFirst()
use regex.
String message = "Hello World";
String replaced = message.replace('l', 'a'); // Result: Heao Worad
String replacedAll = message.replaceAll("l", "a"); // Result: Heao Worad
String replacedFirst = message.replaceFirst("l", "a"); // Result: Heao World
Important Info:
replaceAll()
andreplaceFirst()
offer more flexibility but can be slower due to regex processing.- Use
replace()
for simple character replacements unless patterns are required.
9. Searching for Substrings
Searching for substrings is performed using indexOf()
, lastIndexOf()
, contains()
, startsWith()
, and endsWith()
methods.
String message = "Hello World";
int index1 = message.indexOf('o'); // Returns index of first occurrence: 4
int index2 = message.lastIndexOf('o'); // Returns index of last occurrence: 7
boolean containsO = message.contains("o"); // Result: true
boolean startsWithHello = message.startsWith("Hello"); // Result: true
boolean endsWithWorld = message.endsWith("World"); // Result: true
Important Info:
indexOf()
andlastIndexOf()
return -1 if the substring is not found.contains()
,startsWith()
, andendsWith()
return boolean values based on substring presence.
10. Splitting Strings
Splitting a string into an array of substrings is accomplished with the split()
method which uses regex.
String message = "Hello World";
String[] words = message.split(" "); // Splits on spaces, Result: ["Hello", "World"]
Important Info:
- The
split()
method uses regex, so be cautious when using special characters. - Handle edge cases like multiple consecutive delimiters or strings starting/ending with delimiters.
11. Reversing Strings
Reversing a string requires converting it to a StringBuilder
or StringBuffer
and then utilizing the reverse()
method.
String message = "Hello World";
StringBuilder sb = new StringBuilder(message);
String reversed = sb.reverse().toString(); // Result: dlroW olleH
Important Info:
StringBuilder
is preferred overStringBuffer
due to better performance sinceStringBuilder
is not thread-safe.- Use
toString()
to convertStringBuilder
back to a regular string after manipulation.
12. Formatted Strings
Creating formatted strings is done with String.format()
or using formatted literals (%s %d...
).
String name = "Alice";
int age = 25;
String formatted = String.format("Name: %s, Age: %d", name, age); // Result: Name: Alice, Age: 25
// Alternately with formatted literals in Java 15+
String anotherFormatted = "Name: %s, Age: %d".formatted(name, age); // Result: Name: Alice, Age: 25
Important Info:
%s
stands for string,%d
for decimal,%f
for floating-point numbers, etc.- Be consistent with argument types passed to the format specifiers.
13. Empty and Null Checks
Null-safe checks involve verifying whether a string is either null or empty.
String str1 = null;
String str2 = "";
boolean isEmpty = str1 == null || str1.isEmpty(); // Safe check for null and empty: true
boolean isEmpty2 = str2.isEmpty(); // Check only for empty: true
Important Info:
- Regular
str.isEmpty()
throwsNullPointerException
ifstr
is null. Always check for nullity before checking emptiness. - Utilize libraries like Apache Commons Lang which provide convenient
StringUtils
class functions for such checks.
14. Checking Patterns
Pattern matching with strings utilizes matches()
, startsWith()
, and endsWith()
methods or regular expressions.
String dateStr = "2024-01-01";
boolean isValidDate = dateStr.matches("\\d{4}-\\d{2}-\\d{2}"); // Check if matches YYYY-MM-DD pattern: true
Important Info:
- Regular expressions are powerful but can become complex. Write clear and maintainable patterns.
- Use online tools or libraries for advanced pattern analysis and debugging.
15. Joining Strings
Joining multiple strings into one can be done efficiently using String.join()
or Collectors.joining()
in Java Streams.
List<String> fruits = Arrays.asList("Apple", "Banana", "Cherry");
String joinedFruits1 = String.join(", ", fruits); // Result: Apple, Banana, Cherry
String joinedFruits2 = fruits.stream().collect(Collectors.joining("; ")); // Result: Apple; Banana; Cherry
Important Info:
String.join()
is straightforward and easy to use.- Streams provide greater flexibility when joining with other data transformations.
16. Padding Strings
Padding strings involves adding spaces (or any specified character) to make their length uniform. While there's no direct method, this can be achieved using loops or third-party libraries.
String message = "Hi";
String paddedMessage = String.format("%5s", message); // Right padded, Result: Hi
String leftPaddedMessage = String.format("%-5s", message); // Left padded, Result: Hi
Important Info:
- Use
String.format()
or libraries likeApache Commons Lang
for padding. - Consider whether padding should happen at the beginning (left) or the end (right).
17. Removing Specific Characters
Removing specific characters from strings involves using replaceAll()
with appropriate regex patterns or loops.
String message = "Hello123";
String cleanedMessage = message.replaceAll("\\d", ""); // Remove digits, Result: Hello
Important Info:
replaceAll("\\d", "")
effectively removes all digits from a string.- Regular expressions provide flexibility but can be costly in terms of performance for large-scale operations.
18. Repeating Strings
To repeat a string multiple times, consider using String.repeat()
added in Java 11.
String symbol = "*";
String repeatedSymbol = symbol.repeat(5); // Repeat '*' 5 times, Result: *****
Important Info:
String.repeat()
makes code concise and readable.- Avoid excessive repetition which may lead to memory issues.
Online Code run
Step-by-Step Guide: How to Implement Java Programming Common String Manipulations
Example 1: Concatenation of Strings
Problem: Concatenate two strings.
public class ConcatStrings {
public static void main(String[] args) {
String firstString = "Hello";
String secondString = "World";
// Using + operator
String concatenatedString1 = firstString + " " + secondString;
// Using concat method
String concatenatedString2 = firstString.concat(" ").concat(secondString);
System.out.println("Using + operator: " + concatenatedString1);
System.out.println("Using concat method: " + concatenatedString2);
}
}
Output:
Using + operator: Hello World
Using concat method: Hello World
Example 2: Finding Substrings
Problem: Extract a substring from a given string.
public class SubstringExample {
public static void main(String[] args) {
String originalString = "Hello World";
// Extract substring from index 6 to the end
String substring1 = originalString.substring(6);
// Extract substring from index 0 to 5 (not including 5)
String substring2 = originalString.substring(0, 5);
System.out.println("Substring from index 6 to end: " + substring1);
System.out.println("Substring from index 0 to 5: " + substring2);
}
}
Output:
Substring from index 6 to end: World
Substring from index 0 to 5: Hello
Example 3: Replacing Characters or Substrings
Problem: Replace parts of a string.
public class ReplaceExample {
public static void main(String[] args) {
String originalString = "Hello World";
// Replace all occurrences of 'o' with '*'
String replacedString1 = originalString.replace('o', '*');
// Replace first occurrence of "World" with "Java"
String replacedString2 = originalString.replaceFirst("World", "Java");
// Replace all occurrences of "o" with "*"
String replacedString3 = originalString.replaceAll("o", "*");
System.out.println("Replace 'o' with '*': " + replacedString1);
System.out.println("Replace first 'World' with 'Java': " + replacedString2);
System.out.println("Replace all 'o' with '*': " + replacedString3);
}
}
Output:
Replace 'o' with '*': Hell* W*rld
Replace first 'World' with 'Java': Hello Java
Replace all 'o' with '*': Hell* W*rld
Example 4: Converting Strings to Upper and Lower Case
Problem: Convert a string to upper and lower case.
public class UpperLowerCaseExample {
public static void main(String[] args) {
String originalString = "Hello World";
// Convert to upper case
String upperCaseString = originalString.toUpperCase();
// Convert to lower case
String lowerCaseString = originalString.toLowerCase();
System.out.println("Original String: " + originalString);
System.out.println("Upper Case: " + upperCaseString);
System.out.println("Lower Case: " + lowerCaseString);
}
}
Output:
Original String: Hello World
Upper Case: HELLO WORLD
Lower Case: hello world
Example 5: Removing Leading and Trailing Spaces
Problem: Trim spaces from a string.
public class TrimExample {
public static void main(String[] args) {
String stringWithSpaces = " Hello World ";
// Trim leading and trailing spaces
String trimmedString = stringWithSpaces.trim();
System.out.println("Original String: \"" + stringWithSpaces + "\"");
System.out.println("Trimmed String: \"" + trimmedString + "\"");
}
}
Output:
Original String: " Hello World "
Trimmed String: "Hello World"
Example 6: Splitting Strings
Problem: Split a string into parts based on a delimiter.
public class SplitExample {
public static void main(String[] args) {
String originalString = "apple,banana,cherry";
// Split string by ','
String[] parts = originalString.split(",");
System.out.println("Original String: " + originalString);
System.out.println("Split parts:");
for (String part : parts) {
System.out.println(part);
}
}
}
Output:
Original String: apple,banana,cherry
Split parts:
apple
banana
cherry
Example 7: Checking if a String Contains a Specific Substring
Problem: Check if a string contains a specific substring.
public class ContainsExample {
public static void main(String[] args) {
String originalString = "Hello World";
// Check if the string contains "World"
boolean containsWorld = originalString.contains("World");
// Check if the string contains "Java"
boolean containsJava = originalString.contains("Java");
System.out.println("Does the string contain 'World'? " + containsWorld);
System.out.println("Does the string contain 'Java'? " + containsJava);
}
}
Output:
Top 10 Interview Questions & Answers on Java Programming Common String Manipulations
1. How do you find the length of a string in Java?
Answer:
In Java, you can find the length of a string by using the length()
method of the String
class. Here’s how you can use it:
String str = "Hello, Java!";
int length = str.length();
System.out.println("Length of the string is: " + length);
2. How can you convert a string to lowercase or uppercase in Java?
Answer:
Java provides toLowerCase()
and toUpperCase()
methods of the String
class to convert all the characters of a string to lowercase and uppercase, respectively.
String str = "Java Programming";
String lowerCaseStr = str.toLowerCase();
String upperCaseStr = str.toUpperCase();
System.out.println("Lowercase: " + lowerCaseStr);
System.out.println("Uppercase: " + upperCaseStr);
3. How do you find a substring in a string?
Answer:
The substring()
method of the String
class allows you to find a substring within a string. You can specify the start index or both start and end indices.
String str = "Hello, Java!";
String substring1 = str.substring(7); // Extracts from index 7 to end
String substring2 = str.substring(0, 5); // Extracts from index 0 to 4
System.out.println("Substring1: " + substring1);
System.out.println("Substring2: " + substring2);
4. How do you check if a string contains a specific substring?
Answer:
You can use the contains()
method of the String
class to check if a string contains a specific substring.
String str = "Hello, Java!";
boolean containsJava = str.contains("Java");
System.out.println("Contains 'Java'? : " + containsJava);
5. How do you replace characters in a string?
Answer:
You can replace characters or substrings in a string using the replace()
, replaceAll()
, or replaceFirst()
methods of the String
class.
String str = "Hello, Java!";
String replacedStr1 = str.replace('J', 'C'); // Replaces 'J' with 'C'
String replacedStr2 = str.replaceAll("Java", "World"); // Replaces "Java" with "World"
String replacedStr3 = str.replaceFirst("o", "oo"); // Replaces first occurrence of 'o' with "oo"
System.out.println("Replaced String 1: " + replacedStr1);
System.out.println("Replaced String 2: " + replacedStr2);
System.out.println("Replaced String 3: " + replacedStr3);
6. How do you split a string into multiple substrings?
Answer:
The split()
method of the String
class divides a string into an array of substrings based on a specified delimiter.
String str = "Hello,Java,World";
String[] substrings = str.split(",");
for (String substring : substrings) {
System.out.println(substring);
}
7. How do you check if two strings are equal?
Answer:
To check if two strings are equal in terms of their content, you should use the equals()
method of the String
class. Don’t use the ==
operator since it only checks for object reference equality.
String str1 = "Hello";
String str2 = "Hello";
boolean areEqual = str1.equals(str2);
System.out.println("Are strings equal? : " + areEqual);
8. How do you reverse a string in Java?
Answer:
Java doesn't provide a built-in method to reverse a string directly, but you can accomplish this by using a StringBuilder
or a StringBuffer
.
String str = "Hello, Java!";
StringBuilder sb = new StringBuilder(str);
sb.reverse();
String reversedStr = sb.toString();
System.out.println("Reversed String: " + reversedStr);
9. How do you trim spaces from a string?
Answer:
You can use the trim()
method to remove leading and trailing whitespace from a string.
String str = " Hello, Java! ";
String trimmedStr = str.trim();
System.out.println("Trimmed String: '" + trimmedStr + "'");
10. How do you concatenate strings in Java?
Answer:
Strings can be concatenated in Java using the +
operator, concat()
method, or StringBuilder
.
Login to post a comment.