worksheet 2 string(output)
worksheet 2 string(output)
String s1 = "Java";
String s2 = new String("Java");
System.out.println(s1 == s2);
a) true b) false
c) Compile-time error d) Runtime error
a) "Hello".substring(1, 4) b) "Hello".substring(1, 5)
c) "Hello".substring(1, 6) d) "Hello".substring(0, 5)
String s = "JavaProgramming";
String result = s.substring(3, 3);
System.out.println(result);
a) "Java" b) "" (empty string)
c) "Pro" d) Throws an exception
4) Which of the following methods can be used to efficiently modify a string in Java?
a) StringBuffer b) StringBuilder
c) Both a and b d) String
s.trim();
System.out.println(s.length());
a) 6 b) 7
c) 5 d) 8
6 ) Which of the following methods is used to compare two strings lexicographically, ignoring case
differences?
a) equalsIgnoreCase() b) compareTo()
c) compareToIgnoreCase() d) equals()
String s = "abcde";
System.out.println(s.indexOf("cd", 3));
a) -1 b) 2
c) 3 d) 4
a) Two strings with the same content are always the same object.
b) String literals are automatically interned by the JVM.
c) new String("Hello") creates an interned string.
d) Interned strings cannot be garbage collected.
9) What will the following code print?
String s1 = "hello";
String s2 = "world";
System.out.println(s1.concat(s2) == s1 + s2);
a) true b) false
c) Compile-time error d) Runtime exception
a) StringBuilder is mutable.
b) StringBuilder is synchronized.
c) StringBuilder can be used when we need to modify strings frequently.
d) StringBuilder is faster than StringBuffer.
SOLUTIONS
Answer: 1 b) false
Explanation: The == operator compares the memory reference, not the content. s1 and s2 refer to
different objects in memory.
Answer: 2 c) "Hello".substring(1, 6)
Explanation: The string "Hello" has indices from 0 to 4. Attempting to use an index beyond 5 will
result in an exception.
Explanation: The trim() method does not modify the original string, as strings are immutable. The
original string remains unchanged.
Answer: 5 d) 8
Explanation: The search starts at index 3, and "cd" starts at index 2, so it is not found.
Answer: 6 c) compareToIgnoreCase()
Answer: 7 a) -1
Explanation: The JVM automatically interns string literals to improve memory efficiency, but using
new String() creates a new object that is not automatically interned.
Answer:9 b) false
Explanation: concat() creates a new string, but the + operator may result in a different memory
reference even if the content is the same.