1 / 22

String in Java Interview Questions PDF By ScholarHat

String in Java Interview Questions PDF By ScholarHat

scholarhat
Download Presentation

String in Java Interview Questions PDF By ScholarHat

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Top 30+ String in Java Interview Questions with Answers 2025 Top 35 String in Java Interview Questions If you're getting ready for a Java interview, understanding Strings is essential. You might be asked to explain String properties and behavior write code involving String operations. Familiarity with concepts like immutability, the String Pool, and common String methods is very helpful. In this interview tutorial, we’ll cover the top 35 Java String interview questions with simple examples and clear explanations. By the end, you’ll f confident and prepared to tackle any String-related question. Plus, these skills will enhance your real-world programming expertise. Get ready excel in your Java interview! What can you expect in Java String interview questions? Java String interview questions are designed to test your understanding of how Strings work and how well you can apply this knowledge to so problems. You can expect to be asked about concepts like immutability, the String Pool, and common String methods, as well as how manipulate and optimize String operations. Whether you're a fresher or an experienced developer, you might need to write code, explain ho Strings behave in different scenarios, and address performance considerations. Being well-prepared for these questions, including tricky ed cases, can greatly improve your chances of success. Read More: Java Interview Questions and Answers. Basic Interview Questions on String in Java 1. What is a String in Java? Ans: A string in Java is a sequence of characters, like a sentence or a word. It's a predefined class in Java’s java.lang package and represents te So when you declare String name = "Hello";, you're creating an object that holds the characters "Hello."

  2. 2. How are Strings stored in memory in Java? Ans:Strings in Java are stored in a special area of memory called the String Pool. When you create a String using double quotes, Java checks if identical string already exists in the pool. If it does, Java just points to the existing String instead of creating a new one, saving memory. 3. How do you compare two Strings in Java? Ans: To compare two Strings in Java, you have a couple of options: .equals() method: This checks if the actual contents of the two strings are the same. == operator: This checks if both strings point to the same memory location, so it’s more of a reference comparison rather than checking t content. 4. What is the difference between == and .equals() when comparing Strings? Ans: The == operator in Java compares references (i.e., memory locations), while .equals() compares the actual content of the strings. So, if y have two different String objects with the same content, == will return false (since they're at different locations), but .equals() will return true. 5. What is String immutability in Java? Ans:Strings in Java are immutable, meaning once you create a String, you can't change it. So, if you try to modify a String (like adding to it), Ja will create a new String object instead of changing the original one. This is done for security and optimization reasons. 6. How does the substring() method work in Java? Ans: The substring() method in Java allows you to extract a portion of a String. For example, "Hello".substring(1, 3) would give you "el" takes two parameters, the starting index (inclusive) and the ending index (exclusive), and returns the specified part of the String. 7. Can you modify a String after it is created in Java? Ans:No, because Strings are immutable. However, if you want to change or manipulate text, you can use or , wh StringBuilder StringBuffer are mutable alternatives. They allow you to modify the content without creating a new object each time. String Programming Interview Questions in Java for Experienced 8. How would you reverse a String in Java without using built-in methods? Ans: You can reverse a String by iterating from the end and adding each character to a new String: publicclassReverseString { publicstaticvoidmain(String[] args) {

  3. String str = "Hello"; String reversed = ""; for (int i = str.length() - 1; i >= 0; i--) { reversed += str.charAt(i); } System.out.println("Reversed String: " + reversed); } } Try it Yourself >> Output Reversed String: olleH Explanation This Java program reverses a string by iterating from the last character to the first. The Looping Statements in Java build a new string by appendi each character in reverse order. Practice with these Articles: Reverse a String in C# Reverse a String in Java 9. Write a Java program to check if a String is a palindrome. Ans: A palindrome reads the same forward and backward: publicclassPalindromeCheck { publicstaticvoidmain(String[] args) { String str = "madam"; boolean isPalindrome = true; for (int i = 0; i < str.length() / 2; i++) { if (str.charAt(i) != str.charAt(str.length() - 1 - i)) { isPalindrome = false; break; } } System.out.println("Is Palindrome: " + isPalindrome); } } Try it Yourself >> Output Is Palindrome: true Explanation

  4. The program checks if the input string is a palindrome by comparing characters from the beginning and end towards the center. If all characte match symmetrically, it is a palindrome. 10. How do you find the first non-repeated character in a String? Ans: Use nested loops to find the first unique character: publicclassFirstNonRepeatedCharacter { publicstaticvoidmain(String[] args) { String str = "swiss"; char firstNonRepeated = '\0'; for (int i = 0; i < str.length(); i++) { boolean isUnique = true; for (int j = 0; j < str.length(); j++) { if (i != j && str.charAt(i) == str.charAt(j)) { isUnique = false; break; } } i f ( i s U n i q u e ) { firstNonRepeated = str.charAt(i); break; } } System.out.println("First Non-Repeated Character: " + firstNonRepeated); } } Try it Yourself >> Output First Non-Repeated Character: w Explanation This program finds the first non-repeated character by iterating through each character and checking for duplicates. It stops at the first uniq character found. 11. Write a program to count the occurrences of each character in a String. Ans:Count each character's occurrences using nested loops: publicclassCharacterCount { publicstaticvoidmain(String[] args) { String str = "banana"; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); int count = 0; for (int j = 0; j < str.length(); j++) { if (c == str.charAt(j)) { count++; }

  5. } S y s t e m . o u t . p r i n t l n ( " C h a r a c t e r " + c + " : " + c o u n t ) ; } } } Try it Yourself >> Output Character b: 1 Character a: 3 Character n: 2 Character a: 3 Character n: 2 Character a: 3 Explanation This program counts each character's occurrences in the string by iterating through all characters. Each character's count is printed on the scre as it’s checked. 12. How do you check if two Strings are anagrams of each other in Java? Ans: To check if two strings are anagrams, sort the characters in each string and compare the sorted strings. If they’re the same, they a anagrams: import java.util.Arrays; publicclassAnagramCheck { publicstaticvoidmain(String[] args) { String str1 = "listen"; String str2 = "silent"; boolean isAnagram = areAnagrams(str1, str2); System.out.println("Are Anagrams: " + isAnagram); } publicstatic boolean areAnagrams(String str1, String str2) { if (str1.length() != str2.length()) { return false; } char[] arr1 = str1.toCharArray(); char[] arr2 = str2.toCharArray(); Arrays.sort(arr1); Arrays.sort(arr2); return Arrays.equals(arr1, arr2); } } Try it Yourself >>

  6. Output Are Anagrams: true Explanation This program converts each string to a character array, sorts the arrays, and then checks if they are equal. If they match, the two strings a anagrams. 13. How would you remove all white spaces from a String? Ans: To remove all white spaces from a string, use a loop to build a new string without spaces: publicclassRemoveWhitespace { publicstaticvoidmain(String[] args) { String str = "Hello World"; String withoutSpaces = ""; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) != ' ') { withoutSpaces += str.charAt(i); } } S y s t e m . o u t . p r i n t l n ( " S t r i n g w i t h o u t s p a c e s : " + w i t h o u t S } } Try it Yourself >> Output String without spaces: HelloWorld Explanation This code removes spaces by iterating through each character and adding it to a new string only if it is not a space character. 14. Write a program to check if a String contains only digits. Ans: To check if a string contains only digits, loop through each character and ensure each one is a digit: publicclassOnlyDigitsCheck { publicstaticvoidmain(String[] args) { String str = "12345"; boolean onlyDigits = true;

  7. for (int i = 0; i < str.length(); i++) { if (!Character.isDigit(str.charAt(i))) { onlyDigits = false; break; } } System.out.println("Contains only digits: " + onlyDigits); } } Try it Yourself >> Output Contains only digits: true Explanation This code checks each character in the string to see if it is a digit. If all characters are digits, it returns true; otherwise, it returns false. Java String Interview Questions for 5 Years Experience 15. How would you find if a String contains only unique characters? Ans: You can check if a string contains only unique characters by using a set to track characters you've already encountered: import java.util.HashSet; publicclassUniqueCharacters { publicstaticvoidmain(String[] args) { String str = "abcdef"; boolean hasUniqueChars = true; HashSet set = newHashSet<>(); for (int i = 0; i < str.length(); i++) { if (!set.add(str.charAt(i))) { hasUniqueChars = false; break; } } System.out.println("Contains only unique characters: " + hasUniqueChars); } } Try it Yourself >> Output Contains only unique characters: true

  8. Explanation This program uses a HashSet to store characters as they are encountered. If a character is already in the set, the string contains duplica characters. Otherwise, it only has unique characters. 16. What is the difference between String, StringBuilder, and StringBuffer in terms of performance? Ans: The differences are as follows: String:Immutable, meaning that every time you modify a string, a new object is created. This can be inefficient for frequent modifications. StringBuilder:Mutable and faster than StringBuffer. It is not synchronized, which makes it faster for single-threaded applications. StringBuffer:Mutable and synchronized, meaning it's thread-safe but slower than StringBuilder due to synchronization overhead. 17. How would you implement your own split() method for String in Java? Ans: You can split a string by iterating over it and finding the delimiters manually: publicclassCustomSplit { publicstaticvoidmain(String[] args) { String str = "apple,banana,cherry"; String delimiter = ","; String[] result = customSplit(str, delimiter); for (String s : result) { System.out.println(s); } } publicstatic String[] customSplit(String str, String delimiter) { int count = 0; String temp = ""; for (int i = 0; i < str.length(); i++) { if (str.substring(i, i + delimiter.length()).equals(delimiter)) { count++; } } String[] result = newString[count + 1]; int index = 0; temp = ""; for (int i = 0; i < str.length(); i++) { if (str.substring(i, i + delimiter.length()).equals(delimiter)) { result[index++] = temp; temp = ""; i += delimiter.length() - 1; } else { temp += str.charAt(i); } } result[index] = temp; // Last part return result; } }

  9. Try it Yourself >> Output apple banana cherry Explanation This code splits a string by iterating through it and identifying occurrences of the delimiter. It then stores each part between the delimiters in Ja arrays. 18. Write a program to find the first occurrence of a substring in a String. Ans: You can use a loop to check for the first occurrence of a substring: publicclassSubstringSearch { publicstaticvoidmain(String[] args) { String str = "Hello, welcome to Java programming!"; String substr = "welcome"; int index = str.indexOf(substr); System.out.println("First occurrence of substring: " + index); } } Try it Yourself >> Output First occurrence of substring: 7 Explanation method to find the first occurrence of a substring within a string. It returns the index of the first charac This program uses the built-in indexOf() of thefound substring. 19. How would you compare two Strings lexicographically without using the compareTo() method? Ans: You can compare two stringslexicographically by comparing each character one by one: publicclassLexicographicComparison { publicstaticvoidmain(String[] args) { String str1 = "apple"; String str2 = "banana"; int result = lexicographicCompare(str1, str2); System.out.println("Comparison result: " + result); }

  10. publicstatic int lexicographicCompare(String str1, String str2) { int minLength = Math.min(str1.length(), str2.length()); for (int i = 0; i < minLength; i++) { if (str1.charAt(i) != str2.charAt(i)) { return str1.charAt(i) - str2.charAt(i); } } r e t u r n s t r 1 . l e n g t h ( ) - s t r 2 . l e n g t h ( ) ; } } Try it Yourself >> Output Comparison result: -1 Explanation This program compares two strings character by character. If a mismatch is found, it returns the difference between the characters. If mismatch is found, it compares the lengths of the strings. 20. How do you convert a String to a char array and vice versa in Java? Ans: You can use to convert a string to a char array, and to convert a char array back to a string: toCharArray() new String(charArray) publicclassStringToCharArray { publicstaticvoidmain(String[] args) { String str = "Hello"; // String to char array char[] charArray = str.toCharArray(); System.out.println("Char Array: " + Arrays.toString(charArray)); // Char array back to String String newStr = newString(charArray); System.out.println("New String: " + newStr); } } Try it Yourself >> Output Char Array: [H, e, l, l, o] New String: Hello Explanation This program converts a string to a character array using toCharArray() and then converts it back to a string using the String constructor. It is l breaking a word into individual letters and then joining them back together. The output shows both the character array and the recreated string.

  11. Java String Programming Questions for 10+ Years’ Experience 21. How would you implement your own immutable String class in Java? Ans: To implement an immutable String class, you need to ensure that once the object is created, its state cannot be changed. This can be done declaring the fields as final and providing no setter methods: publicclassImmutableString { privatefinal char[] value; publicImmutableString(String str) { value = str.toCharArray(); } public char charAt(int index) { return value[index]; } public int length() { return value.length; } public String toString() { returnnewString(value); } } Try it Yourself >> Explanation field is and cannot be modified after initialization. There are no methods that modify the strin The class is immutable because the value final value, only methods that retrieve its state. 22. Explain the memory structure when creating new Strings using literals and new keywords. Ans: When creating strings in Java: String literals: Java maintains a String Pool. If a string with the same literal already exists, Java will return a reference to that string. This avo creating duplicate strings, optimizing memory usage. Using the new keyword: When you create a new string using new, it always creates a new object, even if the exact same string already exists the pool. This can lead to memory overhead. 23. Write an efficient program to find the longest common prefix in an array of Strings. Ans: A commonapproach is to compare the characters of each string at the same index: publicclassLongestCommonPrefix { publicstaticvoidmain(String[] args) { String[] strs = {"flower", "flow", "flight"}; String result = longestCommonPrefix(strs); System.out.println("Longest Common Prefix: " + result); }

  12. publicstatic String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) { return ""; } String prefix = strs[0]; for (int i = 1; i < strs.length; i++) { while (strs[i].indexOf(prefix) != 0) { prefix = prefix.substring(0, prefix.length() - 1); if (prefix.isEmpty()) { return ""; } } } } r e t u r n p r e f i x ; } Try it Yourself >> Output Longest Common Prefix: fl Explanation meth This program checks each string in the array and gradually reduces the common prefix until it matches for all strings. It uses the indexOf to check the prefix. 24. How would you optimize memory usage when dealing with large Strings? Ans: To optimize memory when handling large strings, consider these approaches: Use StringBuilder: If you need to perform many modifications to a string, use StringBuilder as it is mutable and more memory efficient. Use String pooling wisely: If you frequently reuse the same string, Java’s String Pool can help save memory. Trim unnecessary characters: Avoid creating new strings unnecessarily and use the substring()method carefully as it may still reference t original string. Lazy loading: For very large text, consider loading parts of the string only when needed, such as using streams or memory-mapped buffers. 25. Discuss how the String.format() method works and give examples of its usage. Ans: The method allows you to create formatted strings by substituting placeholders with values. Here's an example: String.format() publicclassStringFormatExample { publicstaticvoidmain(String[] args) { String formattedString = String.format("My name is %s and I am %d years old.", "John", 25); System.out.println(formattedString); } } Try it Yourself >>

  13. Output My name is John and I am 25 years old. Explanation is used to format a string and %s is used for an integer. %d replaces these placeholders with the provid In this example, String.format() arguments. 26. How would you use regular expressions to validate a String in Java? Ans: To validate a string using regular expressions, you can use the method of the class: matches() String publicclassRegexValidation { publicstaticvoidmain(String[] args) { String str = "john.doe@example.com"; boolean isValid = str.matches("^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$") } System.out.println("Is valid email: " + isValid); } Try it Yourself >> Output Is valid email: true Explanation method returns if the stri The program checks if the input string matches a regular expression for a valid email address. The matches() true matches the pattern, otherwise false. 27. Write a program to rotate a String by a given number of positions. Ans: You can rotate a string by slicing it and swapping the parts: publicclassStringRotation { publicstaticvoidmain(String[] args) { String str = "abcdef"; int positions = 2; String rotated = rotateString(str, positions); System.out.println("Rotated String: " + rotated); } publicstatic String rotateString(String str, int positions) { positions = positions % str.length(); // To handle larger positions return str.substring(positions) + str.substring(0, positions); } } Try it Yourself >>

  14. Output Rotated String: cdefab Explanation The program rotates the string by the specified number of positions by slicing the string and concatenating the two parts in reverse order. String Coding Questions in Java 28. Reverse a String without using built-in functions. Ans: To reverse a string without using built-in functions, you can iterate through the string in reverseorder and construct a new string: publicclassReverseStringWithoutBuiltIn { publicstaticvoidmain(String[] args) { String str = "Hello"; String reversed = ""; for (int i = str.length() - 1; i >= 0; i--) { reversed += str.charAt(i); } System.out.println("Reversed String: " + reversed); } } Try it Yourself >> Explanation This program manually reverses the string by iterating through it from the last character to the first, appending each character to the result. 29. Check if a String is a palindrome using recursion. Ans: A string is a palindrome if it reads the same forward and backward. This can be checked recursively by comparing the first and last characte and then calling the function on the substring: publicclassPalindromeRecursion { publicstaticvoidmain(String[] args) { String str = "madam"; boolean isPalindrome = isPalindrome(str, 0, str.length() - 1); System.out.println("Is Palindrome: " + isPalindrome); } publicstatic boolean isPalindrome(String str, int start, int end) { if (start >= end) { return true; } i f ( s t r . c h a r A t ( s t a r t ) ! = s t r . c h a r A t ( e n d ) ) { return false; } return isPalindrome(str, start + 1, end - 1); } }

  15. Try it Yourself >> Explanation This recursive function checks if the characters at the start and end of the string are the same. If they are, it calls itself on the substring from t next start and end indices until it checks all characters. 30. Write a program to remove duplicate characters from a String. Ans: To remove duplicatecharacters, iterate through the string and add each character to a set or check if it has already been seen: import java.util.HashSet; publicclassRemoveDuplicates { publicstaticvoidmain(String[] args) { String str = "programming"; StringBuilder result = newStringBuilder(); HashSet seen = newHashSet<>(); for (int i = 0; i < str.length(); i++) { char currentChar = str.charAt(i); if (!seen.contains(currentChar)) { seen.add(currentChar); result.append(currentChar); } } S y s t e m . o u t . p r i n t l n ( " S t r i n g w i t h o u t d u p l i c a t e s : " + r e s u } } Try it Yourself >> Explanation to track the characters that have already been encountered and append only the unique characters to HashSet This program uses a StringBuilder. 31. Write a program to capitalize the first letter of each word in a String. Ans: To capitalize the first letter of each word, split the string into words and capitalize the first character of each word: publicclassCapitalizeWords { publicstaticvoidmain(String[] args) { String str = "hello world"; String[] words = str.split(" "); StringBuilder capitalized = newStringBuilder(); for (String word : words) { capitalized.append(word.substring(0, 1).toUpperCase()) .append(word.substring(1)).append(" "); }

  16. System.out.println("Capitalized String: " + capitalized.toString().trim()); } } Try it Yourself >> Explanation and . The result This program splits the string into words, then capitalizes the first letter of each word by using substring() toUpperCase() concatenated into a new string. 32. Write a program to check if a String contains only letters and digits. Ans: You can use the method with a regular expression that checks for only letters and digits: matches() publicclassCheckLettersAndDigits { publicstaticvoidmain(String[] args) { String str = "Hello123"; boolean isValid = str.matches("[a-zA-Z0-9]+"); System.out.println("Contains only letters and digits: " + isValid); } } Try it Yourself >> Explanation , which ensures that the string contains only alphabetic characters (both uppercase a This program uses the regular expression [a-zA-Z0-9]+ lowercase) and digits. Advanced Interview Programs on String in Java 33. Implement your own version of the replace() method. method, you can iterate through the string and replace occurrences of the target substring with t Ans: To implement your own replace() replacement: publicclassReplaceString { publicstaticvoidmain(String[] args) { String str = "hello world"; String target = "world"; String replacement = "Java"; String result = customReplace(str, target, replacement); System.out.println("Replaced String: " + result); } publicstatic String customReplace(String str, String target, String replacement) { return str.replaceAll(target, replacement); } }

  17. Try it Yourself >> Explanation functionality by using the method. The method replaces the target substring with the provid This program mimics the replace() replaceAll() replacement throughout the string. 34. Write a program to check if one String is a rotation of another String. Ans: To check if one string is a rotation of another, concatenate the first string with itself and check if the second string is a substring of t concatenated string: publicclassStringRotation { publicstaticvoidmain(String[] args) { String str1 = "abcde"; String str2 = "deabc"; boolean isRotation = isRotation(str1, str2); System.out.println("Is Rotation: " + isRotation); } publicstatic boolean isRotation(String str1, String str2) { if (str1.length() != str2.length()) { return false; } String concatenated = str1 + str1; return concatenated.contains(str2); } } Try it Yourself >> Explanation str1. This program concatenates with itself and checks if is a substring of the concatenated string. If it is, then is a rotation of str2 str1 str2 35. Write a program to find the most frequent word in a String. Ans: To find the most frequent word, split the string into words and use a map to count the occurrences: import java.util.HashMap; import java.util.Map; publicclassMostFrequentWord { publicstaticvoidmain(String[] args) { String str = "this is a test this is a test test"; String mostFrequentWord = findMostFrequentWord(str); System.out.println("Most Frequent Word: " + mostFrequentWord); }

  18. publicstatic String findMostFrequentWord(String str) { String[] words = str.split(" "); Map wordCount = newHashMap<>(); for (String word : words) { wordCount.put(word, wordCount.getOrDefault(word, 0) + 1); } String mostFrequent = null; int maxCount = 0; for (Map.Entry entry : wordCount.entrySet()) { if (entry.getValue() > maxCount) { mostFrequent = entry.getKey(); maxCount = entry.getValue(); } } return mostFrequent; } } Try it Yourself >> Explanation This program splits the input string into words, counts their occurrences using a , and then finds the word with the maximumcount. HashMap 36. Write a program to find the longest repeating sequence in a String. Ans: To find the longest repeating sequence, you can use a sliding window approach to check for repeated substrings: publicclassLongestRepeatingSequence { publicstaticvoidmain(String[] args) { String str = "abcdabc"; String longestSeq = findLongestRepeatingSequence(str); System.out.println("Longest Repeating Sequence: " + longestSeq); } publicstatic String findLongestRepeatingSequence(String str) { String longest = ""; for (int i = 0; i < str.length(); i++) { for (int j = i + 1; j < str.length(); j++) { String subStr = str.substring(i, j); if (str.indexOf(subStr, j) != -1 && subStr.length() > longest.length()) { longest = subStr; } } } return longest; } }

  19. Try it Yourself >> Explanation This program uses nested loops to find all substrings and checks if they appear more than once in the string. It returns the longest substring th repeats. 37. Implement a program that performs basic string compression (e.g., "aaabbc" -> "a3b2c1"). Ans: For string compression, iterate through the string and count consecutive characters, then build the compressed string: publicclassStringCompression { publicstaticvoidmain(String[] args) { String str = "aaabbc"; String compressed = compressString(str); System.out.println("Compressed String: " + compressed); } publicstatic String compressString(String str) { StringBuilder compressed = newStringBuilder(); int count = 1; for (int i = 1; i < str.length(); i++) { if (str.charAt(i) == str.charAt(i - 1)) { count++; } else { compressed.append(str.charAt(i - 1)).append(count); count = 1; } } compressed.append(str.charAt(str.length() - 1)).append(count); return compressed.toString(); } } Try it Yourself >> Explanation This program iterates through the string, counting consecutive occurrences of each character and appending the character followed by its count the result. String Programs in Java for Practice Here are some simple string programs to help you practice Java concepts. These programs cover common tasks like reversing a string, checki for palindromes, and finding substrings so you can improve your string manipulation skills. 38. Count the number of words in a String. Ans: To count the number of words, split the string into words and count the resulting array length: publicclassWordCount { publicstaticvoidmain(String[] args) {

  20. String str = "This is a sample string"; int wordCount = countWords(str); System.out.println("Number of Words: " + wordCount); } publicstatic int countWords(String str) { String[] words = str.split("\\s+"); return words.length; } } Try it Yourself >> Explanation to match any whitespace) and counts the length of the resulting arr This program splits the string by spaces (using the regular expression \\s+ which gives the word count. 39. Replace spaces with "%20" in a given String (URL encoding). Ans: You can replace spaces with "%20" by using the method: replace() publicclassReplaceSpaces { publicstaticvoidmain(String[] args) { String str = "Hello World, how are you?"; String encoded = encodeSpaces(str); System.out.println("Encoded String: " + encoded); } publicstatic String encodeSpaces(String str) { return str.replace(" ", "%20"); } } Try it Yourself >> Explanation This program uses the method to replace all spaces in the string with "%20", which is the URL encoding for a space. replace() 40. Write a program to sort the characters of a String in alphabetical order. Ans: You can convert the string into a character array, sort it, and then reconstruct the string: import java.util.Arrays; publicclassSortString { publicstaticvoidmain(String[] args) { String str = "dbca"; String sorted = sortString(str); System.out.println("Sorted String: " + sorted); }

  21. publicstatic String sortString(String str) { char[] chars = str.toCharArray(); Arrays.sort(chars); returnnewString(chars); } } Try it Yourself >> Explanation This program converts the string into a character array and sorts it using , and then convert the sorted array back to a string. Arrays.sort() 41. Check if a given String is a valid number (e.g., "123", "-456", "0.789"). Ans: You can use regular expressions or try parsing the string into a number: publicclassValidNumber { publicstaticvoidmain(String[] args) { String str = "-123.45"; boolean isValid = isValidNumber(str); System.out.println("Is Valid Number: " + isValid); } publicstatic boolean isValidNumber(String str) { try { Double.parseDouble(str); return true; } catch (NumberFormatException e) { return false; } } } Try it Yourself >> Explanation using . If it succeeds, the string is a valid number; otherwise, it Double.parseDouble() This program attempts to parse the string into a double not. 42. Write a program to remove all occurrences of a given character from a String. Ans: You can remove all occurrences of a character using the method: replace() publicclassRemoveCharacter { publicstaticvoidmain(String[] args) { String str = "hello world"; char ch = 'o'; String result = removeCharacter(str, ch); System.out.println("Result String: " + result);

  22. } publicstatic String removeCharacter(String str, char ch) { return str.replace(String.valueOf(ch), ""); } } Try it Yourself >> Explanation method to replace all occurrences of the specified character with an empty string, effectively removing it fro This program uses the replace() the original string. Summary This article covers essential interview questions related to Strings in Java, focusing on their properties, behavior, and common methods explains key concepts such as immutability, the String Pool, and String operations with practical examples. Whether you're a beginner or experienced developer, this guide will help you strengthen your knowledge and prepare for real interview scenarios involving Java Strings.

More Related