Java interview questions on strings
Strings in Java are immutable, meaning once they are created, their values cannot be changed. If you plan to modify text frequently, String should not be used, as it creates new objects instead of modifying existing ones. Instead,StringBuffer orStringBuilder should be used for efficient string manipulation.
For effective string handling, this guide provides an introduction to common Java string interview questions, covering topics from beginner to advanced levels with explanations and example code.
1. Basics of Strings in Java
A String is a sequence of characters. In Java, strings are objects of the String class, which is part of the java.lang package. Strings are immutable, meaning their values cannot be changed once created.
Example:
String str = "Hello, World!";
A string in Java can be created in two ways:
- String Literal: Created using double quotes.
- Using the new Keyword: Created using the new operator.
Example:
// Method 1: String Literal
String str1 = "Hello";
// Method 2: Using new Keyword
String str2 = new String("Hello");
- String: Immutable and thread-safe.
- StringBuilder: Mutable and not thread-safe.
- StringBuffer: Mutable and thread-safe.
Example:
String str = "Hello";
StringBuilder sb = new StringBuilder("Hello");
StringBuffer sbf = new StringBuffer("Hello");
Use the length() method of the String class.
Example:
String str = "Hello";
System.out.println(str.length()); // Output: 5
2. String Manipulation
You can reverse a String using StringBuilder or by iterating through the characters.
Example:
// Using StringBuilder
String str = "Hello";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println(reversed); // Output: olleH
A palindrome is a string that reads the same forward and backward.
Example:
public static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
Use the replaceAll() method with a regular expression.
Example:
String str = " Hello, World! ";
String trimmed = str.replaceAll("\\s", "");
System.out.println(trimmed); // Output: Hello,World!
3. String Comparison
Use the equals() method for content comparison and == for reference comparison.
Example:
String str1 = "Hello";
String str2 = new String("Hello");
System.out.println(str1.equals(str2)); // Output: true (content comparison)
System.out.println(str1 == str2); // Output: false (reference comparison)
- equals(): Compares two strings for an exact content match.
- equalsIgnoreCase(): Compares two strings ignoring case differences.
Example:
String str1 = "Hello";
String str2 = "hello";
System.out.println(str1.equals(str2)); // Output: false
System.out.println(str1.equalsIgnoreCase(str2)); // Output: true
4. String Conversion
Use the Integer.parseInt() method.
Example:
String str = "123";
int num = Integer.parseInt(str);
System.out.println(num); // Output: 123
Use theInteger.toString() method or concatenation with an empty string.
Example:
int num = 123;
String str1 = Integer.toString(num);
String str2 = "" + num;
System.out.println(str1); // Output: 123
System.out.println(str2); // Output: 123
Use the toCharArray() method.
Example:
String str = "Hello";
char[] charArray = str.toCharArray();
for (char c : charArray) {
System.out.println(c);
}
5. Advanced String Questions
Use aLinkedHashMap to maintain the order of characters and count their occurrences.
Example:
import java.util.LinkedHashMap;
import java.util.Map;
public static char firstNonRepeatedChar(String str) {
Map<Character, Integer> map = new LinkedHashMap<>();
for (char c : str.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() == 1) {
return entry.getKey();
}
}
return '\0'; // No non-repeated character found
}
Split the string by spaces and count the resulting array's length.
Example:
public static int countWords(String str) {
if (str == null || str.isEmpty()) {
return 0;
}
String[] words = str.split("\\s+");
return words.length;
}
No comments