Top 50 Java String Interview Questions And Answers

These questions cover various aspects of working with strings in Java. Remember to understand the concepts behind each answer and practice coding to reinforce your knowledge.

Q1: What is a string in Java?
A: In Java, a string is an object that represents a sequence of characters. It is an instance of the String class and is immutable.

Q2: How do you create a string in Java?
A: Strings can be created using string literals or the new keyword:

String str1 = "Hello";
String str2 = new String("World");

Q3: Explain the difference between == and equals() when comparing strings.
A: The == operator compares object references, while equals() compares the content of strings. Use equals() for content comparison:

String str1 = "Hello";
String str2 = "Hello";
System.out.println(str1 == str2);        // true (same reference in the string pool)
System.out.println(str1.equals(str2));   // true (same content)
Q4: How do you concatenate strings in Java?
A: Strings can be concatenated using the + operator or the concat() method:
String str1 = "Hello";
String str2 = "World";
String concatenated = str1 + " " + str2;
String concatenated2 = str1.concat(" ").concat(str2);

Q5: How do you find the length of a string in Java?
A: Use the length() method to get the number of characters in a string:

String str = "Hello, World!";
int length = str.length(); // length is 13
Q6: Explain the concept of string immutability in Java.
A: In Java, strings are immutable, meaning their value cannot be changed after creation. Any operation that appears to modify a string creates a new string object.

Q7: How do you convert a string to uppercase and lowercase in Java?
A: Use toUpperCase() and toLowerCase() methods:
String str = "Hello, World!";
String upperCaseStr = str.toUpperCase();
String lowerCaseStr = str.toLowerCase();

Q8: How do you check if a string starts or ends with a specific substring?
A: Use startsWith() and endsWith() methods:

String str = "Hello, World!";
boolean startsWithHello = str.startsWith("Hello");
boolean endsWithWorld = str.endsWith("World!");

Q9: How do you extract a substring from a string in Java?
A: Use the substring() method:

String str = "Hello, World!";
String subStr = str.substring(7);      // "World!"
String subStr2 = str.substring(0, 5);  // "Hello"
Q10: How do you compare two strings lexicographically?
A: Use the compareTo() method:
String str1 = "Apple";
String str2 = "Banana";
int result = str1.compareTo(str2);
// result will be a negative value since "A" comes before "B" in lexicographic order

Q11: How do you check if two strings are equal, ignoring their case?

 A: Use the equalsIgnoreCase() method:

String str1 = "HELLO";
String str2 = "hello";
boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2); // true

Q12: How do you find the index of a specific character or substring in a string?

A: Use indexOf() and lastIndexOf() methods:

String str = "Hello, Hello, World!";
int firstOccurrence = str.indexOf("Hello");      // 0
int lastOccurrence = str.lastIndexOf("Hello");   // 7

Q13: How do you replace a specific character or substring in a string? 

A: Use the replace() method:

String str = "Hello, World!";
String replaced = str.replace("o", "X");   // "HellX, WXXrld!"

Q14: How do you split a string into an array of substrings based on a delimiter? 

A: Use the split() method:

String str = "apple,banana,orange";
String[] fruits = str.split(","); // ["apple", "banana", "orange"]

Q15: How do you remove leading and trailing whitespaces from a string? 

A: Use the trim() method:

String str = "   Hello, World!   ";
String trimmedStr = str.trim(); // "Hello, World!"

Q16: How do you convert a string to an integer or other primitive data types? 

A: Use methods like parseInt(), parseDouble(), parseBoolean(), etc.

String numStr = "123";
int num = Integer.parseInt(numStr);

Q17: How do you convert a character array to a string? 

A: Use the String constructor that takes a character array as an argument:

char[] charArray = {'H', 'e', 'l', 'l', 'o'};
String str = new String(charArray);


Q18: How do you check if a string is empty or null? 

A: Use the isEmpty() method to check if it's empty and == null to check if it's null:

String str = "";
boolean isEmpty = str.isEmpty();   // true

String anotherStr = null;
boolean isNull = anotherStr == null; // true


Q19: How can you replace all occurrences of a substring in a string? 

A: Use the replaceAll() method with regular expressions:

String str = "Hello, Hello, World!";
String replacedAll = str.replaceAll("Hello", "Hi"); // "Hi, Hi, World!"


Q20: How do you check if a string contains a specific character or substring? 

A: Use the contains() method:

String str = "Hello, World!";
boolean containsHello = str.contains("Hello");   // true
boolean containsJava = str.contains("Java");     // false


Q21: How can you format a string using placeholders? 

A: Use the String.format() method or the printf() method:

String name = "John";
int age = 30;
String formattedStr = String.format("My name is %s and I'm %d years old.", name, age);
System.out.printf("My name is %s and I'm %d years old.", name, age);


Q22: How do you convert a string to a character array? 

A: Use the toCharArray() method:

String str = "Hello";
char[] charArray = str.toCharArray(); // ['H', 'e', 'l', 'l', 'o']


Q23: How can you reverse a string in Java? 

A: You can use a loop or StringBuilder to reverse a string:

// Using loop
String str = "Hello";
StringBuilder reversed = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
    reversed.append(str.charAt(i));
}
String reversedStr = reversed.toString();

// Using StringBuilder
String str = "Hello";
String reversedStr = new StringBuilder(str).reverse().toString();


Q24: How do you convert a string to a byte array? 

A: Use the getBytes() method:

String str = "Hello";
byte[] byteArray = str.getBytes();


Q25: How can you check if a string is a palindrome (reads the same backward as forward)? 

A: Check if the string is equal to its reverse:

String str = "level";
String reversedStr = new StringBuilder(str).reverse().toString();
boolean isPalindrome = str.equals(reversedStr); // true


Q26: How do you check if a string contains only numeric characters? 

A: Use a regular expression to match numeric characters:

String str = "12345";
boolean isNumeric = str.matches("\\d+"); // true


Q27: How can you count the occurrences of a specific character in a string? 

A: Iterate through the string and count occurrences manually:

String str = "Hello, World!";
char ch = 'l';
int count = 0;
for (int i = 0; i < str.length(); i++) {
    if (str.charAt(i) == ch) {
        count++;
    }
}


Q28: How do you compare two strings without considering their case? 

A: Convert both strings to lowercase (or uppercase) and then use equals():

String str1 = "hello";
String str2 = "HELLO";
boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2); // true


Q29: How can you join multiple strings into a single string with a delimiter? 

A: Use String.join() method:

String[] words = {"Hello", "World", "Java"};
String joinedStr = String.join(", ", words); // "Hello, World, Java"


Q30: How do you check if a string is a valid number (integer or decimal)? 

A: Use a regular expression to check for valid numeric format:

String str = "123.45";
boolean isValidNumber = str.matches("-?\\d+(\\.\\d+)?"); // true


Q31: How can you convert a string to a date object? 

A: Use SimpleDateFormat or DateTimeFormatter for Java 8+:

String dateStr = "2023-07-28";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(dateStr); // Thu Jul 28 00:00:00 UTC 2023


Q32: How do you remove specific characters from a string? 

A: Use replaceAll() with a regular expression to remove characters:

String str = "Hello, World!";
String removedChars = str.replaceAll("[, !]", ""); // "HelloWorld"


Q33: How can you check if a string is a valid email address?  

A: Use a regular expression to match a valid email format:

String email = "user@example.com";
boolean isValidEmail = email.matches("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}"); // true


Q34: How do you convert an int to a string with leading zeros? 

A: Use String.format() or DecimalFormat:

int num = 7;
String formatted = String.format("%04d", num); // "0007"


Q35: How can you check if a string contains only alphabetic characters?  

A: Use a regular expression to match alphabetic characters:

String str = "Hello";
boolean isAlphabetic = str.matches("[a-zA-Z]+"); // true


Q36: How do you remove duplicate characters from a string? 

A: Iterate through the string and build a new string without duplicates:

String str = "hello";
StringBuilder uniqueStr = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
    char ch = str.charAt(i);
    if (uniqueStr.indexOf(String.valueOf(ch)) == -1) {
        uniqueStr.append(ch);
    }
}
String result = uniqueStr.toString(); // "helo"


Q37: How can you reverse words in a string while keeping the word order?  

A: Use split() and StringBuilder to reverse words:

String sentence = "Hello World Java";
String[] words = sentence.split(" ");
StringBuilder reversedSentence = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
    reversedSentence.append(words[i]).append(" ");
}
String reversed = reversedSentence.toString().trim(); // "Java World Hello"


Q38: How do you convert a string to a boolean value ("true" or "false")? 

A: Use Boolean.parseBoolean():

String str = "true";
boolean value = Boolean.parseBoolean(str); // true


Q39: How can you find the first non-repeated character in a string? 

A: Iterate through the string and use a map to track character occurrences:

String str = "abacddbec";
Map charCount = new LinkedHashMap<>();
for (char ch : str.toCharArray()) {
    charCount.put(ch, charCount.getOrDefault(ch, 0) + 1);
}
char firstNonRepeated = ' ';
for (Map.Entry entry : charCount.entrySet()) {
    if (entry.getValue() == 1) {
        firstNonRepeated = entry.getKey();
        break;
    }
}


Q40: How do you check if a string contains only uppercase letters? 

A: Use a regular expression to match uppercase letters:

String str = "HELLO";
boolean isUpperCase = str.matches("[A-Z]+"); // true


Q41: How can you check if a string is a valid URL? 

A: Use a regular expression to match a valid URL format:


String url = "https://www.example.com";
boolean isValidURL = url.matches("^(http|https)://[a-zA-Z0-9./?=_-]+"); // true


Q42: How do you check if a string contains only lowercase letters? 

A: Use a regular expression to match lowercase letters:

String str = "hello";
boolean isLowerCase = str.matches("[a-z]+"); // true


Q43: How can you find the most frequent character in a string? 

A: Iterate through the string and use a map to track character occurrences:

String str = "hello";
Map charCount = new HashMap<>();
for (char ch : str.toCharArray()) {
    charCount.put(ch, charCount.getOrDefault(ch, 0) + 1);
}
int maxOccurrences = 0;
char mostFrequent = ' ';
for (Map.Entry entry : charCount.entrySet()) {
    int occurrences = entry.getValue();
    if (occurrences > maxOccurrences) {
        maxOccurrences = occurrences;
        mostFrequent = entry.getKey();
    }
}


Q44: How do you check if a string contains only alphanumeric characters? 

A: Use a regular expression to match alphanumeric characters:

String str = "Hello123";
boolean isAlphanumeric = str.matches("[a-zA-Z0-9]+"); // true


Q45: How can you find the longest palindrome in a given string? 

A: Iterate through the string and expand around each character to find palindromes:

String str = "abacddbec";
String longestPalindrome = "";
for (int i = 0; i < str.length(); i++) {
    // Odd-length palindrome
    String oddPalindrome = expandAroundCenter(str, i, i);
    // Even-length palindrome
    String evenPalindrome = expandAroundCenter(str, i, i + 1);
    // Update the longest palindrome
    if (oddPalindrome.length() > longestPalindrome.length()) {
        longestPalindrome = oddPalindrome;
    }
    if (evenPalindrome.length() > longestPalindrome.length()) {
        longestPalindrome = evenPalindrome;
    }
}
private static String expandAroundCenter(String s, int left, int right) {
    while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
        left--;
        right++;
    }
    return s.substring(left + 1, right);
}


Q46: How do you count the number of words in a string?  

A: Use split() method with a regular expression to split words and then count them:

String sentence = "Hello World Java";
String[] words = sentence.split("\\s+");
int wordCount = words.length; // 3


Q47: How can you check if a string is a valid IP address? 

A: Use a regular expression to match a valid IP address format:

String ipAddress = "192.168.1.1";
boolean isValidIP = ipAddress.matches(
    "^((25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)$"
); // true


Q48: How do you convert a string to a double or float?  

A: Use Double.parseDouble() for double or Float.parseFloat() for float:

String numStr = "3.14";
double numDouble = Double.parseDouble(numStr);
float numFloat = Float.parseFloat(numStr);


Q49: How can you check if a string is a valid credit card number? 

A: Use a regular expression to match a valid credit card number format:

String creditCardNumber = "1234-5678-9012-3456";
boolean isValidCreditCard = creditCardNumber.matches("^\\d{4}-\\d{4}-\\d{4}-\\d{4}$"); // true


Q50: How do you convert a string to a long or integer? 

A: Use Long.parseLong() for long or Integer.parseInt() for int:

String numStr = "123456";
long numLong = Long.parseLong(numStr);
int numInt = Integer.parseInt(numStr);

Additionally, practice coding these concepts to gain confidence and improve your problem-solving skills.
Next Post Previous Post