Java String Quiz - Multiple Choice Questions

In this post, we have provided Java String multiple-choice questions to test your knowledge about String in Java.

Learn and Master Java Programming: Learn Java Programming with Examples

Learn everything about Java 8 features: Java 8 Tutorial and Examples

Check out 100+ quiz questions: 100+ Quiz Questions to Test Your Java, Spring Boot, Microservices, Hibernate, REST API SkillsWe would suggest you, try these code snippets in Eclipse IDE and understand how the program works (However, the answer with the explanation given at the end of this post). These questions may ask in interviews or similar questions may appear in interviews so prepare yourself.

Q1. Consider the following program:

public class StrEqual {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = new String("hello");
        String s3 = "hello";
        if (s1 == s2) {
            System.out.println("s1 and s2 equal");
        } else {
            System.out.println("s1 and s2 not equal");
        }
        if (s1 == s3) {
            System.out.println("s1 and s3 equal");
        } else {
            System.out.println("s1 and s3 not equal");
        }
    }
}
Which one of the following options provides the output of this program when executed?
a)
s1 and s2 equal
s1 and s3 equal
b)
s1 and s2 equal
s1 and s3 not equal
c)
s1 and s2 not equal
s1 and s3 equal
d)
s1 and s2 not equal
s1 and s3 not equal

Answer:

c)
s1 and s2 not equal
s1 and s3 equal

Explanation: 

JVM sets a constant pool in which it stores all the string constants used in the type. If two references are declared with a constant, then both refer to the same constant object. The == operator checks the similarity of the objects themselves (and not the values in it). Here, the first comparison is between two distinct objects, so we get s1 and s2 not equal. On the other hand, since references to s1 and s3 refer to the same object, we get s1 and s3 equal.

Q2. Consider the following program:

public class Test {
    public static void main(String[] args) {
        String str = null;
        System.out.println(str.valueOf(10));
    }
}
Which of the following statements correctly describes the behavior of this program?
a) This program will result in a compiler error.
b) This program will throw a NullPointerException.
c) This program will print 10 in the console.
d) This program will print null in the console.

Answer:

c) This program will print 10 in the console.

Explanation: 

The valueOf(int) method is a static method in String that returns the String representation of the integer value that is passed as its argument. Since calling a static method does not require dereferencing the reference variable on which it is called, this program does not throw a NullPointerException.

Q3. Consider the following program and predict the output:

public class Test {
    public static void main(String[] args) {
        String s = new String("5");
        System.out.println(1 + 10 + s + 1 + 10);
    }
}
a) 11511
b) 1105110
c) 115110
d) 27 

Answer:

c) 115110

Explanation: 

The string concatenation operator works as follows: if both the operands are numbers, it performs the addition; otherwise, it concatenates the arguments by calling the toString() method if needed. It evaluates from left to right. Hence, the expression in the program results in the string 115110.

Q4. Consider the following program and predict its output:

public class Test {
    public static void main(String[] args) {
        String str = null;
        switch (str) { // #1
            case "null":
                System.out.println("null string"); // #2
                break;
        }
    }
}
a) This program results in a compiler error in statement #1.
b) This program results in a compiler error in statement #2.
c) This program results in throwing a NullPointerException.
d) This program prints the following: null string. 

Answer:

c) This program results in throwing a NullPointerException.

Explanation: 

If a null value is passed to a switch statement, it results in a NullPointerException.

Q5. What will be the output of the below statements?

public class Test {

    public static void main(String[] args) {
        String s1 = null;
        System.out.println(s1); //line 2
        System.out.println(s1.toString()); //line 3
    }
}
a) null null
b) null NullPointerException
c) NullPointerException NullPointerException
d) None 

Answer:

b) null NullPointerException

Explanation: 

Line 2 will print null because the println() method has a null check like below.
if (s == null) {
    s = "null";
}

Q6. Select all the classes that extend the String class

a) StringBuffer
b) StringBuilder
c) StringWriter
d) None

Answer: 

d) None

Explanation: 

 The String is a final class, so you can't extend it.

Q7. What is the output of the following program?

public class Test {

    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = new String("hello");

        s2 = s2.intern();
        System.out.println(s1 == s2);
    }
}
a) false
b) true
c) none

Answer: 

b) true

Explanation: 

We know that the intern() method will return the String object reference from the string pool since we assign it back to s2 and now both s1 and s2 are having the same reference. It means that s1 and s2 references point to the same object.

Q8. What will be the output of the below statements?

public class Test {

    public static void main(String[] args) {
        String s1 = "abc";
        StringBuffer s2 = new StringBuffer(s1);
        System.out.println(s1.equals(s2));
    }
}
a) false
b) true
c) ClassCastException at runtime
d) Compile-time error

Answer: 

a) false

Explanation: 

It will print false because s2 is not of type String. If you will look at the equals method implementation in the String class, you will find a check using instanceof operator to check if the type of passed object is String? If not, then return false.

Q9. What is the result of the following code?

String s1 = "Java";
String s2 = "Java";
StringBuilder sb1 = new StringBuilder();
sb1.append("Ja").append("va");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
System.out.println(sb1.toString() == s1);
System.out.println(sb1.toString().equals(s1));
A. true is printed out exactly once.
B. true is printed out exactly twice.
C. true is printed out exactly three times.
D. true is printed out exactly four times.
E. The code does not compile.

Answer: 

C. true is printed out exactly three times.

Explanation: 

String literals are used from the string pool. This means that s1 and s2 refer to the same object and are equal. Therefore, the first two print statements print true. The third print statement prints false because toString() uses a method to compute the value and it is not from the string pool. The final print statement again prints true because equals() looks at the values of String objects.

Q10. What is the difference between StringBuilder and StringBuffer in Java? 

a) StringBuilder is mutable, while StringBuffer is immutable.
b) StringBuilder is not a thread-safe, while StringBuffer is a thread-safe.
c) StringBuilder is synchronized, while StringBuffer is not synchronized.
d) There is no difference; they can be used interchangeably.

Answer: 

b) StringBuilder is not a thread-safe, while StringBuffer is a thread-safe.

Q11. What happens when two String objects are concatenated using the + operator in Java? 

a) A new String object is created.
b) The first String object is modified.
c) The second String object is modified.
d) The original String objects remain unchanged.

Answer: 

a) A new String object is created.

Q12. What is the output of the following code snippet?

String str = "Hello";
str += " World!";
System.out.println(str.length());
a) 5
b) 11
c) 12
d) Compile-time error

Answer: 

c) 12

Explanation: 

When "Hello" is concatenated with " World!", it forms a new string "Hello World!". The length of this string is 12 characters, so the output is 12.

Q13. What is the output of the following code snippet?

public class Main {
    public static void main(String[] args) {
        String str = "Java";
        str.concat(" Programming");
        System.out.println(str);
    }
}
a) Java
b) Java Programming
c) Programming
d) Compile-time error

Answer:

a) Java

Explanation:

The concat() method returns a new string resulting from concatenating the specified string to the original string. However, in this code, the result of concat() is not assigned back to the str variable. Therefore, the original string "Java" remains unchanged, and the output is "Java".

Q14. Which of the following methods is used to compare two strings for equality in Java?

a) equals()
b) compareTo()
c) contains()
d) concat()

Answer:

a) equals()

Explanation: 

The equals() method is used to compare two strings for equality in Java. It returns true if the two strings have the same characters in the same order, and false otherwise.

Q15. Which method is used to convert a string to uppercase in Java? 

a) toLowerCase()
b) toUpperCase()
c) trim()
d) replace()

Answer:

b) toUpperCase()

Explanation:

The toUpperCase() method is used to convert a string to uppercase in Java. It returns a new string with all characters converted to uppercase letters.

Q 16. What will be the output of the following code?

public class Main{
     public static void main(String []args){
        String str1 = "Java";
        String str2 = "Java";
        String str3 = new String("Java");

        System.out.println(str1.equals(str2) && str1.equals(str3));
     }
}
A) true
B) false
C) Compile error
D) Runtime error

Answer:

The correct answer is A) true.

Explanation:

In this code, str1 and str2 both refer to the same string literal "Java." Therefore, str1.equals(str2) returns true. The equals() method compares the actual contents of the strings.

Conclusion 

Congratulations on completing our Java String basics quiz! These questions tested your knowledge of string manipulation, including concatenation, comparison, extraction, and case conversion. By understanding these concepts, you'll be better equipped to work with strings effectively in Java programming.

Learn and Master Java Programming: Learn Java Programming with Examples

Learn everything about Java 8 features: Java 8 Tutorial and Examples

Check out 100+ quiz questions: 100+ Quiz Questions to Test Your Java, Spring Boot, Microservices, Hibernate, REST API Skills Keep exploring and practicing to enhance your skills in working with Java strings!

Comments