Welcome to the Java String Coding Quiz. In this quiz, we present 10 coding MCQ questions to test your coding knowledge on the Java String topic. Each question has a correct and brief explanation.
1. What is the output of the following Java code snippet?
String str = "Hello World";
System.out.println(str.length());
Answer:
Explanation:
The length() method returns the number of characters in the string, including spaces. "Hello World" has 11 characters.
2. What does this Java code snippet output?
String s1 = "Java";
String s2 = new String("Java");
System.out.println(s1 == s2);
Answer:
Explanation:
'==' compares references, not values. s1 and s2 refer to different objects, so the output is false.
3. Identify the output of the following code:
String text = "JavaProgramming";
System.out.println(text.substring(4, 7));
Answer:
Explanation:
substring(int startIndex, int endIndex) returns the string from startIndex (inclusive) to endIndex (exclusive). Here, it's "Pro".
4. What will be printed by this Java code?
String str1 = "Java";
String str2 = "Java";
System.out.println(str1.equals(str2));
Answer:
Explanation:
The equals() method compares the values of strings. str1 and str2 have the same value, so the result is true.
5. What does this code snippet output?
String word = "Hello";
word.concat(" World");
System.out.println(word);
Answer:
Explanation:
Strings in Java are immutable. concat() creates a new string, which is not assigned to a word. So, the word remains unchanged.
6. What is the result of executing this code?
String a = "Java";
String b = " Programming";
String c = a + b;
System.out.println(c);
Answer:
Explanation:
The + operator concatenates two strings, creating a new string "Java Programming".
7. What will the following Java code snippet output?
String str = "Java";
System.out.println(str.toUpperCase());
Answer:
Explanation:
The toUpperCase() method converts all characters in the string to upper case.
8. What does the following code snippet print?
String text = "Java";
System.out.println(text.replace('a', 'x'));
Answer:
Explanation:
The replace(char oldChar, char newChar) method replaces all occurrences of the specified old character with the new character.
9. Determine the output of this Java code:
String s = "programming";
System.out.println(s.charAt(3));
Answer:
Explanation:
charAt(int index) returns the char value at the specified index. Indexing starts from 0, so s.charAt(3) is 'g'.
10. What is the result of the following code snippet?
String first = "Java";
String second = "Python";
System.out.println(first.compareTo(second));
Answer:
Explanation:
compareTo() compares two strings lexicographically. Since "Java" is lexicographically less than "Python", it returns a negative number.
Comments
Post a Comment
Leave Comment