Sun Certified Java Programmer(SCJP 1.4)
1 Which of the following can prevent a thread from executing?
(1) A call to its pause method
(2) A call to Thread.yield()
(3) Another thread is given higher priority
(4) A call to its halt() method
Answer : -------------------------
2 Which of the following represent correct syntax for assertions?
(1) assertion(b==false);
(2) assert (b==false);
(3) assert() b==false;
(4) if(b!=true) assert;
Answer : -------------------------
3
What will happen if you attempt to compile and run the following code?
public class Master{
boolean bContinue=false;
public static void main(String argv[]){
Master m = new Master();
m.go();
}
public void go(){
Slave s = new Slave(this);
Thread t1 = new Thread(s);
t1.start();
while(bContinue==false){
}
s.setPrice(200);
}
}
class Slave implements Runnable{
int iPrice =100;
Master master;
Slave(Master m){
master=m;
}
synchronized public void setPrice(int iM){
iPrice=iM;
}
synchronized public void run(){
master.bContinue=true;
while(true){
System.out.println(iPrice);
}
}
}
(1) Compilation but no output as the run method of slave is not correct
(2) Compilation and output of 100 several times followed by 200 several times
(3) Compilation and repeated output of 100
(4) Compile time error, while cannot be given an unconditional boolean value
Answer : -------------------------
4 What will happend when you attempt to compile and run the following code?
public class Tux extends Thread{
static String sName = "Techno";
public static void main(String argv[]){
Tux t = new Tux();
t.name(sName);
System.out.println(sName);
}
public void name(String sName){
sName = sName + " park";
start();
}
public void run(){
for(int i=0;i < 4; i++){
sName = sName + " " + i;
}
}
}
(1) Compile time error
(2) Compilation and output of "Techno park"
(3) Compilation and output of "Techno park 0 1 2 3"
(4) Compilation and probably output of "Techno" but possible output of "Techno 0 1 2 3"
Answer : -------------------------
5 Which of the following require explicit try/catch exception handling by the programmer?
(1) Traversing each member of an array
(2) Attempting to open a file
(3) Attempting to open a network socket
(4) Accessing a method in other clas
Answer : -------------------------
6 What will be the result when you attempt to compile this program?
public class RandomExample{
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 : -------------------------
7 Which of the following statements are true?
(1) The vaue of the Integer class can be changed using the = operator
(2) The value of the Integer class can be changed using the setValue method
(3) The value of the Integer class can be changed using the setInt method
(4) Once assigned the value of an instance of Integer cannot be changed
Answer : -------------------------
8 What will happen when you attempt to compile and run the following code?
import java.util.*;
public class TechnoExample{
public static void main(String argv[]){
TechnoExample junk = new TechnoExample();
junk.sampleMap();
}
public void sampleMap(){
TreeMap tm = new TreeMap();
tm.put("a","Bill");
tm.put("b","Kathy");
tm.put("c","Carl");
Iterator it = tm.keySet().iterator();
while(it.hasNext()){
System.out.print(tm.get(it.next()));
}
}
}
(1) Compile time error, a19 cannot be used as a method name
(2) Compilation and output of BillKathyCarl
(3) Compilation and output of BillCarlKathy
(4) Compilation and output of abc
Answer : -------------------------
9 What will happen when you attempt to compile and run the following code?
class Biddy{
public Biddy(){
System.out.print(" Biddy ");
}
}
class Val extends Biddy{
public Val(){
System.out.print(" Val ");
}
}
public class BluePeter extends Val{
public static void main(String argv[]){
BluePeter bp = new BluePeter();
bp.shep(3);
}
public void shep(float i){
System.out.println(i);
}
}
(1) Compilation and output of Val Biddy 3
(2) Compilation and output of Val Biddy 3.0
(3) Compilation and output of Biddy Val 3.0
(4) Compile time error, wrong parameter type passed to method shep
Answer : -------------------------
10 which of the following statements are true of the ArrayList class?
(1) It can store primitive or references as elements
(2) It implements the List interface
(3) It has a get(int index) method which returns the element at the specified position in the
list
(4) The elements are ordered but not sorted
Answer : -------------------------
11 What will happen when you attempt to compile and run the following code?
class Base{
public int iAcres=3;
}
public class Mfields extends Base{
private int iAcres=3.5;
public static void main(String args[]){
Base mf = new Mfields();
System.out.println(mf.iAcres);
}
}
(1) Compile time error
(2) Compilation and output fo 3.5
(3) Compilation and output of 3
(4) Compilation but no output at runtime
Answer : -------------------------
12 Which of the following statements are true?
(1) A variable declared as public within a method will always be visible from code anywhere
else in the class
(2) A variable declared as public at class level will always be visible from code anywhere
else in the class
(3) A method with no visibility modifier can be less visible than one declared with the
protected modifier
(4) Only one copy will ever exist of a method variable declared as static
Answer : -------------------------
13 Which of the following are valid uses of the assert statement?
(1) assert();
(2) assert {
int > 0;
}
(3) assert(iMonth < 12);
(4) assert (iAge = 0);
Answer : -------------------------
14 At what point will the object created on line 8 be eligible for garbage collection?
1 public class RJMould{
2 StringBuffer sb;
3 public static void main(String argv[]){
4 RJMould rjm = new RJMould();
5 rjm.kansas();
6 }
7 public void kansas(){
8 sb = new StringBuffer("Manchester");
9 StringBuffer sb2 = sb;
10 StringBuffer sb3 = new StringBuffer("Chester");
11 sb=sb3;
12 sb3=null;
13 sb2=null;
14 }
15 }
(1) Line 11
(2) Line 9
(3) Line 12
(4) Line 13
Answer : -------------------------
15 What will happen when you attempt to compile and run the following code?
public class HarHam{
public static void main(String argv[]){
HarHam hh = new HarHam();
hh.go();
}
public void go(){
String har = new String ("har");
String ham = new String("har");
collar:
for(int i=0; i < 2 ; i ++){
if(har==ham){
break collar;
}
if(i > 0){
continue collar;
}
System.out.print(i);
} // for i
}
}
(1) Compile time error, System.out has no print method
(2) No output at runtime
(3) Output of 0
(4) Compile error, break cannot occur after its target label
Answer : -------------------------
16 What will happen when you attempt to compile the following code?
protected class Wmid{
private Wmid(String sName){
System.out.println("Wmid");
}
Wmid(){}
}
public class Ombers extends Wmid{
public static void main(String argv[]){
Ombers o = new Ombers();
}
}
(1) Compile time error, class Wmid may not be marked as protected
(2) Compile time error, a constructor may not be marked as private
(3) Compilation and output of Wmid
(4) Compilation but no output
Answer : -------------------------
17 What will happen when you attempt to compile and run the following code?
public class Mickle extends Thread implements Runnable{
public static void main(String argv[]){
Mickle m = new Mickle();
m.start();
}
public void run(){
go();
}
public void go(){
int i;
while(true){
try{
wait();
System.out.println("interrupted");
}catch (InterruptedException e) {}
}
}
}
(1) Compile time error
(2) Compilation but runtime exception
(3) Compilation but no output at runtime
(4) Compilation and output of "interrupted" at runtime
Answer : -------------------------
18 Which of the following statements are true?
(1) A LinkedHashMap preserves the order in which objects are added
(2) A TreeMap ensures that its elements will be in sorted order
(3) Elements in a LinkedList are sorted but not ordered
(4) Collections that implement the List interface allow duplicate elements
Answer : -------------------------
19 Select one correct statement about the following code.
public class TechnoSample {
public static void main(String[] args) {
int i=3;
System.out.println(getBoolean()? i=2*i++:i+++ ++i);
}
public static boolean getBoolean(){
if((int)(Math.random()*2)==0)
return false;
else
return true;
}
}
(1) Prints randomly 6 or 8 at each execution
(2) Prints randomly 7 or 8 at each execution
(3) Always prints 6 at each execution
(4) Prints randomly 6 or 11 at each execution
(5) Compilation error
Answer : -------------------------
20 An ArithmeticException is a checked exception. True Or False?
(1) True
(2) False
Answer : -------------------------
21 Assume the bit pattern of byte x is: 10110001. What will the sign of x be after x >> 2?
Fill with positive Or negative. Caution: No spaces or extra characters.
Answer : -------------------------
22 In a switch statement, the argment to the case label (case argument:) can be any
variable which can fit within an int. True/False?
(1) True
(2) False
Answer : -------------------------
23 Overloaded methods must not throw new checked exceptions not thrown by the original
method. True/False?
(1) True
(2) False
Answer : -------------------------
24 Which of the following statements are true?
(1) Assigning null to a reference causes the object to be garbage collected
(2) Assigning null to a reference causes the object to become eligable for garbage collection
(3) An object is eligable for garbage collection once it is unreachable via any reference
(4) Any object created within a method will be eligable for garbage collection once the
method ceases execution
Answer : -------------------------
25 Which of the following statements are true about the LinkedHashSet class?
(1) It may not contain duplicate elements
(2) The elements are ordered but not sorted
(3) The elements are sorted
(4) It does not permit null elements
Answer : -------------------------
26 Given the following code, which option if inserted after the line with the
comment //Here will result in code that will compile and output SupEx?
class Super{
public void go(){
System.out.print("Super");
}
}
public class SupEx extends Super{
public static void main(String argv[]){
//Here
s.go();
}
public void go(){
System.out.println("SupEx");
}
}
(1) SupEx s = new Super();
(2) Super s = new SupEx();
(3) SupEx s = new SupEx();
(4) Super s = new Super();
Answer : -------------------------
27 Which of the following will result in an output of 10?
(1) System.out.println(Math.round(10.1));
(2) System.out.println(Math.floor(10.1));
(3) System.out.println(Math.abs(10.1));
(4) System.out.println(Math.min(10.1));
Answer : -------------------------
28 Given this code, which of the following statements are true?
public class Photos {
private int iKey;
private String sValue;
public Photos(int iKey, String sValue){
this.iKey=iKey;
this.sValue=sValue;
}
public int hashCode(){
return super.hashCode();
}
public boolean equals(Object o){
if(o instanceof Photos){
if(this.hashCode() == o.hashCode()){
return true;
}
}
return false;
}
}
(1) The hashCode method is correctly implemented
(2) The hashCode method is not correct because it is inconsistant with the equals method
(3) The code will not compile because there is a circular reference to the hashCode method
(4) The code will not compile because the return value of this.hashCode is not an int value
(5) The code will not compile because it does not implement the comparable interface
Answer : -------------------------
29 Which of the following statements are true?
(1) A higher priority Thread will prevent a lower priorty Thread from getting any access to
the CPU
(2) The yield method only allows any higher priority priority thread to execute
(3) The Thread class has a static method called yield
(4) Calling yield with an integer parameter causes it to yield for a specific time
Answer : -------------------------
30 How do you set the priority of the thread "newThread" to the minimum of two values:
maximum priority and current priority incremented to the next level. [Use the Thread
priority constants and do not insert any extra characters or leave any blank spaces]
Answer : -------------------------
31 Variables declared within methods cannot be marked as static. True/False?
(1) True
(2) False
Answer : -------------------------
32 What is the initial capacity of an empty StringBuffer object?
ie., new StringBuffer()
[No extra characters Or spaces]
Answer : -------------------------
33 What is the capacity of strBuf object after executing the following statement?
StringBuffer strBuf = new StringBuffer("Technopark");
(1) 0
(2) 6
(3) 25
(4) 255
(5) -1
(6) None of the above
Answer : -------------------------
34 How can you remove the superfluous capacity of a StringBuffer object say strBuf (if
there is any)?
(Hint: Use SetLength() and length() methods. Please do not include any extra
characters Or spaces)
Answer : -------------------------
35 What will be the result of attempting to compile and run the following code?
public class MyClass
{
public static void main(String[] args)
{
String s = "hello";
StringBuffer sb = new StringBuffer(s);
sb.reverse();
if (s == sb)
System.out.println("a");
if (s.equals(sb))
System.out.println("b");
if (sb.equals(s))
System.out.println("c");
}
} // MyClass
(1) The code will fail to compile, since the constructor of the String class is not properly
called
(2) The code will fail to compile, since (s == sb) is an illegal expression
(3) The code will fail to compile, since the expression (s.equals(sb)) is illegal
(4) The code will print c when run
(5) The program will throw a ClassCastException when run
Answer : -------------------------
36 At which point will the word "Harpic" be printed out when this code is executied?
class Harpic{
public void finalize(){
System.out.println("Harpic");
}
}
public class ArmitageShanks{
Harpic har;
public static void main(String argv[]){
ArmitageShanks as = new ArmitageShanks();
as.oui();
}
public void oui(){
har = new Harpic();
mno(har);
//one
har=null;
}
public void mno(Harpic har){
Harpic pic=har;
//two
pic=null;
//three
har=null;
}
}
(1) After executing the line after the comment //one
(2) After executing the line after the comment //two
(3) After executing the line after the comment //three
(4) It is impossible to say, the String "Harpic" may not be output at all
Answer : -------------------------
37 What will happen when you attempt to compile and run the following code?
class TSamp extends Thread {
public native String getTime();
}
public class Multi implements Runnable {
boolean bStop;
public static void main(String argv[]){
Multi m = new Multi();
m.go();
}
public void go(){
TSamp ts = new TSamp(this);
ts.start();
bStop=true;
}
public void run(){
if(bStop==true){
return;
}
System.out.println("running");
}
}
(1) Compilation, but output at runtime will cannot be exactly determined
(2) Compilation and output of "running"
(3) Compilation but no output at runtime
(4) Compile time error
Answer : -------------------------
38 What will happen if you compile the following code with assertions enabled?
public class Cote{
public static void main(String argv[]){
Cote c = new Cote();
c.go(argv[0]);
}
public void go(String s){
int i = Integer.parseInt(s);
if(i > 0){
System.out.println(i);
}else{
throw new AssertionError(i);
}
}
}
(1) Compile time error, AssertionError has no int constructor
(2) Compile time error AssertionError does not exist
(3) Assertion Error at runtime if given a command line parameter of 0
(4) If given a command line parameter of 1, 1 will be output at runtime
Answer : -------------------------
39 What will happen if you attempt to compile and run the following code?
import java.util.*;
public class Chawson{
public static void main(String argv[]){
Chawson c = new Chawson();
c.whittan();
}
public void whittan(){
HashSet hs = new HashSet();
hs.add("one");
hs.add("two");
hs.add("one");
wyche(hs);
}
public void wyche(Set s){
HashSet hs = (HashSet) s;
System.out.println(hs.size());
}
}
(1) Compilation and output of 3
(2) Compile time error, duplicate elements cannot be added to HashSet
(3) Runtime error due to an attempt to add duplicate elements to a HashSet
(4) Compilation and output of 2
Answer : -------------------------
40 AssertionError exceptions are checked exceptions. True Or False?
(1) True
(2) False
Answer : -------------------------
41 What will the output be when the following method is executed?
public static void main(String[] args ){
int n = 11 ;
do {
System.out.print( " " + n-- );
}while( (n % 4) != 0 );
System.out.println( " final " + n );
}
(1) 11 10 9 final 8
(2) 10 9 8 final 8
(3) 11 10 9 8 final 8
(4) 11 final 10
Answer : -------------------------
42 Consider the following main method in the TechnoSample class:
public static void main (String[] args){
String s1 = " Arg " + args[1] ;
s1.trim();
String s2 = ":" + s1 + args[2] ;
System.out.println( s2 + ":" );
}
What will be printed when this is executed with the following command line?
java TechnoSample alpha beta gamma delta
(1) :Arg betagamma:
(2) :Argbetagamma:
(3) : Arg betagamma:
(4) : Arg alphabeta:
(5) :Arg alphabeta:
Answer : -------------------------
43
What will happen when you attempt to compile and run the following code?
class WornPadException extends RuntimeException{
}
public class Wheel{
public static void main(String argv[]){
Wheel w = new Wheel();
System.out.print(w.roll());
}
public int roll(){
int iDistance =0;
try{
for(int i =0; i < 2 ;i ++){
System.out.print("roll");
iDistance = iDistance * i;
}
return iDistance;
}finally{
brake();
System.out.print("finished");
return iDistance+1;
}
}
public void brake() throws WornPadException{
System.out.print("brake");
}
}
(1) Compile time error, calls to brake must be within a try/catch block
(2) Compile time error the try block has no catch clause
(3) Runtime error, the call to brake is not within a try/catch block
(4) Runtime error the call to brake is within a finally clause
(5) Compilation and output of rollrollbrakefinished0
(6) Compilation and output of rollrollbrakefinished1
Answer : -------------------------
44 Select all of the following statements that are true.
(1) The Float class has constructors that take type String, type double and type float
(2) The * operator can be used to multiply the values of instances of the Integer class
(3) The setValue method can be used to alter the value of an instance of Integer, Float or
Double
(4) The Character class can store either a char value or a String value
(5) The Integer.parseInt method will convert an appropriate String to its int value
Answer : -------------------------
45 When programming a local inner class inside a method code block, which of the
following statements is true? Check all which apply.
(1) The inner class will only have access to static variables in the enclosing class
(2) The inner class can use any local variables declared in the method
(3) The only local variables an inner class can use are those that are declared final
(4) The only local variables an inner class can use are those that are declared static
(5) The inner class will only have access to instance and local variables if they are declared
final
Answer : -------------------------
46 Which of the following are public variables or methods that belong to an instance of
Thread?
Do not select static variables, static methods, or deprecated methods.
(1) wait() method
(2) sleep() method
start() method
(3)
(4) MAX_PRIORITY - an int variable
(5) daemon - a boolean variable
Answer : -------------------------
47 Which of the following is not a Java keyword? (Java SDK v1.4)
(1) transient
(2) generic
(3) assert
(4) strictfp
(5) friend
(6) sizeof
Answer : -------------------------
48 Consider the variables declared in the following code:
public class TechnoSample{
static Object theObj ;
static Object[] someObj ;
static String letters[] = {"A", "B", "C", "D" };
static char[] caps = {'A', 'B', 'C', 'D' };
public static void main (String[] args){
someObj = new Object[ 3 ] ;
int[] theInts = null ;
// what can go here?
}
Select statements that could replace the comment without causing a compiler error.
(1) theInts = caps;
(2) theObj = theInts;
(3) someObj = theInts;
(4) theObj = caps;
Answer : -------------------------
49
What will happen when we try to compile and run this code?
1 public void testC(char ch) {
2 Integer ss = new Integer( ch );
1] 2,3
Explanation:
pause() and halt() are not methods of the Thread class.
* * * *
2] 2
Explanation:
Please see the Java 1.4 documentation.
3 Character cc = new Character( ch ) ;
4 if( ss.equals( cc )) System.out.println("equals");
5 if( ss.intValue() == cc.charValue() ){
6 System.out.println("EQ");
7 }
8 }
(1) The compiler will object to line 4 because the object types of ss and cc don't match
(2) The program will compile and run, producing "EQ"
(3) The program will compile and run, producing "equalsEQ"
(4) The program will compile and run, producing "equals"
(5) The compiler will object to creating an Integer from a char in line 2
Answer : -------------------------
50 Your program has two object references, x and y. In some method the following logical
tests are done:
boolean hashFlag = ( x.hashCode() == y.hashCode() );
boolean equalsFlag = x.equals( y );
boolean eqFlag = ( x == y );
Which of the following statements about the relationship between these tests are true.
(1) If equalsFlag is true, then hashFlag must be true
(2) If hashFlag is true, then eqFlag must be true
(3) If equalsFlag is false, then eqFlag must be false
(4) if hashFlag is false, then eqFlag must be false
Answer : -------------------------
* * * *
3] 2
Explanation:
Although bContinue does get set to true, the setPrice call is blocked because setPrice and run are both
synchronized.
* * * *
4] 4
Explanation:
If that seems a vauge answer it is because you cannot be certain of the system that the underlying OS uses for
allocating cycles for a Thread. The chances are that once the thread has been spun off in the call to start in the
methodname() the main method will run to completion and the value of sName will still be vandeluer before the
Thread modifies it. You cannot be certain of this though.
Just because sName is static does not mean that passing it to a method gives the method the original copy. The
method only sees a locally created copy and any changes to it will not be reflected on return to the calling
method.
* * * *
5] 2,3
Explanation:
Generally speaking, all I/O operations require explicit exception handling with try/catch blocks. The JDK 1.4
exams does not explicitly cover I/O but it may be referred to in the context of exception handling.
* * * *
6] 1
Explanation:
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 isneeded to convert a double to an int.
* * * *
7] 4
Explanation:
All wrapper class objects are immutable.
* * * *
8] 2
Explanation:
The TreeMap class stores the keys rather than the values in sorted order.
* * * *
9] 3
Explanation:
Constructors are executed in order of the oldest ancester down, so the output from Biddy is seen before Val.
Although the the paremeter for shep has no floating point component, a widening conversion involves no loss of
precisionand thus the value is cast to a float by the method shep. By default a float will have a decimal component
and thus it has a trailing zero in this example.
* * * *
10] 2,3,4
Explanation:
Please see Java 1.2/1.4 API documentation.
* * * *
11] 1
Explanation:
An int cannot have a fractional component, under JDK1.4 this produced the error message
possible loss of precision found : double required: int
private int iAcres=3.5;
* * * *
12] 2,3
Explanation:
A variable declared as public within a method is only visible within the method. They are sometimes called
automatic variables as they automatically come into scope when the method runs and are out of scope when the
method hasfinished execution. Variables declared within methods cannot be marked as static. A method declared
with no visibility modifier is accessible anywhere from within the current package.A method declared with the
protected modifier is also accessible in child classes that are not in the current package.
* * * *
13] 3
Explanation:
Option 4 is incorrect because an assert statment must make a comparison and the single = sign indicates an
assignment.The assert statement does not use curly braces and assert cannot be used like a parameterless
method call as in assert() in option 1.
* * * *
14] 4
Explanation:
On line 9 the object created on line 8 has the reference sb2 pointed to it. Until something happens to make that
reference unable to reach the object it will not be eligible for garbage collection.
* * * *
15] 3
Explanation:
The == operator should never be used to test the equivalence of strings as it will only test the reference, not the
sequence of characters. To test if the Strings match use the String equals() method.
* * * *
16] 1
Explanation:
There is no rule against constructors being marked as private.
* * * *
17] 2
Explanation:
This code will produce a java.lang.IllegalMonitorStateException at runtime because the wait/notify code is not
within synchronized code.
* * * *
18] 1,2,4
Explanation:
The LinkedHashMap was added with JDK1.4. Option 3 is nonsense because if something is sorted that imposes an
order (however something may be ordered without being sorted).
* * * *
19] 1
Explanation:
No problem here, the code compiles fine. One thing to be aware of is that i+++ ++i compiles fine because of the
way Java code is actually parsed. The parser tokenizes the source in bunches of longest valid character
sequences. i+++ ++i will betokenized as i,++,+,++,i and interpreted as i++ + ++i, that is i post-incremented
plus i pre-incremented. Then you have to know how the ternary conditional ?: operator works, that is, it always
evaluates its first operand and then depending onthe results, evaluates the second OR the third operand (never
both). So getBoolean() returns either true or false, thus the code either prints i=2*i++ or i+++ ++i. The former
is equivalent to i=2*i and the latter to 2*i+2.
* * * *
20] 2
Explanation:
ArithmeticExceptions are considered programmer problems, and are not checked by the compiler. A divide-byzero
error, for example, should be checked for by your own code. (from Java Ranch round up game)
* * * *
21] negative
Explanation:
The right shift operator fills all bits from the left with the same value as the original sign bit -- in this case 1. (from
Java Ranch round up game)
* * * *
22] 2
Explanation:
The case argument must be either an int literal, or an int-compatible variable which is a constant ie., static final.
* * * *
23] 2
Explanation:
This would be true for overriding methods, but overloaded methods are free to throw new checked exceptions.
(from Java Ranch)
* * * *
24] 3
Explanation:
Assigning null to a reference will only cause the object it references to be ready for garbage collection if no other
reference points to it.It is possible to create an object inside a method and to also assign a reference created
outside the method to the same object,so the completion of a method is no guarantee that an object is eligable for
garbage collection.
* * * *
25] 1,2
Explanation:
Please see the relevant API.
* * * *
26] 2,3
Explanation:
--
* * * *
27] 1
Explanation:
Options 2 will output 10.0 and option 3 will output 10.1. Option 4 will cause a compilation error, because the
Math.min method takes two arguments (from www.examulator.com)
* * * *
28] 1
Explanation:
This represents a fairly useless but correct implementation of hashCode by using the version inherited from Object
which uses the memory address of the object to generatethe hashCode value. (from www.examulator.com)
* * * *
29] 3
Explanation:
A call to yield can allow any waiting thread to execute depending on the scheduling system of the underlying
operating system. There is no version of yield that takes aninteger parameter.Weather a higher priority thread
gets CPU time than a lower priorty thread is platform dependent and cannot be certain. (from
www.examulator.com)
* * * *
30] newThread.setPriority(Math.min(Thread.MAX_PRIORITY,newThread.getPriority()+1));
Explanation:
--
* * * *
31] 1
Explanation:
--
* * * *
32] 16
Explanation:
The default capacity for any StringBuffer object is 16 + the length of the String specified as the argument. If none
specified, it will be 16. Capacity can also be specifiedusing the other constructor StringBuffer(int capacity).
* * * *
33] 3
Explanation:
Capacity of a StringBuffer object is always the length of the string + 16 (unless the capacity is specified using
StringBuffer(int capacity))
* * * *
34] strBuf.setLength(strBuf.length());
Explanation:
Please see the StringBuffer API.
* * * *
35] 2
Explanation:
The expression tries to compare two references and will fail, since neither String nor StringBuffer is a super class
of the other [from Khalid's book]
* * * *
36] 4
Explanation:
The instance of the Harpic class will probably not be garbage collected at all, and thus the finalize method will not
be run (but it could be).(from www.examulator.com)
* * * *
37] 4
Explanation:
The TSamp has no constructor defined that takes a class of type Runnable, and as constructors are not inherited
the code will not compile. (from www.examulator.com)
* * * *
38] 3,4
Explanation:
--
* * * *
39] 4
Explanation:
Because the code attempts to insert the string "one" twice, the HashSet hs has only two elements.
It is a good idea when using the add method of HashSet to check the boolean value returned to ensure that the
new element wassuccessfully added.
* * * *
40] 2
Explanation:
java.lang.AssertionError class is a subclass of java.lang.Error and that makes it unchecked.
* * * *
41] 1
Explanation:
Note that n is decremented after the value is printed. (from LanWrights exam)
* * * *
42] 3
Explanation:
The result is ": Arg betagamma:" because the call to trim() does not change s1. (from LanWrights exam)
* * * *
43] 6
Explanation:
Choice 1 & 2 are not correct, 'cause WornPadException extends RuntimeException it is not mandatory to surround
calls to it with a try/catch block. Choice 3 is not correct since thecompiler checks the need for try/catch, not the
runtime. Choice 4 is not correct, because a finally clause can have any code in it. Choice 5 is not correct, since the
final valuereturned is 1. Choice 6 is correct because WornPadException extends RuntimeException it is not
mandatory to surround calls to it with a try/catch block. It is perfectly correct &sometimes useful to have a
try/finally block without a catch statement. Because the finally clause 'll be executed the value returned 'll be that
within the finally clause.
* * * *
44] 1,5
Explanation:
Facts:
The * operator can only work with primitives. The value in a wrapper class object can't be changed once created.
The Character class can only store a char value.(from LanWrights exam)
* * * *
45] 3
Explanation:
Only local variables declared final can be used by the inner class. (from LanWrights exam)
* * * *
46] 1,3
Explanation:
Since wait is a method in Object and Thread is an object; sleep is a static method; start is an instance method of
Thread; MAX_PRIORITY is a static final variable of Thread;the daemon boolean variable is a private instance
variable. (from LanWrights exam)
* * * *
47] 2,5,6
Explanation:
transient is used as a modifier for variables; generic is not a keyword; as of Java 1.4, assert is a keyword; the
keyword strictfp controls floating point calculations; friend is nota keyword; Java does not use sizeof.
* * * *
48] 2,4
Explanation:
you can't cast any primitive array to another primitive array type, no matter how reasonable it seems; any array
can be cast to an Object reference; you can't cast a primitive arrayto an reference type array. The compiler does
not care that theInts will have a null value when the program runs. (from LanWrights exam)
* * * *
49] 2
Explanation:
the equals method is defined in terms of taking an Object reference so there is no problem; the equals test fails
because the objects are of different types, but the charValuereturn is promoted to int and the result is true; the
equals test fails because the objects are of different types; only the == comparison will result in true. Note that
the compilerpromotes the charValue return to int; promotion of the char value to int is automatic. (Credit:
LanWrights)
* * * *
50] 1,3,4
Explanation:
(1) yes, this is a requirement for hashcodes and the equals method; (2) no, two objects not equal by the == test
may still have identical hashcodes (3) Yes, if the equals() testreturns false, x and y can't possibly refer to the
same object (4) Yes, this is a requirement for hashcodes and the equals method. (Credit: LanWrights)
* * * *
JavaBeat 2005, India (www.javabeat.net)
Submit a Site - Directory - Submit Articles
1 Which of the following can prevent a thread from executing?
(1) A call to its pause method
(2) A call to Thread.yield()
(3) Another thread is given higher priority
(4) A call to its halt() method
Answer : -------------------------
2 Which of the following represent correct syntax for assertions?
(1) assertion(b==false);
(2) assert (b==false);
(3) assert() b==false;
(4) if(b!=true) assert;
Answer : -------------------------
3
What will happen if you attempt to compile and run the following code?
public class Master{
boolean bContinue=false;
public static void main(String argv[]){
Master m = new Master();
m.go();
}
public void go(){
Slave s = new Slave(this);
Thread t1 = new Thread(s);
t1.start();
while(bContinue==false){
}
s.setPrice(200);
}
}
class Slave implements Runnable{
int iPrice =100;
Master master;
Slave(Master m){
master=m;
}
synchronized public void setPrice(int iM){
iPrice=iM;
}
synchronized public void run(){
master.bContinue=true;
while(true){
System.out.println(iPrice);
}
}
}
(1) Compilation but no output as the run method of slave is not correct
(2) Compilation and output of 100 several times followed by 200 several times
(3) Compilation and repeated output of 100
(4) Compile time error, while cannot be given an unconditional boolean value
Answer : -------------------------
4 What will happend when you attempt to compile and run the following code?
public class Tux extends Thread{
static String sName = "Techno";
public static void main(String argv[]){
Tux t = new Tux();
t.name(sName);
System.out.println(sName);
}
public void name(String sName){
sName = sName + " park";
start();
}
public void run(){
for(int i=0;i < 4; i++){
sName = sName + " " + i;
}
}
}
(1) Compile time error
(2) Compilation and output of "Techno park"
(3) Compilation and output of "Techno park 0 1 2 3"
(4) Compilation and probably output of "Techno" but possible output of "Techno 0 1 2 3"
Answer : -------------------------
5 Which of the following require explicit try/catch exception handling by the programmer?
(1) Traversing each member of an array
(2) Attempting to open a file
(3) Attempting to open a network socket
(4) Accessing a method in other clas
Answer : -------------------------
6 What will be the result when you attempt to compile this program?
public class RandomExample{
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 : -------------------------
7 Which of the following statements are true?
(1) The vaue of the Integer class can be changed using the = operator
(2) The value of the Integer class can be changed using the setValue method
(3) The value of the Integer class can be changed using the setInt method
(4) Once assigned the value of an instance of Integer cannot be changed
Answer : -------------------------
8 What will happen when you attempt to compile and run the following code?
import java.util.*;
public class TechnoExample{
public static void main(String argv[]){
TechnoExample junk = new TechnoExample();
junk.sampleMap();
}
public void sampleMap(){
TreeMap tm = new TreeMap();
tm.put("a","Bill");
tm.put("b","Kathy");
tm.put("c","Carl");
Iterator it = tm.keySet().iterator();
while(it.hasNext()){
System.out.print(tm.get(it.next()));
}
}
}
(1) Compile time error, a19 cannot be used as a method name
(2) Compilation and output of BillKathyCarl
(3) Compilation and output of BillCarlKathy
(4) Compilation and output of abc
Answer : -------------------------
9 What will happen when you attempt to compile and run the following code?
class Biddy{
public Biddy(){
System.out.print(" Biddy ");
}
}
class Val extends Biddy{
public Val(){
System.out.print(" Val ");
}
}
public class BluePeter extends Val{
public static void main(String argv[]){
BluePeter bp = new BluePeter();
bp.shep(3);
}
public void shep(float i){
System.out.println(i);
}
}
(1) Compilation and output of Val Biddy 3
(2) Compilation and output of Val Biddy 3.0
(3) Compilation and output of Biddy Val 3.0
(4) Compile time error, wrong parameter type passed to method shep
Answer : -------------------------
10 which of the following statements are true of the ArrayList class?
(1) It can store primitive or references as elements
(2) It implements the List interface
(3) It has a get(int index) method which returns the element at the specified position in the
list
(4) The elements are ordered but not sorted
Answer : -------------------------
11 What will happen when you attempt to compile and run the following code?
class Base{
public int iAcres=3;
}
public class Mfields extends Base{
private int iAcres=3.5;
public static void main(String args[]){
Base mf = new Mfields();
System.out.println(mf.iAcres);
}
}
(1) Compile time error
(2) Compilation and output fo 3.5
(3) Compilation and output of 3
(4) Compilation but no output at runtime
Answer : -------------------------
12 Which of the following statements are true?
(1) A variable declared as public within a method will always be visible from code anywhere
else in the class
(2) A variable declared as public at class level will always be visible from code anywhere
else in the class
(3) A method with no visibility modifier can be less visible than one declared with the
protected modifier
(4) Only one copy will ever exist of a method variable declared as static
Answer : -------------------------
13 Which of the following are valid uses of the assert statement?
(1) assert();
(2) assert {
int > 0;
}
(3) assert(iMonth < 12);
(4) assert (iAge = 0);
Answer : -------------------------
14 At what point will the object created on line 8 be eligible for garbage collection?
1 public class RJMould{
2 StringBuffer sb;
3 public static void main(String argv[]){
4 RJMould rjm = new RJMould();
5 rjm.kansas();
6 }
7 public void kansas(){
8 sb = new StringBuffer("Manchester");
9 StringBuffer sb2 = sb;
10 StringBuffer sb3 = new StringBuffer("Chester");
11 sb=sb3;
12 sb3=null;
13 sb2=null;
14 }
15 }
(1) Line 11
(2) Line 9
(3) Line 12
(4) Line 13
Answer : -------------------------
15 What will happen when you attempt to compile and run the following code?
public class HarHam{
public static void main(String argv[]){
HarHam hh = new HarHam();
hh.go();
}
public void go(){
String har = new String ("har");
String ham = new String("har");
collar:
for(int i=0; i < 2 ; i ++){
if(har==ham){
break collar;
}
if(i > 0){
continue collar;
}
System.out.print(i);
} // for i
}
}
(1) Compile time error, System.out has no print method
(2) No output at runtime
(3) Output of 0
(4) Compile error, break cannot occur after its target label
Answer : -------------------------
16 What will happen when you attempt to compile the following code?
protected class Wmid{
private Wmid(String sName){
System.out.println("Wmid");
}
Wmid(){}
}
public class Ombers extends Wmid{
public static void main(String argv[]){
Ombers o = new Ombers();
}
}
(1) Compile time error, class Wmid may not be marked as protected
(2) Compile time error, a constructor may not be marked as private
(3) Compilation and output of Wmid
(4) Compilation but no output
Answer : -------------------------
17 What will happen when you attempt to compile and run the following code?
public class Mickle extends Thread implements Runnable{
public static void main(String argv[]){
Mickle m = new Mickle();
m.start();
}
public void run(){
go();
}
public void go(){
int i;
while(true){
try{
wait();
System.out.println("interrupted");
}catch (InterruptedException e) {}
}
}
}
(1) Compile time error
(2) Compilation but runtime exception
(3) Compilation but no output at runtime
(4) Compilation and output of "interrupted" at runtime
Answer : -------------------------
18 Which of the following statements are true?
(1) A LinkedHashMap preserves the order in which objects are added
(2) A TreeMap ensures that its elements will be in sorted order
(3) Elements in a LinkedList are sorted but not ordered
(4) Collections that implement the List interface allow duplicate elements
Answer : -------------------------
19 Select one correct statement about the following code.
public class TechnoSample {
public static void main(String[] args) {
int i=3;
System.out.println(getBoolean()? i=2*i++:i+++ ++i);
}
public static boolean getBoolean(){
if((int)(Math.random()*2)==0)
return false;
else
return true;
}
}
(1) Prints randomly 6 or 8 at each execution
(2) Prints randomly 7 or 8 at each execution
(3) Always prints 6 at each execution
(4) Prints randomly 6 or 11 at each execution
(5) Compilation error
Answer : -------------------------
20 An ArithmeticException is a checked exception. True Or False?
(1) True
(2) False
Answer : -------------------------
21 Assume the bit pattern of byte x is: 10110001. What will the sign of x be after x >> 2?
Fill with positive Or negative. Caution: No spaces or extra characters.
Answer : -------------------------
22 In a switch statement, the argment to the case label (case argument:) can be any
variable which can fit within an int. True/False?
(1) True
(2) False
Answer : -------------------------
23 Overloaded methods must not throw new checked exceptions not thrown by the original
method. True/False?
(1) True
(2) False
Answer : -------------------------
24 Which of the following statements are true?
(1) Assigning null to a reference causes the object to be garbage collected
(2) Assigning null to a reference causes the object to become eligable for garbage collection
(3) An object is eligable for garbage collection once it is unreachable via any reference
(4) Any object created within a method will be eligable for garbage collection once the
method ceases execution
Answer : -------------------------
25 Which of the following statements are true about the LinkedHashSet class?
(1) It may not contain duplicate elements
(2) The elements are ordered but not sorted
(3) The elements are sorted
(4) It does not permit null elements
Answer : -------------------------
26 Given the following code, which option if inserted after the line with the
comment //Here will result in code that will compile and output SupEx?
class Super{
public void go(){
System.out.print("Super");
}
}
public class SupEx extends Super{
public static void main(String argv[]){
//Here
s.go();
}
public void go(){
System.out.println("SupEx");
}
}
(1) SupEx s = new Super();
(2) Super s = new SupEx();
(3) SupEx s = new SupEx();
(4) Super s = new Super();
Answer : -------------------------
27 Which of the following will result in an output of 10?
(1) System.out.println(Math.round(10.1));
(2) System.out.println(Math.floor(10.1));
(3) System.out.println(Math.abs(10.1));
(4) System.out.println(Math.min(10.1));
Answer : -------------------------
28 Given this code, which of the following statements are true?
public class Photos {
private int iKey;
private String sValue;
public Photos(int iKey, String sValue){
this.iKey=iKey;
this.sValue=sValue;
}
public int hashCode(){
return super.hashCode();
}
public boolean equals(Object o){
if(o instanceof Photos){
if(this.hashCode() == o.hashCode()){
return true;
}
}
return false;
}
}
(1) The hashCode method is correctly implemented
(2) The hashCode method is not correct because it is inconsistant with the equals method
(3) The code will not compile because there is a circular reference to the hashCode method
(4) The code will not compile because the return value of this.hashCode is not an int value
(5) The code will not compile because it does not implement the comparable interface
Answer : -------------------------
29 Which of the following statements are true?
(1) A higher priority Thread will prevent a lower priorty Thread from getting any access to
the CPU
(2) The yield method only allows any higher priority priority thread to execute
(3) The Thread class has a static method called yield
(4) Calling yield with an integer parameter causes it to yield for a specific time
Answer : -------------------------
30 How do you set the priority of the thread "newThread" to the minimum of two values:
maximum priority and current priority incremented to the next level. [Use the Thread
priority constants and do not insert any extra characters or leave any blank spaces]
Answer : -------------------------
31 Variables declared within methods cannot be marked as static. True/False?
(1) True
(2) False
Answer : -------------------------
32 What is the initial capacity of an empty StringBuffer object?
ie., new StringBuffer()
[No extra characters Or spaces]
Answer : -------------------------
33 What is the capacity of strBuf object after executing the following statement?
StringBuffer strBuf = new StringBuffer("Technopark");
(1) 0
(2) 6
(3) 25
(4) 255
(5) -1
(6) None of the above
Answer : -------------------------
34 How can you remove the superfluous capacity of a StringBuffer object say strBuf (if
there is any)?
(Hint: Use SetLength() and length() methods. Please do not include any extra
characters Or spaces)
Answer : -------------------------
35 What will be the result of attempting to compile and run the following code?
public class MyClass
{
public static void main(String[] args)
{
String s = "hello";
StringBuffer sb = new StringBuffer(s);
sb.reverse();
if (s == sb)
System.out.println("a");
if (s.equals(sb))
System.out.println("b");
if (sb.equals(s))
System.out.println("c");
}
} // MyClass
(1) The code will fail to compile, since the constructor of the String class is not properly
called
(2) The code will fail to compile, since (s == sb) is an illegal expression
(3) The code will fail to compile, since the expression (s.equals(sb)) is illegal
(4) The code will print c when run
(5) The program will throw a ClassCastException when run
Answer : -------------------------
36 At which point will the word "Harpic" be printed out when this code is executied?
class Harpic{
public void finalize(){
System.out.println("Harpic");
}
}
public class ArmitageShanks{
Harpic har;
public static void main(String argv[]){
ArmitageShanks as = new ArmitageShanks();
as.oui();
}
public void oui(){
har = new Harpic();
mno(har);
//one
har=null;
}
public void mno(Harpic har){
Harpic pic=har;
//two
pic=null;
//three
har=null;
}
}
(1) After executing the line after the comment //one
(2) After executing the line after the comment //two
(3) After executing the line after the comment //three
(4) It is impossible to say, the String "Harpic" may not be output at all
Answer : -------------------------
37 What will happen when you attempt to compile and run the following code?
class TSamp extends Thread {
public native String getTime();
}
public class Multi implements Runnable {
boolean bStop;
public static void main(String argv[]){
Multi m = new Multi();
m.go();
}
public void go(){
TSamp ts = new TSamp(this);
ts.start();
bStop=true;
}
public void run(){
if(bStop==true){
return;
}
System.out.println("running");
}
}
(1) Compilation, but output at runtime will cannot be exactly determined
(2) Compilation and output of "running"
(3) Compilation but no output at runtime
(4) Compile time error
Answer : -------------------------
38 What will happen if you compile the following code with assertions enabled?
public class Cote{
public static void main(String argv[]){
Cote c = new Cote();
c.go(argv[0]);
}
public void go(String s){
int i = Integer.parseInt(s);
if(i > 0){
System.out.println(i);
}else{
throw new AssertionError(i);
}
}
}
(1) Compile time error, AssertionError has no int constructor
(2) Compile time error AssertionError does not exist
(3) Assertion Error at runtime if given a command line parameter of 0
(4) If given a command line parameter of 1, 1 will be output at runtime
Answer : -------------------------
39 What will happen if you attempt to compile and run the following code?
import java.util.*;
public class Chawson{
public static void main(String argv[]){
Chawson c = new Chawson();
c.whittan();
}
public void whittan(){
HashSet hs = new HashSet();
hs.add("one");
hs.add("two");
hs.add("one");
wyche(hs);
}
public void wyche(Set s){
HashSet hs = (HashSet) s;
System.out.println(hs.size());
}
}
(1) Compilation and output of 3
(2) Compile time error, duplicate elements cannot be added to HashSet
(3) Runtime error due to an attempt to add duplicate elements to a HashSet
(4) Compilation and output of 2
Answer : -------------------------
40 AssertionError exceptions are checked exceptions. True Or False?
(1) True
(2) False
Answer : -------------------------
41 What will the output be when the following method is executed?
public static void main(String[] args ){
int n = 11 ;
do {
System.out.print( " " + n-- );
}while( (n % 4) != 0 );
System.out.println( " final " + n );
}
(1) 11 10 9 final 8
(2) 10 9 8 final 8
(3) 11 10 9 8 final 8
(4) 11 final 10
Answer : -------------------------
42 Consider the following main method in the TechnoSample class:
public static void main (String[] args){
String s1 = " Arg " + args[1] ;
s1.trim();
String s2 = ":" + s1 + args[2] ;
System.out.println( s2 + ":" );
}
What will be printed when this is executed with the following command line?
java TechnoSample alpha beta gamma delta
(1) :Arg betagamma:
(2) :Argbetagamma:
(3) : Arg betagamma:
(4) : Arg alphabeta:
(5) :Arg alphabeta:
Answer : -------------------------
43
What will happen when you attempt to compile and run the following code?
class WornPadException extends RuntimeException{
}
public class Wheel{
public static void main(String argv[]){
Wheel w = new Wheel();
System.out.print(w.roll());
}
public int roll(){
int iDistance =0;
try{
for(int i =0; i < 2 ;i ++){
System.out.print("roll");
iDistance = iDistance * i;
}
return iDistance;
}finally{
brake();
System.out.print("finished");
return iDistance+1;
}
}
public void brake() throws WornPadException{
System.out.print("brake");
}
}
(1) Compile time error, calls to brake must be within a try/catch block
(2) Compile time error the try block has no catch clause
(3) Runtime error, the call to brake is not within a try/catch block
(4) Runtime error the call to brake is within a finally clause
(5) Compilation and output of rollrollbrakefinished0
(6) Compilation and output of rollrollbrakefinished1
Answer : -------------------------
44 Select all of the following statements that are true.
(1) The Float class has constructors that take type String, type double and type float
(2) The * operator can be used to multiply the values of instances of the Integer class
(3) The setValue method can be used to alter the value of an instance of Integer, Float or
Double
(4) The Character class can store either a char value or a String value
(5) The Integer.parseInt method will convert an appropriate String to its int value
Answer : -------------------------
45 When programming a local inner class inside a method code block, which of the
following statements is true? Check all which apply.
(1) The inner class will only have access to static variables in the enclosing class
(2) The inner class can use any local variables declared in the method
(3) The only local variables an inner class can use are those that are declared final
(4) The only local variables an inner class can use are those that are declared static
(5) The inner class will only have access to instance and local variables if they are declared
final
Answer : -------------------------
46 Which of the following are public variables or methods that belong to an instance of
Thread?
Do not select static variables, static methods, or deprecated methods.
(1) wait() method
(2) sleep() method
start() method
(3)
(4) MAX_PRIORITY - an int variable
(5) daemon - a boolean variable
Answer : -------------------------
47 Which of the following is not a Java keyword? (Java SDK v1.4)
(1) transient
(2) generic
(3) assert
(4) strictfp
(5) friend
(6) sizeof
Answer : -------------------------
48 Consider the variables declared in the following code:
public class TechnoSample{
static Object theObj ;
static Object[] someObj ;
static String letters[] = {"A", "B", "C", "D" };
static char[] caps = {'A', 'B', 'C', 'D' };
public static void main (String[] args){
someObj = new Object[ 3 ] ;
int[] theInts = null ;
// what can go here?
}
Select statements that could replace the comment without causing a compiler error.
(1) theInts = caps;
(2) theObj = theInts;
(3) someObj = theInts;
(4) theObj = caps;
Answer : -------------------------
49
What will happen when we try to compile and run this code?
1 public void testC(char ch) {
2 Integer ss = new Integer( ch );
1] 2,3
Explanation:
pause() and halt() are not methods of the Thread class.
* * * *
2] 2
Explanation:
Please see the Java 1.4 documentation.
3 Character cc = new Character( ch ) ;
4 if( ss.equals( cc )) System.out.println("equals");
5 if( ss.intValue() == cc.charValue() ){
6 System.out.println("EQ");
7 }
8 }
(1) The compiler will object to line 4 because the object types of ss and cc don't match
(2) The program will compile and run, producing "EQ"
(3) The program will compile and run, producing "equalsEQ"
(4) The program will compile and run, producing "equals"
(5) The compiler will object to creating an Integer from a char in line 2
Answer : -------------------------
50 Your program has two object references, x and y. In some method the following logical
tests are done:
boolean hashFlag = ( x.hashCode() == y.hashCode() );
boolean equalsFlag = x.equals( y );
boolean eqFlag = ( x == y );
Which of the following statements about the relationship between these tests are true.
(1) If equalsFlag is true, then hashFlag must be true
(2) If hashFlag is true, then eqFlag must be true
(3) If equalsFlag is false, then eqFlag must be false
(4) if hashFlag is false, then eqFlag must be false
Answer : -------------------------
* * * *
3] 2
Explanation:
Although bContinue does get set to true, the setPrice call is blocked because setPrice and run are both
synchronized.
* * * *
4] 4
Explanation:
If that seems a vauge answer it is because you cannot be certain of the system that the underlying OS uses for
allocating cycles for a Thread. The chances are that once the thread has been spun off in the call to start in the
methodname() the main method will run to completion and the value of sName will still be vandeluer before the
Thread modifies it. You cannot be certain of this though.
Just because sName is static does not mean that passing it to a method gives the method the original copy. The
method only sees a locally created copy and any changes to it will not be reflected on return to the calling
method.
* * * *
5] 2,3
Explanation:
Generally speaking, all I/O operations require explicit exception handling with try/catch blocks. The JDK 1.4
exams does not explicitly cover I/O but it may be referred to in the context of exception handling.
* * * *
6] 1
Explanation:
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 isneeded to convert a double to an int.
* * * *
7] 4
Explanation:
All wrapper class objects are immutable.
* * * *
8] 2
Explanation:
The TreeMap class stores the keys rather than the values in sorted order.
* * * *
9] 3
Explanation:
Constructors are executed in order of the oldest ancester down, so the output from Biddy is seen before Val.
Although the the paremeter for shep has no floating point component, a widening conversion involves no loss of
precisionand thus the value is cast to a float by the method shep. By default a float will have a decimal component
and thus it has a trailing zero in this example.
* * * *
10] 2,3,4
Explanation:
Please see Java 1.2/1.4 API documentation.
* * * *
11] 1
Explanation:
An int cannot have a fractional component, under JDK1.4 this produced the error message
possible loss of precision found : double required: int
private int iAcres=3.5;
* * * *
12] 2,3
Explanation:
A variable declared as public within a method is only visible within the method. They are sometimes called
automatic variables as they automatically come into scope when the method runs and are out of scope when the
method hasfinished execution. Variables declared within methods cannot be marked as static. A method declared
with no visibility modifier is accessible anywhere from within the current package.A method declared with the
protected modifier is also accessible in child classes that are not in the current package.
* * * *
13] 3
Explanation:
Option 4 is incorrect because an assert statment must make a comparison and the single = sign indicates an
assignment.The assert statement does not use curly braces and assert cannot be used like a parameterless
method call as in assert() in option 1.
* * * *
14] 4
Explanation:
On line 9 the object created on line 8 has the reference sb2 pointed to it. Until something happens to make that
reference unable to reach the object it will not be eligible for garbage collection.
* * * *
15] 3
Explanation:
The == operator should never be used to test the equivalence of strings as it will only test the reference, not the
sequence of characters. To test if the Strings match use the String equals() method.
* * * *
16] 1
Explanation:
There is no rule against constructors being marked as private.
* * * *
17] 2
Explanation:
This code will produce a java.lang.IllegalMonitorStateException at runtime because the wait/notify code is not
within synchronized code.
* * * *
18] 1,2,4
Explanation:
The LinkedHashMap was added with JDK1.4. Option 3 is nonsense because if something is sorted that imposes an
order (however something may be ordered without being sorted).
* * * *
19] 1
Explanation:
No problem here, the code compiles fine. One thing to be aware of is that i+++ ++i compiles fine because of the
way Java code is actually parsed. The parser tokenizes the source in bunches of longest valid character
sequences. i+++ ++i will betokenized as i,++,+,++,i and interpreted as i++ + ++i, that is i post-incremented
plus i pre-incremented. Then you have to know how the ternary conditional ?: operator works, that is, it always
evaluates its first operand and then depending onthe results, evaluates the second OR the third operand (never
both). So getBoolean() returns either true or false, thus the code either prints i=2*i++ or i+++ ++i. The former
is equivalent to i=2*i and the latter to 2*i+2.
* * * *
20] 2
Explanation:
ArithmeticExceptions are considered programmer problems, and are not checked by the compiler. A divide-byzero
error, for example, should be checked for by your own code. (from Java Ranch round up game)
* * * *
21] negative
Explanation:
The right shift operator fills all bits from the left with the same value as the original sign bit -- in this case 1. (from
Java Ranch round up game)
* * * *
22] 2
Explanation:
The case argument must be either an int literal, or an int-compatible variable which is a constant ie., static final.
* * * *
23] 2
Explanation:
This would be true for overriding methods, but overloaded methods are free to throw new checked exceptions.
(from Java Ranch)
* * * *
24] 3
Explanation:
Assigning null to a reference will only cause the object it references to be ready for garbage collection if no other
reference points to it.It is possible to create an object inside a method and to also assign a reference created
outside the method to the same object,so the completion of a method is no guarantee that an object is eligable for
garbage collection.
* * * *
25] 1,2
Explanation:
Please see the relevant API.
* * * *
26] 2,3
Explanation:
--
* * * *
27] 1
Explanation:
Options 2 will output 10.0 and option 3 will output 10.1. Option 4 will cause a compilation error, because the
Math.min method takes two arguments (from www.examulator.com)
* * * *
28] 1
Explanation:
This represents a fairly useless but correct implementation of hashCode by using the version inherited from Object
which uses the memory address of the object to generatethe hashCode value. (from www.examulator.com)
* * * *
29] 3
Explanation:
A call to yield can allow any waiting thread to execute depending on the scheduling system of the underlying
operating system. There is no version of yield that takes aninteger parameter.Weather a higher priority thread
gets CPU time than a lower priorty thread is platform dependent and cannot be certain. (from
www.examulator.com)
* * * *
30] newThread.setPriority(Math.min(Thread.MAX_PRIORITY,newThread.getPriority()+1));
Explanation:
--
* * * *
31] 1
Explanation:
--
* * * *
32] 16
Explanation:
The default capacity for any StringBuffer object is 16 + the length of the String specified as the argument. If none
specified, it will be 16. Capacity can also be specifiedusing the other constructor StringBuffer(int capacity).
* * * *
33] 3
Explanation:
Capacity of a StringBuffer object is always the length of the string + 16 (unless the capacity is specified using
StringBuffer(int capacity))
* * * *
34] strBuf.setLength(strBuf.length());
Explanation:
Please see the StringBuffer API.
* * * *
35] 2
Explanation:
The expression tries to compare two references and will fail, since neither String nor StringBuffer is a super class
of the other [from Khalid's book]
* * * *
36] 4
Explanation:
The instance of the Harpic class will probably not be garbage collected at all, and thus the finalize method will not
be run (but it could be).(from www.examulator.com)
* * * *
37] 4
Explanation:
The TSamp has no constructor defined that takes a class of type Runnable, and as constructors are not inherited
the code will not compile. (from www.examulator.com)
* * * *
38] 3,4
Explanation:
--
* * * *
39] 4
Explanation:
Because the code attempts to insert the string "one" twice, the HashSet hs has only two elements.
It is a good idea when using the add method of HashSet to check the boolean value returned to ensure that the
new element wassuccessfully added.
* * * *
40] 2
Explanation:
java.lang.AssertionError class is a subclass of java.lang.Error and that makes it unchecked.
* * * *
41] 1
Explanation:
Note that n is decremented after the value is printed. (from LanWrights exam)
* * * *
42] 3
Explanation:
The result is ": Arg betagamma:" because the call to trim() does not change s1. (from LanWrights exam)
* * * *
43] 6
Explanation:
Choice 1 & 2 are not correct, 'cause WornPadException extends RuntimeException it is not mandatory to surround
calls to it with a try/catch block. Choice 3 is not correct since thecompiler checks the need for try/catch, not the
runtime. Choice 4 is not correct, because a finally clause can have any code in it. Choice 5 is not correct, since the
final valuereturned is 1. Choice 6 is correct because WornPadException extends RuntimeException it is not
mandatory to surround calls to it with a try/catch block. It is perfectly correct &sometimes useful to have a
try/finally block without a catch statement. Because the finally clause 'll be executed the value returned 'll be that
within the finally clause.
* * * *
44] 1,5
Explanation:
Facts:
The * operator can only work with primitives. The value in a wrapper class object can't be changed once created.
The Character class can only store a char value.(from LanWrights exam)
* * * *
45] 3
Explanation:
Only local variables declared final can be used by the inner class. (from LanWrights exam)
* * * *
46] 1,3
Explanation:
Since wait is a method in Object and Thread is an object; sleep is a static method; start is an instance method of
Thread; MAX_PRIORITY is a static final variable of Thread;the daemon boolean variable is a private instance
variable. (from LanWrights exam)
* * * *
47] 2,5,6
Explanation:
transient is used as a modifier for variables; generic is not a keyword; as of Java 1.4, assert is a keyword; the
keyword strictfp controls floating point calculations; friend is nota keyword; Java does not use sizeof.
* * * *
48] 2,4
Explanation:
you can't cast any primitive array to another primitive array type, no matter how reasonable it seems; any array
can be cast to an Object reference; you can't cast a primitive arrayto an reference type array. The compiler does
not care that theInts will have a null value when the program runs. (from LanWrights exam)
* * * *
49] 2
Explanation:
the equals method is defined in terms of taking an Object reference so there is no problem; the equals test fails
because the objects are of different types, but the charValuereturn is promoted to int and the result is true; the
equals test fails because the objects are of different types; only the == comparison will result in true. Note that
the compilerpromotes the charValue return to int; promotion of the char value to int is automatic. (Credit:
LanWrights)
* * * *
50] 1,3,4
Explanation:
(1) yes, this is a requirement for hashcodes and the equals method; (2) no, two objects not equal by the == test
may still have identical hashcodes (3) Yes, if the equals() testreturns false, x and y can't possibly refer to the
same object (4) Yes, this is a requirement for hashcodes and the equals method. (Credit: LanWrights)
* * * *
JavaBeat 2005, India (www.javabeat.net)
Submit a Site - Directory - Submit Articles
No comments:
Post a Comment