SCJP5 Ver1 (1) .0
SCJP5 Ver1 (1) .0
Code Options
Gen<T>
Gen<?>
Gen
?
T
Ratna Prasad
Page 1 of 36
Ver 1.0
SCJP 5.0
private T object;
public Gen(T object){
this.object = object;
}
public T getObject() {
return object;
}
}
public static void main(String[] args) {
Gen<String> str = new Gen<String>(answer);
Gen<Integer> intg = new Gen<Integer>(42);
System.out.println(str.getObject() + = + intg.getObject());
}
}
2) Given:
public void takeList(List<? extends String> list) {
// insert code here
}
Place the compilation results on each code statement to indicate whether or not
that code will compile if inserted into the takeList() method.
Code Statements
Compilation Result
List.add(Foo);
List = new ArrayList<String>();
List = new ArrayL:ist<Object>();
String s = list.get(0);
Object o = list
Ratna Prasad
Page 2 of 36
Compilation Fails
Compilation Succeeds
Compilation Fails
Compilation Succeeds
Compilation Succeeds
Ver 1.0
SCJP 5.0
3) Place the correct description of the compiler output on the code fragments to be
inserted at liens 4 and 5. The same compiler output may be used more than once.
import java.util.*;
public class X {
public static void main(String[] args){
// insert code here
// insert code here
}
public static void foo(List<Object> list) {}
}
Code
a) ArrayList<String> x1 = new ArrayList<String>();
foo(x1);
b) ArrayList<Object> x2 = new ArrayList<String>();
foo(x2);
c) ArrayList<Object> x3 = new ArrayList<Object>();
foo(x3);
d) ArrayList x4 = new ArrayList ();
foo(x4);
Compiler Output
1) Compilation succeeds
2) Compilation fails due to an error in the first statement
3) Compilation of the first statement succeeds, but compilation fails due to error
in the second statement.
Solution:a=3
b=2
c=1
d=1
Ratna Prasad
Page 3 of 36
Ver 1.0
SCJP 5.0
4) Place the output option in the actual output sequence to indicate the output
from this code.
class Alpha {
public void foo(String args)
{ System.out.println(Alpha:foo);}
public void bar(String a)
{ System.out.println(Alpha:bar);}
}
public class Beta extends Alpha {
public void foo(String a)
{ System.out.println(Beta:foo);}
public void bar(String a)
{ System.out.println(Beta:bar);}
public static void main(String[] argv){
Alpha a = new Beta();
Beta b = (Beta)a;
a.foo(test);
a.bar(test);
b.foo(test);
b.bar(test);
}
}
2)
3)
4)
Output options
Alpha:foo
Alpha:bar
Beta:foo
Beta:bar
Solution:-
Ratna Prasad
4) Beta:bar
Page 4 of 36
Ver 1.0
SCJP 5.0
Solution
EARTH, WIND,
FIRE { public string info() {return Hot;}
};
public string info() {return element;}
}
Ratna Prasad
Page 5 of 36
Ver 1.0
SCJP 5.0
6) Place the code elements in order so that the resulting java sources file will
compile correctly, resulting in a class called com.sun.cert.AddressBook.
Source file
1st
2nd
3rd
ArrayList entries;
}
Code Element
package com.sun,cert;
package com.sun,cert.*;
import java.util.*;
import java.*;
public class AddressBook {
public static class AddressBook{
Ratna Prasad
Page 6 of 36
Ver 1.0
SCJP 5.0
7) Place the code fragment in position to complete the displayable interface.
interface Reloadable {
public void reload();
}
interface diplayable place here place here {
place here
}
Code Fragments:
extends
implements
Reloadable
Edit
Solution:interface Reloadable {
public void reload();
}
interface diplayable extends Reloadable {
public void display();
}
8) Place the correct code in the code sample to achieve the expected results:
Expected Results:Output: 1 2 4 8 16 32
Code Sample:int [] y = { 1, 2, 4, 8, 16, 32};
System.out.print (Output: );
Place here
System.out.prinr (x);
System.out.print( );
}
Ratna Prasad
Page 7 of 36
Ver 1.0
SCJP 5.0
Code:1)
2)
3)
4)
5)
for(int x : y) {
for(int x = y[ ]){
foreach(y as x) {
foreach(int x : y) {
for (int x=1; x=y[ ]; x++){
Constructor
new FileReader(
new BufferedReader(
new PrintReader(
new FileWrite(
new BufferedReader(
new PrintWriter(
Ratna Prasad
Page 8 of 36
Ver 1.0
SCJP 5.0
Place the code fragments into position to use a BufferedReader to read in an entire
text file:
class PrintFile {
public static void main(String[] args){
BufferedReader buffReader = null;
//More code here to initialize buffReader
try{
String temp;
while ( place here
place here ) {
System.out.printin(temp);
}
} catch place here
e.printStackTrace();
}
}
}
Code Fragments
(temp = buffReader.readLine() )
(temp = buffReader.nextLine())
!= null
&& buffReader.hasNext()
(IOException e) {
(FileNotFoundException e){
Solution:class PrintFile {
public static void main(String[] args){
BufferedReader buffReader = null;
//More code here to initialize buffReader
try{
String temp;
while ((temp = buffReader.readLine() ) != null ) {
System.out.printin(temp);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Ratna Prasad
Page 9 of 36
Ver 1.0
SCJP 5.0
10) Given:
class A {
String name = A;
String getName() {
return name;
}
String greeting(){
return class A;
}
}
class B extends A {
String name = B;
String greeting(){
return class B;
}
}
public class Client {
public static void main(String[] args) {
A a = new A();
A b = new B();
System.out.println(a.greeting() + has name + a.getName());
System.out.println(b.greeting() + has name + b.getName());
}
}
Place the names A and B in the following output:
class place here
class place here
has name
has name
place here
place here
Names
A
Solution:class A
class B
Ratna Prasad
has name
has name
A
A
Page 10 of 36
Ver 1.0
SCJP 5.0
11) Car is Vehicle and Collectable class A implements B,C{}
Car Has Steering Wheel class A{B b;}
Car Has Wheels class A{List<B> b;}
Mini is A Car class A extends B{}
Car is an Object class A{}
12) Given:
System.out.printf(Pi is approximately %f and E is approximately %b, Math.PI,
Math.E );
Place the values where they would appear in the output.
Pi approximately place here
and E is approximately place here
Values
3
2
3.141593
2.718282
true
false
Math.PI
Math.E
13) The doesFileExist method takes an array of directory names representing a path
from the root filesystem and a file name. The method returns true if the file exists,
false if it does not.
Please the code fragments in position to complete this method.
public static boolean doesFileExist(String[] directories, String filename) {
Place here
for( String dir : directories) {
Place here
}
Please here
Please here
}
Ratna Prasad
Page 11 of 36
Ver 1.0
SCJP 5.0
Code Fragments
path =
path.getSubdirectory(dir);
String path = ;
return file.exists();
path = new File(path, dir);
return !file.isNew();
path =
path.getFile(filename);
return path.isFile();
File path = new
File(File.separator);
Solution: -
Ratna Prasad
Page 12 of 36
Ver 1.0
SCJP 5.0
14) Given:
import java.util.*;
class A{}
class B extends A {}
public class Test {
public static void main(String[] args){
List<A> listA = new LikedList<A>();
List<B> listB = new LikedList<B>();
List<Object> listO = new LinkedList<Object>();
// insert code here
}
public static void m1(List<? extends A> list) {}
public static void m2(List<A> list) {}
}
Place a result onto each method call to indicate what would happen if the method
call where inserted al line 9. Note: Results can be used more than once.
Method Calls
m1(listA)
m1(listB)
m1(listO)
m2(listA)
m2(listB)
m2(listO)
Results
Does not compile
Compiles and runs without error
An exception thrown at run time
Solution:m1(listA)
m1(listB)
m1(listO)
m2(listA)
m2(listB)
m2(listO)
Ratna Prasad
Page 13 of 36
Ver 1.0
SCJP 5.0
15) Given:
NumberNames nn = new NumberNames();
nn.put(one, 1);
System.out.println(nn.getNames());
Place the code into position to create a class that maps from Strings to integer
values. The result of execution must be [one]. Some options may be used more
than once.
public class NumberNames {
private HashMap< place here, place here> map =
new HashMap< place here, place here place here ;
public void put( String name, int value) {
map.put(place here, place here);
}
public place here getNames() {
return map.keySet();
}
}
Code
Set<int>
Set<Integer, String>
Set<String, int>
String
>
Value
Set<Integer>
Set<int, String>
Set<String>
Integer
>()
map
HashSet
Set<String, Integer>
NumberNames
int
name
Ratna Prasad
Page 14 of 36
Ver 1.0
SCJP 5.0
Solution:class Alpha {
public void bar( int x ) {}
public void bar( int x ) {}
}
public class Beta extends Alpha {
public void bar(int x) {}
public int bar(String x) {return 1;}
public void bar(int x, int y) {}
}
Ratna Prasad
Page 15 of 36
Ver 1.0
SCJP 5.0
17) Replace two of the modifiers that appear in the Single class to make the code
compile. Note: Three modifiers will not be used and four modifiers in the code
will remain unchanged.
Code
public class Single {
private static Single instance;
public static Single getInstance() {
if(instance == null) instance = create();
return instance;
}
private Single() {}
protected Single create() { return new Single();}
}
class SingleSub extends Single {
}
Modifiers
final
protected
private
abstract
static
Solution:public class Single {
private static Single instance;
public final Single getInstance() {
if(instance == null) instance = create();
return instance;
}
protected Single() {}
protected Single create() { return new Single();}
}
class SingleSub extends Single {
}
Ratna Prasad
Page 16 of 36
Ver 1.0
SCJP 5.0
18) Given:
Runnable r = new Runnable() {
public void run() {
try {
Thread.sleep(1000);
} catch(InterruptedException e){
System.out.println(Interrupted);
}
System.out.println(ran);
}
};
Thread t = new Thread(r);
t.start();
System.out.println(started);
t.sleep(2000);
System.out.println(interrupting);o
t.interrupt();
System.out.println(ended);
Assume that sleep(n) executes in exactly n milliseconds, and all other code executes in an
insignificant amount of time.
Place the fragments in the output area to show the result of running this code.
Output
Place here
Place here
Place here
Place here
Place here
Fragments
interrupted
ran
started
interrupting
ended
InterruptedException
(no more output)
Solution:
started
ran
interrupting
ended
(no more output)
Ratna Prasad
Page 17 of 36
Ver 1.0
SCJP 5.0
Solution:-
run()
wait()
notify()
sleep()
start()
join()
Ratna Prasad
java.lang.Thread
java.lang.Object
java.lang.Object
java.lang.Thread
java.lang.Thread
java.lang.Thread
Page 18 of 36
Ver 1.0
SCJP 5.0
20) Place the code fragments into position to produce the output:
true
true
false
Code
Scanner scanner = new Scanner( One, 5, true, 3, true, 6, 7, false );
scanner.useDelimiter( , );
while(
place here )
place here + );
scanner.hasNextBoolean()
scanner.next()
scanner.nextBoolean()
scanner.hasNext()
if( scanner.hasNextBoolean()) {
System.out.println( scanner.nextBoolean() + );
} else scanner.next() ;
}
Ratna Prasad
Page 19 of 36
Ver 1.0
SCJP 5.0
21) Place the code in the appropriate places such that this program will always
output[1,2].
import java.util.*;
public class MyInt Place here
Place here
Ratna Prasad
extends
public
compare(MyInt o,
MyInt i2)
compareTo(MyInt
o)
Sortable
i i2.i
compare(Object o,
Object i2)
protected
Page 20 of 36
Object
i
sort(Object o)
compareTo(Object
o)
Ver 1.0
SCJP 5.0
Solution:
import java.util.*;
public class MyInt implements Comparable{
public static void main(String[] args) {
ArrayList<MyInt> list = new ArrayList<MyInt>();
list.add(new MyInt(2));
list.add(new MyInt(1));
Collections.sort(list);
System.out.println(list);
}
private int i;
public MyInt(int i){ this.i = i ; }
public String toString() { return Integer.toString(i); }
public int compareTo(Object o){
MyInt i2 = (MyInt)o;
return i-i2.i;
}
}
Ratna Prasad
Page 21 of 36
Ver 1.0
SCJP 5.0
Statements
allows access to elements by their integer index
defines the method: V get(Object key)
is designed for holding elements prior to processing
contains no pair of elements e1 and e2, such that
e1.equals(e2)
Collection Types
java.util.Map
java.util.Set
java.util.List
java.util.Queue
Solution:
Ratna Prasad
java.util.List
java.util.Map
java.util.Queue
java.util.Set
Page 22 of 36
Ver 1.0
SCJP 5.0
23) Place the code into the GenericB class definition to make the class compile
successfully.
import java.util.*;
public class GenericB< Place > {
public Place foo;
public void setFoo( Place foo) {
this.foo = foo;
}
public Place getFoo() {
return foo;
}
public static void main(String [] args) {
Generic<B> bar = new Generic<B>();
bar. setFoo(new Cat());
Cat c = bar.getFoo();
}
}
interface Pet { }
class Cat implements Pet { }
Code
? extends Pet
T extends Pet
? implements Pet
T implements Pet
Pet extends T
Ratna Prasad
?
T
<?>
Pet
Page 23 of 36
Ver 1.0
SCJP 5.0
Solution:
import java.util.*;
public class GenericB< T extends Pet > {
public T foo;
public void setFoo( T foo) {
this.foo = foo;
}
public T getFoo() {
return foo;
}
public static void main(String [] args) {
Generic<B> bar = new Generic<B>();
bar. setFoo(new Cat());
Cat c = bar.getFoo();
}
}
interface Pet { }
class Cat implements Pet { }
Ratna Prasad
Page 24 of 36
Ver 1.0
SCJP 5.0
24) Place the fragments into position so the output is: The quantity is 420.
place here
}
public void callUpdate() {
int quant = 100;
Place here
System.out.println(The quantity is: + quant);
}
Code fragments
public int
public void
Solution:
Ratna Prasad
Page 25 of 36
Ver 1.0
SCJP 5.0
25) Place the code elements in position so that the flags2 class will compile and make
appropriate use of the wait/notify mechanism. Note: You may reuse code
elements.
public class Flags2 {
private boolean isReady = false;
public place here void produce() {
isReady = true;
place here;
}
public place here void consume() {
while(!isReady) {
try {
place here ;
} catch(Exception e) {}
}
isReady = place here;
}
}
Code Elements
synchronized
Volatile
true
synchronized()
false
notifyAll()
wait()
synchronize
Solution:
public class Flags2 {
private boolean isReady = false;
public synchronized void produce() {
isReady = true;
notifyAll();
}
public synchronized void consume() {
while(!isReady) {
try {
wait();
} catch(Exception e) {}
}
isReady = false;
}
}
Ratna Prasad
Page 26 of 36
Ver 1.0
SCJP 5.0
26) Place the code elements into the class so that the code compiles and prints Run.
Run. doIt. In exactly that order. Note that there may be more than one correct
solution.
public class TesTwo extends Thread {
public static void main(String[] a) throws Exception {
TesTwo t = new TesTwo();
t.start();
place here
place here
place here
}
public void run() {
System.out.print(Run. );
}
public void doIt() {
System.out.print(doIt. )
}
}
Code Elements
t.start();
t.run();
t.join();
t.doIt();
t.pause(10);
doIt();
run();
Solution:
public class TesTwo extends Thread {
public static void main(String[] a) throws Exception {
TesTwo t = new TesTwo();
t.start();
t.join();
t.run();
t.doIt();
}
public void run() {
System.out.print(Run. );
}
public void doIt() {
System.out.print(doIt. )
}
}
Ratna Prasad
Page 27 of 36
Ver 1.0
SCJP 5.0
Ratna Prasad
Page 28 of 36
Compilation Succeeds
Compilation Fails
Compilation Succeeds
Compilation Succeeds
Compilation Fails
Ver 1.0
SCJP 5.0
28) Given:
import java.util.*;
public class TestGenericConversion {
public static void main(String[] args) {
List list = new LinkedList();
list.add(one);
list.add(two);
System.out.print(((String)list.get(0)).length());
}
}
Refractor this class to use generics without changing the codes behavior.
import java.util.*;
public class TestGenericConversion {
public static void main(String[] args) {
Place here
list.add(one);
list.add(two);
Place here
}
}
Code
List list = new LinkedList();
List<String> list = new
LinkedList<String>();
List<String> list = new
LinkedList();
List list = new
LinkedList<String>();
Ratna Prasad
System.out.print(list.get(0).length());
System.out.print(list.get<String>(0).length());
System.out.print(<String>list.get(0).length());
System.out.print((list<String>)list.get(0)).length());
Page 29 of 36
Ver 1.0
SCJP 5.0
Solution:
import java.util.*;
public class TestGenericConversion {
public static void main(String[] args) {
List<String> list = new LinkedList<String>();
list.add(one);
list.add(two);
System.out.print(list.get(0).length());
}
}
29) Place the fragments into the program, so that the program will get lines from a
text file, display them, and then close all the resources.
Program
import java.io.*;
public class ReadFile {
public static void main(String[] args){
try{
File ? = new File(MyText.txt);
Place here ? = new Place here (x1);
Place here x4 = new Place here (x2);
String x3 = null;
while(( x3 = ? . place here()) != null) {
System.out.println(x3);
}?.place here();
} catch(Exception ex) {ex.printStackTrce();}
}
}
Code Fragments
BufferedReader
readLn
x1
Ratna Prasad
SreamReader
read
x2
FileReader
closeFile
x3
Page 30 of 36
readLine
close
x4
Ver 1.0
SCJP 5.0
Solution:
import java.io.*;
public class ReadFile {
public static void main(String[] args){
try{
File x1 = new File(MyText.txt);
FileReader x2 = new FileReader(x1);
BufferedReader x4 = new BufferedReader (x2);
String x3 = null;
while(( x3 = x4.readLine()) != null) {
System.out.println(x3);
}x4.close();
} catch(Exception ex) {ex.printStackTrce();}
}
}
Ratna Prasad
Page 31 of 36
Ver 1.0
SCJP 5.0
30) Insert six modifiers into the code such that it meets all of these requirements:
1) It must be possible to create instances of Alpha and Beta from outside the
packages in which they are defined.
2) When an object of type Alpha (or any potential subclass of Alpha) has been
created, the instance variable alpha may never be changed.
3) The value of the instance variable alpha must always be A for objects of type
Alpha.
Code:
package alpha;
place here class Alpha {
Place here String alpha;
Place here Alpha() { this(A);}
Place here Alpha(String a) { alpha = a;}
}
package beta;
place here class Beta extends alpha.Alpha {
place here Beta(String a) { super(a); }
}
Modifiers
private
Ratna Prasad
protected
public
Page 32 of 36
Ver 1.0
SCJP 5.0
Solution:
package alpha;
public class Alpha {
private String alpha;
public Alpha() { this(A);}
protected Alpha(String a) { alpha = a;}
}
package beta;
public class Beta extends alpha.Alpha {
public Beta(String a) { super(a); }
}
31) Place the Types in one of the Type columns, and the Relationship in the
Relationship column, to define appropriate has-a and is a relationship.
Type
Relationship
Place here
Place here
Type
Animal
Forest
Place here
Place here
Rectangle
Place here
Place here
Place here
Place here
Programming Book
Relationships
is a
has a
Types
Dog
Side
Tail
Square
Tree
Book
Java Book
Pen
Solution:
Ratna Prasad
Page 33 of 36
Ver 1.0
SCJP 5.0
Type
Dog
Relationship
is-a
Forest
has-a
Rectangle
has-a
Java Book
is-a
Ratna Prasad
Type
Animal
Tree
Side
Programming Books
Page 34 of 36
Ver 1.0
SCJP 5.0
32) Given:
public class Doubler {
public static int doubleMe(Holder h) {
return h.getAmount() * 2;
}
}
And:
public class Holder {
int amount = 10;
public void doubleAmount() { amount = Doubler.doubleMe(this);}
public int getAmount() {return amount;}
//more code here
}
Place the code fragments in position to reduce the coupling between Doubler and
Holder.
public class Doubler {
public static int doubleMe( Place here h) {
return Place here * 2;
}
}
public class Holder {
int amount = 10;
public void doubleAmount() { amount = Doubler.doubleMe( Place here );}
public int getAmount() {return amount;}
//more code here
}
Code Fragments
void
h.getAmount()
Ratna Prasad
Holder
H
int
this
Page 35 of 36
doubler
amount
Ver 1.0
SCJP 5.0
Solution:
public static int doubleMe(int h){
return h*2
}
method call should be amount=Doubler.doubleMe(amount);
33) Place each Collection Type on its function. Note: Not all functions will be used.
Function
provides array manipulation utility
provides Collection manipulation utility
defines base methods for all array objects
defines base methods for all Collection
objects
provides a concrete implementation of an
ordered set
defines base methods for an ordered set
defines methods for linear access to a
collection
defines methods for random access to a
collection
Collection Type
Java.util.SortedSet
Java.util.Arrays
Java.util.Iterator
Java.util.TreeSet
Java.util.Collection
Solution:
SortedSet : defines base methods for ordered Set
Arrays : provides Array manipulation utilities
Iterator : defines methods for Linear access to a collection
TreeSet : provides a concrete implementation of an ordered set
Collection : defines Base Methods for all collection Objects
Ratna Prasad
Page 36 of 36
Ver 1.0