Java MCQs on string handling in Java Programming Language.
1. Which of these class is superclass of String and StringBuffer class? Answer: b 2. Which of these operators can be used to concatenate two or more String objects? Answer: a 3. Which of this method of class String is used to obtain a length of String object? Answer: d 4. Which of these method of class String is used to extract a single character from a String object? Answer: c 5. Which of these constructors is used to create an empty String object? Answer: a 6. Which of these is an incorrect statement? Answer: c 7. What will be the output of the following Java program? a) a 8. What will be the output of the following Java program? a) ABC 9. What will be the output of the following Java program? a) 3 0
a) java.util
b) java.lang
c) ArrayList
d) None of the mentioned
Clarification: None.
a) +
b) +=
c) &
d) ||
Clarification: Operator + is used to concatenate strings, Example String s = “i ” + “like ” + “java”; String s contains “I like java”.
a) get()
b) Sizeof()
c) lengthof()
d) length()
Clarification: Method length() of string class is used to get the length of the object which invoked method length().
a) CHARAT()
b) chatat()
c) charAt()
d) ChatAt()
Clarification: None.
a) String()
b) String(void)
c) String(0)
d) None of the mentioned
Clarification: None.
a) String objects are immutable, they cannot be changed
b) String object can point to some other reference of String variable
c) StringBuffer class is used to store string in a buffer for later use
d) None of the mentioned
Clarification: StringBuffer class is used to create strings that can be modified after they are created.
class String_demo
{
public static void main(String args[])
{
char chars[] = {'a', 'b', 'c'};
String s = new String(chars);
System.out.println(s);
}
}
b) b
c) c
d) abc
Clarification: String(chars) is a constructor of class string, it initializes string s with the values stored in character array chars, therefore s contains “abc”.
output:
$ javac String_demo.java
$ java String_demo
abc
class String_demo
{
public static void main(String args[])
{
int ascii[] = { 65, 66, 67, 68};
String s = new String(ascii, 1, 3);
System.out.println(s);
}
}
b) BCD
c) CDA
d) ABCD
Clarification: ascii is an array of integers which contains ascii codes of Characters A, B, C, D. String(ascii, 1, 3) is an constructor which initializes s with Characters corresponding to ascii codes stored in array ascii, starting position being given by 1 & ending position by 3, Thus s stores BCD.
output:
$ javac String_demo.java
$ java String_demo
BCD
class String_demo
{
public static void main(String args[])
{
char chars[] = {'a', 'b', 'c'};
String s = new String(chars);
String s1 = "abcd";
int len1 = s1.length();
int len2 = s.length();
System.out.println(len1 + " " + len2);
}
}
b) 0 3
c) 3 4
d) 4 3
Clarification: None.
output:
$ javac String_demo.java
$ java String_demo
4 3
