http://www.javabeat.net/javabeat/scjp5/mocks/Generics-part1-6questions.php
1. What is result of compiling and running the following code?
1)ArrayList sampleList = new ArrayList<Integer>();
2)sampleList.add(40);
3)sampleList.add(20);
4)sampleList.add(70);
5)for(int num : sampleList)
6)System.out.println(num + "");
Options :
a) compiler error at line 1.
b) compiler error at line 2,3,4.
c) compiler error at line 5.
d) compiles fine and prints 40 20 70.
Answer :
c) ArrayList sampleList is not type safe, so it will return "Object" in line 5 which cannot be changed in to type int.
2. What is result of compiling and running the following code?
HashSet<String> hs = new HashSet<String>();
hs.add("scjp");
hs.add("exam");
HashSet<Object> s = new HashSet<Object>();
s=hs;
System.out.println(s);
Options:
a) compiler error
b) ClassCastException is thrown at runtime.
c) prints [scjp, exam]
d) prints [exam, scjp]
Answer :
a) class will not compile since HashSet<String> and HashSet<Object> are incompatible types
3. What is result of compiling and running the following code?
import java.util.*;
class Vehicle {}
class Car extends Vehicle {}
class Bus extends Vehicle {}
class TestSamp {
public static void main(String [] args) {
ArrayList<Car> a = new ArrayList<Car>();
a.add(new Car());
ArrayList b = a;
ArrayList<Bus> c = (ArrayList<Bus>)b;
c.add(new Bus());
for (Object obj : b)
System.out.println(obj);
}
}
Options:
a)compiler error
b)compiles with warning and gives some output
c)compiles without warning and gives some output
d)compiles and run with no output
Answer:
b) ArrayList b = a; This assignment assigns a typesafe arraylist in to a non-typesafe arraylist, So this assignment causes warning during compilation.
4. Source Code
List <? super Integer> al = new ArrayList<Number>(); //line 1
al.add(12); //line 2
al.add(12+ 13); //line 3
for (Number no:al) //line 4
{
System.out.println(no);
}
What will be the possible result of the above program?
a) Error at Line 1
b) Error at Line 2
c) Error at Line 3
d) Error at Line 4
e) Compile and execute Sucuessfully
Answer d)
a)-->(<? super Integer)Lower Bound is perfectly accepatable.
b)-->Since 12 is Number.AutoBoxing works Automatically.It is accepatable.
c)-->al.add(12+ 13)Before add method is going to work, addition of number takes place
and 25 is added into al.
d)Error.Because in the declaration we have specified any super type of Integer,But in for each
loop we are specifying Number,We cannot restrict whenever we are using lowerbound.So accepatble
thing in line 4 is for (Object no:al).
e)It wont compile because of error at line 4.
5. List <Integer> ls = new ArrayList<Integer>(); //line 1
ls.add(12); //line 2
ls.add((int)12.0f); //line 3
ls.add((Integer)12*12); //line 4
ls.add((Integer)(12.0f)); //line 5
for (Integer ll:ls)
{
System.out.println(ll);
}
What will be the possible result of the above program?
a)Error at line 3
b)Error at line 4
c)Error at line 5
d)Run Time error
e)Executes Sucuessfully
Answer c)
a)-->float can be type cast into int and added into list.so no problem.
b)-->12*12 will produce 144 and added into list with (r) without using (Integer)Object conversion.
c)-->Result in Error because float value can be convert to int value but not to Integer Object.
To make it work convert into int value and then to Integer Object.Like this (Integer)(int)(12.0f).
d)-->Results in Compile time error.So cannot go for execution.
e)-->Because of line 5 cannot compile and execute.
6. Find errors if any, in the following lines of code
List<Integer> ls1 = new LinkedList(); //line 1
List<String> ls2 = new LinkedList(); //line 2
List ls3 = new LinkedList(); //line 3
List ls4 = ls1; //line 4
List ls5 = ls2; //line 5
List ls6 = ls5 = ls4; //line 6
a) Error at Line 1 and Line 2
b) Error at Line 4 and Line 5
c) Error at line 6
d) Run time Error
e) No Error
Answer is e)
a)-->we can very well assign legacy type to Generic Type.
b)-->we can very well assign Generic type to Legacy Type.
c)-->ls6,ls5,ls4 are of legacy type, so no problem in assigning.
d)-->No runtime Error in the above specified lines.
e)-->Executes Sucuessfully, possibly no output.
http://www.javabeat.net/javabeat/scjp5/mocks/Generics-part3-10questions.php
Author : Jagadeesh Jeeva
1) what is the result compiling and running the following piece of code?
import java.util.*;
class Test {
public static void main(String [] args) {
Set vals = new TreeSet<String>();
vals.add("one");
vals.add(1);
vals.add("two");
System.out.println(vals);
}
}
Options :
a) Does not Compile
b) Compiles with warning and prints output [one, 1, two]
c) Compiles without warning and prints output [one, 1, two]
d) Compiles with warning and throws exception at runtime
e) Compiles without warning and throws exception at runtime
Answer :
D are correct Answers.
Compiles with warning due to un-safe assignment List vals = new ArrayList<String>();
Since TreeSet<String> is used, it will try to sort by natural order. Due to the presence of Integer (vals.add(1);) in the collection, it will throw ClassCastException at runtime(While try to cast Integer in to String).
2. which of the following piece of code can be inserted to make the following code to compile?
import java.util.*;
class PickThePiece {
public static void main(String [] args) {
//insert the first line here
datas.add("delhi");
datas.add(new Object());
//insert the second line here
}
}
Options :
a) List<Object> datas = new LinkedList<Object>();
String data = datas.get(0);
b) List<Object> datas = new LinkedList<Object>();
String data = (String)datas.get(0);
c) List<String> datas = new LinkedList<String>();
String data = (String)datas.get(0);
d) List<String> datas = new LinkedList<String>();
String data = datas.get(0);
e) all the above
Answer :
B is the correct answer.
A is wrong because datas.get(0) will return a Object which cannot be directly assigned to a String without casting. C and D are wrong because Object cannot be added to a List of String.
3. What is the result of compiling and running the following code?
import java.util.*;
class SampleTest {
public static void main(String [] args) {
List samples = new ArrayList();
samples.add("100");
samples.add(200);
samples.add("300");
printData(samples);
}
static void printData(List<String> samples) {
for(String sample : samples) {
System.out.print(sample + " ");
}
}
}
Options :
a) Prints 100 200 300
b) Compile time error
c) Compiles without warning
d) Compiles with warning
e) Runtime Exception
Answer :
D, E are correct answers.
It produces warning since un-safe List samples is passed to a type safe collections(as a method argument).
Since samples.add(200), adds a Integer in to collection. While iterating through enhanced for loop, Integer is tried to cast to String causes ClassCastException.
4. Consider the following code, select the valid options given below.
class Fruit {}
class Apple extends Fruit {}
class Orange extends Fruit {}
Options :
a) List<? extends Fruit> stmt = new ArrayList<Fruit>();
b) List<? super Apple> stmt = new ArrayList<Fruit>();
c) List<? extends Fruit> stmt = new ArrayList<Apple>();
d) List<? super Orange> stmt = new ArrayList<Orange>();
e) All the above
f) None of these
Answer :
E is the correct answer. All these options are valid.
Keyword "super " – allows the type followed by keyword and its super type(parent ).
Keyword "extends" – allows the type followed by keyword and its sub type(child).
5) What is the output of the following code?
import java.util.*;
class Color {}
class Blue extends Color {}
class Red extends Color {}
class TestColor {
public static void main(String [] args) {
1) List<Color> colors = new ArrayList<Color>();
2) colors.add(new Color());
3) colors.add(new Blue());
4) colors.add(new Red());
5) alterColor(colors);
6) System.out.println(colors);
}
static void alterColor(List clrs) {
7) clrs.add(new Object());
}
}
Options :
a) Compile time error due to lines 3 and 4.
b) Compile time error due to line 5.
c) Compile time error due to line 7.
d) Compiles with warning and produces some output.
e) Compiles without warning and produces some output.
f) Compiles fine and Exception is thrown at runtime.
Answers :
D is the correct answer.
Warning is due to non-type safe method call. Within the alterColor() method adding a new Object is not a issue because the collection becomes non-type safe.
6) what is the result of the following code ?
import java.util.*;
class Bird {}
class Duck extends Bird {}
class Hen extends Bird {}
class FuzzyTest {
public static void main(String [] args) {
Map<String, Bird> birds = new HashMap<String, Bird>();
birds.put("bird", new Bird());
birds.put("hen", new Hen());
birds.put("duck", new Duck());
Map bs = addBirds(birds);
for(String b : bs.keySet())
System.out.print(b + " ");
}
static Map addBirds(Map brds) {
brds.put("bird", new Object());
return brds;
}
}
Options :
a) Compiles and prints output "bird hen duck".
b) Compiles and prints output "bird duck hen".
c) Compiles and prints some output order cannot be determined.
d) Run time Exception.
e) Compilation fails.
Answer :
E is the correct answer.
Since bs is non-typesafe collection, bs.keySet() returns Object. But in enhanced for loop string is used to catch the returned values, that leads to compilation error.
7) what are the valid statements can be filled in the blank, to make the code to compile and run?
import java.util.*;
interface Eat{}
class Animal implements Eat{}
class Dog extends Animal {}
class Cat extends Animal {}
class AnimalTest {
public static void main(String[] args) {
List<Animal> a = new ArrayList<Animal>();
List<Dog> d = new ArrayList<Dog>();
List<Cat> c = new ArrayList<Cat>();
checkAnimal(a);
checkAnimal(d);
checkAnimal(c);
}
static void checkAnimal( ________________ pets) {
System.out.print("animals checked here");
}
}
Options :
a) List<? extends Animal>
b) List<? super Animal>
c) List<? extends Eat>
d) List<? super Eat>
e) List<?>
f) All of the above
Answer :
A , C and E are the correct answers.
Keyword "super " – allows the type followed by keyword and its super type(parent ).
Keyword "extends" – allows the type followed by keyword and its sub type(child).
Wild card ? – allows everything.
8) what is the output of the following code?
import java.util.*;
class Example {
public static void main(String [] args) {
Set<String> values = new TreeSet<String>();
values.add("yet");
values.add("get");
values.add("bet");
displayValues(values);
}
static void displayValues(Set<?> values) {
values.add("wet");
for(Object v : values)
System.out.print(v + " ");
}
}
Options :
a) Compiles and gives output "yet get bet wet".
b) Compiles and gives output "bet get wet yet".
c) Compilation fails
d) Compiles with warning and Exception thrown at runtime.
e) Compiles without warning and Exception thrown at runtime.
Answer :
C is the correct answer.
When we use wildcard(?) to catch the collection , then modifications are not allowed in that collection. Here values.add("wet") will throw error at compilation time.
9) Choose the valid ways to create an object for the following class.
class GenTest<T super Number> {
T num;
public T checkNumber(T n) {
return n;
}
}
Options :
a) Compilation fails.
b) GenTest<Number> gt = new GenTest<Number>();
c) GenTest<Integer> gt = new GenTest<Integer>();
d) GenTest<Object> gt = new GenTest<Object>();
e) None of the above.
Answer :
A is the correct answer.
Since <T super Number> is an invalid syntax. If super keyword is replaced by extends, then B and C will be the valid answers.
10) Choose the valid constructors for the following class.
class Generics<T>{}
Options :
a) public Generics(){}
b) public Generics<T>(){}
c) public <T> Generics(T t){}
d) public <T> Generics(){}
e) All the above.
Answer :
A,C and D are correct answers.
B is incorrect because of improper syntax.
|