String Interview Questions In Java: Java is one of the most popular programming languages in the world, so there is a high demand for Java developers. String manipulation is a crucial part of programming in Java, and as a result, Java Strings interview questions are a vital part of Java developer interviews.
Java Strings interview questions assess a candidate’s understanding of various operations that can be performed on strings in Java, including creating and manipulating strings, string comparison, and substring extraction. In this context, this article contains some commonly asked Java Strings interview questions that can help Java developers prepare for interviews and better understand String manipulation in Java.
Java Interview Questions On Strings
- What is the meaning of Immutable in the context of a String class in Java?
- Why is a String object considered immutable in Java?
- How many objects does the following code create?
- How many ways are there in Java to create a String object?
- How many objects does the following code create?
- What is String interning?
- Why does Java use the String literal concept?
- What is the basic difference between a String and StringBuffer object?
- How will you create an immutable class in Java?
- What is the use of the toString() method in Java?
- Arrange the three classes String, StringBuffer, and StringBuilder in the order of efficiency for String processing operations.
Strings Interview Questions For Testers
What is the difference between String and String Buffer in Java?
Ans: The main difference between String and StringBuffer in Java is that the String is immutable while StringBuffer is mutable. This means you can modify a StringBuffer object once you have created it without creating any new objects.
What is the difference between StringBuilder and StringBuffer in Java?
Ans: StringBuffer and StringBuilder in Java have the same methods with one difference: synchronization. StringBuffer is synchronized, which means it is thread-safe, and hence, you can use it when you implement threads for your methods, whereas StringBuilder is not synchronized and is not threaded-safe. So, if you aren’t going to use threading, use the StringBuilder class, as it will be more efficient than StringBuffer due to the absence of synchronization.
How many ways are there to create a String?
Ans: In Java, you can create a string from a byte array, char array, another string, StringBuffer, or from StringBuilder. Java String class provides a constructor for all of these.
Why is String immutable in Java? Mention at least two reasons.
Ans: String has been widely used as a parameter for many java classes, e.g., for opening network connection, you can pass hostname and port number as a string:
- You can pass the database URL as a string to open the database connection.
- You can open any file by passing the name of the file as an argument to File I/O classes.
Since the string is immutable, it can be safely shared between many threads. This is very important for multithreaded programming. String immutability also helps avoid any synchronization issues in Java.
State the difference between the new operator and without a new operator in a string.
Ans:
String string=” Software Testingo”
Whenever we create an object of String object with a double quote, it allocates the memory in the string literal pool in the indexing manner.
String string=new String(“Software Testingo”);
Whenever we create the String object with the new operator, it allocates memory for the String object in the heap area in the indexing manner.
What is the difference between declaring a variable and defining a variable?
Ans: In the declaration, we mention the variable type and its name. We do not initialize it. But defining means declaration + initialization.
Example: String s; It is just a declaration while String s = new String (“abcd”); Or String s = “abcd”; is the definition.
What is the default value of an object reference declared as an instance variable?
Ans: The default value will be null unless we define it explicitly.
What is the difference between the String and StringBuffer classes?
Ans: String objects are constants, whereas StringBuffer objects are not constants.
If a variable is declared as private, from where can the variable be accessed?
Ans: A private variable may only be accessed within the class in which it is declared.
Is “abc” a primitive value?
Ans: The String literal “abc” is not a primitive value. It is a String object.
What happens when you add a double value to a String?
Ans: When we add a double value to a string, the result is a String object.
What is your platform’s default character encoding?
Ans: If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1.
Java String Programs For Automation Testing Interview
What is a String Constant Pool Area or String Literal Pool?
Ans: It is a separate block of memory where JVM holds the string objects. If a string object is created directly using the assignment operator, then it is stored in the string constant pool area. For example:
package com.softwaretestingo.java.basics; public class Test { public static void main(String[] args) { String str1 = "Hello"; String str2 = "Hello"; System.out.print(str1 == str2); } }
The result is: true
Predict the output of the following code snippet. Explain why?
Ans:
package com.softwaretestingo.java.basics; public class Test { public static void main(String[] args) { String s1="Software Testingo"; String s2=new String("Software Testingo"); if(s1 == s2) { System.out.println("Strings s1 and s2 both are same"); } else { System.out.println("Strings s1 and s2 both are not same"); } } }
Output:
Strings s1 and s2 both are not the same
Reason: The “==” operator always checks the objects’ addresses. As s1 and s2 have different addresses, it only executes the else block.
What is the difference between equals() and “==” in Java?
Ans: equals() “==” operator It is a method that can only be applied on any Java object by passing another Java object. It is a comparison operator, and it is applicable for both primitive and object types. It always compares content to present the objects. When we apply to primitive types, it compares the values of primitive types. And when we apply it to the object type, it compares the address of the objects.
Compile and run the below code. Provide the reason for the output that it gives.
Ans:
package com.softwaretestingo.java.basics; public class Test { public static void main(String[] args) { StringBuffer sb1 = new StringBuffer("SoftwareTestingo"); StringBuffer sb2 = new StringBuffer("SoftwareTestingo"); System.out.println("using == :" + (sb1 == sb2)); System.out.println("using equals() method: " + sb1.equals(sb2)); } }
Prints:
using == :false using equals() method: false
Reason: Using “==”: It always compares the address of the objects, so here we have used the new operator to create a string object it creates two different objects with two different addresses. Using equals() method: If we apply the equals() method on StringBuffer objects, it always prints false because, in the StringBuffer class, they did not override the equals() method. So it uses the Object class equals() method.
Compile and run the below code. Provide the reason for the output that it gives.
Ans:
package com.softwaretestingo.java.basics; public class Test { public static void main(String[] args) { Test t1=new Test(); System.out.println(t1); String s2="SoftwareTestingo"; System.out.println(s2); } }
Output:
com.softwaretestingo.java.basics.Test@15db9742 SoftwareTestingo
Reason: In the Test class, they didn’t override the toString() method in the println() method. It uses the Object class toString() method, producing a hash code of the Test class. In the String class, they override the toString() method to return the String.
What is the output of the following code? Provide the reason for the output that it gives.
Ans:
package com.softwaretestingo.java.basics; public class Test { public static void main(String[] args) { Integer i1=new Integer(123); String s1=new String(i1); System.out.println(s1); } }
Output:
compilation error because there is no constructor in the String class accepting to Integer object.
What is the output of the following code? Provide the reason for the output that it gives.
Ans: “Factory Method” is a static method of a class, which produces an object of the same class or at least its child class:
package com.softwaretestingo.java.basics; public class Test { public static void main(String[] args) { String s1=new String(); String s2=new String(""); if(s1.equals("")) { System.out.println("s1 and s2 are same"); } else { System.out.println("s1 and s2 are not same"); } } }
Output:
s1 and s2 are same
Because s1 holding the empty string object exactly matches with the object String s1=new String(“);
What is the output of the following code?
Ans: Sample code1:
package com.softwaretestingo.java.basics; public class Test { public static void main(String[] args) { String s1=null; if(null==s1) { System.out.println("s1 is having null"); } else { System.out.println("s1 is not having null"); } } }
Sample code2:
package com.softwaretestingo.java.basics; public class Test { public static void main(String[] args) { String s1=null; if(null.equals(s1)) { System.out.println("s1 is having null"); } else { System.out.println("s1 is not having null"); } } }
The output of sample Code 1: It executes the ‘if’ block because s1 can be initialized with the value null, and == operator compares the content present in the s1 with null both are the same. Hence, it executes the ‘if’ block and prints “s1 is having null”.
The output of Sample Code 2 gives a compilation error stating that “null cannot be dereferenced. “
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot invoke equals(String) on the primitive type null at com.softwaretestingo.java.basics.Test.main(Test.java:7)
What is the functionality of java.lang.String.intern()?
Ans: The java.lang.String.intern() returns an interned string, one with an entry in the global string pool. If the string is not already in the global string pool, it will be added.
package com.softwaretestingo.java.basics; public class Test { public static void main(String[] args) { // Create three strings in three different ways. String s1 = "Hello"; String s2 = new StringBuffer("He").append("llo").toString(); String s3 = s2.intern(); // Determine which strings are equivalent using the == // operator System.out.println("s1 == s2? " + (s1 == s2)); System.out.println("s1 == s3? " + (s1 == s3)); } }
Output:
s1 == s2? false s1 == s3? true
Can we pass more than one delimiter to a StringTokenizer?
Ans: Yes. We can pass any number of delimiters as an argument to a String Tokenizer. To work this, we have to separate each delimiter by “//” (double forward slash), or we can directly represent them.
Example:
package com.softwaretestingo.java.basics; import java.util.StringTokenizer; public class Test { public static void main(String[] args) { String sentence="10,10@10@10,10.10/10&10"; String temp; int k, total = 0; StringTokenizer s1 = new StringTokenizer(sentence,",/.@&"); //StringTokenizer s1 = new StringTokenizer(sentence,",/////.//@//&"); System.out.println("Total Number of tokens:" + s1.countTokens()); while (s1.hasMoreTokens()) { temp = s1.nextToken(); k = Integer.parseInt(temp); total += k; System.out.print(k + "\t"); } System.out.println(); System.out.println("Sum of tokens :" + total); } }
Output:
Total Number of tokens:8 10 10 10 10 10 10 10 10 Sum of tokens :80
Note: We can also pass “/” (single slash as a delimiter to the StringTokenizer) followed by “//”.
From the following input string: “this is apple 10 this is apple 20 this is apple 30 this is apple 40” Print the following output.
This is apple
This is apple
This is apple
This is apple
Program:
package com.softwaretestingo.java.basics; public class Test { public static void main(String[] args) { String sentence=" this is apple 10 this is apple 20 this is apple 30 this is apple 40"; String arr[]=sentence.split("\\d+"); /* ”\” for representing the \ d (d for digits) and + to allow multiple numbers in regular expression */ for(String token: arr) System.out.println(token); } }
Output:
this is apple this is apple this is apple this is apple
Ref: article