Java Mock Tests For SCJP
Java Mock Tests For SCJP
4)
JavaBeat Home SCJP 1.4 Home Objectives Forums Mock Exams Online Mock Exam Resources
Mock Exams
MockQuestions - 1 MockQuestions - 2 MockQuestions - 3 MockQuestions - 4
MockQuestions - 5 MockQuestions - 6 MockQuestions - 7 MockQuestions - 8
MockQuestions - 9 MockQuestions - 10 MockQuestions - 11 MockQuestions - 12
MockQuestions - 13 MockQuestions - 14 MockQuestions - 15 MockQuestions - 16
MockQuestions - 17 MockQuestions - 18 MockQuestions - 19 MockQuestions - 20
1.What is the result when you compile and run the following code?
class Top {
void myTop() {
System.out.println("Testing myTop method in Down class");
}
public static void main(String [] args) {
Top t = new Down();
t.myTop();
}
}
3. What is the result of the following program, when you compile and run?
final int x;
public MyTest() {
System.out.println( x + 10 );
}
public static void main( String args[] ) {
MyTest mt = new MyTest();
}
}
4. What is the output when you compile and run the following code fragment?
class MyTest {
5. Select all the exceptions thrown by wait() method of an Object class, which you can replace in
the place of xxx legally?
6. Which of the following are examples of immutable classes , select all correct answer(s)?
A) String
B) StringBuffer
C) Double
D) Integer
7. Select the correct answer for the code fragment given below?
8. What is the result when you compile and run the following code?
A) int100
B) byte
C) aString
D) a-Big-Integer
E) Boolean
F) strictfp
10. Select the equivalent answer for the code given below?
boolean b = true;
if ( b ) {
x = y;
} else {
x = z;
}
A) x = b ? x = y : x = z ;
B) x = b ? y : z ;
C) b = x ? y : z ;
D) b = x ? x = y : x = z ;
12. Consider the following code and select the correct answer?
class Vehicle {
String str ;
public Vehicle() {
}
public Vehicle ( String s ) {
str = s;
}
}
13. Java source files are concerned which of the following are true ?
A) Java source files can have more than one package statements.
B) Contains any number of non-public classes and only one public class
C) Contains any number of non-public classes and any number of public classes
D) import statements can appear anywhere in the class
E) Package statements should appear only in the first line or before any import statements of source file
int a = -1;
int b = -1;
a = a >>> 31;
b = b >> 31;
A) a = 1, b =1
B) a = -1, b -1
C) a = 1, b = 0
D) a = 1, b = -1
15. What is the value of a , when you compile and run the following code?
int a = 10;
int b = 9;
int c = 7;
a = a ^ b ^ c;
System.out.println ( a );
A) 10
B) 9
C) 7
D) 4
16. The following code has some errors, select all the correct answers from the following?
A) At class declaration
B) myTest() method declaration
C) Test() method declaration
D) No errors, compiles successfully
17. At what point the following code shows compile time error?
class A {
A() {
System.out.println("Class A constructor");
}
}
class B extends A {
B() {
System.out.println("Class B constructor");
}
}
18. Which of the following statements would return false? if given the following statements.
A) s == s1
B) s.equals(s1);
C) s = s1;
D) None of the above
19. Select all correct answers about what is the definition of an interface?
A) It is a blue print
B) A new data type
C) Nothing but a class definition
D) To provide multiple inheritance
20. Select all correct answers from the following code snippets?
A) // Comments
import java.awt.*;
package com;
B) import java.awt.*;
// Comments
package com;
C) package com;
import java.awt.*;
// Comments
D) // Comments
package com;
import java.awt.*;
public class MyTest {}
21. What is the result when you compile and run the following code?
A) Prints 0 to 9 in sequence
B) No output
C) Runtime error
D) Compile time error
22. There are two computers are connected to internet, one computer is trying to open a socket
connection to read the home page of another computer, what are the possible exceptions thrown
while connection and reading InputStream?.
A) IOException
B) MalformedURLException
C) NetworkException
D) ConnectException
23. What is the result from the following code when you run?
import java.io.*;
class A {
24. What is the result from the following code when you run?
import java.io.*;
class A {
A() {
System.out.println ("Executing class A constructor");
}
A(int a) throws Exception {
System.out.println ("Executing class A constructor");
throw new IOException();
}
25. What is the result when you compile and run the following code?
27. Which subclasses of the Component class will display the MenuBar?
A) Window, Applet
B) Applet, Panel
C) Frame
D) Menu, Dialog
A) java.awt.TextArea.SCROLLBARS_NONE
B) java.awt.TextArea does not generate Key events
C) java.awt.TextField generates Key events and Action events
D) java.awt.TextArea can be scrolled using the <-- and --> keys.
31. What is the result if you try to compile and run the following code ?
}
public static void main(String[] args) {
myTest();
myMethod();
}
import java.io.*;
}
}
import java.io.*;
class FileWrite {
public static void main(String args[]) {
try {
String strString = "Now is the time to take Sun Certification";
char buffer[] = new char[strString.length()];
strString.getChars(0, strString.length(), buffer, 0);
FileWriter f = new FileWriter("MyFile1.txt");
FileWriter f1 = f;
f1.close();
for (int i=0; i < buffer.length; i += 2) {
f.write(buffer[i]);
}
f.close();
34. Which line of the program could be throwing an exception, if the program is as listed below.
Assume that "MyFile2.txt" is a read only file.
import java.io.*;
class FileWrite {
public static void main(String args[]) {
try {
String strString = "Updating the critical data section"
char buffer[] = new char[strString.length()];
strString.getChars(0, strString.length(), buffer, 0);
FileWriter f = new FileWriter("MyFile1.txt");
FileWriter f1 = f;
for (int i=0; i < buffer.length; i += 2) {
f1.write(buffer[i]);
}
f1.close();
36. Using File class, you can navigate the different directories and list all the files in the those
directories?
A) True
B) False
A) FileOutputStream(FileDescriptor fd)
B) FileOutputStream(String fileName, boolean append)
C) FileOutputStream(RandomAccessFile raFile)
D) FileOutputStream( String dirName, String filename)
39. In an applet programing the requirement is that , what ever the changes you do in the applets
graphics context need to be accumulated to the previous drawn information. Select all the correct
code snippets?
41. Which of the following answers can be legally placed in the place of XXX?
class Check {
Check() { }
}
if ( o instanceof XXX) {
System.out.println("True");
}
}
42. There are 20 threads are waiting in the waiting pool with same priority, how can you invoke
15th thread from the waiting pool?.
44. The thread run() method has the following code, what is the result when the thread runs?
try {
sleep( 200 );
System.out.println( "Printing from thread run() method" );
} catch ( IOException ie) { }
45. What is the result when you compile and run the following code?
import java.awt.*;
A) Double
B) Boolean
C) Integer
D) Byte
D) Math.round(3.4) returns 3
Math.round(-3.4) returns -------
51. Select from the following which is legal to put in the place of XXX?
52. If you save and compile the following code, it gives compile time error. How do you correct the
compile time error?
54. What is the result when you compile and run the following code?
import java.util.*;
public class MyVector {
55. What is the output on the screen when compile and run the following code?
A) 1
B) 2
C) -1
D) -2
A) AWTEvent
B) EventObject
C) InputEvent
D) MouseEvent
A) As a HashMap
B) As a Queue
C) As a TreeSet
D) As a Stack
A) Compilation error
B) Runtime error
C) Compile successfully, nothing is printed.
D) inside throwMethod. followed by caught: java.lang.IllegalAccessException: demo
Answers
Answer 1:
Explanation:
Generally static methods can be overridden by static methods only .. Static methods may not be overridden by
non static methods..
Answer 2:
Explanation:
Answer C) will cause an "ArrayOutOfBoundsException" if you do not pass the command line arguments to the
Java Program. A) and B) will work without any problem.
Answer 3:
Explanation:
The final variables behaves like constants, so the final variables must be initialized before accessing them. They
can be initialized where they are declared or in every "constructor" if the class. ( even if class has one or more
constructors defined ).
Answer 4:
B) Printing myTest in Test class followed by Printing myStat in MyTest class
Explanation:
Static methods are determined at compile time but the non static ( instance methods ) methods are identified at
runtime using Run Time Type Identification ( RTTI).
Answer 5:
Explanation:
The wait() method of an Object class throws InterruptedException when the thread moving from running state
to wait state. If the value of timeout is negative or the value of nanos is not in the range 0-999999 then wait()
method throws IllegalArgumentException exception at runtime. If the current thread is not the owner of this
object's monitor then it throws IllegalMonitorStateException exception. Click here for more information from
Java Documentation.
Answer 6:
A) String
C) Double
D) Integer
Explanation:
String, Integer, Double are immutable classes, once assign a values it cannot be changed. Please refer the
wrapper classes for more information on Integer, and Double.
Answer 7:
Explanation:
Assigning or interchanging the object references does not change the values, but if you change the values
through object references , changes the values .
Answer 8:
B) Runtime error
C) ArrayOutOfBoundsException
Explanation:
This piece of code throws an ArrayOutOfBoundsException at runtime . If you modify the code int myArray[] =
new int[1]; to int myArray[] = new int[2]; , it prints 1 on the screen. The changes you made on the array
subscript seen by the caller.
Answer 9:
A) int 100
C) aString
E) Boolean
Explanation:
The byte, strictfp are Java keywords and cannot be defined as identifiers, the a-Big-Integer has "-" which is not
a valid identifier. The identifiers must starts with letters, $, or _ ( underscore), subsequent characters may be
letters, dollar signs, underscores or digits, any other combination will gives you the compiler error.
Answer 10:
B) x = b ? y : z ;
Explanation
If b is true the value of x is y, else the value is z. This is "ternary" operator provides the way to simple
conditions into a single expression. If the b is true, the left of ( : ) is assigned to x else right of the ( : ) is
assigned to x. Both side of the ( : ) must have the data type.
Answer 11:
Explanation:
Multidimensional arrays in Java are just arrays within arrays. Multidimensional arrays are defined as rows and
columns. The outer array must be initialized. If you look at the answers the outer arrays are initialized.
Answer 12:
Explanation:
In Java final variables are treated as constants ( comparing to other languages like Visual Basic and etc.) , once
it is initialized you cannot change the values of primitive, if final variables are object references then you cannot
assign any other references.
Answer 13:
B) Contains any number of non-public classes and only one public class
E) Package statements should appear only in the first line or before any import statements of source file
Explanation:
The source files always contains only one package statement, you cannot define multiple package statements
and these statements must be before the import statements. At any point of time Java source files can have any
number of non-public class definitions and only one public definition class. If you have any import statements
those should be defined before class definition and after the package definition.
Answer 14:
D) a = 1, b = -1
Explanation:
The operator >>> is unsigned right shift, the new bits are set to zero, so the -1 is shifted 31 times and became
1 ( because a is defined as integer ). The operator >> is signed right shift operator, the new bits take the value
of the MSB ( Most Significant Bit ) . The operator << will behave like same as >>> operator. The sifting
operation is applicable to only integer data types.
Answer 15:
D) 4
Explanation:
The operator is bitwise XOR operator. The values of a, b, c are first converted to binary equivalents and
calculated using ^ operator and the results are converted back to original format.
Answer 16:
Explanation:
The abstract methods cannot have body. In any class if one method is defined as abstract the class should be
defined as abstract class. So in our example the Test() method must be redefined.
Answer 17:
Explanation:
According to the inheritance rules, a parent class references can appear to the child class objects in the
inheritance chain from top to bottom. But in our example class B, and class C are in the same level of hierarchy
and also these two classes does not have parent and child relationship which violates the inheritance rules.
Answer 18:
A) s == s1
B) s.equals(s1);
Explanation:
The string objects can be compared for equality using == or the equals() method ( even though these two have
different meaning ). In our example the string objects have same wording but both are different in case. So the
string object object comparison is case sensitive.
Answer 19:
A) It is a blue print
B) A new data type
D) To provide multiple inheritance
Explanation:
One of the major fundamental change in Java comparing with C++ is interfaces. In Java the interfaces will
provide multiple inheritance functionality. In Java always a class can be derived from only one parent, but in
C++ a class can derive from multiple parents.
Answer 20:
C) package com;
import java.awt.*;
// Comments
D) // Comments
package com;
import java.awt.*;
public class MyTest {}
Explanation
In a given Java source file, the package statement should be defined before all the import statement or the first
line in the .java file provided if you do not have any comments or JavacDoc definitions. The sequence of
definitions are:
// Comments ( if any)
Package definition
Multiple imports
Class definition
Answer 21:
Explanation:
The code fails at the time Math class instantiation. The java.lang.Math class is final class and the default
constructor defined as private. If any class has private constructors , we cannot instantiate them from out the
class ( except from another constructor ).
Answer 22:
A) IOException
B) MalformedURLException
Explanation:
In Java the the URL class will throw "MalformedURLException while construncting the URL, and while reading
incoming stream of data they will throw IOException..
Answer 23:
Explanation:
In Java the constructors can throw exceptions. If parent class default constructor is throwing an exception, the
derived class default constructor should handle the exception thrown by the parent.
Answer 24:
Explanation:
In Java the constructors can throw exceptions. According to the Java language exceptions, if any piece of code
throwing an exception it is callers worry is to handle the exceptions thrown by the piece of code. If parent class
default constructor is throwing an exception, the derived class default constructor should handle the exception
thrown by the parent. But in our example the non default constructor is throwing an exception if some one calls
that constructor they have to handle the exception.
Answer 25:
C) Compile time error while multiplication
Explanation:
This does not compile because according to the arithmetic promotion rules, the * ( multiplication ) represents
binary operator. There are four rules apply for binary operators. If one operand is float,double,long then other
operand is converted to float,double,long else the both operands are converted to int data type. So in our
example we are trying put integer into byte which is illegal.
Answer 26:
Explanation:
The component class is the parent class of all AWT components like Button, List, Label and etc. Using these
methods you can set the properties of components. The add(), remove() methods are used to add PopMenu and
to remove MenuComponent.
Answer 27:
C) Frame
Explanation:
Java supports two kinds of menus, pull-down and pop-up menus. Pull-down menus are accessed are accessed
via a menu bar. Menu bars are only added to Frames.
Answer 28:
Explanation:
In Java AWT each container has it's own default layout manager implemented as part of implementation. For
example Frame has default layout manager is BorderLayout , Applet has FlowLayout and etc. The Canvas is kind
of component where you can draw custom drawings. The Canvas generates Mouse, MouseMotion, and Key
events .
Answer 29:
Explanation:
The java.awt.List has methods to select , count the visible rows.
void addItem(String s) --> adds an item to the bottom of the list
int getRows() --> returns the number of visible lines in the list
int[] getSelectedIndexes() --> returns array of indexes currently selected items
int getItemCount() --> returns the number of items in the list
String[] getSelectedItems() --> returns array of string values of currently selected items
Answer 30:
A) java.awt.TextArea.SCROLLBARS_NONE
C) java.awt.TextField generates Key events and Action events
D) java.awt.TextArea can be scrolled using the <-- and --> keys.
Explanation:
The TextArea and TextField are the subclasses of TextComponent class. The TextArea has static fields to give
you the functionality of horizontal and vertical scroll bars. These are the following fields:
java.awt.TextArea.SCROLLBARS_BOTH
java.awt.TextArea.SCROLLBARS_NONE
java.awt.TextArea.SCROLLBARS_HORIZONTAL_ONLY
java.awt.TextArea.SCROLLBARS_VERTICAL_ONLY
The TextArea and TextField will generate Key events and TextField will generate Action events apart from the
Key events.
Answer 31:
Explanation:
In Java there are two types of methods , static and non static methods. Static methods are belong to class and
non static methods are belongs to instances. So from a non static method you can call static as well as static
methods, but from a static method you cannot call non static methods ( unless create a instance of a class ) but
you can call static methods.
Answer 32:
Explanation:
While constructing the FileReader object, if the file is not found in the file system the "FileNotFoundException" is
thrown. If the input stream is closed before reading the stream throws IOException.
Answer 33:
Explanation:
While writing to a IO stream if the stream is closed before writing throws an IOException. In our example the f
( stream ) is closed via f1 reference variable before writing to it.
Answer 34:
Explanation:
Constructing the FileWriter object, if the file already exists it overrides it (unless explicitly specified to append to
the file). FileWriter will create the file before opening it for output when you create the object. In the case of
read-only files, if you try to open and IOException will be thrown.
Answer 35:
Explanation:
The File class has three methods to create empty files, those are createNewFile(), createTempFile(String prefix,
String suffix) and createTempFile(String prefix, String suffix, File directory).
File class has two utility methods mkdir() and mkdirs() to create directories. The mkdir() method creates the
directory and returns either true or false. Returning false indicates that either directory already exists or
directory cannot be created because the entire path does not exists. In the situation when the path does not
exists use the mkdirs() method to create directory as well as parent directories as necessary.
Answer 36:
A) True
Explanation:
File class can be used to navigate the directories in the underlying file system. But in the File class there is no
way you change the directory . Constructing the File class instance will always point to only one particular
directory. To go to another directory you may have to create another instance of a File class.
Answer 37:
A) FileOutputStream(FileDescriptor fd)
B) FileOutputStream(String fileName, boolean append)
Explanation:
The valid FileOutputStream constructors are:
FileOutputStream(String fileName)
FileOutputStream(File file)
FileOutputStream(FileDescriptor fd)
FileOutputStream(String fileName, boolean append)
Answer 38:
Explanation:
The Font class gives you to set the font of a graphics context. While constructing the Font object you pass font
name, style, and size of the font. The font availability is dependent on platform. The Font class has three types
of font names called " Serif", "SanSerif", Monospaced" these are called in JDK 1.1 and after "Times Roman",
Helavatica" and "Courier".
Answer 39:
Explanation:
If you want accumulate the previous information on the graphics context override the update() and inside the
method call the paint() method by passing the graphics object as an argument. The repaint() method always
calls update() method
Answer 40:
Explanation:
The Applet and Toolkit classes has a method getImage() , which has two forms:
getImage(URL file)
getImage(URL dir, String file)
These are two ways to refer an image in the server . The Applet class getDocumentBase() methods returns the
URL object which is your url to the server where you came from or where your image resides.
Answer 41:
Explanation:
The instanceof operator checks the class of an object at runtime. In our example o refers to Object class and
Check and ICheck refers to the subclasses of Object class. Due to the inheritance hierarchy Check and ICheck
returns true.
Answer 42:
Explanation:
There is no way to call a particular thread from a waiting pool. The methods notify() will calls thread from
waiting pool, but there is no guaranty which thread is invoked. The method notifyAll() method puts all the
waiting threads from the waiting pool in ready state.
Answer 43:
Explanation:
The keyword controls accessing the single resource from multiple threads at the same time. A method or a piece
of code can be synchronized, but there is no way to synchronize a calls. To synchronize a method use
synchronized keyword before method definition. To synchronize block of code use the synchronized keyword and
the arbitrary instance.
Answer 44:
Explanation:
The IOException never thrown here. The exception is thrown is InterruptedException. To correct instead of
catching IOException use InterruptedException.
Answer 45:
Explanation:
The Frame is not going to be visible unless you call setVisible(true) method on the Frame's instance. But the
frame instance is available in computers memory. If do not set the size of the Frame you see default size of the
frame ( i.e.. in minimized mode)
Answer 46:
Explanation:
The abstract methods does not have method bodies. In any given class if one method is defined as abstract the
class must defined as abstract class.
Answer 47:
Explanation:
The toString() is defined in Object class the parent all classes which will gives you the string representation of
the object's state. This more useful for debugging purpose. The wait(), notify(), notifyAll() methods are also
defined in Object class are very helpful for Thread communication. These methods are called only in
synchronized methods.
Answer 48:
Explanation:
To define transient variables just include "transient" keyword in the variable definition. The transient variables
are not written out any where, this is the way when you do object serialization not to write the critical data to a
disk or to a database.
The "synchronized" keyword controls the single resource not to access by multiple threads at the same time.
The synchronized keyword can be applied to a method or to a block of code by passing the arbitrary object
instance name as an argument.
Answer 49:
A) Double
C) Integer
D) Byte
Explanation:
In Java all the primitive data types has wrapper classes to represent in object format and will throw
"NumberFormatException". The Boolean does not throw "NumberFormatException" because while constructing
the wrapper class for Boolean which accepts string also as an argument.
Answer 50:
D) Math.round(3.4) returns 3
Math.round(-3.4) returns -3
Explanation:
The Math class abs() method returns the absolute values, for negative values it just trips off the negation and
returns positive absolute value. This method returns always double value.
The method ceil(), returns double value not less than the integer ( in our case 3 ). The other ways to say this
method returns max integer value . ( All the decimals are rounded to 1 and is added to integer value ). For
negative values it behaves exactly opposite.
The method floor() is exactly reverse process of what ceil() method does.
Answer 51:
Explanation:
The static methods are class level methods to execute those you do not need a class instance. If you try to
execute any non static method or variables from static methods you need to have instance of a class. In our
example we need to have OuterClass reference to execute InnerClass method.
Answer 52:
Explanation:
In Java it is possible to declare a class inside a method. If you do this there are certain rules will be applied to
access the variables of enclosing class and enclosing methods. The classes defined inside any method can access
only final variables of enclosing class.
Answer 53:
C) This is convention adopted by Sun , to insure that there is no ambiguity between packages and inner classes.
Explanation:
This is convention adopted to distinguish between packages and inner classes. If you try to use Class.forName()
method the call will fail instead use getCLass().getName() on an instance of inner class.
Answer 54:
Explanation:
The method in Vector class , addElement() returns type of void which you cannot return in our example. The
myVector() method in our MyVector class returns only type of Vector.
Answer 55:
C) -1
Explanation:
Internally the x value first gets inverted ( two's compliment ) and then shifted 1 times. First when it is inverted
it becomes negative value and shifted by one bit.
Answer 56:
C) InputEvent
Explanation:
The InputEvent class has method getWhen() which returns the time when the event took place and the return
type is long.
Answer 57:
Explanation:
The super class of all event handling is java.util.EventObject which has a method called getSource() , which
returns the object that originated the event.
The subclass of EventObject is AWTEvent has a method getID() , which returns the ID of the event which
specifies the nature of the event.
Answer 58:
Explanation:
The event listeners are instance of the class that implements listener interface . An event source is an instance
of class like Button or TextField that can register listener objects and sends notifications whenever event occurs.
Answer 59:
B) As a Queue
D) As a Stack
Explanation:
This implements java.util.List interface and uses linked list for storage. A linked list allows elements to be added,
removed from the collection at any location in the container by ordering the elements. With this implementation
you can only access the elements in sequentially.You can easily treat the LinkedList as a stack, queue and etc.,
by using the LinkedList methods.
Answer 60:
A) Compilation error
Explanation:
The method throwMethod() is throwing and type Exception class instance, while catching the exception you are
catching the subclass of Exception class.