Java String Quiz

Filed Under: Java


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

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.

Best of Luck!

What will be the output of below statements?

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

Correct! Wrong!

It will throw the runtime exception.


Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 16
	at java.lang.String.charAt(String.java:658)
	at com.journaldev.java.Test.main(Test.java:11)
Note that index value starts from 0.

What will be output of below statements?

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

Correct! Wrong!

It will throw the runtime exception.


Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
	at java.lang.String.substring(String.java:1967)
	at com.journaldev.java.Test.main(Test.java:11)
It's because the end index is smaller than the start index.

Select all valid methods of String class.

Please select 2 correct answers

Correct! Wrong!

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

What will be the output of below statements?

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

Correct! Wrong!

When we use double quotes to create a String, it first looks for String with the same value in the String pool, if found it just 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.

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

Please select 2 correct answers

Correct! Wrong!

Read more at java switch case string

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

Please select 2 correct answers

Correct! Wrong!

StringBuffer is thread-safe because it's 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

String implementation follows which of the below design pattern?

Correct! Wrong!

String pool implementation follows flyweight design pattern.

What will be the output of below statements?

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

Correct! Wrong!

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 "abc" precedes "def", hence negative integer is returned. Then lowest index with different char is 0. a-d equals to -3.

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);
	}
}

Correct! Wrong!

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

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);
	}
}

Correct! Wrong!

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.

What will be the output of below statements?

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

Correct! Wrong!

First expression in the bracket is executed, then it's all + operators and 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"

How many String objects created in below statements?

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

Correct! Wrong!

Line 1, "abc" created in String pool. Line 2, first "abcd" created in the string pool, then passed as an argument to String new operator and another string gets created in heap memory. So a total of 3 string objects gets created.

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());

Correct! Wrong!

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.

Select all the interfaces implemented by String class.

Please select 3 correct answers

Correct! Wrong!

Check String class java documentation.

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

Please select 3 correct answers

Correct! Wrong!

Read more at string HashMap key

What will be the output of below code snippet?

String s1 = new String("pankaj");
String s2 = new String("PANKAJ");

System.out.println(s1 = s2);

Correct! Wrong!

It will print "PANKAJ" because the argument inside the println() function is an assignment. So it will be treated as System.out.println("PANKAJ")

What will be the output of below statements?

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

Correct! Wrong!

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.

What will be the output of below code snippet?

String s1 = "abc";
String s2 = new String("abc");

s2.intern();
System.out.println(s1==s2);

Correct! Wrong!

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 and hence both s1 and s2 are having a different reference. If we change the code inline 3 to s2 = s2.intern(); then output will be true.

Select all the classes that extend String class.

Correct! Wrong!

It's a tricky question. The String is a final class, so you can't extend it.

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

Please select 3 correct answers

Correct! Wrong!

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".

What will be the output of below statements?

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

Correct! Wrong!

Line 2 will print null because println method has null check like below.


if (s == null) {
    s = "null";
}
Line 3 will throw NullPointerException because we are trying to invoke toString() function on null.

Java String Quiz
Quiz Results: Pass
You have a decent understanding of the Java String class. Please read this tutorial and try again the Quiz to improve your score.
Quiz Result: Distinction
Awesome! You have a deep understanding of the Java String class and its internal implementation. You should now try Core Java Quiz.
Quiz Result: Poor
You lack basics of Java String. Please read this tutorial and try again the Quiz to score better.

Share your Results:

Comments

  1. rohit says:

    Hi Pls provide some finding an output type comments

  2. CTM says:

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

  3. Rajesh says:

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

  4. anirtek says:

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

    1. Pankaj says:

      Yes, you are right. Thanks for commenting and bringing it to our notice. We are working on fixing it as we speak.

  5. Mana says:

    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.

    1. Pankaj says:

      The question is related to Map Key. Even if you subclass it, it doesn’t matter to String class. Now you can always say that we can break things with Reflection, but let’s not go there.

  6. Gaurav Singh says:

    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?

  7. WuJing says:

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

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages