SCJP Certification Questions
SCJP Certification Questions
Test # 1
1.Which declaration of the main method below would allow a class to be started as a standalone
program. Select all correct answers.
A.public static int main(char args[]);
B.public static void main(String args[]);
C.public static void MAIN(String args[]);
D.public static void main(String args);
E.public static void main(char args[]);
2.What all gets printed when the following code is compiled and run? Select all correct answers.
A.i=0 j=0
B.i=0 j=1
C.i=0 j=2
D.i=1 j=0
E.i=1 j=1
F.i=1 j=2
G.i=2 j=0
H.i=2 j=1
I.i=2 j=2
3.What gets printed when the following code is compiled and run with the following command -
java test 2
Select the one correct answer.
if(args.length > 1)
System.out.println(i);
if(args.length > 0)
System.out.println(i - 1);
else
System.out.println(i - 2);
}
}
A.test
B.test -1
C.0
D.1
E.2
4.In Java what expression can be used to represent number of elements in an array named arr ?
array.length
5.How would the number 5 be represented in hex using up-to four characters.
6.Which of the following is a Java keyword. Select all correct answers.
A.extern
B.synchronized
C.volatile
D.friend
E.friendly
F.transient
G.this
H.then
7.Is the following statement true or false. The constructor of a class must not have a return type.
A.true
B.false
8.What is the number of bytes used by Java primitive long. Select the one correct answer.
A.The number of bytes is compiler dependent.
B.2
C.4
D.8
E.64
9.What is the result of invoking the method substring(2, 4) on the string "example"? Include the
answer in quotes as the result is of type String. “ampl”
10.Which of the following is correct ? Select all correct answers.
A.The native keyword indicates that the method is implemented in another language like
C/C++.
B.The only statements that can appear before an import statement in a Java file are comments.
C.The method definitions inside interfaces are public and abstract. They cannot be private or
protected.
D.A class constructor may have public or protected keyword before them, nothing else.
11.What is the result of evaluating the expression 14 ^ 23. Select the one correct answer.
A.25
B.37
C.6
D.31
E.17
F.9
G.24
12.Which of the following are true. Select all correct answers.
A.&& operator is used for short-circuited logical AND.
B.~ operator is the bit-wise XOR operator.
C.| operator is used to perform bitwise OR and also short-circuited logical OR.
D.The unsigned right shift operator in Java is >>.
13.Name the access modifier which when used with a method, makes it available to all the classes in
the same package and to all the subclasses of the class. Protected/public
14.Which of the following is true. Select all correct answers.
A.A class that is abstract may not be instantiated.
B.The final keyword indicates that the body of a method is to be found elsewhere. The code is
written in non-Java language, typically in C/C++.
C.A static variable indicates there is only one copy of that variable.
D.A method defined as private indicates that it is accessible to all other classes in the same
package.
15.What all gets printed when the following program is compiled and run. Select all correct answers.
A.0
B.1
C.2
D.3
16.What all gets printed when the following program is compiled and run. Select all correct answers.
A.0
B.1
C.2
D.The program does not compile because of statement "i=++i;"
17.What all gets printed when the following gets compiled and run. Select all correct answers.
A.0
B.1
C.2
D.3
E.4
18.What all gets printed when the following gets compiled and run. Select all correct answer.
A.0
B.1
C.2
D.3
E.4
19.What all gets printed when the following gets compiled and run. Select all correct answer.
A.1
B.2
C.3
D.4
20.What all gets printed when the following gets compiled and run. Select all correct answer.
if(s1 == s2)
System.out.println(1);
else
System.out.println(2);
if(s1.equals(s2))
System.out.println(3);
else
System.out.println(4);
}
}
A.1
B.2
C.3
D.4
21.The default layout manager for a Frame is ...
A.FlowLayout
B.BorderLayout
C.GridLayout
D.GridBagLayout
E.CardLayout
22.Which of the following are valid adapter classes in Java. Select all correct answers.
A.ComponentAdapter
B.ActionAdapter
C.AdjustmentAdapter
D.ItemAdapter
E.FocusAdapter
23.Which of the following are legal array declarations. Select all correct answers.
A.int i[5][];
B.int i[][];
C.int []i[];
D.int i[5][5];
E.int[][] a;
24.What is the range of values that can be specified for an int. Select the one correct answer.
A.The range of values is compiler dependent.
B.-231 to 231 - 1
C.-231-1 to 231
D.-215 to 215 - 1
E.-215-1 to 215
25.How can you ensure that the memory allocated by an object is freed. Select the one correct answer.
A.By invoking the free method on the object.
B.By calling system.gc() method.
C.By setting all references to the object to new values (say null).
D.Garbage collection cannot be forced. The programmer cannot force the compiler to free the
memory used by an object.
26.What gets printed when the following code is compiled. Select the one correct answer.
A.0
B.1
C.2
D.-1
27.Which of these is a legal definition of a method named m assuming it throws IOException, and
returns void. Also assume that the method does not take any arguments. Select all correct answers.
A.void m() throws IOException{}
B.void m() throw IOException{}
C.void m(void) throws IOException{}
D.m() throws IOException{}
E.void m() {} throws IOException
28.Which of the following are legal identifier names in Java. Select all correct answers.
A.%abcd
B.$abcd
C.1abcd
D.package
E._a_long_name
29.At what stage in the following method does the object initially referenced by s becomes available
for garbage collection. Select the one correct answer.
System.out.println(i);
}
}
A.4
B.5
C.6
D.6.1
E.9
47.Is the following statement true or false. As the toString method is defined in the Object class,
System.out.println can be used to print any object.
A.true
B.false
48.Which of these classes defined in java.io and used for file-handling are abstract. Select all correct
answers.
A.InputStream
B.PrintStream
C.Reader
D.FileInputStream
E.FileWriter
49.Which of these are valid Event Listener interfaces. Select all correct answer.
A.MouseMotionListener
B.WindowListener
C.DialogListener
D.PaintListener
50.Name the collection interface used to represent collections that maintain unique elements. vector
51.What is the result of compiling and running the following program.
str1.concat(str2);
System.out.println(str1);
}
}
A.abc
B.def
C.abcabc
D.abcdef
E.defabc
F.abcdefdef
52.Select the one correct answer. The number of characters in an object of a class String is given by
A.The member variable called size
B.The member variable called length
C.The method size() returns the number of characters.
D.The method length() returns the number of characters.
53.Select the one correct answer. Which method defined in Integer class can be used to convert an
Integer object to primitive int type.
A.valueOf
B.intValue
C.getInt
D.getInteger
54.Name the return type of method hashCode() defined in Object class, which is used to get the unique
hash value of an Object.
55.Which of the following are correct. Select all correct answers.
A.An import statement, if defined, must always be the first non-comment statement of the
file.
B.private members are accessible to all classes in the same package.
C.An abstract class can be declared as final.
D.Local variables cannot be declared as static.
56.Name the keyword which makes a variable belong to a class, rather than being defined for each
instance of the class. Select the one correct answer.
A.static
B.final
C.abstract
D.native
E.volatile
F.transient
57.Which of these are core interfaces in the collection framework. Select all correct answers.
A.Tree
B.Stack
C.Queue
D.Array
E.LinkedList
F.Map
58.Which abstract class is the super class of all menu-related classes.
59.Which of these statements are true. Select all correct answers.
A.For each try block there must be at least one catch block defined.
B.A try block may be followed by any number of finally blocks.
C.A try block must be followed by at least one finally or catch block.
D.If both catch and finally blocks are defined, catch block must precede the finally block.
Answers
1.b
2.b, c, f
3.d
4.arr.length
5.Any of these is correct - 0x5, 0x05, 0X05, 0X5
6.b, c, f, g
7.a
8.d
9."am"
10.a, c. b is not correct. A package statement may appear before an import statement.
11.a
12.a
13.protected
14.a, c
15.b, c
16.c
17.a, d, e
18.d, e
19.a, c
20.b, c
21.b
22.a, e
23.b, c, e
24.b
25.d
26.a
27.a
28.b, e
29.d
30.c
31.c, d
32.a, c
33.b, d
34.Object getSource();
35.a, b, e, f
36.Menu
37.b, c
38.d
39.c
40.c
41.c
42.a
43.b, c
44.f
45.long
46.e
47.a
48.a, c
49.a, b
50.Set
51.a
52.d
53.b
54.int
55.d
56.a
57.f
58.MenuComponent
59.c, d
Test # 2
1. Select all correct declarations, or declaration and initializations of an array?
A) String str[];
B) String str[5] = new String[5];
C) String str[]=new String [] {"string1", "string 2", "string3", "string4", "string5"};
D) String str[]= {"string1","string2", "string3", "string4", "string5"};
5. Given the piece of code, select the correct to replace at the comment line?
class A {
A(int i) { }
}
public class B extends A {
B() {
// xxxxx
}
public static void main(String args[]) {
B b = new B();
}
}
A) super(100);
B) this(100);
C) super();
D) this();
8. How can you change the break statement below so that it breaks out of the inner and middle loops
and continues with the next iteration of the outer loop?
outer: for ( int x =0; x < 3; x++ ) {
middle: for ( int y=0; y < 3; y++ ) {
if ( y == 1) {
break;
}
}
}
A) break inner:
B) break middle:
C) break outer:
D) continue
E) continue middle
10. What is the result when you compile the and run the following code?
public class ThrowsDemo {
static void throwMethod() {
System.out.println("Inside throwMethod.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwMethod();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
A) Compilation error
B) Runtime error
C) Compile successfully, nothing is printed.
D) inside demoMethod. followed by caught: java.lang.IllegalAccessExcption: demo
12. From the following code how many objects are garbage collected?
String string1 = "Test";
String string2 = "Today";
string1 = null;
string1 = string2;
A) 1
B) 2
C) 3
D) 0
14. Select the correct form for anonymous inner class declaration ?
A) new Outer.new Inner
B) new Inner() {
C) new Inner()
D) Outer.new Inner()
18. What is the result of compiling the following code? When you run like given below?
java Test Hello How Are You
public class Test {
public static void main ( String[] args) {
for ( int i = 0; i < args.length; i++)
System.out.print(args[i]);
}
}
A) Compile and runs with no output
B) Compiles and runs printing out "HelloHowAreYou"
C) Does not compile
D) Compiles but generates run time error
22. What is the numeric range for a Java int data type?
A) 0 to (2^32)
B) -(2^31) to (2^31)
C) -(2^31) to (2^31 - 1)
D) -(2^15) to (2^15 - 1)
26. Which of the following are correct, if you compile the following code?
public class CloseWindow extends Frame implements WindowListener {
public CloseWindow() {
addWindowListener(this); // This is listener registration
setSize(300, 300);
setVisible(true);
}
public void windowClosing(WindowEvent e) {
System.exit(0);
}
public static void main(String args[]) {
CloseWindow CW = new CloseWindow();
}
}
A) Compile time error
B) Run time error
C) Code compiles but Frames does not listen to WindowEvents
D) Compile and runs successfully.
28. Given the byte with a value of 01110111, which of the following statements will produce 00111011?
A) 0x77 << 1;
B) 0x77 >>> 1;
C) 0x77 >> 1;
D) None of the above
29. Which of the following will compile without error?
A) char c = 'a';
B) double d = 45.6;
C) int i = d;
D) int k = 8;
30. Which of the following returns true when replace with XXXXXXXXX?
public class TestType {
public static void main(String args[] ) {
Button b = new Button("BUTTON");
if( XXXXXXXXX) {
System.out.print("This is an instance of Button");
}
}
}
A) b instanceof Button
B) Button instanceof b
C) b == Button
D) Button == (Object) b
32. What will happen when you attempt to compile and run the following code?
public class MyClass {
public static void main(String args[]) {
String s1 = new String("Test One");
String s2 = new String("Test One");
if ( s1== s2 ) {
System.out.println("Both are equal");
}
Boolean b = new Boolean(true);
Boolean b1 = new Boolean(false);
if ( b.equals(b1) ) {
System.out.println("These wrappers are equal");
}
}
}
A) Compile time error
B) Runtime error.
C) No output
D) "These wrappers are equal"
33. What is the result when you try to compile the following code?
public class TestBit {
public static void main(String args[]) {
String s = "HelloWorld";
if ((s != null) && (s.length() > 6))
System.out.println("The value of s is " + s );
}
}
A) Compile time error
B) Runtime error
C) No output is printed
D) "The value of s is HelloWorld" is printed on the screen
34. Given the following declaration which of the following statements equals to true
boolean b1 = true;
boolean b2 = false;
A) b1 == b2;
B) b1 || b2;
C) b1 |& b2;
D) b1 && b2;
37. Given the following class definition, which of the following methods could be legally placed after
the comment ?
public class Test{
public void amethod(int i, String s){}
//Here
}
A) public void amethod(String s, int i){}
B) public int amethod(int i, String s){}
C) public void amethod(int i, String mystring){}
D) public void Amethod(int i, String s) {}
38. Given the following class definition which of the following can be legally placed after the
comment line?
class Base{
public Base(int i){}
}
public class Derived extends Base{
public static void main(String arg[]){
Derived d = new Derived(10);
}
Derived(int i){
super(i);
}
Derived(String s, int i){
this(i);
//Here
}
}
A) Derived d = new Derived();
B) super();
C) this("Hello",10);
D) Base b = new Base(10);
46. Which of the following statements are true about the fragment below?
import java.lang.Math;
public class Test {
public static void main(String args[]) {
Math m = new Math();
System.out.println(m.abs(2.6);
}
}
A) Compiler fails at line 1
B) Compiler fails at line 2
C) Compiler fails at the time of Math class instantiation
D) Compiler succeeds.
49. Which of the following implement clear notion of one item follows
another (order)?
A) List
B) Set
C) Map
D) Iterator
53. If you run the following code on a PC from the directory c:\source:
import java.io.*;
class Path {
public static void main(String[] args) throws Exception {
File file = new File("Ran.test");
System.out.println(file.getAbsolutePath());
}
}
What do you expect the output to be? Select the one right answer.
A) Ran.test
B) source\Ran.test
C) c:\source\Ran.test
D) c:\source
E) null
55. You have an 8-bit file using the character set defined by ISO 8859-8. You
are writing an application to display this file in a TextArea. The local
encoding is already set to 8859-8. How can you write a chunk of code to
read the first line from this file?
You have three variables accessible to you:
myfile is the name of the file you want to read
stream is an InputStream object associated with this file
s is a String object
Select all valid answers.
A)
InputStreamReader reader = new InputStreamReader(stream, "8859-8");
BufferedReader buffer = new BufferedReader(reader);
s = buffer.readLine();
B)
InputStreamReader reader = new InputStreamReader(stream);
BufferedReader buffer = new BufferedReader(reader);
s = buffer.readLine();
C)
InputStreamReader reader = new InputStreamReader(myfile, "8859-8");
BufferedReader buffer = new BufferedReader(reader);
s = buffer.readLine();
D)
InputStreamReader reader = new InputStreamReader(myfile);
BufferedReader buffer = new BufferedReader(reader);
s = buffer.readLine();
E)
FileReader reader = new FileReader(myfile);
BufferedReader buffer = new BufferedReader(reader);
s = buffer.readLine();
56. Which of the following used to read and write to network sockets, which
are super classes of Low level streams?
A) InputStream
B) StreamReaders
C) OutputStream
D) Writers
E) Readers
F) Streams
57. Low Level Streams read input as bytes and writes as bytes, then select
the correct declarations of Streams.
A) FileInputStream FIS = new FileInputStream("test.txt")
B) File file = new File("test.txt"); FileInputStream FIS = new FileInputStream(file)
C) File file = new File("c:\\"); File file1 = new File(file,"test.txt"); FileOutputStream
FOS = new FileOutputStream(file1);
D) FileInputStream FIS = new FileInputStream("c:\\","test.txt")
58. Choose all valid forms of the argument list for the FileOutputStream
constructor shown below:
A) FileOutputStream( FileDescriptor fd )
B) FileOutputStream( String n, boolean a )
C) FileOutputStream( boolean a )
D) FileOutputStream()
E) FileOutputStream( File f )
59. What is the class that has "mode" argument such as "r" or "rw" is
required in the constructor:
A) DataInputStream
B) InputStream
C) RandomAccessFile
D) File
Answers # 2
1. Answer
A) String str[];
C) String str[ ]=new string [ ] {"string1", "string 2", "string3", "string4", "string5"};
D) String str[ ]= {"string1","string2", "string3", "string4", "string5"};
2. Answer
A) final
D) static
3. Answer
B) Method declarations.
C) Block of code declarations
4. Answer
A) "Class A Constructor" followed by "Class B Constructor"
5. Answer
A) super(100);
6. Answer
A) Overridden methods have the same method name and signature
D) Overloaded methods have the same method name and different signature
7. Answer
C) The values 100,100,100 printed
8. Answer
B) break middle;
9. Answer
A) Compile time error
D) MyMethod() cannot throw an exception in MyExp2 class
10. Answer
A) Compilation error
11. Answer
A) The garbage collector runs in low memory situations
C) When it runs it releases the memory allocated by an object.
12. Answer
A) 1
13. Answer
B) goto
E) import, package
NOTE: The keywords 'const' and 'goto' are reserved by Java, even though they are not currently used in
Java. For more information at http://java.sun.com/docs/books/jls/html/3.doc.html#229308
14. Answer
B) new Inner() {
15. Answer
A) An anonymous class cannot have any constructors
D) An anonymous class instantiated and declared in the same place.
16. Answer
B) abstract class A { abstract void Method() ; }
17. Answer
C) Does not compile
18. Answer
B) Compiles and runs printing out "HelloHowAreYou"
19. Answer
A) goto
B) synchronized
C) extends
D) implements
E) this
20. Answer
C) Exception is thrown
21. Answer
A) long l = 698.65;
B) float f = 55.8;
22. Answer
C) -(2^31) to (2^31 - 1)
23. Answer
0X7, 0x7, 0x07, 0X07
24.Answer
0 to 2^16-1
25. Answer
A) int getID()
26. Answer
A) Compile time error
27. Answer
B) Java 1.0 and Java 1.1 event handling models are not compatible
C) Event listeners are the objects that implements listener interfaces.
D) You can add multiple listeners to any event source, then there is no guarantee that the listeners will be
notified in the order in which they were added.
28. Answer
B) 0x77 >>> 1;
C) 0x77 >> 1;
29. Answer
A) char c = 'a';
B) double d = 45.6;
D) int k = 8;
30. Answer
A) b instanceof Button
31. Answer
C) A equals A modulus 5.
32. Answer
C) No output
33. Answer
D) "The value of s is HelloWorld" is printed on the screen
34. Answer
B) b1 || b2;
Explanation:
A) This returns false. == is used as comparison operator.
B) This returns true. Because of OR operation.
C) There is no operator like that.
D) This returns false. This is because of AND operation.
NOTE: The operators ||, && are called Short-Circuit operators. The operator || ( OR Operation ) returns
true if one operand is true without regard to the other operand. The operator && ( AND Operation ) returns
false if one operand is false, without regard to the other operand . In our example b1 is true and b2 is false.
35. Answer
A) "The x value is 20.
36. Answer
B) By making methods are public and variables as private
37. Answer
A) public void amethod(String s, int i){}
D) public void Amethod(int i, String s) {}
38. Answer
D) Base b = new Base(10);
Explanation:
A) This is wrong because there is no maching constructor defined in Derived class.
B) The super keyword suppose to be the first line in the constructor.
C) The this keyword suppose to be first line in hte constructor.
D) This is correct because there is matching constructor in Base class.
39. Answer
A) An anonymous class cannot have any constructors
D) An anonymous inner class can implement an interface
40. Answer
A) The compiler error
41. Answer
A) Threads start() method automatically calls run() method .
B) Thread dies after the run() returns
D) A stop() method kills the currently running Thread
42. Answer
A) Allow threads to be manipulated as group
C) May contain other ThreadGroups
43. Answer
A) Frame's default Layout Manager is Border
B) Applet's is Flow Layout
C) Panel's is Flow Layout
D) A Dialog is a pop up window and used as BorderLayout as default.
44. Answer
A) Weight x and weight y should be 0.0 and 1.0
B) If fill is both, anchor does not make sense.
C) While constructing GridBagLayout , you won't tell how many rows and columns
the underlying grid has.
45. Answer
A) gridwidth, gridheight, specifies how many columns and rows to span.
B) gridx, gridy has GridBagConstraints.RELATIVE which adds left to right and top to
bottom, still you can specify gridwidth and gridheight except for last component,
which you have to set GridBagConstraints.REMAINDER.
46. Answer
C) Compiler fails at the time of Math class instantiation
47. Answer
A) 145.0 followed by -145.0
48. Answer
A) int a = 10; float f = 10; if ( a = = f) { System.out.println("Equal");}
49.Answer
A) List
50. Answer
A) true
51. Answer
B) collection
52. Answer
C) List
53. Answer
C) c:\source\Ran.test
54. Answer
A) File f = new File("/","autoexec.bat");
B) DataInputStream d = new DataInputStream(System.in);
C) OutputStreamWriter o = new OutputStreamWriter(System.out);
55. Answer
A)
InputStreamReader reader = new InputStreamReader(stream, "8859-8");
BufferedReader buffer = new BufferedReader(reader);
s = buffer.readLine();
B)
InputStreamReader reader = new InputStreamReader(stream);
BufferedReader buffer = new BufferedReader(reader);
s = buffer.readLine();
E)
FileReader reader = new FileReader(myfile);
BufferedReader buffer = new BufferedReader(reader);
s = buffer.readLine();
56. Answer
A) InputStream
C) OutputStream
57. Answer
A) FileInputStream FIS = new FileInputStream("test.txt")
B) File file = new File("test.txt"); FileInputStream FIS = new FileInputStream(file)
C) File file = new File("c:\\"); File file1 = new File(file,"test.txt"); FileOutputStream
FOS = new FileOutputStream(file1);
58. Answer
A) FileOutputStream( FileDescriptor fd )
B) FileOutputStream( String n, boolean a )
E) FileOutputStream( File f )
59. Answer
C) RandomAccessFile
60. Answer
B) 7890
Test # 3
(Sun)
. Given:
1. public class ArrayTest {
2. public static void main (String[] args) {
3. Object[] ov;
4. String[] sa = { "Green", "Blue", "Red" };
5. ov = sa;
6. System.out.println("Color = " + ov[1]);
7. }
8. }
What is the result?
A.fails to compile
B.prints Color=Blue
C.prints Color=Green
D.generates an exception at runtime
2. Given:
1. public class OuterClass {
2. private double d1 = 1.0;
3. //insert code here
4. }
You need to insert an inner class declaration at line 3. Which two inner class declarations are
valid?(Choose two.)
A.class InnerOne{
public static double methoda() {return d1;}
}
B.public class InnerOne{
static double methoda() {return d1;}
}
C.private class InnerOne{
double methoda() {return d1;}
}
D.static class InnerOne{
protected double methoda() {return d1;}
}
E.abstract class InnerOne{
public abstract double methoda();
}
3. Given:
1. public class X {
2. public void m(Object x) {
3. x = new Integer(99);
4. Integer y = (Integer)x;
5. y = null;
6. System.out.println("x is" + x);
7. }
8. }
When is the Integer object, created in line 3, eligible for garbage collection?
A.never
B.just after line 4
C.just after line 5
D.just after line 6 (that is, as the method returns)
E.when the calling method sets the argument it passed into this method to null
7. Given
double pi = Math.PI;
Which two are valid ways to round pi to an int?(Choose two.)
A.int p = pi;
B.int p = Math.round(pi);
C.int p = (int)Math.round(pi);
D.int p = (int)Math.min(pi + 0.5d);
E.int p = (int)Math.floor(pi + 0.5d);
8. Which two statements are true for the class java.util.TreeSet? (Choose two.)
A.The elements in the collection are ordered.
B.The collection is guaranteed to be immutable.
C.The elements in the collection are guaranteed to be unique.
D.The elements in the collection are accessed using a unique key.
E.The elements in the collection are guaranteed to be synchronized
Answers # 3
1. prints Color=Blue
Because Object Class is Super Class of Every Class therefore, String array object can be
assigned to Object array. For example ,
class Super{}
class Derived extends Super{}
class Test{
public static void main(String []argv)
{
Super supobj = new Derived();
}
}
2. C&E
private class InnerOne
{
double methoda()
{
return d1;
}
}
And,
other options are false because a non-static inner class cannot have static
context i.e for options A and B. for D it is false because the variable cannot be referenced
from static context, because of static inner class.
Because the Object x has local scope i.e it is in the method therefore it will be garbage
Collected after method returns to caller.
4. C _object
options A is boolean literal and B is keywords for Java where as – (miuns) is not allowed
as identifier for object or variablebane. So C is correct.
5. B and D
Because 12 >> 2 gives 3 and 12/4 also gives 3
12 represented as 8 4 2 1 0
1 1 0 0 0 >> 2
0 0 1 1 0 == 3
6. D and E
public class Species{ }
public class Animal{private Species species;}
interface Component{ }
class Container implements Component{
private Component[] children;
}
7. C and E
int p = (int)Math.round(pi);
int p = (int)Math.floor(pi + 0.5d);
8. A and C
The elements in the collection are ordered.
The elements in the collection are guaranteed to be unique.
Test # 4
Question 1
What will happen if you compile/run this code?
1: public class Q1 extends Thread
2: {
3: public void run()
4: {
5: System.out.println("Before start method");
6: this.stop();
7: System.out.println("After stop method");
8: }
9:
10: public static void main(String[] args)
11: {
12: Q1 a = new Q1();
13: a.start();
14: }
15: }
Question 2
What will happen if you compile/run the following code?
1: class Test
2: {
3: static void show()
4: {
5: System.out.println("Show method in Test class");
6: }
7:}
8:
9: public class Q2 extends Test
10: {
11: static void show()
12: {
13: System.out.println("Show method in Q2 class");
14: }
15: public static void main(String[] args)
16: {
17: Test t = new Test();
18: t.show();
19: Q2 q = new Q2();
20: q.show();
21:
22: t = q;
23: t.show();
24:
25: q = t;
26: q.show();
27: }
28: }
D) Compilation error.
Answer
Question 3
The following code will give
1: class Test
2: {
3: void show()
4: {
5: System.out.println("non-static method in Test");
6: }
7: }
8: public class Q3 extends Test
9: {
10: static void show()
11: {
12: System.out.println("Overridden non-static method in Q3");
13: }
14:
15: public static void main(String[] args)
16: {
17: Q3 a = new Q3();
18: }
19: }
Answer
Question No :4
The following code will give
1: class Test
2: {
3: static void show()
4: {
5: System.out.println("Static method in Test");
6: }
7: }
8: public class Q4 extends Test
9: {
10: void show()
11: {
12: System.out.println("Overridden static method in Q4");
13: }
14: public static void main(String[] args)
15: {
16: }
17: }
Answer
Question No :5
The following code will print
1: int i = 1;
2: i <<= 31;
3: i >>= 31;
4: i >>= 1;
5:
6: int j = 1;
7: j <<= 31;
8: j >>= 31;
9:
10: System.out.println("i = " +i );
11: System.out.println("j = " +j);
A) i = 1
j = 1
B) i = -1
j = 1
C) i = 1
j = -1
D) i = -1
j = -1
Answer
Question No :6
The following code will print
A) True
True
B) True
False
C) False
True
D) False
False
Answer
Question No :7
1: if( new Boolean("true") == new Boolean("true"))
2: System.out.println("True");
3: else
4: System.out.println("False");
A) Compilation error.
B) No compilation error, but runtime exception.
C) Prints "True".
D) Prints "False".
Answer
Question No :8
1: public class Q8
2: {
3: int i = 20;
4: static
5: {
6: int i = 10;
7:
8: }
9: public static void main(String[] args)
10: {
11: Q8 a = new Q8();
12: System.out.println(a.i);
13: }
14: }
Answer
Question No :9
Answer
Question No :10
What will happen if you compile/run this code?
Answer # 4
Question No: 1
D. After the execution of stop() method, thread won't execute any
more statements.
Back to Question 1
Question No: 2
D. Explicit casting is required at line 25.
Back to Question 2
Question No: 3
B. You cann't override an non-static method with static method.
Back to Question 3
Question No: 4
B. You cann't override a static method with non-static method.
Back to Question 4
Question No: 5
D.
Back to Question 5
Question No: 6
C.
Back to Question 6
Question No: 7
D.
Back to Question 7
Question No: 8
D. Here the variable '"i" defined in static initializer is local
to that block only.
The statements in the static initializers will be executed
(only once) when the class is first created.
Back to Question 8
Question No: 9
C.
Back to Question 9
Question No: 10
C. Conditional operators have high precedence than assignment
operators.
Back to Question 10
Test # 5
Question 11
What will happen if you compile/run the following code?
Answer
Question 12
What is the output of the following code?
1: class Test
2: {
3: Test(int i)
4: {
5: System.out.println("Test(" +i +")");
6: }
7: }
8:
9: public class Q12
10: {
11: static Test t1 = new Test(1);
12:
13: Test t2 = new Test(2);
14:
15: static Test t3 = new Test(3);
16:
17: public static void main(String[] args)
18: {
19: Q12 Q = new Q12();
20: }
21: }
A) Test(1)
Test(2)
Test(3)
B) Test(3)
Test(2)
Test(1)
C) Test(2)
Test(1)
Test(3)
D) Test(1)
Test(3)
Test(2)
Answer
Question 13
What is the output of the following code?
1: int i = 16;
2: int j = 17;
3:
4: System.out.println("i >> 1 = " + (i >> 1));
5: System.out.println("j >> 1 = " + (j >> 1));
Answer
Question 14
What is the output of the following code?
1: int i = 45678;
2: int j = ~i;
3:
4: System.out.println(j);
Answer
Question 15
What will happen when you invoke the following method?
1: void infiniteLoop()
2: {
3: byte b = 1;
4:
5: while ( ++b > 0 )
6: ;
7: System.out.println("Welcome to Java");
8: }
Answer
Question 16
In the following applet, how many Buttons will be displayed?
1: import java.applet.*;
2: import java.awt.*;
3:
4: public class Q16 extends Applet
5: {
6: Button okButton = new Button("Ok");
7:
8: public void init()
9: {
10: add(okButton);
11: add(okButton);
12: add(okButton);
13: add(okButton);
14:
15: add(new Button("Cancel"));
16: add(new Button("Cancel"));
17: add(new Button("Cancel"));
18: add(new Button("Cancel"));
19:
20: setSize(300,300);
21: }
22: }
Answer
Question 17
In the following, which is correct Container-Default layout combination?
A) Applet - FlowLayout
B) Applet - BorderLayout
C) Applet - CardLayout
D) Frame - Flowlayout
E) Frame - BorderLayout
F) Frame - CardLayout
G) Panel - FlowLayout
H) Panel - BorderLayout.
Answer
Question 18
What is the output of the following code?
Answer
Question 19
What is the output of the following code?
1: class MyClass
2: {
3: static int maxElements;
4:
5: MyClass(int maxElements)
6: {
7: this.maxElements = maxElements;
8: }
9:
10: }
11:
12: public class Q19
13: {
14: public static void main(String[] args)
15: {
16:
17: MyClass a = new MyClass(100);
18: MyClass b = new MyClass(100);
19:
20: if(a.equals(b))
21: System.out.println("Objects have the same
values");
22: else
23: System.out.println("Objects have different
values");
24: }
25: }
Answer
Question 20
1: import java.applet.*;
2: import java.awt.*;
3:
4: public class Q20 extends Applet
5: {
6: Button okButton = new Button("Ok");
7:
8: public void init()
9: {
10: setLayout(new BorderLayout());
11:
12: add("South", okButton);
13: add("North", okButton);
14: add("East", okButton);
15: add("West", okButton);
16: add("Center", okButon);
17:
18: setSize(300,300);
19: }
20: }
A) Five Buttons with label "Ok" at Top, Bottom, Right, Left and
Center of the Applet.
B) Only one Button with label "Ok" at the Top of the Applet.
C) Only one Button with label "Ok" at the Bottom of the applet.
D) Only one Button with label "Ok" at the Center of the Applet.
Answer
Answer # 5
Question No 11
C. Here the main method was overloaded, so it won't give
compilation error.
Back to Question 11
Question No 12
D. No matter where they declared, static variables will be
intitialized before non-static variables.
Back to Question 12
Question No 13
A. 16 >> 1 is 8 and 17 >> 1 also 8.
Back to Question 13
Question No 14
D. Java allows you to use ~ operator for integer type variables.
The simple way to calculate is ~i = (- i) - 1.
Back to Question 14
Question No 15
B. Here the variable 'b' will go upto 127.
After that overflow will occur, so 'b' will be set to -ve value,
the loop ends and prints "Welcome to Java"
Back to Question 15
Question No 16
B.
Back to Question 16
Question No 17
A, E and G. For Applets and Panels FlowLayout is the default one,
BorderLayout is default for Window and Frames.
Back to Question 17
Question No 18
C. Strings are immutable. So str.concat("to Java!") will not append
anything to str.
Infact it will create another string "Welcome to Java!" and
leaves it.
Back to Question 18
Question No 19
D. equals() method was available in base class Object. So it won't
give any compilation error.
Here MyClass is a user-defined class, so the user has to
implement equals() method according to his requirments.
Back to Question 19
Question No 20
D.
Back to Question 20
Test # 6
What will happen if you compile/run the following code?
Question 22
What will happen if run the following code?
Answer
Question 23
Which of the following are valid array declarations/definitions?
1: int iArray1[10];
2: int iArray2[];
3: int iArray3[] = new int[10];
4: int iArray4[10] = new int[10];
5: int []iArray5 = new int[10];
6: int iArray6[] = new int[];
7: int iArray7[] = null;
A) 1.
B) 2.
C) 3.
D) 4.
E) 5.
F) 6.
G) 7.
Answer
Question 24
What is the output for the following lines of code?
1: System.out.println(" " +2 + 3);
2: System.out.println(2 + 3);
3: System.out.println(2 + 3 +"");
4: System.out.println(2 + "" +3);
Question 25
The following declaration(as a member variable) is legal.
static final transient int maxElements = 100;
A) True.
B) False.
Answer
Question 26
What will happen if you compile/run the following lines of code?
1: int[] iArray = new int[10];
2:
3: iArray.length = 15;
4:
5: System.out.println(iArray.length);
A) Prints 10.
B) Prints 15.
C) Compilation error, you can't change the length of an array.
D) Runtime exception at line 3.
Answer
Question 27
What will happen if you compile/run the folowing lines of code?
1: Vector a = new Vector();
2:
3: a.addElement(10);
4:
5: System.out.println(a.elementAt(0));
A) Prints 10.
B) Prints 11.
C) Compilation error at line 3.
D) Prints some garbage.
Answer
Question 28
What will happen if you invoke the following method?
1: public void check()
2: {
3: System.out.println(Math.min(-0.0,+0.0));
4: System.out.println(Math.max(-0.0,+0.0));
5: System.out.println(Math.min(-0.0,+0.0) ==
Math.max(0.0,+0.0));
6: }
Question 29
What will happen if you compile/run this code?
1: int i = 012;
2: int j = 034;
3: int k = 056;
4: int l = 078;
5:
6: System.out.println(i);
7: System.out.println(j);
8: System.out.println(k);
A) Prints 12,34 and 56.
B) Prints 24,68 and 112.
C) Prints 10, 28 and 46.
D) Compilation error.
Answer
Question 30
When executed the following line of code will print
System.out.println(-1 * Double.NEGATIVE_INFINITY);
A) -Infinity
B) Infinity
C) NaN
D) -NaN
Answer
Answer # 6
Question No 21
D. Constructors should not return any value. Java won't allow to
indicate with void.
In this case void Q21() is an ordinary method which has the same
name of the Class.
Back to Question 21
Question No 22
C. By default objects will be initialized to null and primitives to
their corresponding default vaulues.
The same rule applies to array of objects and primitves.
Back to Question 22
Question No 23
B,C,E and G. You can't specify the array dimension in type
specification(left hand side),
so A and D are invalid. In line 6 the array dimension is
missing(right hand side) so F is invalid.
You can intialize an array with null. so G is valid.
Back to Question 23
Question No 24
B.
Back to Question 24
Question No 25
A.
Back to Question 25
Question No 26
C. Once array is created then it is not possible to change the
length of the array.
Back to Question 26
Question No 27
C. You can't add primitives to Vector. Here 10 is int type
primitive.
Back to Question 27
Question No 28
B. The order of floating/double values is
-Infinity --> Negative Numbers/Fractions --> -0.0 --> +0.0 -->
Positive Numbers/Fractions --> Infinity.
Back to Question 28
Question No 29
D. Here integers are assinged by octal values. Octal numbers will
contain digits from 0 to 7.
8 is illegal digit for an octal value, so you get compilation
error.
Back to Question 29
Question No 30
B. Compile and see the result.
Back to Question 30
Test # 7
Marcus Green Test # 1
Question 1)
Which of the following lines will compile without warning or error.
1) float f=1.3;
2) char c="a";
3) byte b=257;
4) boolean b=null;
5) int i=10;
Answer to Question 1
Question 2)
What will happen if you try to compile and run the following code
public class MyClass {
public static void main(String arguments[]) {
amethod(arguments);
}
public void amethod(String[] arguments) {
System.out.println(arguments);
System.out.println(arguments[1]);
}
}
1) error Can't make static reference to void amethod.
2) error method main not correct
3) error array must include parameter
4) amethod must be declared with String
Answer to Question 2
Question 3)
Which of the following will compile without error
1)
import java.awt.*;
package Mypackage;
class Myclass {}
2)
package MyPackage;
import java.awt.*;
class MyClass{}
3)
/*This is a comment */
package MyPackage;
import java.awt.*;
class MyClass{}
Answer to Question 3
Question 4)
A byte can be of what size
1) -128 to 127
2) (-2 power 8 )-1 to 2 power 8
3) -255 to 256
4)depends on the particular implementation of the Java Virtual machine
Answer to Question 4
Question 5)
What will be printed out if this code is run with the following command line?
java myprog good morning
public class myprog{
public static void main(String argv[])
{
System.out.println(argv[2])
}
}
1) myprog
2) good
3) morning
4) Exception raised: "java.lang.ArrayIndexOutOfBoundsException: 2"
Answer to Question 5
Question 6)
Which of the following are keywords or reserved words in Java?
1) if
2) then
3) goto
4) while
5) case
Answer to Question 6
Question 7)
Which of the following are legal identifiers
1) 2variable
2) variable2
3) _whatavariable
4) _3_
5) $anothervar
6) #myvar
Answer to Question 7
Question 8)
What will happen when you compile and run the following code?
Question 9)
What will happen if you try to compile and run the following code?
public class Q {
public static void main(String argv[]){
int anar[]=new int[]{1,2,3};
System.out.println(anar[1]);
}
}
1) 1
2) Error anar is referenced before it is initialized
3) 2
4) Error: size of array must be defined
Answer to Question 9
Question 10)
What will happen if you try to compile and run the following code?
public class Q {
public static void main(String argv[]){
int anar[]=new int[5];
System.out.println(anar[0]);
}
}
1) Error: anar is referenced before it is initialized
2) null
3) 0
4) 5
Answer to Question 10
Question 11)
What will be the result of attempting to compile and run the following code?
abstract class MineBase {
abstract void amethod();
static int i;
}
public class Mine extends MineBase {
public static void main(String argv[]){
int[] ar=new int[5];
for(i=0;i < ar.length;i++)
System.out.println(ar[i]);
}
}
1) a sequence of 5 0's will be printed
2) Error: ar is used before it is initialized
3) Error Mine must be declared abstract
4) IndexOutOfBoundes Error
Answer to Question 11
Question 12)
What will be printed out if you attempt to compile and run the following code ?
int i=1;
switch (i) {
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
case 2:
System.out.println("two");
default:
System.out.println("default");
}
1) one
2) one, default
3) one, two, default
4) default
Answer to Question 12
Question 13)
What will be printed out if you attempt to compile and run the following code?
int i=9;
switch (i) {
default:
System.out.println("default");
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
case 2:
System.out.println("two");
}
1) default
2) default, zero
3) error default clause not defined
4) no output displayed
Answer to Question 13
Question 14)
Which of the following lines of code will compile without error
1)
int i=0;
if(i) {
System.out.println("Hello");
}
2)
boolean b=true;
boolean b2=true;
if(b==b2) {
System.out.println("So true");
}
3)
int i=1;
int j=2;
if(i==1|| j==2)
System.out.println("OK");
4)
int i=1;
int j=2;
if(i==1 &| j==2)
System.out.println("OK");
Answer to Question 14
Question 15)
What will be output if you try to compile and run the following code, but there is
no file called Hello.txt in the current directory?.
import java.io.*;
public class Mine {
public static void main(String argv[]){
Mine m=new Mine();
System.out.println(m.amethod());
}
public int amethod() {
try {
FileInputStream dis=new FileInputStream("Hello.txt");
}catch (FileNotFoundException fne) {
System.out.println("No such file found");
return -1;
}catch(IOException ioe) {
} finally{
System.out.println("Doing finally");
}
return 0;
}
}
1) No such file found
2 No such file found ,-1
3) No such file found, Doing finally, -1
4) 0
Answer to Question 15
Question 16)
Which of the following statements are true?
1) Methods cannot be overriden to be more private
2) Static methods cannot be overloaded
3) Private methods cannot be overloaded
4) An overloaded method cannot throw exceptions not checked in the base class
Answer to Question 16
Question 17)
What will happen if you attempt to compile and run the following code?
1) Compile and run without error
2) Compile time Exception
3) Runtime Exception
class Base {}
class Sub extends Base {}
class Sub2 extends Base {}
public class CEx{
public static void main(String argv[]){
Base b=new Base();
Sub s=(Sub) b;
}
}
Answer to Question 17
Question 18)
Which of the following statements are true?
1) System.out.println( -1 >>> 2);will output a result larger than 10
2) System.out.println( -1 >>> 2); will output a positive number
3) System.out.println( 2 >> 1); will output the number 1
4) System.out.println( 1 <<< 2); will output the number 4
Answer to Question 18
Question 19)
You are browsing the Java HTML documentation for information on the
java.awt.TextField component. You want to create Listener code to respond to focus
events. The only Listener method listed is addActionListener. How do you go about
finding out about Listener methods?
1) Define your own Listener interface according to the event to be tracked
2) Use the search facility in the HTML documentation for the listener needed
3) Move up the hierarchy in the HTML documentation to locate methods in base
classes
4) Subclass awt.event with the appropriate Listener method
Answer to Question 19
Question 20)
What will be displayed when you attempt to compile and run the following code
//Code start
import java.awt.*;
public class Butt extends Frame{
public static void main(String argv[]){
Butt MyBut=new Butt();
}
Butt(){
Button HelloBut=new Button("Hello");
Button ByeBut=new Button("Bye");
add(HelloBut);
add(ByeBut);
setSize(300,300);
setVisible(true);
}
}
//Code end
1) Two buttons side by side occupying all of the frame, Hello on the left and Bye on
the right
2) One button occupying the entire frame saying Hello
3) One button occupying the entire frame saying Bye
4) Two buttons at the top of the frame one saying Hello the other saying Bye
Answer to Question 20
Question 21)
Question 22)
If g is a graphics instance what will the following code draw on the screen?.
g.fillArc(45,90,50,50,90,180);
1) An arc bounded by a box of height 45, width 90 with a centre point of 50,50, starting
at an angle of 90 degrees traversing through 180 degrees counter clockwise.
2) An arc bounded by a box of height 50, width 50, with a centre point of 45,90 starting
at an angle of 90 degrees traversing through 180 degrees clockwise.
3) An arc bounded by a box of height 50, width 50, with a top left at coordinates of 45,
90, starting at 90 degrees and traversing through 180 degrees counter clockwise.
4) An arc starting at 45 degrees, traversing through 90 degrees clockwise bounded by a
box of height 50, width 50 with a centre point of 90, 180.
Answer to Question 22
Question 23)
Which of the following methods can be legally inserted in place of the comment //Method Here ?
class Base{
public void amethod(int i) { }
}
public class Scope extends Base{
public static void main(String argv[]){
}
//Method Here
}
1) void amethod(int i) throws Exception {}
2) void amethod(long i)throws Exception {}
3) void amethod(long i){}
4) public void amethod(int i) throws Exception {}
Answer to Question 23
Question 24)
Question 25)
What will happen if you attempt to compile and run the following code?
Integer ten=new Integer(10);
Long nine=new Long (9);
System.out.println(ten + nine);
int i=1;
System.out.println(i + ten);
1) 19 followed by 20
2) 19 followed by 11
3) Error: Can't convert java lang Integer
4) 10 followed by 1
Answer to Question 25
Question 26)
Question 27)
If you wanted to find out where the position of the letter v (ie return 2) in the string s
containing "Java", which of the following could you use?
1) mid(2,s);
2) charAt(2);
3) s.indexOf('v');
4) indexOf(s,'v');
Answer to Question 27
Question 28)
Given the following declarations
String s1=new String("Hello")
String s2=new String("there");
String s3=new String();
Which of the following are legal operations?
1) s3=s1 + s2;
2) s3=s1-s2;
3) s3=s1 & s2;
4) s3=s1 && s2
Answer to Question 28
Question 29)
What is the result of the following operation?
System.out.println(4 | 3);
1) 6
2) 0
3) 1
4) 7
Answer to Question 29
Question 30)
public class MyClass1 {
public static void main(String argv[]){ }
/*Modifier at XX */ class MyInner {}
}
What modifiers would be legal at XX in the above code?
1) public
2) private
3) static
4) friend
Answer to Question 30
Question 31)
Question 32)
An Applet has its Layout Manager set to the default of FlowLayout. What code would be correct to change
to another Layout Manager.
1) setLayoutManager(new GridLayout());
2) setLayout(new GridLayout(2,2));
3) setGridLayout(2,2);
4) setBorderLayout();
Answer to Question 32
Question 33)
What will happen when you attempt to compile and run the following code?.
1) It will compile and the run method will print out the increasing value of i.
2) It will compile and calling start will print out the increasing value of i.
3) The code will cause an error at compile time.
4) Compilation will cause an error because while cannot take a parameter of true.
class Background implements Runnable{
int i=0;
public int run(){
while(true){
i++;
System.out.println("i="+i);
} //End while
return 1;
}//End run
}//End class
Answer to Question 33
Question 34)
You have created an applet that draws lines. You have overriden the paint operation and used the graphics
drawLine method, and increase one of its parameters to multiple lines across the screen. When you first test
the applet you find that the news lines are redrawn, but the old lines are erased. How can you modify your
code to allow the old lines to stay on the screen instead of being cleared.
1) Override repaint thus
public void repaint(Graphics g){
paint(g);
}
2)Override update thus
public void update(Graphics g) {
paint(g);
}
3) turn off clearing with the method setClear();
4) Remove the drawing from the paint Method and place in the calling code
Answer to Question 34
Question 35)
What will be the result when you attempt to compile and run the following code?.
public class Conv{
public static void main(String argv[]){
Conv c=new Conv();
String s=new String("ello");
c.amethod(s);
}
public void amethod(String s){
char c='H';
c+=s;
System.out.println(c);
}
}
1) Compilation and output the string "Hello"
2) Compilation and output the string "ello"
3) Compilation and output the string elloH
4) Compile time error
Answer to Question 35
Question 36)
Given the following code, what test would you need to put in place of the comment line?
//place test here
to result in an output of
Equal
public class EqTest{
public static void main(String argv[]){
EqTest e=new EqTest();
}
EqTest(){
String s="Java";
String s2="java";
//place test here {
System.out.println("Equal");
}else
{
System.out.println("Not equal");
}
}
}
1) if(s==s2)
2) if(s.equals(s2)
3) if(s.equalsIgnoreCase(s2))
4)if(s.noCaseMatch(s2))
Answer to Question 36
Question 37)
Given the following code
import java.awt.*;
public class SetF extends Frame{
public static void main(String argv[]){
SetF s=new SetF();
s.setSize(300,200);
s.setVisible(true);
}
}
How could you set the frame surface color to pink
1)s.setBackground(Color.pink);
2)s.setColor(PINK);
3)s.Background(pink);
4)s.color=Color.pink
Answer to Question 37
Question 38)
How can you change the current working directory using an instance of the File class called FileName?
1) FileName.chdir("DirName")
2) FileName.cd("DirName")
3) FileName.cwd("DirName")
4) The File class does not support directly changing the current directory.
Answer to Question 38
Question 39)
If you create a TextField with a constructor to set it to occupy 5 columns, what difference will it make if
you use it with a proportional font (ie Times Roman) or a fixed pitch typewriter style font (Courier).
1)With a fixed font you will see 5 characters, with a proportional it will depend on the width of the
characters
2)With a fixed font you will see 5 characters,with a proportional it will cause the field to expand to fit the
text
3)The columns setting does not affect the number of characters displayed
4)Both will show exactly 5 characters
Answer to Question 39
Question 40)
Given the following code how could you invoke the Base constructor that will print out the string "base
constructor";
class Base{
Base(int i){
System.out.println("base constructor");
}
Base(){
}
}
public class Sup extends Base{
public static void main(String argv[]){
Sup s= new Sup();
//One
}
Sup()
{
//Two
}
public void derived()
{
//Three
}
}
1) On the line After //One put Base(10);
2) On the line After //One put super(10);
3) On the line After //Two put super(10);
4) On the line After //Three put super(10);
Answer to Question 40
Question 41)
Given the following code what will be output?
public class Pass{
static int j=20;
public static void main(String argv[]){
int i=10;
Pass p = new Pass();
p.amethod(i);
System.out.println(i);
System.out.println(j);
}
public void amethod(int x){
x=x*2;
j=j*2;
}
}
1) Error: amethod parameter does not match variable
2) 20 and 40
3) 10 and 40
4) 10, and 20
Answer to Question 41
Question 42)
What code placed after the comment //For loop would populate the elements of the array ia[] with values of
the variable i.?
public class Lin{
public static void main(String argv[]){
Lin l = new Lin();
l.amethod();
}
public void amethod(){
int ia[] = new int[4];
//Start For loop
{
ia[i]=i;
System.out.println(ia[i]);
}
}
}
1) for(int i=0; i < ia.length() -1; i++)
2) for (int i=0; i< ia.length(); i++)
3) for(int i=1; i < 4; i++)
4) for(int i=0; i< ia.length;i++)
Answer to Question 42
Question 43)
What will be the result when you try to compile and run the following code?
private class Base{
Base(){
int i = 100;
System.out.println(i);
}
}
public class Pri extends Base{
static int i = 200;
public static void main(String argv[]){
Pri p = new Pri();
System.out.println(i);
}
}
1) Error at compile time
2) 200
3) 100 followed by 200
4) 100
Answer to Question 43
Question 44)
What will the following code print out?
public class Oct{
public static void main(String argv[]){
Oct o = new Oct();
o.amethod();
}
public void amethod(){
int oi= 012;
System.out.println(oi);
}
}
1)12
2)012
3)10
4)10.0
Answer to Question 44
Question 45
What will happen when you try compiling and running this code?
public class Ref{
public static void main(String argv[]){
Ref r = new Ref();
r.amethod(r);
}
public void amethod(Ref r){
int i=99;
multi(r);
System.out.println(i);
}
public void multi(Ref r){
r.i = r.i*2;
}
}
1) Error at compile time
2) An output of 99
3) An output of 198
4) An error at runtime
Answer to Question 45
Question 46)
You need to create a class that will store a unique object elements. You do not need to sort these elements
but they must be unique.
What interface might be most suitable to meet this need?
1)Set
2)List
3)Map
4)Vector
Answer to Question 46
Question 47)
Which of the following will successfully create an instance of the Vector class and add an element?
1) Vector v=new Vector(99);
v[1]=99;
2) Vector v=new Vector();
v.addElement(99);
3) Vector v=new Vector();
v.add(99);
4 Vector v=new Vector(100);
v.addElement("99");
Answer to Question 47
Question 48)
You have created a simple Frame and overridden the paint method as follows
public void paint(Graphics g){
g.drawString("Dolly",50,10);
}
What will be the result when you attempt to compile and run the program?
1) The string "Dolly" will be displayed at the centre of the frame
2) An error at compilation complaining at the signature of the paint method
3) The lower part of the word Dolly will be seen at the top of the frame, with the top hidden.
4) The string "Dolly" will be shown at the bottom of the frame.
Answer to Question 48
Question 49)
What will be the result when you attempt to compile this program?
public class Rand{
public static void main(String argv[]){
int iRand;
iRand = Math.random();
System.out.println(iRand);
}
}
1) Compile time error referring to a cast problem
2) A random number between 1 and 10
3) A random number between 0 and 1
4) A compile time error about random being an unrecognised method
Answer to Question 49
Question 50)
Given the following code
import java.io.*;
public class Th{
public static void main(String argv[]){
Th t = new Th();
t.amethod();
}
public void amethod(){
try{
ioCall();
}catch(IOException ioe){}
}
}
What code would be most likely for the body of the ioCall method
1) public void ioCall ()throws IOException{
DataInputStream din = new DataInputStream(System.in);
din.readChar();
}
2) public void ioCall ()throw IOException{
DataInputStream din = new DataInputStream(System.in);
din.readChar();
}
3) public void ioCall (){
DataInputStream din = new DataInputStream(System.in);
din.readChar();
}
4) public void ioCall throws IOException(){
DataInputStream din = new DataInputStream(System.in);
din.readChar();
}
Answer to Question 50
Question 51)
What will happen when you compile and run the following code?
public class Scope{
private int i;
public static void main(String argv[]){
Scope s = new Scope();
s.amethod();
}//End of main
public static void amethod(){
System.out.println(i);
}//end of amethod
}//End of class
1) A value of 0 will be printed out
2) Nothing will be printed out
3) A compile time error
4) A compile time error complaining of the scope of the variable i
Answer to Question 51
Question 52)
You want to lay out a set of buttons horizontally but with more space between the first button and the rest.
You are going to use the GridBagLayout manager to control the way the buttons are set out. How will you
modify the way the GridBagLayout acts in order to change the spacing around the first button?
1) Create an instance of the GridBagConstraints class, call the weightx() method and then pass the
GridBagConstraints instance with the component to the setConstraints method of the GridBagLayout class.
2) Create an instance of the GridBagConstraints class, set the weightx field and then pass the
GridBagConstraints instance with the component to the setConstraints method of the GridBagLayout class.
3) Create an instance of the GridBagLayout class, set the weightx field and then call the setConstraints
method of the GridBagLayoutClass with the component as a parameter.
4) Create an instance of the GridBagLayout class, call the setWeightx() method and then pass the
GridBagConstraints instance with the component to the setConstraints method of the GridBagLayout class.
Answer to Question 52
Question 53)
Which of the following can you perform using the File class?
1) Change the current directory
2) Return the name of the parent directory
3) Delete a file
4) Find if a file contains text or binary information
Answer to Question 53
Question 54)
Which of the following code fragments will compile without error
1)
public void paint(Graphics g){
int polyX[] = {20,150,150};
int polyY[]= {20,20,120};
g.drawPolygon(polyX, polyY,3);
}
2)
public void paint(Graphics g){
int polyX[] = {20,150,150};
int polyY[]= {20,20,120};
g.drawPolygon(polyX, polyY);
}
3)
public void paint(Graphics g){
int polyX[3] = {20,150,150};
int polyY[3]= {20,20,120};
g.drawPolygon(polyX, polyY,3);
}
4)
public void paint(Graphics g){
int polyX[] = {20,150,150};
int polyY[]= {20,20,120};
drawPolygon(polyX, polyY);
}
Answer to Question 54
Question 55)
You are concerned that your program may attempt to use more memory than is available. To avoid this
situation you want to ensure that the Java Virtual Machine will run its garbage collection just before you
start a complex routine. What can you do to be certain that garbage collection will run when you want .
1) You cannot be certain when garbage collection will run
2) Use the Runtime.gc() method to force garbage collection
3) Ensure that all the variables you require to be garbage collected are set to null
4) Use the System.gc() method to force garbage collection
Answer to Question 55
Question 56)
You are using the GridBagLayout manager to place a series of buttons on a Frame. You want to make the
size of one of the buttons bigger than the text it contains. Which of the following will allow you to do that?
1) The GridBagLayout manager does not allow you to do this
2) The setFill method of the GridBagLayout class
3) The setFill method of the GridBagConstraints class
4) The fill field of the GridBagConstraints class
Answer to Question 56
Question 57)
Which of the following most closely describes a bitset collection?
1) A class that contains groups of unique sequences of bits
2) A method for flipping individual bits in instance of a primitive type
3) An array of boolean primitives that indicate zeros or ones
4) A collection for storing bits as on-off information, like a vector of bits
Answer to Question 57
Question 58)
You have these files in the same directory. What will happen when you attempt to compile and run
Class1.java if you have not already compiled Base.java
//Base.java
package Base;
class Base{
protected void amethod(){
System.out.println("amethod");
}//End of amethod
}//End of class base
package Class1;
//Class1.java
public class Class1 extends Base{
Question 59)
What will happen when you attempt to compile and run the following code
class Base{
private void amethod(int iBase){
System.out.println("Base.amethod");
}
}
class Over extends Base{
}
1) Compile time error complaining that Base.amethod is private
2) Runtime error complaining that Base.amethod is private
3) Output of "Base.amethod"
4) Output of "Over.amethod"
Answer to Question 59
Question 60)
You are creating an applet with a Frame that contains buttons. You are using the GridBagLayout manager
and you have added Four buttons. At the moment the buttons appear in the centre of the frame from left to
right. You want them to appear one on top of the other going down the screen. What is the most appropriate
way to do this.
1) Set the gridy value of the GridBagConstraint class to a value increasing from 1 to 4
2) set the fill value of the GridBagConstraint class to VERTICAL
3) Set the ipady value of the GridBagConstraint class to a value increasing from 0 to 4
4) Set the fill value of the GridBagLayout class to GridBag.VERTICAL
Answer to Question 60
If you have a copy of the Roberts and Heller Java2 Guide that says the exam does not cover the
GridBagLayout, this is an error. You can confirm this by looking at the online errata at
http://www.sybex.com/cgi-bin/rd_err_temp.pl?2463err.html.
Answers
Answer 1)
Back to question 1)
Objective 4.5)
5) int i=10;
explanation:
1) float f=1.3;
Will not compile because the default type of a number with a floating point component is a double. This
would compile with a cast as in
float f=(float) 1.3
2) char c="a";
Will not compile because a char (16 bit unsigned integer) must be defined with single quotes. This would
compile if it were in the form
char c='a';
3) byte b=257;
Will not compile because a byte is eight bits. Take of one bit for the sign component you can define
numbers between
-128 to +127
4) a boolean value can either be true of false, null is not allowed.
Answer 2)
Back to question 2)
Objective 4.1
1) Can't make static reference to void amethod.
Because main is defined as static you need to create an instance of the class in order to call any non-static
methods. Thus a typical way to do this would be.
MyClass m=new MyClass();
m.amethod();
Answer 2 is an attempt to confuse because the convention is for a main method to be in the form
String argv[]
That argv is just a convention and any acceptable identifier for a string array can be used. Answers 3 and 4
are just nonsense.
Answer 3)
back to Question 3)
Objective 4.1)
2 and 3 will compile without error.
1 will not compile because any package declaration must come before any other code. Comments may
appear anywhere.
Answer 4)
Back to question 4)
Objective 4.5)
1) A byte is a signed 8 bit integer.
Answer 5)
Back to question 5)
Objective 4.2)
4) Exception raised: "java.lang.ArrayIndexOutOfBoundsException: 2"
Unlike C/C++ java does not start the parameter count with the program name. It does however start from
zero. So in this case zero starts with good, morning would be 1 and there is no parameter 2 so an exception
is raised.
Answer 6)
Back to question 6)
Objective 1.5)
1) if
3) goto
4) while
5) case
then is not a Java keyword, though if you are from a VB background you might think it was. Goto is a
reserved word in Java.
Answer 7)
Back to Question 7)
Objective 1.10)
2) variable2
3) _whatavariable
4) _3_
5) $anothervar
An identifier can begin with a letter (most common) or a dollar sign($) or an underscore(_). An identifier
cannot start with anything else such as a number, a hash, # or a dash -. An identifier cannot have a dash in
its body, but it may have an underscore _. Choice 4) _3_ looks strange but it is an acceptable, if unwise
form for an identifier.
Answer 8)
Back to Question 8)
Objective 1.6)
4) 0
Class level variables are always initialised to default values. In the case of an int this will be 0. Method
level variables are not given default values and if you attempt to use one before it has been initialised it will
cause the
Error Variable i may not have been initialized
type of error.
Answer 9)
Back to Question 9)
Objective 1.7,3.4)
3)2
No error will be triggered.
Like in C/C++, arrays are always referenced from 0. Java allows an array to be populated at creation time.
The size of array is taken from the number of initializers. If you put a size within any of the square brackets
you will get an error.
Answer 10)
Back to question 10)
Objective 1.7)
3) 0
Arrays are always initialised when they are created. As this is an array of ints it will be initalised with
zeros.
Answer 11)
Back to Question 11)
Objective 3.6
3) Error Mine must be declared abstract
A class that contains an abstract method must itself be declared as abstract. It may however contain non
abstract methods. Any class derived from an abstract class must either define all of the abstract methods or
be declared abstract itself.
Answer 12)
Back to Question 12)
Objective 4.1)
3) one, two, default
Code will continue to fall through a case statement until it encounters a break.
Answer 13)
Back to Question 13)
Objective 4.1)
2) default, zero
Although it is normally placed last the default statement does not have to be the last item as you fall
through the case block. Because there is no case label found matching the expression the default label is
executed and the code continues to fall through until it encounters a break.
Answer 14)
Back to Question 14)
Objective 4.2,
2,3
Example 1 will not compile because if must always test a boolean. This can catch out C/C++ programmers
who expect the test to be for either 0 or not 0.
Answer 15)
Back to Question 15)
Objective 4.5)
3) No such file found, doing finally, -1
The no such file found message is to be expected, however you can get caught out if you are not aware that
the finally clause is almost always executed, even if there is a return statement.
Answer 16)
Objective
Back to Question 16)
1) Methods cannot be overriden to be more private
Static methods cannot be overriden but they can be overloaded. There is no logic or reason why private
methods should not be overloaded. Option 4 is a jumbled up version of the limitations of exceptions for
overriden methods
Answer 17)
Back to Question 17)
Objective 5.8 (sort of)
3) Runtime Exception
Without the cast to sub you would get a compile time error. The cast tells the compiler that you really mean
to do this and the actual type of b does not get resolved until runtime. Casting down the object hierarchy as
the compiler cannot be sure what has been implemented in descendent classes. Casting up is not a problem
because sub classes will have the features of the base classes. This can feel counter intuitive if you are
aware that with primitives casting is allowed for widening operations (ie byte to int).
Answer 18)
Back to question 18)
Objective 5.1)
1) System.out.println( -1 >>> 2);will output a result larger than 10
2) System.out.println( -1 >>> 2); will output a positive number
3) System.out.println( 2 >> 1); will output the number 1
You can test this with the following class
public class shift{
static int i=2;
public static void main(String argv[]){
System.out.println( -1 >>> 2);
System.out.println( -1 >>> 2);
System.out.println( 2 >> 1);
}
}
Java does not have a <<< operator. The operation 1 << 2 would output 4
Because of the way twos complement number representation works the unsigned right shift operation
means a small shift in a negative number can return a very large value so the output of option 1 will be
much larger than 10.
The unsigned right shift places no significance on the leading bit that indicates the sign. For this shift the
value 1 of the bit sign is replaced with a zero turning the result into a positive number for option 2.
Answer 19)
Back to Question 19)
Objective 1.1)
3) Move up the hierarchy in the HTML documentation to locate methods in base
classes
The documentation created by JavaDoc is based on tags placed into the sourcecode. The convention for
documentation is that methods and fields of ancestors are not duplicated in sub classes. So if you are
looking for something and it does not appear to be there, you move up the class hierarchy to find it.
Answer 20)
Back to Question 20)
Objective 10.4)
3) One button occupying the entire frame saying Bye
The default layout manager for a Frame is a border layout. If directions are not given (ie North, South, East
or West), any button will simply go in the centre and occupy all the space. An additional button will simply
be placed over the previous button. What you would probably want in a real example is to set up a flow
layout as in
setLayout(new FlowLayout());
Which would allow the buttons to both appear side by side, given the appropriate font and size.
Applets and panels have a default FlowLayout manager
Answer 21)
Back to Question 21)
Objective 4.4)
1,2
Value for i=1 Value for j=1
Value for i=2 Value for j=1
The statement continue outer causes the code to jump to the label outer and the for loop increments to the
next number.
Answer 22)
Back to Question 22)
Objective 9.5)
3) An arc bounded by a box of height 50, width 50, with a top left at coordinates of 45,
90, starting at 90 degrees and traversing through 180 degrees counter clockwise.
fillArc(int x, int y, int width, int height, int startDegrees, int arcDegrees)
The fillArc function draws an arc in a box with a top left at coordinates X & Y.
If the ArcDegrees is a positive number the arc is drawn counter clockwise.
Answer 23)
Back to Question 23)
Objective 4.7)
2,3
Options 1, & 4 will not compile as they attempt to throw Exceptions not declared in the base class. Because
options 2 and 4 take a parameter of type long they represent overloading not overriding and there is no such
limitations on overloaded methods.
Answer 24)
Back to Question 24)
Objective 8.1)
3) System.out.println(Math.ceil(-4.7));
Options 1 and 2 will produce -5 and option 4 will not compile because the min method requires 2
parameters.
Answer 25)
Back to Question 25
Objective 2.2
3) Error: Cant convert java lang Integer
The wrapper classes cannot be used like primitives.
Wrapper classes have similar names to primitives but all start with upper case letters.
Thus in this case we have int as a primitive and Integer as a wrapper. The objectives do not specifically
mention the wrapper classes but don't be surprised if they come up.
Answer 26)
Back to Question 26)
Objective 8.2)
2) ic
This is a bit of a catch question. Anyone with a C/C++ background would figure out that addressing in
strings starts with 0 so that 1 corresponds to i in the string Bicycle. The catch is that the second parameter
returns the endcharacter minus 1. In this case it means instead of the "icy" being returned as intuition would
expect it is only "ic".
Answer 27)
Back to Question 27)
Objective 8.2)
3) s.indexOf('v');
charAt returns the letter at the position rather than searching for a letter and returning the position, MID is
just to confuse the Basic Programmers, indexOf(s,'v'); is how some future VB/J++ nightmare hybrid, might
perform such a calculation.
Answer 28)
Objective 2.2
Back to Question 28
1) s3=s1 + s2;
Java does not allow operator overloading as in C++, but for the sake of convenience the + operator is
overridden for strings.
Answer 29)
Back to Question 29)
Objective 2.5)
4) 7
The | is known as the Or operator, you could think of it as the either/or operator. Turning the numbers into
binary gives
4=100
3=011
For each position, if either number contains a 1 the result will contain a result in that position. As every
position contains a 1 the result will be
111
Which is decimal 7.
Answer 30)
Back to Question 30
Objective 3.7)
1,2,3
public, private, static are all legal access modifiers for this inner class.
Answer 31)
Back to Question 31
Objective 9.6)
Opening an image file requires an Image object, The Image class has no constructor that takes the name of
an image file . For an application (rather than an applet) an image is created using the Toolkit class as in
option 2.
2) Image image=Toolkit.getDefaultToolkit().getImage("MyPicture.jpg");
Answer 32)
Back to Question 32)
Objective 1.3)
2) setLayout(new GridLayout(2,2));
Changing the layout manager is the same for an Applet or an application. Answer 1 is wrong though it
might have been a reasonable name for the designers to choose. Answers 3 and 4 are incorrect because
changing the layout manager always requires an instance of one of the Layout Managers and these are
bogus methods.
Instead of creating the anonymous instance of the Layout manager as in option 2 you can also create a
named instance and pass that as a parameter. This is often what automatic code generators such as
Borland/Inprise JBuilder do.
Answer 33)
Back to Question 33)
Objective 7.2)
3) The code will cause an error at compile time
The error is caused because run should have a void not an int return type.
Any class that is implements an interface must create a method to match all of the methods in the interface.
The Runnable interface has one method called run that has a void return type.The sun compiler gives the
error
Method redefined with different return type: int run() was defined as void run();
Answer 34)
Back to Question 34)
Objective 11.1)
2) public void update(Graphics g) {
paint(g);
}
If not overridden the update method clears the background and calls paint(); By overriding the update
method, any previously drawn graphics will not be cleared. This is only a trivial way of preserving any
graphics drawn. If the application is resized or the drawing area covered in some way the graphics will be
cleared.
Answer 35)
Back to Question 35
Objective 2.2
4) Compile time error
The only operator overloading offered by java is the + sign for the String class. A char is a 16 bit integer
and cannot be concatenated to a string with the + operator.
Answer 36)
Back to Question 36
Objective 8.2)
3) if(s.equalsIgnoreCase(s2))
String comparison is case sensitive so using the equals string method will not return a match. Using
the==operator just compares where memory address of the references and noCaseMatch was just
something I made up to give me a fourth slightly plausible option.
Answer 37)
Back to Question 37
Objective 9.1)
1) s.setBackground(Color.pink);
For speakers of the more British spelt English note that there is no letter u in Color. Also the constants for
colors are in lower case.
Answer 38)
Back to Question 38)
Objective 13.1)
4) The File class does not support directly changing the current directory.
This seems rather surprising to me, as changing the current directory is a very common requirement. You
may be able to get around this limitation by creating a new instance of the File class passing the new
directory to the constructor as the path name.
Answer 39)
Back to Question 39)
Objective 9.2)
1)With a fixed font you will see 5 characters, with a proportional it will depend on the width of the
characters
With a proportional font the letter w will occupy more space than the letter i. So if you have all wide
characters you may have to scroll to the right to see the entire text of a TextField.
Answer 40)
Back to Question 40)
Objective 5.8
3) On the line After //Two put super(10);
Constructors can only be invoked from within constructors.
Answer 41)
Back to Question 41)
Objective 2.8)
3) 10 and 40
when a parameter is passed to a method the method receives a copy of the value. The method can modify
its value without affecting the original copy. Thus in this example when the value is printed out the method
has not changed the value.
Answer 42)
Back to Question 42
Objective 3.3
4) for(int i=0; i< ia.length;i++)
Although you could control the looping with a literal number as with the number 4 used in option 3, it is
better practice to use the length property of an array. This provides against bugs that might result if the size
of the array changes. This question also checks that you know that arrays starts from zero and not One as
option 3 starts from one. Remember that array length is a field and not a function like the string size
method.
Answer 43)
Back to Question 43)
Objective 3.6 (maybe)
1) Error at compile time
This is a slightly sneaky one as it looks like a question about constructors, but it is attempting to test
knowledge of the use of the private modifier. A top level class cannot be defined as private. If you didn't
notice the modifier private, remember in the exam to be real careful to read every part of the question.
Answer 44)
Back to Question 44
Objective 1.11)
3)10
The name of the class might give you a clue with this question, Oct for Octal. Prefixing a number with a
zero indicates that it is in Octal format. Thus when printed out it gets converted to base ten. 012 in octal
means the first column from the right has a value of 2 and the next along has a value of one times eight. In
decimal that adds up to 10.
Answer 45)
Back to Question 45
Objective 3.5)
1) Error at compile time
The variable i is created at the level of amethod and will not be available inside the method multi.
Answer 46)
Back to Question 46
Java2 Objective 10.1)
1) Set
The Set interface ensures that its elements are unique, but does not order the elements. In reality you
probably wouldn't create your own class using the Set interface. You would be more likely to use one of the
JDK classes that use the Set interface such as HashSet or TreeSet.
Answer 47)
Back to Question 47
Java2 Objective 10.1)
4) Vector v=new Vector(100);
v.addElement("99")
A vector can only store objects not primitives. The parameter "99" for the addElement method pases a
string object to the Vector. Option 1) creates a vector OK but then uses array syntax to attempt to assign a
primitive. Option 2 also creates a vector then uses correct Vector syntax but falls over when the parameter
is a primitive instead of an object.
Answer 48)
Objective 9.5)
Back to Question 48
3) The lower part of the word Dolly will be seen at the top of the form
The Second parameter to the drawstring method indicates where the baseline of the string will be placed.
Thus the 3rd parameter of 10 indicates the Y coordinate to be 10 pixels from the top of the Frame. This will
result in just the bottom of the string Dolly showing up or possibly only the descending part of the letter y.
Answer 49)
Back to Question 49)
Objective 8.1)
1) Compile time error referring to a cast problem
This is a bit of a sneaky one as the Math.random method returns a pseudo random number between 0 and 1,
and thus option 3 is a plausible Answer. However the number returned is a double and so the compiler will
complain that a cast is needed to convert a double to an int.
Answer 50)
Objective 4.6)
Back to question 50
1) public void ioCall ()throws IOException{
DataInputStream din = new DataInputStream(System.in);
din.readChar();
}
If a method might throw an exception it must either be caught within the method with a try/catch block, or
the method must indicate the exception to any calling method by use of the throws statement in its
declaration. Without this, an error will occur at compile time.
Answer 51)
Objective 3.10)
Back to Question 51)
3) A compile time error
Because only one instance of a static method exists not matter how many instance of the class exists it
cannot access any non static variables. The JVM cannot know which instance of the variable to access.
Thus you will get an error saying something like
Can't make a static reference to a non static variable
Answer 52)
Java2 Objective 8.2)
Back to Question 52)
2) Create an instance of the GridBagConstraints class, set the weightx field and then pass the
GridBagConstraints instance with the component to the setConstraints method of the GridBagLayout class.
The Key to using the GridBagLayout manager is the GridBagConstraint class. This class is not consistent
with the general naming conventions in the java API as you would expect that weightx would be set with a
method, whereas it is a simple field (variable).
If you have a copy of the Roberts and Heller Java2 Guide that says the exam does not cover the
GridBagLayout, this is an error. You can confirm this by looking at the online errata at
http://www.sybex.com/cgi-bin/rd_err_temp.pl?2463err.html.
Answer 53)
Objective 13.1)
Back to Question 53)
2) Return the name of the parent directory
3) Delete a file
It is surprising that you can't change the current directory. It is not so surprising that you can't tell if a file
contains text or binary information.
Answer 54)
Objective 9.5)
Back to Question 54)
1)
public void paint(Graphics g){
int polyX[] = {20,150,150};
int polyY[]= {20,20,120};
g.drawPolygon(polyX, polyY,3);
}
drawPolygon takes three parameters, the first two are arrays of the X,Y coordinates and the final is an
integer specifying the number of vertices (whatever they are).
Answer 55)
Objective 6.1)
Back to Question 55)
1) You cannot be certain when garbage collection will run
Although there is a Runtime.gc(), this only suggests that the Java Virtual Machine does its garbage
collection. You can never be certain when the garbage collector will run. Roberts and Heller is more
specific abou this than Boone. This uncertainty can cause consternation for C++ programmers who wish to
run finalize methods with the same intent as they use destructor methods.
Answer 56)
Java2 Objective 8.2)
Back to Question 56)
4) The fill field of the GridBagConstraints class
Unlike the GridLayout manager you can set the individual size of a control such as a button using the
GridBagLayout manager. A little background knowledge would indicate that it should be controlled by a
setSomethingOrOther method, but it isn't.
If you have a copy of the Roberts and Heller Java2 Guide that says the exam does not cover the
GridBagLayout, this is an error. You can confirm this by looking at the online errata at
http://www.sybex.com/cgi-bin/rd_err_temp.pl?2463err.html.
Answer 57)
Java2 Objective 10.1)
Back to Question 57)
4) A collection for storing bits as on-off information, like a vector of bits
This is the description given to a bitset in Bruce Eckels "Thinking in Java" book. The reference to unique
sequence of bits was an attempt to mislead because of the use of the word Set in the name bitset. Normally
something called a set implies uniqueness of the members, but not in this context.
Answer 58)
Back to Question 58)
Objective 3.10)
4)Compile error: Superclass Class1.Base of class Class1.Class1 not found
Using the package statement has an effect similar to placing a source file into a different directory. Because
the files are in different packages they cannot see each other. The stuff about File1 not having been
compiled was just to mislead, java has the equivalent of an "automake", whereby if it was not for the
package statements the other file would have been automatically compiled.
Answer 59)
Back to Question 59)
Objective 5.3)
4) Output of Over.amethod()
The names of parameters to an overridden method is not important.
Answer 60)
Java2 Objective 8.2)
Back to Question 60)
Test # 8
Marcus Green Test # 2
Question 1)
What will happen when you attempt to compile and run this code?
abstract class Base{
abstract public void myfunc();
public void another(){
System.out.println("Another method");
}
}
public class Abs extends Base{
public static void main(String argv[]){
Abs a = new Abs();
a.amethod();
}
public void myfunc(){
System.out.println("My func");
}
public void amethod(){
myfunc();
}
}
1) The code will compile and run, printing out the words "My Func"
2) The compiler will complain that the Base class has non abstract methods
3) The code will compile but complain at run time that the Base class has non abstract methods
4) The compiler will complain that the method myfunc in the base class has no body, nobody at all to
looove it
Answer to Question 1
Question 2)
What will happen when you attempt to compile and run this code?
public class MyMain{
public static void main(String argv){
System.out.println("Hello cruel world");
}
}
1) The compiler will complain that main is a reserved word and cannot be used for a class
2) The code will compile and when run will print out "Hello cruel world"
3) The code will compile but will complain at run time that no constructor is defined
4) The code will compile but will complain at run time that main is not correctly defined
Answer to Question 2
Question 3)
Which of the following are Java modifiers?
1) public
2) private
3) friendly
4) transient
4) vagrant
Answer to Question 3
Question 4)
What will happen when you attempt to compile and run this code?
class Base{
abstract public void myfunc();
public void another(){
System.out.println("Another method");
}
}
public class Abs extends Base{
public static void main(String argv[]){
Abs a = new Abs();
a.amethod();
}
public void myfunc(){
System.out.println("My func");
}
public void amethod(){
myfunc();
}
}
1) The code will compile and run, printing out the words "My Func"
2) The compiler will complain that the Base class is not declared as abstract.
3) The code will compile but complain at run time that the Base class has non abstract methods
4) The compiler will complain that the method myfunc in the base class has no body, nobody at all to
looove it
Answer to Question 4
Question 5)
Why might you define a method as native?
1) To get to access hardware that Java does not know about
2) To define a new data type such as an unsigned integer
3) To write optimised code for performance in a language such as C/C++
4) To overcome the limitation of the private scope of a method
Answer to Question 5
Question 6)
What will happen when you attempt to compile and run this code?
class Base{
public final void amethod(){
System.out.println("amethod");
}
}
public class Fin extends Base{
public static void main(String argv[]){
Base b = new Base();
b.amethod();
}
}
1) Compile time error indicating that a class with any final methods must be declared final itself
2) Compile time error indicating that you cannot inherit from a class with final methods
3) Run time error indicating that Base is not defined as final
4) Success in compilation and output of "amethod" at run time.
Answer to Question 6
7) What will happen when you attempt to compile and run this code?
public class Mod{
public static void main(String argv[]){
}
public static native void amethod();
}
1) Error at compilation: native method cannot be static
2) Error at compilation native method must return value
3) Compilation but error at run time unless you have made code containing native amethod available
4) Compilation and execution without error
Answer to Question 7
8) What will happen when you attempt to compile and run this code?
private class Base{}
public class Vis{
transient int iVal;
public static void main(String elephant[]){
}
}
1)Compile time error: Base cannot be private
2)Compile time error indicating that an integer cannot be transient
3)Compile time error transient not a data type
4)Compile time error malformed main method
Answer to Question 8
9) What happens when you attempt to compile and run these two files in the same directory?
//File P1.java
package MyPackage;
class P1{
void afancymethod(){
System.out.println("What a fancy method");
}
}
//File P2.java
public class P2 extends P1{
afancymethod();
}
1) Both compile and P2 outputs "What a fancy method" when run
2) Neither will compile
3) Both compile but P2 has an error at run time
4) P1 compiles cleanly but P2 has an error at compile time
Answer to Question 9
10) You want to find out the value of the last element of an array. You write the following code. What will
happen when you compile and run it.?
public class MyAr{
public static void main(String argv[]){
int[] i = new int[5];
System.out.println(i[5]);
}
}
1) An error at compile time
2) An error at run time
3) The value 0 will be output
4) The string "null" will be output
Answer to Question 10
11) You want to loop through an array and stop when you come to the last element. Being a good java
programmer and forgetting everything you ever knew about C/C++ you know that arrays contain
information about their size. Which of the following can you use?
1)myarray.length();
2)myarray.length;
3)myarray.size
4)myarray.size();
Answer to Question 11
Question 12)
What best describes the appearance of an applet with the following code?
import java.awt.*;
}//End of Application
1) A Frame with buttons marked One to Four placed on each edge.
2) A Frame with buutons marked One to four running from the top to bottom
3) A Frame with one large button marked Four in the Centre
4) An Error at run time indicating you have not set a LayoutManager
Answer to Question 12
Question 13)
How do you indicate where a component will be positioned using Flowlayout?
1) North, South,East,West
2) Assign a row/column grid reference
3) Pass a X/Y percentage parameter to the add method
4) Do nothing, the FlowLayout will position the component
Answer to Question 13)
Question 14)
How do you change the current layout manager for a container
1) Use the setLayout method
2) Once created you cannot change the current layout manager of a component
3) Use the setLayoutManager method
4) Use the updateLayout method
Answer to Question 14)
Question 15)
Which of the following are fields of the GridBagConstraints class?
1) ipadx
2) fill
3) insets
4) width
Answer to Question 15)
Question 16)
What most closely matches the appearance when this code runs?
import java.awt.*;
CompLay(){
Panel p = new Panel();
p.setBackground(Color.pink);
p.add(new Button("One"));
p.add(new Button("Two"));
p.add(new Button("Three"));
add("South",p);
setLayout(new FlowLayout());
setSize(300,300);
setVisible(true);
}
}
1) The buttons will run from left to right along the bottom of the Frame
2) The buttons will run from left to right along the top of the frame
3) The buttons will not be displayed
4) Only button three will show occupying all of the frame
Answer to Question 16)
Question 17)
Which statements are correct about the anchor field?
1) It is a field of the GridBagLayout manager for controlling component placement
2) It is a field of the GridBagConstraints class for controlling component placement
3) A valid setting for the anchor field is GridBagConstraints.NORTH
4) The anchor field controls the height of components added to a container
Answer to Question 17)
Question 18)
What will happen when you attempt to compile and run the following code?
public class Bground extends Thread{
}
1) A compile time error indicating that no run method is defined for the Thread class
2) A run time error indicating that no run method is defined for the Thread class
3) Clean compile and at run time the values 0 to 9 are printed out
4) Clean compile but no output at runtime
Answer to Question 18)
Question 19)
10)When using the GridBagLayout manager, each new component requires a new instance of the
GridBagConstraints class. Is this statement
1) true
2) false
Answer to Question 19)
Question 20)
Which most closely matches a description of a Java Map?
1) A vector of arrays for a 2D geographic representation
2) A class for containing unique array elements
3) A class for containing unique vector elements
4) An interface that ensures that implementing classes cannot contain duplicates
Answer to Question 20)
Question 21)
How does the set collection deal with duplicate elements?
1) An exception is thrown if you attempt to add an element with a duplicate value
2) The add method returns false if you attempt to add an element with a duplicate value
3) A set may contain elements that return duplicate values from a call to the equals method
4) Duplicate values will cause an error at compile time
Answer to Question 21)
Question 22)
What can cause a thread to stop executing?
1) The program exits via a call to exit(0);
2) The priority of another thread is increased
3) A call to the stop method of the Thread class
4) A call to the halt method of the Thread class
Question 23)
For a class defined inside a method, what rule governs access to the variables of the enclosing method?
1) The class can access any variable
2) The class can only access static variables
3) The class can only access transient variables
4) The class can only access final variables
Answer to Question 23)
Question 24)
Under what circumstances might you use the yield method of the Thread class
1) To call from the currently running thread to allow another thread of the same priority to run
2) To call on a waiting thread to allow it to run
3) To allow a thread of higher priority to run
4) To call from the currently running thread with a parameter designating which thread should be allowed
to run
Answer to Question 24)
Question 25)
What will happen when you attempt to compile and run the following code
public class Hope{
public static void main(String argv[]){
Hope h = new Hope();
}
protected Hope(){
for(int i =0; i <10; i ++){
System.out.println(i);
}
}
}
1) Compilation error: Constructors cannot be declared protected
2) Run time error: Constructors cannot be declared protected
3) Compilation and running with output 0 to 10
4) Compilation and running with output 0 to 9
Answer to Question 25)
Question 26)
What will happen when you attempt to compile and run the following code
public class MySwitch{
int k=10;
switch(k){
default: //Put the default at the bottom, not here
System.out.println("This is the default output");
break;
case 10:
System.out.println("ten");
case 20:
System.out.println("twenty");
break;
}
}
}
1) None of these options
2) Compile time errror target of switch must be an integral type
3) Compile and run with output "This is the default output"
4) Compile and run with output "ten"
Answer to Question 26)
Question 27)
Which of the following is the correct syntax for suggesting that the JVM performs garbage collection
1) System.free();
2) System.setGarbageCollection();
3) System.out.gc();
4) System.gc();
Answer to Question 27)
Question 28)
What will happen when you attempt to compile and run the following code
public class As{
int i = 10;
int j;
char z= 1;
boolean b;
public static void main(String argv[]){
As a = new As();
a.amethod();
}
public void amethod(){
System.out.println(j);
System.out.println(b);
}
}
1) Compilation succeeds and at run time an output of 0 and false
2) Compilation succeeds and at run time an output of 0 and true
3) Compile time error b is not initialised
4) Compile time error z must be assigned a char value
Answer to Question 28)
Question 29)
What will happen when you attempt to compile and run the following code with the command line "hello
there"
public class Arg{
String[] MyArg;
public static void main(String argv[]){
MyArg=argv;
}
public void amethod(){
System.out.println(argv[1]);
}
}
1) Compile time error
2) Compilation and output of "hello"
3) Compilation and output of "there"
4) None of the above
Answer to Question 29)
Question 30)
What will happen when you attempt to compile and run the following code
public class StrEq{
Question 31)
1) What will happen when you attempt to compile and run the following code
import java.io.*;
class Base{
public static void amethod()throws FileNotFoundException{}
}
public class ExcepDemo extends Base{
public static void main(String argv[]){
ExcepDemo e = new ExcepDemo();
}
public static void amethod(){}
protected ExcepDemo(){
try{
DataInputStream din = new DataInputStream(System.in);
System.out.println("Pausing");
din.readChar();
System.out.println("Continuing");
this.amethod();
}catch(IOException ioe) {}
}
}
1)Compile time error caused by protected constructor
2) Compile time error caused by amethod not declaring Exception
3) Runtime error caused by amethod not declaring Exception
4) Compile and run with output of "Pausing" and "Continuing" after a key is hit
Question 32)
What will happen when you attempt to compile and run this program
public class Outer{
public String name = "Outer";
public static void main(String argv[]){
Inner i = new Inner();
i.showName();
}//End of main
}
1) Compile and run with output of "Outer"
2) Compile and run with output of "Inner"
3) Compile time error because Inner is declared as private
4) Compile time error because of the line creating the instance of Inner
Answer to Question to 32
Question 33)
What will happen when you attempt to compile and run this code
//Demonstration of event handling
import java.awt.event.*;
import java.awt.*;
Question 34)
What will happen when you attempt to compile and run the following code
public class MyAr{
public static void main(String argv[]) {
MyAr m = new MyAr();
m.amethod();
}
public void amethod(){
static int i;
System.out.println(i);
}
}
1) Compilation and output of the value 0
2)Compile time error because i has not been initialized
3) Compilation and output of null
4) Compile time error
Answer to Question 34)
Question 35)
Which of the following will compile correctly
1) short myshort = 99S;
2) String name = 'Excellent tutorial Mr Green';
3) char c = 17c;
4)int z = 015;
Answer to Question 35)
Question 36)
Which of the following are Java key words
1)double
2)Switch
3)then
4)instanceof
Answer to Question 36)
Question 37
What will be output by the following line?
System.out.println(Math.floor(-2.1));
1) -2
2) 2.0
3) -3
4) -3.0
Answer to Question 37)
Question 38)
Given the following main method in a class called Cycle and a command line of
java Cycle one two
what will be output?
public static void main(String bicycle[]){
System.out.println(bicycle[0]);
}
1) None of these options
2) cycle
3) one
4) two
Answer to Question 38)
Question 39)
Which of the following statements are true?
1) At the root of the collection hierarchy is a class called Collection
2) The collection interface contains a method called enumerator
3) The interator method returns an instance of the Vector class
4) The set interface is designed for unique elements
Answer to Question 39)
Question 40)
Which of the following statements are correct?
1) If multiple listeners are added to a component only events for the last listener added will be processed
2) If multiple listeners are added to a component the events will be processed for all but with no guarantee
in the order
3) Adding multiple listeners to a comnponent will cause a compile time error
4) You may remove as well add listeners to a component.
Answer to Question 40)
Question 41)
Given the following code
class Base{}
1) b=m;
2) m=b;
3) d =i;
4) b1 =i;
Answer to Question 41)
Question 42)
Which of the following statements about threading are true
1) You can only obtain a mutually exclusive lock on methods in a class that extends Thread or implements
runnable
2) You can obtain a mutually exclusive lock on any object
3) A thread can obtain a mutex lock on a method declared with the keyword synchronized
4) Thread scheduling algorithms are platform dependent
Answer to Question 42)
Question 43)
Your chief Software designer has shown you a sketch of the new Computer parts system she is about to
create. At the top of the hierarchy is a Class called Computer and under this are two child classes. One is
called LinuxPC and one is called WindowsPC. The main difference between the two is that one runs the
Linux operating System and the other runs the Windows System (of course another difference is that one
needs constant re-booting and the other runs reliably). Under the WindowsPC are two Sub classes one
called Server and one Called Workstation. How might you appraise your designers work?
1) Give the goahead for further design using the current scheme
2) Ask for a re-design of the hierarchy with changing the Operating System to a field rather than Class type
3) Ask for the option of WindowsPC to be removed as it will soon be obsolete
4) Change the hierarchy to remove the need for the superfluous Computer Class.
Question 44)
Objective 4.1)
Which of the following statements are true
1) An inner class may be defined as static
2) An inner class may NOT be define as private
3) An anonymous class may have only one constructor
4) An inner class may extend another class
Answer to Question 44)
Question 45)
What will happen when you attempt to compile and run the following code
int Output=10;
boolean b1 = false;
if((b1==true) && ((Output+=10)==20)){
System.out.println("We are equal "+Output);
}else
{
System.out.println("Not equal! "+Output);
}
1) Compile error, attempting to peform binary comparison on logical data type
2) Compilation and output of "We are equal 10"
3) Compilation and output of "Not equal! 20"
4) Compilation and output of "Not equal! 10"
Answer to Question 45)
Question 46)
Given the following variables which of the following lines will compile without error?
String s = "Hello";
long l = 99;
double d = 1.11;
int i = 1;
int j = 0;
1) j= i <<s;
2) j= i<<j;
3) j=i<<d;
4)j=i<<l;
Answer to Question 46)
Question 47)
What will be output by the following line of code?
System.out.println(010|4);
1) 14
2) 0
3) 6
4) 12
Answer to Question 47)
Question 48)
Given the following variables
char c = 'c';
int i = 10;
double d = 10;
long l = 1;
String s = "Hello";
Which of the following will compile without error?
1)c=c+i;
2)s+=i;
3)i+=s;
4)c+=s;
Answer to Question 48)
Question 49)
Which of the following will compile without error?
1) File f = new File("/","autoexec.bat");
2) DataInputStream d = new DataInputStream(System.in);
3) OutputStreamWriter o = new OutputStreamWriter(System.out);
4) RandomAccessFile r = new RandomAccessFile("OutFile");
Answer to Question 49)
Question 50)
Given the folowing classes which of the following will compile without error?
interface IFace{}
class CFace implements IFace{}
class Base{}
Question 51)
Given the following code what will be the output?
class ValHold{
public int i = 10;
}
public class ObParm{
public static void main(String argv[]){
ObParm o = new ObParm();
o.amethod();
}
public void amethod(){
int i = 99;
ValHold v = new ValHold();
v.i=30;
another(v,i);
System.out.println(v.i);
}//End of amethod
Question 52)
Given the following class definition, which of the following methods could be legally placed after the
comment
//Here
public class Rid{
public void amethod(int i, String s){}
//Here
}
1)public void amethod(String s, int i){}
2)public int amethod(int i, String s){}
3)public void amethod(int i, String mystring){}
4) public void Amethod(int i, String s) {}
Answer to Question 52)
Question 53)
Given the following class definition which of the following can be legally placed after the comment line
//Here ?
class Base{
public Base(int i){}
}
public class MyOver extends Base{
public static void main(String arg[]){
MyOver m = new MyOver(10);
}
MyOver(int i){
super(i);
}
MyOver(String s, int i){
this(i);
//Here
}
}
1)MyOver m = new MyOver();
2)super();
3)this("Hello",10);
4)Base b = new Base(10);
Answer to Question 53)
Question 54)
Given the following class definition, which of the following statements would be legal after the comment
//Here
class InOut{
String s= new String("Between");
Question 55)
Which of the following are methods of the Thread class?
1) yield()
2) sleep(long msec)
3) go()
4) stop()
Answer to Question 55)
Question 56)
Which of the following methods are members of the Vector class and allow you to input a new element
1) addElement
2) insert
3) append
4) addItem
Answer to Question 56)
Question 57)
Which of the following statements are true?
1) Adding more classes via import statements will cause a performance overhead, only import classes you
actually use.
2) Under no circumstances can a class be defined with the private modifier
3) A inner class can be defined with the protected modifier
4) An interface cannot be instantiated
Answer 57)
Question 58)
Which of the following are correct event handling methods
1) mousePressed(MouseEvent e){}
2) MousePressed(MouseClick e){}
3) functionKey(KeyPress k){}
4) componentAdded(ContainerEvent e){}
Answer 58)
Question 59)
Which of the following are methods of the Collection interface?
1) iterator
2) isEmpty
3) toArray
4) setText
Answer 59)
Question 60)
Which of the following best describes the use of the synhronized keyword?
1) Allows two process to run in paralell but to communicate with each other
2) Ensures only one thread at a time may access a class or object
3) Ensures that two or more processes will start and end at the same time
4) Ensures that two or more Threads will start and end at the same time
Answer 60)
Answers
Answer 1)
Objective 1.2)
1) The code will compile and run, printing out the words "My Func"
A class that contains an abstract method must be declared abstract itself, but may contain non abstract
methods.
Answer 2)
Objective 4.1)
4) The code will compile but will complain at run time that main is not correctly defined
Answer 3)
Objective 4.3)
1) public
2) private
4) transient
The keyword transient is easy to forget as is not frequently used. Although a method may be considered to
be friendly like in C++ it is not a Java keyword.
Answer 4)
Objective 1.2)
2) The compiler will complain that the Base class is not declared as abstract.
If a class contains abstract methods it must itself be declared as abstract
Answer 5)
Objective 1.2)
1) To get to access hardware that Java does not know about
3) To write optimised code for performance in a language such as C/C++
Answer 6)
Objective 1.2)
4) Success in compilation and output of "amethod" at run time.
A final method cannot be ovverriden in a sub class, but apart from that it does not cause any other
restrictions.
Answer 7)
Objective 1.2)
4) Compilation and execution without error
It would cause a run time error if you had a call to amethod though.
Answer 8)
Objective 1.2)
1)Compile time error: Base cannot be private
A top leve (non nested) class cannot be private.
Answer 9)
Objective 1.2)
4) P1 compiles cleanly but P2 has an error at compile time
The package statement in P1.java is the equivalent of placing the file in a different directory to the file
P2.java and thus when the compiler tries to compile P2 an error occurs indicating that superclass P1 cannot
be found.
Answer 10)
Objective 1.1)
2) An error at run time
This code will compile, but at run-time you will get an ArrayIndexOutOfBounds exception. This becuase
counting in Java starts from 0 and so the 5th element of this array would be i[4].
Remember that arrays will always be initialized to default values wherever they are created.
Answer 11)
Objective 1.1)
2)myarray.length;
The String class has a length() method to return the number of characters. I have sometimes become
confused between the two.
Answer 12)
Objective 8.2)
3) A Frame with one large button marked Four in the Centre
The default layout manager for a Frame is the BorderLayout manager. This Layout manager defaults to
placing components in the centre if no constraint is passed with the call to the add method.
Answer 13)
Objective 8.2)
4) Do nothing, the FlowLayout will position the component
Answer 14)
Objective 8.2)
1) Use the setLayout method
Answer 15)
Objective 8.2)
1) ipadx
2) fill
3) insets
Answer 16)
Objective 8.2)
2) The buttons will run from left to right along the top of the frame
The call to the setLayout(new FlowLayout()) resets the Layout manager for the entire frame and so the
buttons end up at the top rather than the bottom.
Answer 17)
Objective 8.2)
2) It is a field of the GridBagConstraints class for controlling component placement
3) A valid settting for the anchor field is GridBagconstraints.NORTH
Answer 18)
Objective 7.1)
4) Clean compile but no output at runtime
This is a bit of a sneaky one as I have swapped around the names of the methods you need to define and
call when running a thread. If the for loop were defined in a method called
public void run()
and the call in the main method had been to b.start()
The list of values from 0 to 9 would have been output.
Answer 19)
Objective 8.2)
2) false
You can re-use the same instance of the GridBagConstraints when added successive components.
Answer 20)
Objective 10.1)
4) An interface that ensures that implementing classes cannot contain duplicates
Answer 21)
Objective 10.1)
2) The add method returns false if you attempt to add an element with a duplicate value
I find it a surprise that you do not get an exception.
Answer 22)
Objective 7.1)
1) The program exits via a call to exit(0);
2) The priority of another thread is increased
3) A call to the stop method of the Thread class
Java threads are somewhat platform dependent and you should be carefull when making assumptions about
Thread priorities. On some platforms you may find that a Thread with higher priorities gets to "hog" the
processor.
Answer 23)
Objective 4.1)
4) The class can only access final variables
Answer 24)
Objective 7.1)
1) To call from the currently running thread to allow another thread of the same priority to run
Answer 25)
Objective 6.2)
Answer 26)
Objective 2.1)
1) None of these options
Because of the lack of a break statement after the break 10; statement the actual output will be
Answer 27)
Objective 3.1)
4) System.gc();
Answer 28)
Objective 4.4)
1) Compilation succeeds and at run time an output of 0 and false
The default value for a boolean declared at class level is false, and integer is 0;
Answer 29)
Objective 1.2)
1) Compile time error
You will get an error saying something like "Cant make a static reference to a non static variable". Note
that the main method is static.
Answer 30)
Objective 5.2)
3) Output of "Not equal"
Despite the actual character strings matching, using the == operator will simply compare memory location.
Because the one string was created with the new operator it will be in a different location in memory to the
other string.
Answer 31)
Objective 2.3)
4) Compile and run with output of "Pausing" and "Continuing" after a key is hit
An overriden method in a sub class must not throw Exceptions not thrown in the base class. In the case of
the method amethod it throws no exceptions and will thus compile without complain. There is no reason
that a constructor cannot be protected.
Answer 32)
Objective 6.3)
4) Compile time error because of the line creating the instance of Inner
This looks like a question about inner classes but it is also a reference to the fact that the main method is
static and thus you cannot directly access a non static method. The line causing the error could be fixed by
changing it to say
Inner i = new Outer().new Inner();
Then the code would compile and run producing the output "Inner"
Answer 33)
Objective 4.6)
1) Error at compile time
If you implement an interface you must create bodies for all methods in that interface. This code will
produce an error saying that MyWc must be declared abstract because it does not define all of the methods
in WindowListener. Option 4 is nonsense as comments can appear anywhere. Option 3 suggesting that it
might compile but not produce output is ment to mislead on the basis that what looks like a constructor is
actually an ordinary method as it has a return type.
Answer 34)
Objective 1.2)
4) Compile time error
An error will be caused by attempting to define an integer as static within a method. The lifetime of a field
within a method is the duration of the running of the method. A static field exists once only for the class. An
approach like this does work with Visual Basic.
Answer 35)
Objective 9.5)
4)int z = 015;
The letters c and s do not exist as literal indicators and a String must be enclosed with double quotes, not
single as in this case.
Answer 36)
Objective 4.3)
1)double
4)instanceof
Note the upper case S on switch means it is not a keyword and the word then is part of Visual Basic but not
Java. Also, instanceof looks like a method but is actually a keyword,
Answer 37)
Objective 9.2)
4) -3.0
Answer 38)
Objective 4.2)
3) one
Command line parameters start from 0 and fromt he first parameter after the name of the compile (normally
Java)
Answer 39)
Objective 10.1)
4) The set is designed for unique elements.
Collection is an interface, not a class. The Collection interface includes a method called iterator. This
returns an instance of the Iterator class which has some similarities with Enumerators.
The name set should give away the purpose of the Set interface as it is analogous to the Set concept in
relational databases which implies uniquness.
Answer 40)
Objective 8.1)
2) If multiple listeners are added to a component the events will be processed for all but with no guarantee
in the order
4) You may remove as well add listeners to a component.
It ought to be fairly intuitive that a component ought to be able to have multiple listeners. After all, a text
field might want to respond to both the mouse and keyboard
Answer 41)
Objective 5.1)
1) b=m;
3) d =i;
You can assign up the inheritance tree from a child to a parent but not the other way without an explicit
casting. A boolean can only ever be assigned a boolean value.
Answer 42)
Objective 7.3)
2) You can obtain a mutually exclusive lock on any object
3) A thread can obtain a mutex lock on a method declared with the keyword synchronized
4) Thread scheduling algorithms are platform dependent
Yes that says dependent and not independent.
Answer 43)
Objective 6.1)
2) Ask for a re-design of the hierarchy with changing the Operating System to a field rather than Class type
Of course there are as many ways to design an object hierarchy as ways to pronounce Bjarne Strousjoup,
but this is the sort of answer that Sun will proabably be looking for in the exam.
Answer 44)
Objective 4.1)/
1) An inner class may be defined as static
4) An inner class may extend another class
How could an anonymous class have a constructor?. Remember a constructor is a method with no return
type and the same name as the class. Inner classes may be defined as private
Answer 45)
Objective 5.3)
4) Compilation and output of "Not equal! 10"
The output will be "Not equal 10". This illustrates that the Output +=10 calculation was never performed
because processing stopped after the first operand was evaluated to be false. If you change the value of b1
to true processing occurs as you would expect and the output is "We are equal 20";.
Answer 46)
Objective 5.1)
2)j= i<<j;
4)j=i<<l;
Answer 47)
Objective 5.3)
4) 12
As well as the binary OR objective this questions requires you to understand the octal notaction which
means that the leading letter zero (not the letter O)) means that the first 1 indicates the number contains one
eight and nothing else. Thus this calculation in decimal mean
8|4
To convert this to binary means
1000
0100
----
1100
----
Which is 12 in decimal
The | bitwise operator means that for each position where there is a 1, results in a 1 in the same position in
the answer.
Answer 48)
Objective 5.1)
2)s+=i;
Only a String acts as if the + operator were overloaded
Answer 49)
Objective 10.1)
Although the objectives do not specifically mention the need to understand the I/O Classes, feedback from
people who have taken the exam indicate that you will get questions on this topic. As you will probably
need to know this in the real world of Java programming, get familiar with the basics. I have assigned these
questions to Objective 10.1 as that is a fairly vague objective.
1) File f = new File("/","autoexec.bat");
2) DataInputStream d = new DataInputStream(System.in);
3) OutputStreamWriter o = new OutputStreamWriter(System.out);
Option 4, with the RandomAccess file will not compile because the constructor must also be passed a mode
parameter which must be either "r" or "rw"
Answer 50)
Objective 5.1)
1)o1=o2;
2)b=ob;
4)o1=b;
Answer 51)
Objective 5.4)
4) 10,0,20
In the call
another(v,i);
A reference to v is passed and thus any changes will be intact after this call.
Answer 52)
Objective 6.2)
1) public void amethod(String s, int i){}
4) public void Amethod(int i, String s) {}
Overloaded methods are differentiated only on the number, type and order of parameters, not on the return
type of the method or the names of the parameters.
Answer 53)
Objective 6.2)
4)Base b = new Base(10);
Any call to this or super must be the first line in a constructor. As the method already has a call to this, no
more can be inserted.
Answer 54)
Objective 4.1)
1)System.out.println(s);
4) System.out.println(iArgs);
A class within a method can only see final variables of the enclosing method. However it the normal
visibility rules apply for variables outside the enclosing method.
Answer 55)
Objective 7.2)
1) yield()
2) sleep
4) stop()
Note, the methods stop and suspend have been deprecated with the Java2 release, and you may get
questions on the exam that expect you to know this. Check out the Java2 Docs for an explanation
Answer 56)
Objective 10.1)
1) addElement
Answer 57)
Objective 4.1)
The import statement allows you to use a class directly instead of fully qualifying it with the full package
name, adding more classess with the import statement does not cause a runtime performance overhad. An
inner class can be defined with the private modifier.
3) An inner class can be defined with the protected modifier
4) An interface cannot be instantiated
Answer 58)
Objective 4.6)
1) mousePressed(MouseEvent e){}
4) componentAdded(ContainerEvent e){}
Answer 59)
Objective 10.1)
1) iterator
2) isEmpty
3) toArray
Answer 60)
Objective 7.3)
2) Ensures only one thread at a time may access a class or object
Test # 9
Marcus Green # 3
Question 1)
Which of the following are legal statements?
1) float f=1/3;
2) int i=1/3;
3) float f=1.01;
4) double d=999d;
Answer to Question 1)
Question 2)
Which of the following are Java keywords?
1) NULL
2) new
3) instanceOf
4) wend
Answer to Question 2)
Question 3)
Which of the following are valid statements?
1) System.out.println(1+1);
2) int i=2+'2';
3) c
4) byte b=255;
Answer to Question 3)
Question 4)
Which of the following statements are true?
1) The garbage collection algorithm in Java is vendor implemented
2) The size of primitives is platform dependent
3) The default type for a numerical literal with decimal component is a float.
4) You can modify the value in an Instance of the Integer class with the setValue method
Answer to Question 4)
Question 5)
Which of the following are true statements?
1) I/O in Java can only be performed using the Listener classes
2) The RandomAccessFile class allows you to move directly to any point a file.
3) The creation of a named instance of the File class creates a matching file in the underlying operating
system only when the close method is called.
4) The characteristics of an instance of the File class such as the directory separator, depend on the current
underlying operating system
Answer to Question 5)
Question 6).
Which of the following statements are true?
1) The instanceof operator can be used to determine if a reference is an instance of a class, but not an
interface.
2) The instanceof operator can be used to determine if a reference is an instance of a particular primitive
wrapper class
3) The instanceof operator will only determine if a reference is an instance of a class immediately above in
the hierarchy but no further up the inheritance chain
4) The instanceof operator can be used to determine if one reference is of the same class as another
reference thus
Answer to Question 6)
Question 7)
Which of the following statements are true?
1) An interface can only contain method and not variables
2) Interfaces cannot have constructors
3) A class may extend only one other class and implement only one interface
4) Interfaces are the Java approach to addressing its lack of multiple inheritance, but require implementing
classes to create the functionality of the Interfaces.
Answer to Question 7)
Question 8)
Which of the following are valid statements
1) public class MyCalc extends Math
2) Math.max(s);
3) Math.round(9.99,1);
4)Math.mod(4,10);
Answer to Question 8)
Question 9)
Which of the following are methods of the Runnable interface
1) run
2) start
3) yield
4) stop
Answer to Question 9)
Question 10)
Which of the following statements are true?
1) A byte can represent between -128 to 127
2) A byte can represent between -127 to 128
3) A byte can represent between -256 to 256
4) A char can represent between -2x2 pow 16 2 x2 pow 16 - 1
Answer to Question 10)
Question 11)
What will happen when you attempt to compile and run the following code
class Base{
public void Base(){
System.out.println("Base");
}
}
public class In extends Base{
public static void main(String argv[]){
In i=new In();
}
}
1) Compile time error Base is a keyword
2) Compilation and no output at runtime
3) Output of Base
4) Runtime error Base has no valid constructor
Answer to Question 11)
Question 12)
You have a public class called myclass with the main method defined as follows
public static void main(String parm[]){
System.out.println(parm[0]);
}
If you attempt to compile the class and run the program as follows
java myclass hello
What will happen?
1) Compile time error, main is not correctly defined
2) Run time error, main is not correctly defined
3) Compilation and output of java
4) Compilation and output of hello
Answer to Question 12)
Question 13)
Which of the following statements are true?
1) If a class has any abstract methods it must be declared abstract itself.
2) All methods in an abstract class must be declared as abstract
3) When applied to a class, the final modifier means it cannot be sub-classed
4) transient and volatile are Java modifiers
Answer to Question 13)
Question 14)
Objective 1.2)
Which of the following are valid methods?
1) public static native void amethod(){}
2) public static void amethod(){}
3) private protected void amethod(){}
4) static native void amethod();
Answer to Question 14)
Question 15)
Objective 6.2)
Which of the following statements are true?
1) Constructors cannot have a visibility modifier
2) Constructors can be marked public and protected, but not private
3) Constructors can only have a primitive return type
4) Constructors are not inherited
Answer to Question 15)
Question 16)
What will happen when you attempt to compile and run the following class?
class Base{
Base(int i){
System.out.println("Base");
void Severn(){
System.out.println("Severn");
}
}
1) Compilation and output of the string "Severn" at runtime
2) Compile time error
3) Compilation and no output at runtime
4) Compilation and output of the string "Base"
Answer to Question 16)
Question 17)
Which of the following statements are true?
1) static methods do not have access to the implicit variable called this
2) a static method may not be overriden
3) a static method may not be overriden to be non-static
4) a static method may not be overloaded
Answer to question 17)
Question 18)
Which of the following will compile without error?
1)
char c='1';
System.out.println(c>>1);
2)
Integer i=Integer("1");
System.out.println(i>>1);
3)
int i=1;
System.out.println(i<<<1);
4)
int i=1;
System.out.println(i<<1);
Answer to Question 18)
Question 19)
Which of the following are true?
1) A component may have only one event listener attached at a time
2) An event listener may be removed from a component
3) The ActionListener interface has no corresponding Adapter class
4) The processing of an event listener requires a try/catch block
Answer to Question 19)
Question 20)
Which of the following are Java keywords?
1) sizeof
2) main
3) transient
4) volatile
Answer to Question 20)
Question 21)
Which of the following statements are true?
1) The default constructor has a return type of void
2) The default constructor takes a parameter of void
3) The default constructor takes no parameters
4) The default constructor is not created if the class has any constructors of its own.
Answer to Question 21)
Question 22)
Which of the following statements are true?
1) All of the variables in an interface are implicitly static
2) All of the variables in an interface are implicitly final
3) All of the methods in an interface are implicitly abstract
4) A method in an interface can access class level variables
Answer to Question 22)
Question 23)
Which of the following statements are true?
1 ) The String class is implemented as a char array, elements are addressed using the stringname[]
convention
2) The + operator is overloaded for concatenation for the String class
3) Strings are a primitive type in Java and the StringBuffer is used as the matching wrapper type
4) The size of a string can be retrieved using the length property
Answer to Question 23)
Question 24)
Which of the following statements are true?
1) A method in an interface must not have a body
2) A class may extend one other class plus at most one interface
3) A class may extends at most one other class plus implement many interfaces
4) An class accesses an interface via the keyword uses
Answer to Question 24)
Question 25)
Which of the following statements are true?
1) The following statement will produce a result of 1. System.out.println( -1 >>>2);
2) Performing an unsigned left shift (<<<) on a negative number will always produce a negative number
result
3) The following statement will produce a result of zero, System.out.println(1 >>1);
4) All the integer primitives in java are signed numbers
Answer to Question 25)
Question 26)
Which of the following statements are true?
1) The elements in a Java array can only be of primitive types, not objects
2) Arrays are initialized to default values wherever they are created
3) An array may be dynamically resized using the setSize method
4) You can find out the size of an array using the size method
Answer to Question 26)
Question 27)
Given the following class
public class Ombersley{
boolean b1 = true;
System.out.println("Hello Crowle");
if(location==true){
System.out.println("Borcetshire");
System.out.println("Powick");
return true;
What will happen when you attempt to compile and run it?
Question 28)
You are given a class hierarchy with an instance of the class Dog. The class Dog is a child of mammal and
the class Mammal is a child of the class Vertibrate. The class Vertibrate has a method called move which
prints out the string "move". The class mammal overrides this method and prints out the string "walks". The
class Dog overrides this method and prints out the string "walks on paws". Given an instance of the class
Dog,. how can you access the ancestor method move in Vertibrate so it prints out the string "move";
1) d.super().super().move();
2) d.parent().parent().move();
3) d.move();
4) none of the above;
Answer to Question 28)
Question 29)
Which of the following most closely describes the process of overriding?
1) A class with the same name replaces the functionality of a class defined earlier in the hierarchy
2) A method with the same name completely replaces the functionality of a method earlier in the hierarchy
3) A method with the same name but different parameters gives multiple uses for the same method name
4) A class is prevented from accessing methods in its immediate ancestor
Answer to Question 29)
Question 30)
Which of the following statements are true?
1) The % is used to calculate a percentage thus: 10 % 20=50
2) The / operator is used to divide one value by another
3) The # symbol may not be used as the first character of a variable
4) The $ symbol may not be used as the first character of a variable
Answer to Question 30)
Question 31)
Which of the following statements are true?
1) The default layout manager for an Applet is FlowLayout
2) The default layout manager for a Frame is FlowLayout
3) A layout manager must be assigned to an Applet before the setSize method is called
4) The FlowLayout manager attempts to honor the preferred size of any components
Answer to Question 31)
Question 32)
Which of the following statements are true about a variable created with the static modifier?
Question 33)
Which of the following statements are true?
1) Java uses a system called UTF for I/O to support international character sets
2) The RandomAccessFile is the most suitable class for supporting international character sets
3) An instance of FileInputStream may not be chained to an instance of FileOutputStream
4) File I/O activities requires use of Exception handling
Answer to Question 33)
Question 34)
What will happen when you attempt to compile and run the following code?
import java.io.*;
class ExBase{
try{
fi.readChar();
}catch(IOException e){
System.exit(0);
Question 35)
What will happen when you attempt to compile and run the following code
public class Borley extends Thread{
b.start();
System.out.println("Running");
}
1) Compilation and run but no output
2) Compilation and run with the output "Running"
3) Compile time error with complaint of no Thread target
4) Compile time error with complaint of no access to Thread package
Answer to Question 35)
Question 36)
Assuming any exception handling has been set up, which of the following will create an instance of the
RandomAccessFile class
1) RandomAccessFile raf=new RandomAccessFile("myfile.txt","rw");
2) RandomAccessFile raf=new RandomAccessFile( new DataInputStream());
3) RandomAccessFile raf=new RandomAccessFile("myfile.txt");
4) RandomAccessFile raf=new RandomAccessFile( new File("myfile.txt"));
Answer to Question 36)
Question 37)
Given the following class definition
public class Upton{
//Here
Which of the following would be legal to place after the comment //Here ?
1) public int amethod(int z){}
2) public int amethod(int i,int j){return 99;}
3) protected void amethod(long l){ }
4) private void anothermethod(){}
Answer to Question 37)
Question 38)
Which of the following statements are true?
1) Code must be written to cause a frame to close on selecting the system close menu
2) The default layout for a Frame is the BorderLayout Manager
3) The layout manager for a Frame cannot be changed once it has been assigned
4) The GridBagLayout manager makes extensive use of the the GridBagConstraints class.
Answer to Question 38)
Question 39)
Given the following class definition
public class Droitwich{
class one{
System.out.println("two");
1) The code will not compile because the classes are nested to more than one level
2) The code will not compile because class two is marked as private
3) The code will compile and output the string two at runtime
4) The code will compile without error
Answer to Question 39)
Question 40)
Given the following code
class Base{
d.amethod();
//Here
}
Which of the following if placed after the comment //Here, will compile and modify the value of the
variable oak?
1) super.oak=1;
2) oak=33;
3) Base.oak=22;
4) oak=50.1;
Answer to Question 40)
Question 41)
You are creating an application that has a form with a text entry field used to enter a persons age. Which of
the following is appropriate for capturing this information.
1) Use the Text field of a TextField and parse the result using Integer
2) Use the getInteger method of the TextField
3) Use the getText methodof a TextBox and parse the result using the getInt method of Integer class
4) Use the getText method of a TextField and use the parseInt method of the Integer class
Answer to Question 41)
Question 42)
Given the following declaration
1) i=10;
2) i.setValue(10);
3) i.parseInt(10);
4) none of the above
Answer to Question 42)
Question 43)
Which of the following statements are true
1) constructors cannot be overloaded
2) constructors cannot be overridden
3) a constructor can return a primitive or an object reference
4) constructor invocation occurs from the current class up the hierarchy to the ancestor class
Answer to Question 43)
Question 44)
Given a reference called
t
to to a class which extends Thread, which of the following will cause it to give up cycles to allow another
thread to execute.
1) t.yield();
2) yield()
3) yield(100) //Or some other suitable amount in milliseconds
4) yield(t);
Answer to Question 44)
Question 45)
What will happen when you attempt to compile and run the following code?
public class Sandys{
System.out.println(s.court);
Sandys(int ballcount){
court=ballcount;
Question 46)
Which of the following statements are true?
1) A method cannot be overloaded to be less public in a child class
2) To be overridden a method must have the same name and parameter types
3) To be overridden a method must have the same name, parameter and return types
4) An overridden method must have the same name, parameter names and parameter types
Answer to Question 46)
Question 47)
What will happen when you attempt to compile and run the following code?
class Base{
Base(){
System.out.println("Base");
super();
Checket(){
System.out.println("Checket");
Question 48)
Which of the following statements are true?
1) Static methods cannot be overriden to be non static
2) Static methods cannot be overloaded
3) Private methods cannot be overloaded
4) An overloaded method cannot throw exceptions not checked in the base class
Answer to Question 48)
Question 49)
Which of the following statements are true?
1) The automatic garbage collection of the JVM prevents programs from ever running out of memory
2) A program can suggest that garbage collection be performed but not force it
3) Garbage collection is platform independent
4) An object becomes eligible for garbage collection when all references denoting it are set to null.
Answer to Question 49)
Question 50)
Given the following code
int x=2000;
What will happen if you attempt to compile and run this code with the
command line
Question 51)
What will happen when you attempt to compile and run the following code
class Base{
Ab a = new Ab();
a.hallow();
System.out.println("Claines "+i);
Question 52)
You have been asked to create a scheduling system for a hotel and catering organsiation.
You have been given the following information and asked to create a set of classes to represent it.
On the catering side of the organsiation they have
Head Chefs
Chefs
Apprentice Chefs
The system needs to store an employeeid, salary and the holiday entitlement
How would you best represent this information in Java
1) Create classes for Head Chef, Chef, Apprentice Chef and store the other values in fields
2) Create an employee class and derive sub classes for Head Chef, Chef, Apprentice Chef abd store the
other values in fields.
3) Create and employee class with fields for Job title and fields for the other values.
4) Create classes for all of the items mentioned and create a container class to represent employees
Answer to Question 52)
Question 53)
You need to read in the lines of a large text file containing tens of megabytes of data. Which of the
following would be most suitable for reading in such a file
1) new FileInputStream("file.name")
2) new InputStreamReader(new FileInputStream("file.name"))
3) new BufferedReader(new InputStreamReader(new FileInputStream("file.name")));
4) new RandomAccessFile raf=new RandomAccessFile("myfile.txt","+rw");
Answer to Question 53)
Question 54)
What will happen when you attempt to compile and run the following code?
public class Inc{
int i =0;
inc.fermin(i);
i = i++;
System.out.println(i);
i++;
Question 55)
What will happen when you attempt to compile and run the following code?
switch(i){
default:
System.out.println("no value given");
case 1:
System.out.println("one");
case 10:
System.out.println("ten");
case 5:
System.out.println("five");
Question 56)
Given the following class
public class ZeroPrint{
int i =0;
//Here
Which of the following lines if placed after the comment //Here will print out 0.
1) System.out.println(i++);
2) System.out.println(i+'0');
3) System.out.println(i);
4) System.out.println(i--);
Answer to Question 56)
Question 57)
Given the following code
class Base {}
Question 58)
What will happen when you attempt to compile and run the following code.
public class Pvf{
}
1) Compile time error
2) compilation and output of false
3) compilation and output of true
4) compilation and output of null
Answer to Question 58)
Question 59)
Which of the following statements are true?
1) The x,y coordinates of an instance of MouseEvent can be obtained using the getX() and getY() methods
2) The x,y coordinates of an instance of MouseEvent can be obtained using the X and Y integer fields
3) The time of a MouseEvent can be extracted using the getTime() method
4) The time of a MouseEvent can be extracted using the when parameter of the MouseEvent constructor
Answer to Question 59)
Question 60)
Given the following code
import java.io.*;
System.out.println("flytwick");
return 99;
}finally{
System.out.println("fliton");
}
return -1;
}
}
Which of the following statements are true if you try to compile and run the program?
1) The program will run and output only "flytwick"
2) The program will run and output only "fliton"
3) The program will run and output both "fliton" and "flytwick"
4) An error will occur at compile time because the method fliton attempts to return two values
Answer to Question 60)
Answers
Answer to Question 1)
Objective 4.5)
1) float f=1/3;
2) int i=1/3;
4) double d=999d;
The fact that option 3 does not compile may be a surprise. The problem is because the default type for a
number with a decimal component is a double and not a float. The additional trailing d in the option with
999 doesn't help, but it doesn't harm.
http://www.software.u-net.com/J2Tutor/04_05Tut.htm
Answer to Question 2)
Objective 4.3)
2) new
The option NULL (note the upper case letter) is definitely not a keyword. There is some discussion as to if
null is a keyword but for the purpose of the exam you should probably assume it is a keyword.
The option instanceOf is a bit of a misleading option that would probably not occur on the exam. The real
keyword is instanceof (note that the of has no capital letter O). I had the incorrect version in an earlier
version of this tutorial as it looks more likely to my eyes. The instanceof keyword looks like a method, but
it is actually an operator.
The option wend is probably valid in some other language to indicate the end of a while loop, but Java has
no such keyword.
http://www.software.u-net.com/J2Tutor/04_03Tut.htm
Answer to Question 3)
Objective 4.5)
1) System.out.println(1+1);
2) int i=2+'2';
Option 3 is not valid because single quotes are used to indicate a character constant and not a string.
Several people have emailed me to say that option 3 will compile. When they eventually compiled the exact
code they have agreed, it will not compile. Let me re-state that
String s="on"+'one';
Will NOT compile.
Option 4 will not compile because 255 is out of the range of a byte
http://www.software.u-net.com/J2Tutor/04_05Tut.htm
Answer to Question 4)
Objective 7.1)
1) The garbage collection algorithm in Java is vendor implemented
Threading and garbage collection are two of the few areas that are platform dependent. This is one of the
reasons why Java is not suitable for realtime programming. It is not a good idea use it to control your
plane or nuclear power station. Once an instance of the Integer class has a value it cannot be changed.
http://www.software.u-net.com/J2Tutor/07_01Tut.htm
Answer to Question 5)
Objective 10.1)
(Not on the official sub objectives but this topic does come up on the exam)
2) The RandomAccessFile class allows you to move directly to any point a file.
4) The characteristics of an instance of the File class such as the directory separator, depend on the current
underlying operating system
The File class can be considered to represent information about a file rather than a real file object. You can
create a file in the underlying operating system by passing an instance of a file to a stream such as
FileOutputStream. The file will be created when you call the close method of the stream.
http://www.software.u-net.com/J2Tutor/10 01Tut.htm
Answer to Question 6)
Objective 5.1)
2) The instanceof operator can be used to determine if a reference is an instance of a particular primitive
wrapper class
The instanceof operator can only be used to make a static comparison with a class type. Java1.1 added the
isInstance method to the class Class to allow you to dynamically determine a class type. The exam does not
test you on isInstance.
"http://www.software.u-net.com/J2Tutor/15 01Tut.htm#The instanceof operator
Answer to Question 7)
Objective 4.1)
2) Interfaces cannot have constructors
If you try to create a constructor for an Interface the compiler will give you an error message something
like
"interface can't have constructors".
4) Interfaces are the Java approach to addressing the single inheritance model, but require implementing
classes to create the functionality of the Interfaces.
An interface may contain variables as well as methods. However any variables are final by default and
must be assigned values on creation. A class can only extend one other class (single inheritance) but may
implement as many interfaces as you like (or is sensible).
http://www.software.u-net.com/J2Tutor/04_01Tut.htm
Answer to Question 8)
Objective 9.1)
None of these are valid statements. The Math class is final and cannot be extended. The max method takes
two parameters, round only takes one parameter and there is no mod parameter. You may get questions in
the exam that have no apparently correct answer. If you are absolutely sure this is the case, do not check
any of the options.
http://www.software.u-net.com/J2Tutor/09_01Tut.htm
Answer to Question 9)
Objective 7.1)
1) The Runnable interface has only one method run that needs to be created in any class that implements it.
The start method is used to actually call and start the run method executing.
http://www.software.u-net.com/J2Tutor/07_01Tut.htm
You can find the size of an array using the length field. The method length is used to return the number of
characters in a String. An array can contain elements of any type but they must all be of the same type. The
size of an array is fixed at creation. If you want to change its size you can of course create a new array and
assign the old one to it. A more flexible approach can be to use a collection class such as Vector.
http://www.software.u-net.com/J2Tutor/04_04Tut.htm
Answer to Question 27)
Objective 5.3)
2) Output of "Hello Crowle"
This code is an example of a short circuited operator. Because the first operand of the || (or) operator returns
true Java sees no reason to evaluate the second. Whatever the value of the second the overall result will
always be true. Thus the method called place is never called.
http://www.jchq.net/tutorial/05_03Tut.htm
http://www.jchq.net/tutorial/01_02Tut.htm
55)Objective 2.2)
60)Objective 3.4)
16)Objective 1.3)
21)Objective 1.3)
49)Objective 3.1)
26)Objective 4.4)
1)Objective 4.5)
3)Objective 4.5)
10)Objective 4.5)
22)Objective 4.1)
7) Objective 4.1)
12)Objective 4.2)
2) Objective 4.3)
23)Objective 4.5)
42)Objective 4.6)
41)Objective 4.6)
19)Objective 4.6)
20)Objective 4.3)
48)Objective 4.4)
59)Objective 4.6)
6) Objective 5.1)
25)Objective 5.1)
18)Objective 5.1)
27)Objective 5.3)
54)Objective 5.4)
56)Objective 5.1)
24)Objective 6.1)
29)Objective 6.1)
52)Objective 6.1)
45)Objective 6.2)
46)Objective 6.2)
47)Objective 6.2)
43)Objective 6.2)
37)Objective 6.2)
28)Objective 6.2)
15)Objective 6.2)
4)Objective 7.1)
9)Objective 7.1)
35)Objective 7.1)
44)Objective 7.1)
31)Objective 8.1)
38)Objective 8.1)
8)Objective 9.1)
5)Objective 10.1)
33)Objective 11.1)
36)Objective 11.1)
53)Objective 11.1)
End of document
Test # 9
Q. 1
Which colour is used to indicate instance methods in the standard "javadoc" format documentation:
A.blue
B.red
C.purple
D.orange
Select the most appropriate answer.
Q. 2
What is the correct ordering for the import, class and package declarations when found in a single file?
A.package, import, class
B.class, import, package
C.import, package, class
D.package, class, import
Select the most appropriate answer.
Q. 3
Which methods can be legally applied to a string object?
A.equals(String)
B.equals(Object)
C.trim()
D.round()
E.toString()
Select all correct answers.
Q. 4
What is the parameter specification for the public static void main method?
A.String args []
B.String [] args
C.Strings args []
D.String args
Select all correct answers.
Q. 5
What does the zeroth element of the string array passed to the public static void main method contain?
A.The name of the program
B.The number of arguments
C.The first argument if one is present
Select the most appropriate answer.
Q. 6
Which of the following are Java keywords?
A.goto
B.malloc
C.extends
D.FALSE
Select all correct answers
Q. 7
What will be the result of compiling the following code:
public class Test {
public static void main (String args []) {
int age;
age = age + 1;
System.out.println("The age is " + age);
}
}
A.Compiles and runs with no output
B.Compiles and runs printing out The age is 1
C.Compiles but generates a runtime error
D.Does not compile
E.Compiles but generates a compile time error
Select the most appropriate answer.
Q. 8
Which of these is the correct format to use to create the literal char value a?
A.‘a’
B."a"
C.new Character(a)
D.\000a
Select the most appropriate answer.
Q. 9
What is the legal range of a byte integral type?
A.0 - 65, 535
B.(–128) – 127
C.(–32,768) – 32,767
D.(–256) – 255
Select the most appropriate answer.
Q. 10
Which of the following is illegal:
A.int i = 32;
B.float f = 45.0;
C.double d = 45.0;
Select the most appropriate answer.
Q. 11
What will be the result of compiling the following code:
public class Test {
static int age;
public static void main (String args []) {
age = age + 1;
System.out.println("The age is " + age);
}
}
A.Compiles and runs with no output
B.Compiles and runs printing out The age is 1
C.Compiles but generates a runtime error
D.Does not compile
E.Compiles but generates a compile time error
Select the most appropriate answer.
Q. 12
Which of the following are correct?
A.128 >> 1 gives 64
B.128 >>> 1 gives 64
C.128 >> 1 gives –64
D.128 >>> 1 gives –64
Select all correct answers
Q. 13
Which of the following return true?
A."john" == "john"
B."john".equals("john")
C."john" = "john"
D."john".equals(new Button("john"))
Select all correct answers.
Q. 14
Which of the following do not lead to a runtime error?
A."john" + " was " + " here"
B."john" + 3
C.3 + 5
D.5 + 5.5
Select all correct answers.
Q. 15
Which of the following are so called "short circuit" logical operators?
A.&
B.||
C.&&
D.|
Select all correct answers.
Q. 16
Which of the following are acceptable?
A.Object o = new Button("A");
B.Boolean flag = true;
C.Panel p = new Frame();
D.Frame f = new Panel();
E.Panel p = new Applet();
Select all correct answers.
Q. 17
What is the result of compiling and running the following code:
public class Test {
static int total = 10;
public static void main (String args []) {
new Test();
}
public Test () {
System.out.println("In test");
System.out.println(this);
int temp = this.total;
if (temp > 5) {
System.out.println(temp);
}
}
}
A.The class will not compile
B.The compiler reports and error at line 2
C.The compiler reports an error at line 9
D.The value 10 is one of the elements printed to the standard output
E.The class compiles but generates a runtime error
Select all correct answers.
Q 18
Which of the following is correct:
A.String temp [] = new String {"j" "a" "z"};
B.String temp [] = { "j " " b" "c"};
C.String temp = {"a", "b", "c"};
D.String temp [] = {"a", "b", "c"};
Select the most appropriate answer.
Q. 19
What is the correct declaration of an abstract method that is intended to be public:
A.public abstract void add();
B.public abstract void add() {}
C.public abstract add();
D.public virtual add();
Select the most appropriate answer.
Q. 20
Under what situations do you obtain a default constructor?
A.When you define any class
B.When the class has no other constructors
C.When you define at least one constructor
Select the most appropriate answer.
Q. 21
Given the following code:
public class Test {
…
}
Which of the following can be used to define a constructor for this class:
A.public void Test() {…}
B.public Test() {…}
C.public static Test() {…}
D.public static void Test() {…}
Select the most appropriate answer.
Q. 22
Which of the following are acceptable to the Java compiler:
A.if (2 == 3) System.out.println("Hi");
B.if (2 = 3) System.out.println("Hi");
C.if (true) System.out.println("Hi");
D.if (2 != 3) System.out.println("Hi");
E.if (aString.equals("hello")) System.out.println("Hi");
Select all correct answers.
Q. 23
Assuming a method contains code which may raise an Exception (but not a RuntimeException), what is the
correct way for a method to indicate that it expects the caller to handle that exception:
A.throw Exception
B.throws Exception
C.new Exception
D.Don't need to specify anything
Select the most appropriate answer.
Q. 24
What is the result of executing the following code, using the parameters 4 and 0:
public void divide(int a, int b) {
try {
int c = a / b;
} catch (Exception e) {
System.out.print("Exception ");
} finally {
System.out.println("Finally");
}
A.Prints out: Exception Finally
B.Prints out: Finally
C.Prints out: Exception
D.No output
Select the most appropriate answer.
Q.25
Which of the following is a legal return type of a method overloading the following method:
public void add(int a) {…}
A.void
B.int
C.Can be anything
Select the most appropriate answer.
Q.26
Which of the following statements is correct for a method which is overriding the following method:
public void add(int a) {…}
A.the overriding method must return void
B.the overriding method must return int
C.the overriding method can return whatever it likes
Select the most appropriate answer.
Q. 27
Given the following classes defined in separate files:
class Vehicle {
public void drive() {
System.out.println("Vehicle: drive");
}
}
class Car extends Vehicle {
public void drive() {
System.out.println("Car: drive");
}
}
public class Test {
public static void main (String args []) {
Vehicle v;
Car c;
v = new Vehicle();
c = new Car();
v.drive();
c.drive();
v = c;
v.drive();
}
}
What will be the effect of compiling and running this class Test?
A.Generates a Compiler error on the statement v= c;
B.Generates runtime error on the statement v= c;
C.Prints out:
Vehicle: drive
Car: drive
Car: drive
D.Prints out:
Vehicle: drive
Car: drive
Vehicle: drive
Select the most appropriate answer.
Q. 28
Where in a constructor, can you place a call to a constructor defined in the super class?
A.Anywhere
B.The first statement in the constructor
C.The last statement in the constructor
D.You can't call super in a constructor
Select the most appropriate answer.
Q. 29
Which variables can an inner class access from the class which encapsulates it?
A.All static variables
B.All final variables
C.All instance variables
D.Only final instance variables
E.Only final static variables
Select all correct answers.
Q. 30
What class must an inner class extend:
A.The top level class
B.The Object class
C.Any class or interface
D.It must extend an interface
Select the most appropriate answer.
Q. 31
In the following code, which is the earliest statement, where the object originally held in e, may be garbage
collected:
1. public class Test {
2. public static void main (String args []) {
3. Employee e = new Employee("Bob", 48);
4. e.calculatePay();
5. System.out.println(e.printDetails());
6. e = null;
7. e = new Employee("Denise", 36);
8. e.calculatePay();
9. System.out.println(e.printDetails());
10.}
11.}
A.Line 10
B.Line 11
C.Line 7
D.Line 8
E.Never
Select the most appropriate answer.
Q. 32
What is the name of the interface that can be used to define a class that can execute within its own thread?
A.Runnable
B.Run
C.Threadable
D.Thread
E.Executable
Select the most appropriate answer.
Q. 33
What is the name of the method used to schedule a thread for execution?
A.init();
B.start();
C.run();
D.resume();
E.sleep();
Select the most appropriate answer.
Q. 34
Which methods may cause a thread to stop executing?
A.sleep();
B.stop();
C.yield();
D.wait();
E.notify();
F.notifyAll()
G.synchronized()
Select all correct answers.
Q. 35
Write code to create a text field able to display 10 characters (assuming a fixed size font) displaying the
initial string "hello":
:
Q. 36
Which of the following methods are defined on the Graphics class:
A.drawLine(int, int, int, int)
B.drawImage(Image, int, int, ImageObserver)
C.drawString(String, int, int)
D.add(Component);
E.setVisible(boolean);
F.setLayout(Object);
Select all correct answers.
Q. 37
Which of the following layout managers honours the preferred size of a component:
A.CardLayout
B.FlowLayout
C.BorderLayout
D.GridLayout
Select all correct answers.
Q. 38
Given the following code what is the effect of a being 5:
public class Test {
public void add(int a) {
loop: for (int i = 1; i < 3; i++){
for (int j = 1; j < 3; j++) {
if (a == 5) {
break loop;
}
System.out.println(i * j);
}
}
}
}
A.Generate a runtime error
B.Throw an ArrayIndexOutOfBoundsException
C.Print the values: 1, 2, 2, 4
D.Produces no output
Select the most appropriate answer.
Q. 39
What is the effect of issuing a wait() method on an object
A.If a notify() method has already been sent to that object then it has no effect
B.The object issuing the call to wait() will halt until another object sends a notify() or notifyAll()
method
C.An exception will be raised
D.The object issuing the call to wait() will be automatically synchronized with any other objects using
the receiving object.
Select the most appropriate answer.
Q. 40
The layout of a container can be altered using which of the following methods:
A.setLayout(aLayoutManager);
B.addLayout(aLayoutManager);
C.layout(aLayoutManager);
D.setLayoutManager(aLayoutManager);
Select all correct answers.
Q. 41
Using a FlowLayout manager, which is the correct way to add elements to a container:
A.add(component);
B.add("Center", component);
C.add(x, y, component);
D.set(component);
Select the most appropriate answer.
Q. 42
Given that a Button can generate an ActionEvent which listener would you expect to have to implement, in
a class which would handle this event?
A.FocusListener
B.ComponentListener
C.WindowListener
D.ActionListener
E.ItemListener
Select the most appropriate answer.
Q. 43
Which of the following, are valid return types, for listener methods:
A.boolean
B.the type of event handled
C.void
D.Component
Select the most appropriate answer.
Q. 44
Assuming we have a class which implements the ActionListener interface, which method should be used to
register this with a Button?
A.addListener(*);
B.addActionListener(*);
C.addButtonListener(*);
D.setListener(*);
Select the most appropriate answer.
Q. 45
In order to cause the paint(Graphics) method to execute, which of the following is the most appropriate
method to call:
A.paint()
B.repaint()
C.paint(Graphics)
D.update(Graphics)
E.None – you should never cause paint(Graphics) to execute
Select the most appropriate answer.
Q. 46
Which of the following illustrates the correct way to pass a parameter into an applet:
A.<applet code=Test.class age=33 width=100 height=100>
B.<param name=age value=33>
C.<applet code=Test.class name=age value=33 width=100 height=100>
D.<applet Test 33>
Select the most appropriate answer.
Q. 47
Which of the following correctly illustrate how an InputStreamReader can be created:
A.new InputStreamReader(new FileInputStream("data"));
B.new InputStreamReader(new FileReader("data"));
C.new InputStreamReader(new BufferedReader("data"));
D.new InputStreamReader("data");
E.new InputStreamReader(System.in);
Select all correct answers.
Q. 48
What is the permanent effect on the file system of writing data to a new FileWriter("report"), given the file
report already exists?
A.The data is appended to the file
B.The file is replaced with a new file
C.An exception is raised as the file already exists
D.The data is written to random locations within the file
Select the most appropriate answer.
Q. 49
What is the effect of adding the sixth element to a vector created in the following manner:
new Vector(5, 10);
A.An IndexOutOfBounds exception is raised.
B.The vector grows in size to a capacity of 10 elements
C.The vector grows in size to a capacity of 15 elements
D.Nothing, the vector will have grown when the fifth element was added
Select the most appropriate answer.
Q. 50
What is the result of executing the following code when the value of x is 2:
switch (x) {
case 1:
System.out.println(1);
case 2:
case 3:
System.out.println(3);
case 4:
System.out.println(4);
}
A.Nothing is printed out
B.The value 3 is printed out
C.The values 3 and 4 are printed out
D.The values 1, 3 and 4 are printed out
Select the most appropriate answer.
Q. 51
Consider the following example:
class First {
public First (String s) {
System.out.println(s);
}
}
public class Second extends First {
public static void main(String args []) {
new Second();
}
}
What is the result of compiling and running the Second class?
A.Nothing happens
B.A string is printed to the standard out
C.An instance of the class First is generated
D.An instance of the class Second is created
E.An exception is raised at runtime stating that there is no null parameter constructor in class First.
F.The class second will not compile as there is no null parameter constructor in the class First
Select the most appropriate answer.
Q. 52 What is the result of executing the following fragment of code:
boolean flag = false;
if (flag = true) {
System.out.println("true");
} else {
System.out.println("false");
}
A.true is printed to standard out
B.false is printed to standard out
C.An exception is raised
D.Nothing happens
Select the most appropriate answer.
Q. 53
Consider the following classes:
public class Test {
public static void test() {
this.print();
}
public static void print() {
System.out.println("Test");
}
public static void main(String args []) {
test();
}
}
What is the result of compiling and running this class?
A.The string Test is printed to the standard out.
B.A runtime exception is raised stating that an object has not been created.
C.Nothing is printed to the standard output.
D.An exception is raised stating that the method test cannot be found.
E.An exception is raised stating that the variable this can only be used within an instance.
F.The class fails to compile stating that the variable this is undefined.
Select all correct answers.
Q. 54
Examine the following class definition:
public class Test {
public static void test() {
print();
}
public static void print() {
System.out.println("Test");
}
public void print() {
System.out.println("Another Test");
}
}
What is the result of compiling this class:
A.A successful compilation.
B.A warning stating that the class has no main method.
C.An error stating that there is a duplicated method.
D.An error stating that the method test() will call one or other of the print() methods.
Select the most appropriate answer.
Q. 55
What is the result of compiling and executing the following Java class:
public class ThreadTest extends Thread {
public void run() {
System.out.println("In run");
suspend();
resume();
System.out.println("Leaving run");
}
public static void main(String args []) {
(new ThreadTest()).start();
}
}
A.Compilation will fail in the method main.
B.Compilation will fail in the method run.
C.A warning will be generated for method run.
D.The string "In run" will be printed to standard out.
E.Both strings will be printed to standard out.
F.Nothing will happen.
Select the most appropriate answer.
Q. 56
Given the following sequence of Java statements
1. StringBuffer sb = new StringBuffer("abc");
2. String s = new String("abc");
3. sb.append("def");
4. s.append("def");
5. sb.insert(1, "zzz");
6. s.concat(sb);
7. s.trim();
Which of the following statements are true:
A.The compiler would generate an error for line 1.
B.The compiler would generate an error for line 2.
C.The compiler would generate an error for line 3.
D.The compiler would generate an error for line 4.
E.The compiler would generate an error for line 5.
F.The compiler would generate an error for line 6.
G.The compiler would generate an error for line 7.
Select all correct answers.
Q. 57
What is the result of executing the following Java class:
import java.awt.*;
public class FrameTest extends Frame {
public FrameTest() {
add (new Button("First"));
add (new Button("Second"));
add (new Button("Third"));
pack();
setVisible(true);
}
public static void main(String args []) {
new FrameTest();
}
}
Select from the following options:
A.Nothing happens.
B.Three buttons are displayed across a window.
C.A runtime exception is generated (no layout manager specified).
D.Only the "first" button is displayed.
E.Only the "second" button is displayed.
F.Only the "third" button is displayed.
Select the most appropriate answer.
Q. 58
Consider the following tags and attributes of tags:
1. CODEBASE
2. ALT
3. NAME
4. CLASS
5. JAVAC
6. HORIZONTALSPACE
7. VERTICALSPACE
8. WIDTH
9. PARAM
10. JAR
Which of the above can be used within the <APPLET> and </APPLET> tags?
A.line 1, 2, 3
B.line 2, 5, 6, 7
C.line 3, 4, 5
D.line 8, 9, 10
E.line 8, 9
Select all correct answers.
Q. 59
Which of the following is a legal way to construct a RandomAccessFile:
A.RandomAccessFile("data", "r");
B.RandomAccessFile("r", "data");
C.RandomAccessFile("data", "read");
D.RandomAccessFile("read", "data");
Select the most appropriate answer.
Q. 60
Carefully examine the following code:
public class StaticTest {
static {
System.out.println("Hi there");
}
public void print() {
System.out.println("Hello");
}
public static void main(String args []) {
StaticTest st1 = new StaticTest();
st1.print();
StaticTest st2 = new StaticTest();
st2.print();
}
}
When will the string "Hi there" be printed?
A.Never.
B.Each time a new instance is created.
C.Once when the class is first loaded into the Java virtual machine.
D.Only when the static method is called explicitly.
Select the most appropriate answer.
Q. 61
Consider the following program:
public class Test { public static void main (String args [])
{ boolean a = false; if (a = true)
System.out.println("Hello");
Else
System.out.println("Goodbye");
}
}
What is the result:
A. Program produces no output but terminates correctly.
B. Program does not terminate.
C. Prints out "Hello"
D. Prints out "Goodbye"
Select the most appropriate answer.
Q. 62
Examine the following code which includes an inner class:
public final class Test4 implements A {
class Inner {
void test() {
if (Test4.this.flag); {
sample();
}
}
}
private boolean flag = false;
public void sample() {
System.out.println("Sample");
}
public Test4() {
(new Inner()).test();
}
public static void main(String args []) {
new Test4();
}
}
What is the result:
A. Prints out "Sample"
B. Program produces no output but terminates correctly.
C. Program does not terminate.
D. The program will not compile
Select the most appropriate answer.
Q. 63
Carefully examine the following class:
public class Test5 { public static void main (String args []) { /* This
is the start of a comment
if (true) {
Test5 = new test5();
System.out.println("Done the test");
}
/* This is another comment */
System.out.println ("The end");
}
}
What is the result:
A. Prints out "Done the test" and nothing else.
B. Program produces no output but terminates correctly.
C. Program does not terminate.
D. The program will not compile.
E. The program generates a runtime exception.
F. The program prints out "The end" and nothing else.
G. The program prints out "Done the test" and "The end"
Select the most appropriate answer.
Q. 64
The following code defines a simple applet:
import java.applet.Applet;
import java.awt.*;
public class Sample extends Applet {
private String text = "Hello World";
public void init() {
add(new Label(text));
}
public Sample (String string) {
text = string;
}
}
It is accessed form the following HTML page:
<html>
<title>Sample Applet</title>
<body>
<applet code="Sample.class" width=200 height=200></applet>
</body>
</html>
What is the result of compiling and running this applet:
A. Prints "Hello World".
B. Generates a runtime error.
C. Does nothing.
D. Generates a compile time error.
Select the most appropriate answer.
Q. 65
Examine the following code:
public class Calc {
public static void main (String args []) {
int total = 0;
for (int i = 0, j = 10; total > 30; ++i, --j) {
System.out.println(" i = " + i + " : j = " + j);
total += (i + j);
}
System.out.println("Total " + total);
}
}
Does this code:
A. Produce a runtime error
B. Produce a compile time error
C. Print out "Total 0"
D. Generate the following as output:
i = 0 : j = 10
i=1:j=9
i=2:j=8
Total 30
Please select the most appropriate answer.