This set of Java Multiple Choice Questions & Answers (MCQs) on “Wildcards”.
1. Which of these is wildcard symbol? Answer: a 2. What is use of wildcards? Answer: a 3. Which of these keywords is used to upper bound a wildcard? Answer: c 4. Which of these is an correct way making a list that is upper bounded by class Number? Answer: a 5. Which of the following keywords are used for lower bounding a wild card? Answer: b 6. What will be the output of the following Java program? a) 0 7. What will be the output of the following Java program? a) 5.0 8. What will be the output of the following Java program? a) H
a) ?
b) !
c) %
d) &
Clarification: In generic code, the question mark (?), called the wildcard, represents an unknown type.
a) It is used in cases when type being operated upon is not known
b) It is used to make code more readable
c) It is used to access members of super class
d) It is used for type argument of generic method
Clarification: The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific). The wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a supertype.
a) stop
b) bound
c) extends
d) implements
Clarification: None.
a) List extends Number>
b) List
c) List(? extends Number)
d) List(? UpperBounds Number)
Clarification: None.
a) extends
b) super
c) class
d) lower
Clarification: A lower bounded wildcard is expressed using the wildcard character (‘?’), following by the super keyword, followed by its lower bound: super A>.
import java.util.*;
class Output
{
public static double sumOfList(List extends Number> list)
{
double s = 0.0;
for (Number n : list)
s += n.doubleValue();
return s;
}
public static void main(String args[])
{
List<Integer> li = Arrays.asList(1, 2, 3);
System.out.println(sumOfList(li));
}
}
b) 4
c) 5.0
d) 6.0
Clarification: None.
Output:
$ javac Output.javac
$ java Output
6.0
import java.util.*;
class Output
{
public static double sumOfList(List extends Number> list)
{
double s = 0.0;
for (Number n : list)
s += n.doubleValue();
return s;
}
public static void main(String args[])
{
List<Double> ld = Arrays.asList(1.2, 2.3, 3.5);
System.out.println(sumOfList(ld));
}
}
b) 7.0
c) 8.0
d) 6.0
Clarification: None.
Output:
$ javac Output.javac
$ java Output
7.0
import java.util.*;
public class genericstack <E>
{
Stack <E> stk = new Stack <E>();
public void push(E obj)
{
stk.push(obj);
}
public E pop()
{
E obj = stk.pop();
return obj;
}
}
class Output
{
public static void main(String args[])
{
genericstack <Integer> gs = new genericstack<Integer>();
gs.push(36);
System.out.println(gs.pop());
}
}
b) Hello
c) Runtime Error
d) Compilation Error
Clarification: generic stack object gs is defined to contain a string parameter but we are sending an integer parameter, which results in compilation error.
Output:
$ javac Output.javac
$ java Output