Tutorial

Java String Quiz

Published on August 3, 2022
author

Pankaj

Java String Quiz

Welcome to Java String Quiz. String is one of the most important classes in Java. If you have done any programming in java, you must have used it.

The string is very popular when it comes to java interview questions or quiz. So I have gathered some great and tricky java string quiz questions that you should try.

Java String Quiz

There are 21 questions in this quiz. If you can correctly answer 15 or more, then consider yourself really good in String concepts. You can check the answer and detailed explanation by clicking on the “Reveal Answer” button after each question.

Let’s start the String Quiz and best of luck.

1. What will be the output of below statements?

String s = "Java String Quiz";
System.out.println(s.charAt(s.toUpperCase().length()));

A. Convert “Z” to int 90 and prints “90”
B. Runtime Exception
C. Prints “z”
D. Prints “Z”

Click to Reveal Answer

**Correct Answer: B
**
It will throw the runtime exception.Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 16 It’s because the index value starts from 0.

2. What will be output of below statements?

String s = "Java String Quiz";
System.out.println(s.substring(5,3));

A. Prints “Str”
B. Runtime Exception
C. IndexOutOfBoundsException Runtime Exception
D. StringIndexOutOfBoundsException Compile-time error

Click to Reveal Answer

**Correct Answer: B
**
It will throw the runtime exception with the error message as Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 5, end 3, length 16. It’s because the end index is smaller than the start index.

3. Select all valid methods of String class.

A. trim()
B. intern()
C. toLower()
D. split()

Click to Reveal Answer

Correct Answer: A, B

Valid methods of String class are - trim(), intern(), toLowerCase(), and split(String regex).

4. What will be the output of below statements?

String s1 = "Cat";
String s2 = "Cat";
String s3 = new String("Cat");
System.out.print(s1 == s2);
System.out.print(s1 == s3);

A. truefalse
B. truetrue
C. falsefalse
D. falsetrue

Click to Reveal Answer

**Correct Answer: A
**
When we use double quotes to create a String, it first looks for String with the same value in the String pool. If found, then it returns the reference else it creates a new String in the pool and then returns the reference.

However using new operator, we force String class to create a new String object in heap space. So s1 and s2 will have reference to the same String in the pool whereas s3 will be a different object outside the pool, hence the output.

5. Which of the following statements are true for string in switch case?

A. String is allowed in switch case for Java 1.5 or higher versions.
B. String is allowed in switch case for Java 1.7 or higher versions.
C. The equals() method is used by switch-case implementation, so add null check to avoid NullPointerException.

Click to Reveal Answer

Correct Answer: B, C

Read more at java switch case string

6. Which of the following statements are True for StringBuffer and StringBuilder?

A. StringBuilder is not thread-safe.
B. StringBuffer is thread safe because its methods are synchronized.
C. StringBuilder was introduced in Java 1.4
D. StringBuffer and StringBuilder are immutable.

Click to Reveal Answer

Correct Answer: A, B

StringBuffer object is thread-safe because its methods are synchronized. But that’s an overhead in most of the cases, hence StringBuilder was introduced in Java 1.5. StringBuilder is not thread-safe. StringBuffer and StringBuilder are mutable classes. Read more at String vs StringBuffer vs StringBuilder.

7. String implementation follows which of the below design pattern?

A. Flyweight Design Pattern
B. Factory Pattern
C. Singleton Pattern
D. None of the above

Click to Reveal Answer

Correct Answer: A

String pool implementation follows the flyweight design pattern.

8. What will be the output of below statements?

String s1 = "abc";
String s2 = "def";
System.out.println(s1.compareTo(s2));

A. 0
B. true
C. -3
D. false

Click to Reveal Answer

**Correct Answer: C
**
From String compareTo() method documentation:

compareTo method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.

This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string – that is, the value:

this.charAt(k)-anotherString.charAt(k)

In our example the “abc” precedes “def”, hence negative integer is returned. Then the lowest index with different char is 0 and a-d equals to -3.

9. What will be the output of below program?

public class Test {
	public static void main(String[] args) {
		String x = "abc";
		String y = "abc";
		x.concat(y);
		System.out.print(x);
	}
}

A. abc
B. abcabc
C. null

Click to Reveal Answer

Correct Answer: A

The x.concat(y) will create a new string but it’s not assigned to x, so the value of x is not changed.

10. What will be the output of below program?

public class Test {
	public static void main(String[] args) {
		String s1 = "abc";
		String s2 = "abc";
		System.out.println("s1 == s2 is:" + s1 == s2);
	}
}

A. false
B. s1 == s2 is:true
C. s1 == s2 is:false
D. true

Click to Reveal Answer

Correct Answer: A

The given statements output will be “false” because in java + operator precedence is more than == operator. So the given expression will be evaluated to “s1 == s2 is:abc” == “abc” i.e false.

11. What will be the output of below statements?

String s = "Java"+1+2+"Quiz"+""+(3+4);
System.out.println(s);

A. Java3Quiz7
B. Java12Quiz7
C. Java12Quiz34
D. Java3Quiz34

Click to Reveal Answer

Correct Answer: B

First of all, the expression in the bracket is executed. Then it’s all + operators, so they get executed from left to right.

We get String with each concatenation, hence the output gets produced as shown below.

“Java”+1+2+“Quiz”+“”+(3+4)
= “Java”+1+2+“Quiz”+“”+7
= “Java1”+2+“Quiz”+“”+7
= “Java12”+“Quiz”+“”+7
= “Java12Quiz”+“”+7
= “Java12Quiz”+7
= “Java12Quiz7”

12. How many String objects created in below statements?

String s = "abc"; // statement 1
String s1 = new String("abcd"); // statement 2

A. 1
B. 2
C. 3
D. 4

Click to Reveal Answer

Correct Answer: C

In statement 1, “abc” is created in the String pool.

In statement 2, first of all “abcd” is created in the string pool. Then it’s passed as an argument to the String new operator and another string gets created in the heap memory.

So a total of 3 string objects gets created.

13. What will be the output of below statements?

String s1 = "abc";
String s2 = new String("abc");
System.out.print(s1==s2);
System.out.println(s1==s2.intern());

A. falsetrue
B. falsefalse
C. truetrue
D. truefalse

Click to Reveal Answer

Correct Answer: A

The s1 is in the string pool whereas s2 is created in heap memory.

Hence s1==s2 will return false.

When s2.intern() method is called, it checks if there is any string with value “abc” in the pool. So it returns the reference of s1. So both s1 and s2 are pointing to the same string instance now.

Hence s1==s2.intern() will return true.

14. Select all the interfaces implemented by String class.

A. Serializable
B. Comparable
C. Constable
D. Cloneable

Click to Reveal Answer

Correct Answer: A, B, C

String is serializable and comparable. The Constable is a new interface from the Java 12 release.

15. Select all the reasons that make String perfect candidate for Map key?

A. String is immutable
B. String is final
C. String properly implements hashCode() and equals() method
C. String hashcode is cached

Click to Reveal Answer

**Correct Answer: A, B, C
**
The proper implementation of hashCode() and equals() method is a must for a Map key. Since the string is final and immutable, there are no chances of corruption of the key data.

16. What will be the output of below code snippet?

String s1 = new String("java");
String s2 = new String("JAVA");
System.out.println(s1 = s2);

A. JAVA
B.java
C. true
D. false

Click to Reveal Answer

**Correct Answer: A
**
It will print “JAVA” because the argument inside the println() method is an assignment. So it will be treated as System.out.println("JAVA").

17. What will be the output of below statements?

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

Click to Reveal Answer

Correct Answer: A

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

18. What will be the output of below code snippet?

String s1 = "abc";
String s2 = new String("abc");
s2.intern();
System.out.println(s1 == s2);

A. false
B. true
C. null

Click to Reveal Answer

Correct Answer: A

It’s a tricky question and output will be false. We know that intern() method will return the String object reference from the string pool, but since we didn’t assign it back to s2, there is no change in s2. Hence both s1 and s2 are having a different reference.

If we change the code in line 3 to s2 = s2.intern(); then the output will be true.

19. Select all the classes that extend String class.

A. StringBuffer
B. StringBuilder
C. StringWriter
D. None

Click to Reveal Answer

**Correct Answer: D
**
It’s a tricky question. The String is a final class, so you can’t extend it.

20. Which of the following statements are true about String in java?

A. We can extend String class like StringBuffer does it.
B. String class is defined in java.util package.
C. String is immutable in Java.
D. String is thread-safe in Java.
E. String is case sensitive in Java.

Click to Reveal Answer

Correct Answer: C, D, E

We can’t extend String class because it’s final. StringBuffer doesn’t extend it. String class is defined in java.lang package.The string is immutable and hence thread-safe in java. String is case sensitive, so “abc” is not equal to “ABC”.

21. What will be the output of below statements?

String s1 = null;
System.out.print(s1); // line 2
System.out.print(s1.toString()); // line 3

A. nullnull
B. null followed by NullPointerException
C. NullPointerException

Click to Reveal Answer

Correct Answer: B

Line 2 will print null because print method has null check like this:

if (s == null) { s = "null";}

Line 3 will throw NullPointerException because we are trying to invoke toString() function on null.

Conclusion

I have tried to cover most of the important points about String in this Quiz. If you think some interesting concept has been missed, please let me know through comments. If you liked the Quiz, share it with others too.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
July 17, 2020

Thank you for the Quiz, it was really useful.

- Suraj

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    March 7, 2020

    Thanks for quizs!

    - Ul

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      November 8, 2019

      in question about s1==s2 s1==s2.intern() i checked falsetrue, and got wrong with answer =“s1 is in the string pool whereas s2 is created in heap memory. Hence s1==s2 will return false. When s2.intern() method is called, it checks if there is any string with value “abc” in the pool. So it returns the reference of s1. So both s1 and s2 are pointing to same string instance now. Hence s1==s2.intern() will return true.” wich seems to me would give falsetrue, wich is what i choose

      - Kamil

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        August 19, 2019

        Hi Pls provide some finding an output type comments

        - rohit

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          August 16, 2019

          Good Questions , especially considering some have muiltiple answers. I am studying for the Java Cert, so this is good practice too.

          - CTM

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            December 21, 2018

            I request to put more questions on String. Questions are really worth to get more insight about the string.

            - Rajesh

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              July 31, 2018

              Why are the code snippets not displayed in the questions where you are asking to find out the output?

              - anirtek

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                July 1, 2018

                Question 4 is too tricky from my perspective and I wouldn’t agree that in question 3 “String is final” is invalid choice, because otherwise you could extend String and override hashcode, equals then pollute collections with unsafe ChildStrings and everything will be broken, benefits of String immutability are lost in this situation.

                - Mana

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  June 26, 2018

                  This was very good quiz on Strings and sharpned some core concepts. Is there any short cut or trick to remember all methods or interfaces as list is too huge and not easy to remember all those as asked in some questions in the quiz?

                  - Gaurav Singh

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    April 10, 2018

                    there is a lot of things that I have learnt after doing this quiz.

                    - WuJing

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Become a contributor for community

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      DigitalOcean Documentation

                      Full documentation for every DigitalOcean product.

                      Resources for startups and SMBs

                      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                      Get our newsletter

                      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                      New accounts only. By submitting your email you agree to our Privacy Policy

                      The developer cloud

                      Scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Get started for free

                      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                      *This promotional offer applies to new accounts only.