Page 2 of 2

Re: jscp java certificate exam mock questions and answers

PostPosted: Wed Jul 13, 2011 9:26 am
by haretu
*** ====================
8.1 What is the result when you compile 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. Compiles successfully, nothing is printed.
D. prints : Inside throwMethod. followed by caught: java.lang.IllegalAccessExcption: demo
Answer: A
Note: java.lang.IllegalAccessExcption must be caught or it must be declared in the throws clause of the throwMethod().

***** ===============
8.2 What will happen when you compile and run the following code?
public class MyClass {
public static void main(String args[]) {
byte b = 0;
b += 1;
System.out.println(b);
}
}
A. Compile time error
B. Runtime error
C. 1
D. None of these
Answer: C
Note: If "b += 1" change to "b = b++", it also prints 1.But if it change to "b = b + 1",then compile errer take place,because "b + 1" case to int.

**** =======================
8.3 It is valid to throw (and re-throw) an exception inside a catch{} clause.
For example:
...
catch (Exception e) {
throw e;
}
A. True
B. False
Answer: A
Note: This is valid. It will cause the exception to be passed to the handlers at the next-higher level. All further catch clauses are ignored in the current try block.

***** =====================
8.4 What is the output of the following code?
1. public class Note
2. {
3. public static void main(String args[])
4. {
5. String name[] = {"Killer","Miller"};
6. String name0 = "Killer";
7. String name1 = "Miller";
8. swap(name0, name1);
9. System.out.println(name0 + ", " + name1);
10. swap(name);
11. System.out.println(name[0] + ", " + name[1]);
12. }
13. public static void swap(String name[])
14. {
15. String temp;
16. temp = name[0];
17. name[0] = name[1];
18. name[1] = temp;
19. }
20. public static void swap(String name0, String name1)
21. {
22. String temp;
23. temp = name0;
24. name0 = name1;
25. name1 = temp;
26. }
27. } // end of Class Note
A. Killer, Miller followed by Killer, Miller
B. Miller, Killer followed by Killer, Miller
C. Killer, Miller followed by Miller, Killer
D. Miller, Killer followed by Killer, Miller
Answer: C
Note: In java all parameters are passed by value. In case of primitives, the copy of the variable is passed while case of object references, its the copy of the reference which is passed.

***** ===================
8.5 Comment if the following code implements equals method of Object class correctly? Select the most appropriate answer.
1. public class BetterString
2. {
3. String str;
4.
5. public BetterString(String s)
6. {
7. str = s;
8. }
9.
10. public boolean equals(Object obj)
11. {
12. if(obj instanceof BetterString)
13. {
14. if(obj == this)
15. return true;
16. else
17. return str.equals(obj);
18. }
19. else if(obj instanceof String)
20. {
21. return str.equals(obj);
22. }
23. return false;
24. }
25. }
A. The code implements equals method correctly
B. The code implements equals method correctly, but does not provide any additional feature over the equals method provided by String class
C. The code does not implement equals method correctly
D. The given code does not contain enough information to comment on the correctness of the equals method implementation
E. None of these
Answer: C
Note: The code attempts to provide equals comparison with a String. String is a built in final class in Java. It is inappropriate as well as incorrect to provide an equals comparison with any built in Java class, as it violates "symmetry" requirement mentioned in the general contract of Object's equals method. It says - for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. This is not valid for the above code, because if an object of class BetterString is passed to the equals method of String class, it would result in false;irrespective of its contents.

**** ===================
8.6 A Java monitor must either extend Thread or implement Runnable. True/False?
A. True
B. False
Answer: B
Note: as a monitor is any object that has synchronized code. Thus a Java monitor need not extends Thread class or implement Runnable interface.

*** =====================
8.7 What will be the result of executing the following code?
Given that Test1 is a class.
1. Test1[] t1 = new Test1[10];
2. Test1[][] t2 = new Test1[10][];
3. System.out.println(t2[0][0]);
A. The code will not compile as we are using t2[0][0] without initializing
B. The code will compile and print null
C. The code will compile but throw a runtime exception
D. None of these
Answer: C
Note: In case of arrays initialization is supposed to be complete when we specify the leftmost dimension of the array. The problem occurs at runtime if we try to access an element of the array which has not been initialized (specification of size).

***** =========================
8.8 What will be the result of executing the following code?
int i = 0;
int myArray[] = new int[0];
for (i = 0; i < myArray.length; i++){
System.out.println(myArray[i]);
}
A. The code will not compile as the size of array should be at least 1
B. The code will compile but throw an exception at runtime
C. The code will compile and "0" will be printed
D. None of these
Answer: D
Note: The code will compile and run perfectly fine but it will not print anything. It is perfectly legal in Java to create arrays of size zero. The flow of control will never enter the for loop as the condition at the beginning of for loop is never satisfied. But note that If you directly print "myArray" and not in the for loop,then complie error that ArrayIndexOutOfBoundException(???).

*** ===================
8.9 For what reasons might a thread stop execution?
A. A thread with higher priority began execution.
B. The thread's wait() method was invoked.
C. The thread invoked its yield() method.
D. The thread's pause() method was invoked. //has destroy(), hasn’t pause().
E. The thread's sleep() method was invoked.
Answer: ABCE

**** =======================
8.10 Which of the following can be used for reading the system property named "count"?
The value of this property will be a string representing a number in the range 1 to 1000.
A. Integer.decode("count");
B. Integer.getProperty("count");
C. Integer.getSystemProperty("count");
D. Integer.getInteger("count");
E. Integer.valueOf("count");
Answer: D
Note: The static method getInteger(String propertyName) is of form:
public static Integer getInteger(String nm)
This method returns the integer value of the system property with the specified name.

Re: jscp java certificate exam mock questions and answers

PostPosted: Wed Jul 13, 2011 9:27 am
by haretu
** ==================
9.1 What will be the output when you compile and execute the following program?
class Base extends Thread {
public void run() {
while(true)
System.out.println("Start running..");
}
static public void main(String[] a) {
Base anObj = new Base();
anObj.start();
}
}
A. Start running..
B. Start running..
..............
in an infinite loop
C. Compilation error. Cannot extend Thread class
D. No output
Answer: B

** =======================
9.2 If a thread executes wait(), and subsequently gets notified, it immediately proceeds with execution of the code that follows the wait() call. True/False?
A. True
B. False
Answer: B

***** =======================
9.3 Will there be any problem in a multi-threaded context if only local variables are declared in a method?
A. Yes, you need synchronized in the blocks of code which read and write a local variable value.
B. Yes, you need synchronized in the blocks of code which read (but not write) a local variable value
C. Absolutely no
D. None of the above.
Answer: C
Note: In case you have local variables (variables declared in a method), then there is no problem of synchronization in a multi-threaded context. The local variables are accessed from the thread's stack, the instance variables are accessed through object references, and static variables are accessed through class or object references. The local variables in the methods that the thread is executing are separate for different threads. There is no way for one thread to access the local variables of another thread. While objects and their instance variables can be shared between threads in a java program, for that one thread needs to pass the object reference to the other thread. The static variables are automatically shared between all threads in a java program.


***** =================
9.4 Which of the following are correct and proper usages of assertions?
A:private void doSomething(int value) {
assert (value > 0 && value < 1000) : "The value must be in the range [1 -999]";
// more code
}
B:public void doSomething(int value) {
assert (value > 0 && value < 1000) : "The value must be in the range [1 -999]";
// more code
}
C:private int doSomething() {
// compute result
assert result > 0 : "Incorrect result";
return result;
}
D:public int doSomething() {
// compute result
assert result > 0 : "Incorrect result";
return result;
}
A. A is a proper usage
B. B is a proper usage
C. C is a proper usage
D. D is a proper usage
Answer: B??????????
Note: This is a very important concept in assertions. Assertions can be used to test preconditions, postconditions and invariants. Java insists that assertions should not be used for testing the preconditions of the public methods. Instead, preconditions on public methods are enforced by explicit checks inside methods resulting in particular, specified exceptions. This is essential for two reasons-
(1) Exceptions can be explicitly mentioned in the throws cause of the method, and checked exceptions must be caught while invoking the method.
(2) Assertions can be disabled while running the code.
However, postcondition checks are best implemented via assertions, whether or not they are specified in public methods.

**** ==================
9.5 Which of the following can be inserted at line 12 so that the code compiles and prints the odd numbers in the given range?
1. import java.util.ArrayList;
2.
3. public class OddNumbers
4. {
5. public static void main(String args[])
6. {
7. ArrayList oddNumbers = new ArrayList();
8. for(int i=0;i < 10;i++)
9. {
10. if(i%2 == 0)
11. continue;
12. // what should be inserted here?
13. oddNumbers.add(number);
14. System.out.println(number);
15. }
16. }
17. }
A. int number = i;
B. Integer number = new Integer(i);
C. Byte number = new Byte(i);
D. Integer number = Integer.parseInt("" + i);
E. Object number = new Integer(i);
Answer: BE

** =====================
9.6 What will happen when you attempt to compile and run the following code?
interface MyInterface{
int x = 0;
int myMethod(int x);
}
class MyImplementation implements MyInterface{
public int myMethod(int x){
return super.x;
}
}
public class MyTest{
public static void main(String args[]) {
MyInterface mi = new MyImplementation();
System.out.println(mi.myMethod(10));
}
}
A. 0
B. 10
C. Compilation error
D. None of the above
Answer: The statement "super.x;" inside myMethod() will cause compilation error as the super class of MyImplementation class (Object class) doesn't define variable x. Please note that MyInterface is not the super class of MyImplementation class as referred by super.x.

**** =========================
9.7 What is displayed when the following piece of code is executed?
class Test extends Thread{
public void run(){
System.out.println("1");
yield();
System.out.println("2");
suspend();
System.out.println("3");
resume();
System.out.println("4");
}
public static void main(String []args) {
Test t = new Test();
t.start();
}
}
A. 1 2 3 4
B. 1 2 3
C. 1 2
D. Nothing. This is not a valid way to create and start a thread.
E. 1
Answer: C
Note: The code will run, but the thread suspends itself after displaying "2". Threads cannot un-suspend themselves (since they ARE suspended and therefore not running!).

** =======================
9.8 Consider the following code fragment, and select the correct statements(s).
1. public class Test extends MyBase implements MyInterface
2. {
3. int x = 0;
4.
5. public Test(int inVal) throws Exception
6. {
7. if (inVal != this.x)
8. {
9. throw new Exception("Invalid input");
10. }
11. }
12.
13. public static void main(String args[])
14. {
15. Test t = new Test(4);
16. }
17. }
A. The code fails to compile at line 1. It is not valid to both implement an interface and extend from a parent class simultaneously.
B. The code fails to compile at line 5. It is not valid for constructors to throw exceptions.
C. The code fails to compile at line 9, because this is not valid way to throw an exception.
D. The code fails to compile at line 15. The compiler complains that there is an uncaught exception.
E. The code fails to compile at line 7, because this is not a valid way to reference variable x.
Answer: D

**** ===================
9.9 The default implementation of equals() method in Object class does not perform "deep" comparison. State true or false.
A. True
B. False
Answer: A

Re: jscp java certificate exam mock questions and answers

PostPosted: Tue Jul 26, 2011 2:15 pm
by haretu
Which declaration of the main method below would allow a class to be started as a standalone program. Select the one correct answer.
public static int main(char args[])
public static void main(String args[])
public static void MAIN(String args[])
public static void main(String args)
public static void main(char args[])
What all gets printed when the following code is compiled and run? Select the three correct answers.

public class xyz {
public static void main(String args[]) {
for(int i = 0; i < 2; i++) {
for(int j = 2; j>= 0; j--) {
if(i == j) break;
System.out.println("i=" + i + " j="+j);
}
}
}
}

i=0 j=0
i=0 j=1
i=0 j=2
i=1 j=0
i=1 j=1
i=1 j=2
i=2 j=0
i=2 j=1
i=2 j=2
What gets printed when the following code is compiled and run with the following command -
java test 2
Select the one correct answer.

public class test {
public static void main(String args[]) {
Integer intObj=Integer.valueOf(args[args.length-1]);
int i = intObj.intValue();

if(args.length > 1)
System.out.println(i);
if(args.length > 0)
System.out.println(i - 1);
else
System.out.println(i - 2);
}
}


test
test -1
0
1
2
In Java technology what expression can be used to represent number of elements in an array named arr ?
How would the number 5 be represented in hex using up-to four characters.
Which of the following is a Java keyword. Select the four correct answers.
extern
synchronized
volatile
friend
friendly
transient
this
then
Is the following statement true or false. The constructor of a class must not have a return type.
true
false
What is the number of bytes used by Java primitive long. Select the one correct answer.
The number of bytes is compiler dependent.
2
4
8
64
What is returned when the method substring(2, 4) is invoked on the string "example"? Include the answer in quotes as the result is of type String.
Which of the following is correct? Select the two correct answers.
The native keyword indicates that the method is implemented in another language like C/C++.
The only statements that can appear before an import statement in a Java file are comments.
The method definitions inside interfaces are public and abstract. They cannot be private or protected.
A class constructor may have public or protected keyword before them, nothing else.
What is the result of evaluating the expression 14 ^ 23. Select the one correct answer.
25
37
6
31
17
9
24
Which of the following are true. Select the one correct answers.
&& operator is used for short-circuited logical AND.
~ operator is the bit-wise XOR operator.
| operator is used to perform bitwise OR and also short-circuited logical OR.
The unsigned right shift operator in Java is >>.
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.
Which of the following is true. Select the two correct answers.
A class that is abstract may not be instantiated.
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++.
A static variable indicates there is only one copy of that variable.
A method defined as private indicates that it is accessible to all other classes in the same package.
What all gets printed when the following program is compiled and run. Select the two correct answers.


public class test {
public static void main(String args[]) {
int i, j=1;
i = (j>1)?2:1;
switch(i) {
case 0: System.out.println(0); break;
case 1: System.out.println(1);
case 2: System.out.println(2); break;
case 3: System.out.println(3); break;
}
}
}


0
1
2
3

What all gets printed when the following program is compiled and run. Select the one correct answer.


public class test {
public static void main(String args[]) {
int i=0, j=2;
do {
i=++i;
j--;
} while(j>0);
System.out.println(i);
}
}


0
1
2
The program does not compile because of statement "i=++i;"
What all gets printed when the following gets compiled and run. Select the three correct answers.

public class test {
public static void main(String args[]) {
int i=1, j=1;
try {
i++;
j--;
if(i/j > 1)
i++;
}
catch(ArithmeticException e) {
System.out.println(0);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println(1);
}
catch(Exception e) {
System.out.println(2);
}
finally {
System.out.println(3);
}
System.out.println(4);
}
}


0
1
2
3
4
What all gets printed when the following gets compiled and run. Select the two correct answers.


public class test {
public static void main(String args[]) {
int i=1, j=1;
try {
i++;
j--;
if(i == j)
i++;
}
catch(ArithmeticException e) {
System.out.println(0);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println(1);
}
catch(Exception e) {
System.out.println(2);
}
finally {
System.out.println(3);
}
System.out.println(4);
}
}


0
1
2
3
4
What all gets printed when the following gets compiled and run. Select the two correct answers.


public class test {
public static void main(String args[]) {
String s1 = "abc";
String s2 = "abc";
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);
}
}


1
2
3
4
What all gets printed when the following gets compiled and run. Select the two correct answers.


public class test {
public static void main(String args[]) {
String s1 = "abc";
String s2 = new String("abc");

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);
}
}


1
2
3
4
Which of the following are legal array declarations. Select the three correct answers.
int i[5][];
int i[][];
int []i[];
int i[5][5];
int[][] a;
What is the range of values that can be specified for an int. Select the one correct answer.
The range of values is compiler dependent.
-231 to 231 - 1
-231-1 to 231
-215 to 215 - 1
-215-1 to 215
How can you ensure that the memory allocated by an object is freed. Select the one correct answer.
By invoking the free method on the object.
By calling system.gc() method.
By setting all references to the object to new values (say null).
Garbage collection cannot be forced. The programmer cannot force the JVM to free the memory used by an object.
What gets printed when the following code is compiled and run. Select the one correct answer.


public class test {
public static void main(String args[]) {
int i = 1;
do {
i--;
} while (i > 2);
System.out.println(i);
}
}


0
1
2
-1
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 the one correct answer.
void m() throws IOException{}
void m() throw IOException{}
void m(void) throws IOException{}
m() throws IOException{}
void m() {} throws IOException
Which of the following are legal identifier names in Java. Select the two correct answers.
%abcd
$abcd
1abcd
package
_a_long_name
At what stage in the following method does the object initially referenced by s becomes available for garbage collection. Select the one correct answer.


void method X() {
String r = new String("abc");
String s = new String("abc");
r = r+1; //1
r = null; //2
s = s + r; //3
} //4


Before statement labeled 1
Before statement labeled 2
Before statement labeled 3
Before statement labeled 4
Never.
String s = new String("xyz");
Assuming the above declaration, which of the following statements would compile. Select the one correct answer.
s = 2 * s;
int i = s[0];
s = s + s;
s = s >> 2;
None of the above.
Which of the following statements related to Garbage Collection are correct. Select the two correct answers.
It is possible for a program to free memory at a given time.
Garbage Collection feature of Java ensures that the program never runs out of memory.
It is possible for a program to make an object available for Garbage Collection.
The finalize method of an object is invoked before garbage collection is performed on the object.
If a base class has a method defined as
void method() { }
Which of the following are legal prototypes in a derived class of this class. Select the two correct answers.
void method() { }
int method() { return 0;}
void method(int i) { }
private void method() { }
In which all cases does an exception gets generated. Select the two correct answers.

int i = 0, j = 1;
if((i == 0) || (j/i == 1))
if((i == 0) | (j/i == 1))
if((i != 0) && (j/i == 1))
if((i != 0) & (j/i == 1))
Which of the following statements are true. Select the two correct answers.
The wait method defined in the Thread class, can be used to convert a thread from Running state to Waiting state.
The wait(), notify(), and notifyAll() methods must be executed in synchronized code.
The notify() and notifyAll() methods can be used to signal and move waiting threads to ready-to-run state.
The Thread class is an abstract class.
Which keyword when applied on a method indicates that only one thread should execute the method at a time. Select the one correct answer.
transient
volatile
synchronized
native
static
final
What is the name of the Collection interface used to represent elements in a sequence (in a particular order). Select the one correct answer.
Collection
Set
List
Map
Which of these classes implement the Collection interface SortedMap. Select the one correct answers.
HashMap
Hashtable
TreeMap
HashSet
TreeSet
Vector
Which of the following are true about interfaces. Select the two correct answers.
Methods declared in interfaces are implicitly private.
Variables declared in interfaces are implicitly public, static, and final.
An interface can extend any number of interfaces.
The keyword implements indicate that an interface inherits from another.
Assume that class A extends class B, which extends class C. Also all the three classes implement the method test(). How can a method in a class A invoke the test() method defined in class C (without creating a new instance of class C). Select the one correct answer.
test();
super.test();
super.super.test();
::test();
C.test();
It is not possible to invoke test() method defined in C from a method in A.
What is the return type of method round(double d) defined in Math class.
What gets written on the screen when the following program is compiled and run. Select the one right answer.

public class test {
public static void main(String args[]) {
int i;
float f = 2.3f;
double d = 2.7;
i = ((int)Math.ceil(f)) * ((int)Math.round(d));

System.out.println(i);
}
}

4
5
6
6.1
9
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.
true
false
Which of these classes defined in java.io and used for file-handling are abstract. Select the two correct answers.
InputStream
PrintStream
Reader
FileInputStream
FileWriter
Name the collection interface used to represent collections that maintain unique elements.
What is the result of compiling and running the following program.

public class test {
public static void main(String args[]) {
String str1="abc";
String str2="def";
String str3=str1.concat(str2);

str1.concat(str2);
System.out.println(str1);
}
}

abc
def
abcabc
abcdef
defabc
abcdefdef
Select the one correct answer. The number of characters in an object of a class String is given by
The member variable called size
The member variable called length
The method size() returns the number of characters.
The method length() returns the number of characters.
Select the one correct answer. Which method defined in Integer class can be used to convert an Integer object to primitive int type.
valueOf
intValue
getInt
getInteger
Name the return type of method hashCode() defined in Object class, which is used to get the unique hash value of an Object.


Which of the following are correct. Select the one correct answer.
An import statement, if defined, must always be the first non-comment statement of the file.
private members are accessible to all classes in the same package.
An abstract class can be declared as final.
Local variables cannot be declared as static.
Name the keyword that makes a variable belong to a class, rather than being defined for each instance of the class. Select the one correct answer.
static
final
abstract
native
volatile
transient
Which of these are core interfaces in the collection framework. Select the one correct answer.
Tree
Stack
Queue
Array
LinkedList
Map
Which of these statements are true. Select the two correct answers.
For each try block there must be at least one catch block defined.
A try block may be followed by any number of finally blocks.
A try block must be followed by at least one finally or catch block.
If both catch and finally blocks are defined, catch block must precede the finally block.

Answers to Sample Test 1
b
b, c, f
d. Note that the program gets one command line argument - 2. args.length will get set to 1. So the condition if(args.length > 1) will fail, and the second check if(args.length > 0) will return true.
arr.length
Any of these is correct - 0x5, 0x05, 0X05, 0X5
b, c, f, g
a
d
"am"
a, c. Please note that b is not correct. A package statement may appear before an import statement. A class constructor may be declared private also. Hence d is incorrect.
a
a
protected
a, c
b, c
c
a, d, e
d, e
a, c
b, c
b, c, e
b
d
a
a
b, e . The option c is incorrect because a Java identifier name cannot begin with a digit.
d
c
c, d
a, c
b, d
b, c
c
c
c
b, c
f
long
e
a
a, c
Set
a
d
b
int
d
a
f
c, d