Java strings interview FAQs with essential questions and answers related to string manipulation, methods, and operations in Java for interview preparation

6.What is the difference between == operator and.equals() method in Java for comparing strings?
The == operator and the.equals() method in Java are used to compare strings.
The == operator compares the memory references of two string objects. It checks whether the two references point to the same memory location.
For example:
String a = "Hello";
String b = "Hello";
System.out.println(a == b); /* true (both refer to the same string in the string pool) */
But if one of the strings is created with the new keyword, the == operator returns false since the two references point to different objects:
String c = new String("Hello");
System.out.println(a == c); // false
The.equals() method however compares the actual content of the strings. It checks whether the character sequences of two strings are identical.
For example:
System.out.println(a.equals(c)); // true (content is the same)
Always use.equals() for content comparison and reserve == for reference comparison.


7.What is the immutability of Strings in Java and how does it affect performance?
Strings in Java are immutable: once created their contents can't be modified.
Here is an example:
String s = "Hello";
s.concat(" World"); /* This generates a new string "Hello World" but doesn't alter 's'.*/
System.out.println(s); // Prints "Hello"
Immutable makes strings thread safe, thus it's fine for concurrent applications. It also means that the language can implement efficient memory management based on a so-called string pool, where equivalent strings are shared.
Here's an example:
String a = "Java";
String b = "Java"; // References the same string object in the string pool.
However, immutability leads to performance degradation when modifications frequently happen, like a loop with a number of concatenations. Here each modification involves creating a new string object, which wastes more bytes in memory and processing power. In this kind of situations StringBuilder or StringBuffer are recommended. Despite all, it has a number of benefits for better safety, reliability and performance in applications.


8.How do you determine if a given string contains a particular substring in Java?
You use the.contains() method. This method returns a boolean to show whether a substring exists in the main string.
For instance:
String text = "Welcome to Java programming";
boolean result = text.contains("Java");
System.out.println(result); // true
This method is case-sensitive. When you need case-insensitive checks, you might convert both input strings to a single case prior to calling contains() using methods .toLowerCase() or .toUpperCase().
For example:
boolean result = text.toLowerCase().contains("java");
The use of the method.contains() is very wide-spread while implementing search functionally or check inputs. This is simple and efficient and without any additional cycles or complex logics. But if you really need more complex pattern matching, look for regular expressions implementation using classes Pattern and Matcher


9.How many methods are available to convert string to number in Java?
In Java, there are methods available inside a wrapper class called Integer, Double or Float.
Following are some examples:
1. Using parseInt() or parseDouble():
String number = "123";
int num = Integer.parseInt(number);
System.out.println(num); // 123
2. Using valueOf():
String number = "456";
Integer num = Integer.valueOf(number); /* Returns an Integer object.*/
System.out.println(num); // 456
3. Using Double.parseDouble() for floating-point numbers:
String decimal = "123.45";
double value = Double.parseDouble(decimal);
System.out.println(value); // 123.45
Always make sure the string is a valid number; otherwise, these methods throw NumberFormatException. You can handle this with try-catch blocks to ensure safe execution.


10.How do you split a string into an array in Java?
To split a string into an array, use the.split() method. This method divides the string based on a specified delimiter and returns an array of substrings.
For example:
String text = "Java,Python,C++";
String[] languages = text.split(",");
for (String lang : languages) {
System.out.println(lang);
}
Output:
Java
Python
C++
The.split() method uses regular expressions as the delimiter.
For example, to split by whitespace:
String text = "Java Programming Language";
String[] words = text.split("\\s+");
Be careful when using .split() methods with special characters, such as. or |. They need to be escaped. It is very useful when parsing CSV files, tokenizing input, or breaking sentences into words.


11.How to remove leading and trailing whitespaces from a string in Java?
To remove leading and trailing whitespaces you use the method .trim().
Example:
String text = " Hello, World! ";
String trimmed = text.trim();
System.out.println(trimmed); // "Hello, World!"
The.trim() method removes only the spaces at the beginning and end of the string but does not affect spaces within the string.
For example:
String text = " Hello World ";
System.out.println(text.trim()); // "Hello World"
If you want to remove all extra spaces (including those within the string), use.trim() in combination with.replaceAll():
String cleaned = text.trim().replaceAll("\\s+", " ");
This technique can be really helpful in the preprocessing of user-input data or cleaning of the data to be processed.


12.What does the intern() method do for Java Strings?
Intern() is a method of Java used for optimizing memory and performance, mainly in terms of string management. The intern() method will first check whether a string exists in the pool if it does, then a reference to that pooled instance will be returned. otherwise, it will be added to the pool, and then the reference to it will be returned.
For example:
String s1 = new String("Java");
String s2 = s1.intern(); // Adds "Java" to the string pool.
String s3 = "Java";
System.out.println(s2 == s3); /* true (both refer to the same pooled instance)*/
The intern() method is particularly helpful in scenarios in which duplicate strings are often generated. Interning strings ensures Java has only one instance of every string in memory, thereby minimizing redundancy. Still, this should be used prudently in order not to overload the string pool.


13.How do you get the length of a string in Java?
To find the length of a string in Java, use the .length() method. This method returns the number of characters in the string, including spaces and special characters but excluding the null terminator.
For example:
String text = "Hello, World!";
int length = text.length();
System.out.println(length); // 13
The.length() method is very simple and effective. It's used often when you need to validate user input or process strings in loops.
For example, you can verify if a string is longer than a certain length:
if (text.length() > 10) {
System.out.println("The string is too long.");
}
This method is also useful when working with strings dynamically to ensure operations are within bounds. Remember that.length() is not the same as the length property for arrays.


14.How to replace characters or substrings in a string in Java?
The.replace() and.replaceAll() methods in Java are used to replace characters or substrings in a string.
1. Using.replace():
The.replace() method replaces all occurrences of a character or substring with another.
For example:
String text = "apple";
String result = text.replace("p", "b");
System.out.println(result); // "abble"
2. Using.replaceAll():
This method allows replacements using regular expressions.
For example:
String text = "123abc456";
String result = text.replaceAll("\\d", "*"); // Replaces all digits.
System.out.println(result); // "***abc***"
For case-insensitive replacement, chain.replaceAll() with.toLowerCase() or.toUpperCase(). Both are useful to clean user input or to output strings in certain formats.


15.What does the String.format() method in Java do and how does it work?
The String.format() method is a strong tool for forming formatted strings in Java. You can embed variables and control how they are presented, such as alignment, padding and number formatting.
Here's an example:
String formatted = String.format("Name: %s, Age: %d", "Alice", 25);
System.out.println(formatted); // "Name: Alice, Age: 25"
You can use the following format specifiers:
•%s for strings
•%d for integers
•%f for floating-point numbers
For example, to format a floating-point number:
String result = String.format("%.2f", 123.456); // two decimal places.
System.out.println(result); // "123.46"
This method is very useful in generating user-friendly outputs, logs and even formatting data for a report, hence it can improve readability and consistency in the manipulation of the strings.