Cracked bits for scjp

394
========================================================== Cracked By Charitra Choudhary Any Help, Plz Feel Free to mail ([email protected]) MCSE, MCSE, CCNA, Comptia A+, N+, JCP, MCAD, MCSD, MVP ========================================================== Question 1) Which of the following lines will compile without warning or error. 1) float f=1.3; 2) char c="a"; 3) byte b=257; 4) boolean b=null; 5) int i=10; Question 2) What will happen if you try to compile and run the following code public class MyClass { public static void main(String arguments[]) { amethod(arguments); } public void amethod(String[] arguments) { System.out.println(arguments); System.out.println(arguments[1]); } } 1) error Can't make static reference to void amethod. 2) error method main not correct 3) error array must include parameter 4) amethod must be declared with String Question 3) Which of the following will compile without error 1) import java.awt.*; package Mypackage; class Myclass {}

description

scjp

Transcript of Cracked bits for scjp

Page 1: Cracked bits for scjp

==========================================================Cracked By Charitra ChoudharyAny Help, Plz Feel Free to mail ([email protected]) MCSE, MCSE, CCNA, Comptia A+, N+, JCP, MCAD, MCSD, MVP==========================================================

Question 1)Which of the following lines will compile without warning or error. 1) float f=1.3; 2) char c="a"; 3) byte b=257; 4) boolean b=null; 5) int i=10;

Question 2)What will happen if you try to compile and run the following code public class MyClass { public static void main(String arguments[]) { amethod(arguments); } public void amethod(String[] arguments) { System.out.println(arguments); System.out.println(arguments[1]); } }1) error Can't make static reference to void amethod. 2) error method main not correct 3) error array must include parameter 4) amethod must be declared with String

Question 3)Which of the following will compile without error 1) import java.awt.*; package Mypackage; class Myclass {}2) package MyPackage; import java.awt.*; class MyClass{}3) /*This is a comment */ package MyPackage; import java.awt.*; class MyClass{}

Page 2: Cracked bits for scjp

Question 4)A byte can be of what size 1) -128 to 127 2) (-2 power 8 )-1 to 2 power 8 3) -255 to 256 4)depends on the particular implementation of the Java Virtual machine

Question 5)What will be printed out if this code is run with the following command line? java myprog good morningpublic class myprog{ public static void main(String argv[]){ System.out.println(argv[2]) }}1) myprog 2) good 3) morning 4) Exception raised: "java.lang.ArrayIndexOutOfBoundsException: 2"

Question 6)Which of the following are keywords or reserved words in Java? 1) if 2) then 3) goto 4) while 5) case

Question 7)Which of the following are legal identifiers 1) 2variable 2) variable2 3) _whatavariable 4) _3_ 5) $anothervar 6) #myvar

Question 8)What will happen when you compile and run the following code?

Page 3: Cracked bits for scjp

public class MyClass{ static int i; public static void main(String argv[]){ System.out.println(i); } }1) Error Variable i may not have been initialized 2) null 3) 1 4) 0

Question 9)What will happen if you try to compile and run the following code? public class Q { public static void main(String argv[]){ int anar[]=new int[]{1,2,3}; System.out.println(anar[1]); } }1) 1 2) Error anar is referenced before it is initialized 3) 2 4) Error: size of array must be defined

Question 10)

What will happen if you try to compile and run the following code? public class Q { public static void main(String argv[]){ int anar[]=new int[5]; System.out.println(anar[0]); } }1) Error: anar is referenced before it is initialized 2) null 3) 0 4) 5

Question 11)

What will be the result of attempting to compile and run the following code? abstract class MineBase { abstract void amethod();

Page 4: Cracked bits for scjp

static int i; }public class Mine extends MineBase { public static void main(String argv[]){ int[] ar=new int[5]; for(i=0;i < ar.length;i++) System.out.println(ar[i]); } }1) a sequence of 5 0's will be printed 2) Error: ar is used before it is initialized 3) Error Mine must be declared abstract 4) IndexOutOfBoundes Error

Question 12)What will be printed out if you attempt to compile and run the following code ? int i=1; switch (i) { case 0: System.out.println("zero"); break; case 1: System.out.println("one"); case 2: System.out.println("two"); default: System.out.println("default"); }1) one 2) one, default 3) one, two, default 4) default

Question 13)What will be printed out if you attempt to compile and run the following code? int i=9; switch (i) { default: System.out.println("default"); case 0: System.out.println("zero"); break; case 1: System.out.println("one");

Page 5: Cracked bits for scjp

case 2: System.out.println("two"); }1) default 2) default, zero 3) error default clause not defined 4) no output displayed

Question 14)Which of the following lines of code will compile without error 1) int i=0; if(i) { System.out.println("Hello"); }2) boolean b=true; boolean b2=true; if(b==b2) { System.out.println("So true"); }3) int i=1; int j=2; if(i==1|| j==2) System.out.println("OK");4) int i=1; int j=2; if(i==1 &| j==2) System.out.println("OK");

Question 15)What will be output if you try to compile and run the following code, but there is no file called Hello.txt in the current directory?. import java.io.*; public class Mine { public static void main(String argv[]){ Mine m=new Mine(); System.out.println(m.amethod()); }public int amethod() { try { FileInputStream dis=new FileInputStream("Hello.txt");

Page 6: Cracked bits for scjp

}catch (FileNotFoundException fne) { System.out.println("No such file found"); return -1; }catch(IOException ioe) { } finally{ System.out.println("Doing finally"); } return 0; } }1) No such file found 2 No such file found ,-1 3) No such file found, Doing finally, -1 4) 0

Question 16)Which of the following statements are true? 1) Methods cannot be overriden to be more private2) Static methods cannot be overloaded3) Private methods cannot be overloaded4) An overloaded method cannot throw exceptions not checked in the base class

Question 17)What will happen if you attempt to compile and run the following code? 1) Compile and run without error 2) Compile time Exception 3) Runtime Exception class Base {} class Sub extends Base {} class Sub2 extends Base {}public class CEx{ public static void main(String argv[]){ Base b=new Base(); Sub s=(Sub) b; }}

Question 18)If the following HTML code is used to display the applet in the code MgAp what will be displayed at the console? 1) Error: no such parameter 2) 0 3) null

Page 7: Cracked bits for scjp

4) 30 <applet name=MgAp code=MgAp.class height=400 width=400 parameter HowOld=30 > </applet> import java.applet.*; import java.awt.*; public class MgAp extends Applet{ public void init(){ System.out.println(getParameter("age")); } }

Question 19)You are browsing the Java HTML documentation for information on the java.awt.TextField component. You want to create Listener code to respond to focus events. The only Listener method listed is addActionListener. How do you go about finding out about Listener methods? 1) Define your own Listener interface according to the event to be tracked 2) Use the search facility in the HTML documentation for the listener needed 3) Move up the hierarchy in the HTML documentation to locate methods in base classes 4) Subclass awt.event with the appropriate Listener method

Question 20)

What will be displayed when you attempt to compile and run the following code //Code start import java.awt.*;public class Butt extends Frame{public static void main(String argv[]){ Butt MyBut=new Butt(); }Butt(){ Button HelloBut=new Button("Hello"); Button ByeBut=new Button("Bye"); add(HelloBut); add(ByeBut); setSize(300,300); setVisible(true); } } //Code end1) Two buttons side by side occupying all of the frame, Hello on the left and Bye on the right

Page 8: Cracked bits for scjp

2) One button occupying the entire frame saying Hello 3) One button occupying the entire frame saying Bye 4) Two buttons at the top of the frame one saying Hello the other saying Bye

Question 21)

What will be output by the following code? public class MyFor{public static void main(String argv[]){ int i; int j; outer: for (i=1;i <3;i++) inner: for(j=1; j<3; j++) { if (j==2) continue outer; System.out.println("Value for i=" + i + " Value for j=" +j); } } }1) Value for i=1 value for j=1 2) Value for i=2 value for j=1 3) Value for i=2 value for j=2 4) Value for i=3 value for j=1

Question 22)

If g is a graphics instance what will the following code draw on the screen?. g.fillArc(45,90,50,50,90,180);1) An arc bounded by a box of height 45, width 90 with a centre point of 50,50, starting at an angle of 90 degrees traversing through 180 degrees counter clockwise. 2) An arc bounded by a box of height 50, width 50, with a centre point of 45,90 starting at an angle of 90 degrees traversing through 180 degrees clockwise. 3) An arc bounded by a box of height 50, width 50, with a top left at coordinates of 45, 90, starting at 90 degrees and traversing through 180 degrees counter clockwise. 4) An arc starting at 45 degrees, traversing through 90 degrees clockwise bounded by a box of height 50, width 50 with a centre point of 90, 180.

Question 23)

Which of the following methods can be legally inserted in place of the comment //Method Here ? class Base{

Page 9: Cracked bits for scjp

public void amethod(int i) { }} public class Scope extends Base{ public static void main(String argv[]){ } //Method Here}1) void amethod(int i) throws Exception {} 2) void amethod(long i)throws Exception {} 3) void amethod(long i){} 4) public void amethod(int i) throws Exception {}

Question 24)

Which of the following will output -4.0 1) System.out.println(Math.floor(-4.7)); 2) System.out.println(Math.round(-4.7)); 3) System.out.println(Math.ceil(-4.7)); 4) System.out.println(Math.min(-4.7));

Question 25)

What will happen if you attempt to compile and run the following code? Integer ten=new Integer(10); Long nine=new Long (9);System.out.println(ten + nine); int i=1;System.out.println(i + ten);1) 19 followed by 20 2) 19 followed by 11 3) Error: Can't convert java lang Integer 4) 10 followed by 1

Question 26)

If you run the code below, what gets printed out? String s=new String("Bicycle"); int iBegin=1; char iEnd=3; System.out.println(s.substring(iBegin,iEnd));1) Bic 2) ic 3) icy

Page 10: Cracked bits for scjp

4) error: no method matching substring(int,char)

Question 27)If you wanted to find out where the position of the letter v (ie return 2) in the string s containing "Java", which of the following could you use? 1) mid(2,s); 2) charAt(2); 3) s.indexOf('v'); 4) indexOf(s,'v');

Question 28)Given the following declarations String s1=new String("Hello") String s2=new String("there"); String s3=new String();Which of the following are legal operations? 1) s3=s1 + s2; 2) s3=s1-s2; 3) s3=s1 & s2; 4) s3=s1 && s2

Question 29)What is the result of the following operation? System.out.println(4 | 3); 1) 6 2) 0 3) 1 4) 7

Question 30)public class MyClass1 {public static void main(String argv[]){ } /*Modifier at XX */ class MyInner {}}What modifiers would be legal at XX in the above code? 1) public 2) private 3) static 4) friend

Question 31)

Page 11: Cracked bits for scjp

How would you go about opening an image file called MyPicture.jpg 1) Graphics.getGraphics("MyPicture.jpg"); 2) Image image=Toolkit.getDefaultToolkit().getImage("MyPicture.jpg"); 3) Graphics.openImage("MyPicture"); 4) Image m=new Image("MyPicture");

Question 32)An Applet has its Layout Manager set to the default of FlowLayout. What code would be correct to change to another Layout Manager. 1) setLayoutManager(new GridLayout()); 2) setLayout(new GridLayout(2,2)); 3) setGridLayout(2,2);4) setBorderLayout();

Question 33)

What will happen when you attempt to compile and run the following code?. 1) It will compile and the run method will print out the increasing value of i. 2) It will compile and calling start will print out the increasing value of i. 3) The code will cause an error at compile time. 4) Compilation will cause an error because while cannot take a parameter of true. class Background implements Runnable{ int i=0; public int run(){ while(true){ i++; System.out.println("i="+i); } //End while

return 1; }//End run }//End class

Question 34)You have created an applet that draws lines. You have overriden the paint operation and used the graphics drawLine method, and increase one of its parameters to multiple lines across the screen. When you first test the applet you find that the news lines are redrawn, but the old lines are erased. How can you modify your code to allow the old lines to stay on the screen instead of being cleared. 1) Override repaint thus public void repaint(Graphics g){ paint(g);

Page 12: Cracked bits for scjp

}2)Override update thus public void update(Graphics g) { paint(g); }3) turn off clearing with the method setClear(); 4) Remove the drawing from the paint Method and place in the calling code

Question 35)

What will be the result when you attempt to compile and run the following code?. public class Conv{ public static void main(String argv[]){ Conv c=new Conv(); String s=new String("ello"); c.amethod(s); } public void amethod(String s){ char c='H'; c+=s; System.out.println(c); } }1) Compilation and output the string "Hello" 2) Compilation and output the string "ello" 3) Compilation and output the string elloH 4) Compile time error

Question 36)Given the following code, what test would you need to put in place of the comment line? //place test here to result in an output of Equalpublic class EqTest{ public static void main(String argv[]){ EqTest e=new EqTest(); }EqTest(){ String s="Java"; String s2="java"; //place test here { System.out.println("Equal"); }else {

Page 13: Cracked bits for scjp

System.out.println("Not equal"); } } }1) if(s==s2) 2) if(s.equals(s2) 3) if(s.equalsIgnoreCase(s2)) 4)if(s.noCaseMatch(s2))

Question 37)Given the following code import java.awt.*;public class SetF extends Frame{public static void main(String argv[]){ SetF s=new SetF(); s.setSize(300,200); s.setVisible(true); }}How could you set the frame surface color to pink 1)s.setBackground(Color.pink); 2)s.setColor(PINK); 3)s.Background(pink); 4)s.color=Color.pink

Question 38)

How can you change the current working directory using an instance of the File class called FileName? 1) FileName.chdir("DirName") 2) FileName.cd("DirName") 3) FileName.cwd("DirName") 4) The File class does not support directly changing the current directory.

Question 39)If you create a TextField with a constructor to set it to occupy 5 columns, what difference will it make if you use it with a proportional font (ie Times Roman) or a fixed pitch typewriter style font (Courier). 1)With a fixed font you will see 5 characters, with a proportional it will depend on the width of the characters 2)With a fixed font you will see 5 characters,with a proportional it will cause the field to expand to fit the text 3)The columns setting does not affect the number of characters displayed

Page 14: Cracked bits for scjp

4)Both will show exactly 5 characters

Question 40)

Given the following code how could you invoke the Base constructor that will print out the string "base constructor"; class Base{ Base(int i){ System.out.println("base constructor"); } Base(){ }}public class Sup extends Base{ public static void main(String argv[]){ Sup s= new Sup(); //One } Sup() { //Two } public void derived() { //Three }}1) On the line After //One put Base(10); 2) On the line After //One put super(10); 3) On the line After //Two put super(10); 4) On the line After //Three put super(10);

Question 41)Given the following code what will be output? public class Pass{static int j=20;public static void main(String argv[]){ int i=10; Pass p = new Pass(); p.amethod(i); System.out.println(i); System.out.println(j); } public void amethod(int x){

Page 15: Cracked bits for scjp

x=x*2; j=j*2; }}1) Error: amethod parameter does not match variable 2) 20 and 40 3) 10 and 40 4) 10, and 20

Question 42)

What code placed after the comment //For loop would populate the elements of the array ia[] with values of the variable i.? public class Lin{public static void main(String argv[]){ Lin l = new Lin(); l.amethod(); } public void amethod(){ int ia[] = new int[4]; //Start For loop { ia[i]=i; System.out.println(ia[i]); } }}1) for(int i=0; i < ia.length() -1; i++) 2) for (int i=0; i< ia.length(); i++) 3) for(int i=1; i < 4; i++) 4) for(int i=0; i< ia.length;i++)

Question 43)

What will be the result when you try to compile and run the following code? private class Base{Base(){ int i = 100; System.out.println(i); }}public class Pri extends Base{static int i = 200;public static void main(String argv[]){

Page 16: Cracked bits for scjp

Pri p = new Pri(); System.out.println(i); }}1) Error at compile time 2) 200 3) 100 followed by 200 4) 100

Question 44)What will the following code print out? public class Oct{public static void main(String argv[]){ Oct o = new Oct(); o.amethod(); } public void amethod(){ int oi= 012; System.out.println(oi); }}1)12 2)012 3)10 4)10.0

Question 45What will happen when you try compiling and running this code? public class Ref{public static void main(String argv[]){ Ref r = new Ref(); r.amethod(r); } public void amethod(Ref r){ int i=99; multi(r); System.out.println(i); } public void multi(Ref r){ r.i = r.i*2; }}1) Error at compile time 2) An output of 99

Page 17: Cracked bits for scjp

3) An output of 198 4) An error at runtime

Question 46)You need to create a class that will store a unique object elements. You do not need to sort these elements but they must be unique. What interface might be most suitable to meet this need? 1)Set 2)List 3)Map 4)Vector

Question 47)Which of the following will successfully create an instance of the Vector class and add an element? 1) Vector v=new Vector(99); v[1]=99; 2) Vector v=new Vector(); v.addElement(99); 3) Vector v=new Vector(); v.add(99); 4 Vector v=new Vector(100); v.addElement("99");

Question 48)You have created a simple Frame and overridden the paint method as follows public void paint(Graphics g){ g.drawString("Dolly",50,10);}

What will be the result when you attempt to compile and run the program? 1) The string "Dolly" will be displayed at the centre of the frame 2) An error at compilation complaining at the signature of the paint method 3) The lower part of the word Dolly will be seen at the top of the frame, with the top hidden. 4) The string "Dolly" will be shown at the bottom of the frame.

Question 49)What will be the result when you attempt to compile this program? public class Rand{public static void main(String argv[]){ int iRand; iRand = Math.random();

Page 18: Cracked bits for scjp

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

Question 50)Given the following code import java.io.*;public class Th{ public static void main(String argv[]){ Th t = new Th(); t.amethod(); } public void amethod(){ try{ ioCall(); }catch(IOException ioe){} } }What code would be most likely for the body of the ioCall method 1) public void ioCall ()throws IOException{ DataInputStream din = new DataInputStream(System.in); din.readChar(); }2) public void ioCall ()throw IOException{ DataInputStream din = new DataInputStream(System.in); din.readChar(); }3) public void ioCall (){ DataInputStream din = new DataInputStream(System.in); din.readChar(); }4) public void ioCall throws IOException(){ DataInputStream din = new DataInputStream(System.in); din.readChar(); }

Question 51)What will happen when you compile and run the following code? public class Scope{

Page 19: Cracked bits for scjp

private int i;public static void main(String argv[]){ Scope s = new Scope(); s.amethod(); }//End of main public static void amethod(){ System.out.println(i); }//end of amethod}//End of class1) A value of 0 will be printed out 2) Nothing will be printed out 3) A compile time error 4) A compile time error complaining of the scope of the variable i

Question 52)

You want to lay out a set of buttons horizontally but with more space between the first button and the rest. You are going to use the GridBagLayout manager to control the way the buttons are set out. How will you modify the way the GridBagLayout acts in order to change the spacing around the first button? 1) Create an instance of the GridBagConstraints class, call the weightx() method and then pass the GridBagConstraints instance with the component to the setConstraints method of the GridBagLayout class. 2) Create an instance of the GridBagConstraints class, set the weightx field and then pass the GridBagConstraints instance with the component to the setConstraints method of the GridBagLayout class. 3) Create an instance of the GridBagLayout class, set the weightx field and then call the setConstraints method of the GridBagLayoutClass with the component as a parameter. 4) Create an instance of the GridBagLayout class, call the setWeightx() method and then pass the GridBagConstraints instance with the component to the setConstraints method of the GridBagLayout class.

Question 53)

Which of the following can you perform using the File class? 1) Change the current directory 2) Return the name of the parent directory 3) Delete a file 4) Find if a file contains text or binary information

Question 54)Which of the following code fragments will compile without error 1)

Page 20: Cracked bits for scjp

public void paint(Graphics g){ int polyX[] = {20,150,150}; int polyY[]= {20,20,120}; g.drawPolygon(polyX, polyY,3); }2)public void paint(Graphics g){ int polyX[] = {20,150,150}; int polyY[]= {20,20,120}; g.drawPolygon(polyX, polyY); }3)public void paint(Graphics g){ int polyX[3] = {20,150,150}; int polyY[3]= {20,20,120}; g.drawPolygon(polyX, polyY,3); }4)public void paint(Graphics g){ int polyX[] = {20,150,150}; int polyY[]= {20,20,120}; drawPolygon(polyX, polyY); }

Question 55)You are concerned that your program may attempt to use more memory than is available. To avoid this situation you want to ensure that the Java Virtual Machine will run its garbage collection just before you start a complex routine. What can you do to be certain that garbage collection will run when you want . 1) You cannot be certain when garbage collection will run 2) Use the Runtime.gc() method to force garbage collection 3) Ensure that all the variables you require to be garbage collected are set to null 4) Use the System.gc() method to force garbage collection

Question 56)You are using the GridBagLayout manager to place a series of buttons on a Frame. You want to make the size of one of the buttons bigger than the text it contains. Which of the following will allow you to do that? 1) The GridBagLayout manager does not allow you to do this 2) The setFill method of the GridBagLayout class 3) The setFill method of the GridBagConstraints class 4) The fill field of the GridBagConstraints class

Page 21: Cracked bits for scjp

Question 57)Which of the following most closely describes a bitset collection? 1) A class that contains groups of unique sequences of bits 2) A method for flipping individual bits in instance of a primitive type 3) An array of boolean primitives that indicate zeros or ones 4) A collection for storing bits as on-off information, like a vector of bits

Question 58)

You have these files in the same directory. What will happen when you attempt to compile and run Class1.java if you have not already compiled Base.java //Base.javapackage Base;class Base{ protected void amethod(){ System.out.println("amethod"); }//End of amethod}//End of class basepackage Class1;//Class1.javapublic class Class1 extends Base{

public static void main(String argv[]){ Base b = new Base(); b.amethod(); }//End of main}//End of Class11) Compile Error: Methods in Base not found 2) Compile Error: Unable to access protected method in base class 3) Compilation followed by the output "amethod" 4)Compile error: Superclass Class1.Base of class Class1.Class1 not found

Question 59)What will happen when you attempt to compile and run the following code class Base{private void amethod(int iBase){ System.out.println("Base.amethod"); }}

class Over extends Base{

public static void main(String argv[]){

Page 22: Cracked bits for scjp

Over o = new Over(); int iBase=0; o.amethod(iBase); } public void amethod(int iOver){ System.out.println("Over.amethod"); }

}1) Compile time error complaining that Base.amethod is private 2) Runtime error complaining that Base.amethod is private 3) Output of "Base.amethod"4) Output of "Over.amethod"

Question 60)You are creating an applet with a Frame that contains buttons. You are using the GridBagLayout manager and you have added Four buttons. At the moment the buttons appear in the centre of the frame from left to right. You want them to appear one on top of the other going down the screen. What is the most appropriate way to do this. 1) Set the gridy value of the GridBagConstraint class to a value increasing from 1 to 4 2) set the fill value of the GridBagConstraint class to VERTICAL 3) Set the ipady value of the GridBagConstraint class to a value increasing from 0 to 4 4) Set the fill value of the GridBagLayout class to GridBag.VERTICAL

Answers

Answer 1) Objective 4.5)5) int i=10; explanation: 1) float f=1.3; Will not compile because the default type of a number with a floating point component is a double. This would compile with a cast as in float f=(float) 1.3 2) char c="a"; Will not compile because a char (16 bit unsigned integer) must be defined with single quotes. This would compile if it were in the form char c='a'; 3) byte b=257; Will not compile because a byte is eight bits. Take of one bit for the sign component you can define numbers between -128 to +127

Page 23: Cracked bits for scjp

4) a boolean value can either be true of false, null is not allowed.

Answer 2) Objective 4.1 1) Can't make static reference to void amethod. Because main is defined as static you need to create an instance of the class in order to call any non-static methods. Thus a typical way to do this would be. MyClass m=new MyClass(); m.amethod(); Answer 2 is an attempt to confuse because the convention is for a main method to be in the form String argv[] That argv is just a convention and any acceptable identifier for a string array can be used. Answers 3 and 4 are just nonsense.

Answer 3)

Objective 4.1)2 and 3 will compile without error. 1 will not compile because any package declaration must come before any other code. Comments may appear anywhere.

Answer 4)

Objective 4.5) 1) A byte is a signed 8 bit integer.

Answer 5)

Objective 4.2) 4) Exception raised: "java.lang.ArrayIndexOutOfBoundsException: 2" Unlike C/C++ java does not start the parameter count with the program name. It does however start from zero. So in this case zero starts with good, morning would be 1 and there is no parameter 2 so an exception is raised.

Answer 6)

Objective 1.5) 1) if 3) goto 4) while 5) case then is not a Java keyword, though if you are from a VB background you might think it was. Goto is a reserved word in Java.

Answer 7)

Page 24: Cracked bits for scjp

Objective 1.10) 2) variable2 3) _whatavariable 4) _3_ 5) $anothervar An identifier can begin with a letter (most common) or a dollar sign($) or an underscore(_). An identifier cannot start with anything else such as a number, a hash, # or a dash -. An identifier cannot have a dash in its body, but it may have an underscore _. Choice 4) _3_ looks strange but it is an acceptable, if unwise form for an identifier.

Answer 8) Objective 1.6) 4) 0 Class level variables are always initialised to default values. In the case of an int this will be 0. Method level variables are not given default values and if you attempt to use one before it has been initialised it will cause the Error Variable i may not have been initializedtype of error.

Answer 9)

Objective 1.7,3.4) 3 ) 2 No error will be triggered. Like in C/C++, arrays are always referenced from 0. Java allows an array to be populated at creation time. The size of array is taken from the number of initializers. If you put a size within any of the square brackets you will get an error.

Answer 10) Objective 1.7) 3) 0 Arrays are always initialised when they are created. As this is an array of ints it will be initalised with zeros.

Answer 11)

Objective 3.6 3) Error Mine must be declared abstract A class that contains an abstract method must itself be declared as abstract. It may however contain non abstract methods. Any class derived from an abstract class must either define all of the abstract methods or be declared abstract itself.

Answer 12)

Page 25: Cracked bits for scjp

Objective 4.1) 3) one, two, default Code will continue to fall through a case statement until it encounters a break.

Answer 13)

Objective 4.1) 2) default, zero Although it is normally placed last the default statement does not have to be the last item as you fall through the case block. Because there is no case label found matching the expression the default label is executed and the code continues to fall through until it encounters a break.

Answer 14) Objective 4.2, 2,3 Example 1 will not compile because if must always test a boolean. This can catch out C/C++ programmers who expect the test to be for either 0 or not 0.

Answer 15)

Objective 4.5) 3) No such file found, doing finally, -1 The no such file found message is to be expected, however you can get caught out if you are not aware that the finally clause is almost always executed, even if there is a return statement.

Answer 16)

Objective 1) Methods cannot be overriden to be more privateStatic methods cannot be overriden but they can be overloaded. There is no logic or reason why private methods should not be overloaded. Option 4 is a jumbled up version of the limitations of exceptions for overriden methods

Answer 17) Objective 5.8 (sort of) 3) Runtime Exception Without the cast to sub you would get a compile time error. The cast tells the compiler that you really mean to do this and the actual type of b does not get resolved until runtime. Casting down the object hierarchy as the compiler cannot be sure what has been implemented in descendent classes. Casting up is not a problem because sub classes will have the features of the base classes. This can feel counter intuitive if you are aware that with primitives casting is allowed for widening operations (ie byte to int).

Page 26: Cracked bits for scjp

Answer 18) Objective unknown 3) null If a parameter is not available the applet will still run, but any attempt to access the parameter will return a null.

Answer 19) Objective 1.1) 3) Move up the hierarchy in the HTML documentation to locate methods in base classes The documentation created by JavaDoc is based on tags placed into the sourcecode. The convention for documentation is that methods and fields of ancestors are not duplicated in sub classes. So if you are looking for something and it does not appear to be there, you move up the class hierarchy to find it.

Answer 20)

Objective 10.4) 3) One button occupying the entire frame saying Bye The default layout manager for a Frame is a border layout. If directions are not given (ie North, South, East or West), any button will simply go in the centre and occupy all the space. An additional button will simply be placed over the previous button. What you would probably want in a real example is to set up a flow layout as in setLayout(new FlowLayout());

Which would allow the buttons to both appear side by side, given the appropriate font and size.Applets and panels have a default FlowLayout manager

Answer 21) Objective 4.4) 1,2 Value for i=1 Value for j=1 Value for i=2 Value for j=1 The statement continue outer causes the code to jump to the label outer and the for loop increments to the next number.

Answer 22) Objective 9.5) 3) An arc bounded by a box of height 50, width 50, with a top left at coordinates of 45, 90, starting at 90 degrees and traversing through 180 degrees counter clockwise.

Page 27: Cracked bits for scjp

fillArc(int x, int y, int width, int height, int startDegrees, int arcDegrees) The fillArc function draws an arc in a box with a top left at coordinates X & Y. If the ArcDegrees is a positive number the arc is drawn counter clockwise.

Answer 23)

Objective 4.7) 2,3 Options 1, & 4 will not compile as they attempt to throw Exceptions not declared in the base class. Because options 2 and 4 take a parameter of type long they represent overloading not overriding and there is no such limitations on overloaded methods.

Answer 24) Objective 8.1) 3) System.out.println(Math.ceil(-4.7)); Options 1 and 2 will produce -5 and option 4 will not compile because the min method requires 2 parameters.

Answer 25) Objective 2.2 3) Error: Cant convert java lang Integer The wrapper classes cannot be used like primitives. Wrapper classes have similar names to primitives but all start with upper case letters. Thus in this case we have int as a primitive and Integer as a wrapper. The objectives do not specifically mention the wrapper classes but don't be surprised if they come up.

Answer 26)

Objective 8.2) 2) ic This is a bit of a catch question. Anyone with a C/C++ background would figure out that addressing in strings starts with 0 so that 1 corresponds to i in the string Bicycle. The catch is that the second parameter returns the endcharacter minus 1. In this case it means instead of the "icy" being returned as intuition would expect it is only "ic".

Answer 27) Objective 8.2) 3) s.indexOf('v'); charAt returns the letter at the position rather than searching for a letter and returning the position, MID is just to confuse the Basic Programmers, indexOf(s,'v'); is how some future VB/J++ nightmare hybrid, might perform such a calculation.

Answer 28)

Page 28: Cracked bits for scjp

Objective 2.2

1) s3=s1 + s2; Java does not allow operator overloading as in C++, but for the sake of convenience the + operator is overridden for strings.

Answer 29) Objective 2.5) 4) 7 The | is known as the Or operator, you could think of it as the either/or operator. Turning the numbers into binary gives 4=100 3=011 For each position, if either number contains a 1 the result will contain a result in that position. As every position contains a 1 the result will be 111 Which is decimal 7.

Answer 30)

Objective 3.7) 1,2,3 public, private, static are all legal access modifiers for this inner class.

Answer 31) Objective 9.6) Opening an image file requires an Image object, The Image class has no constructor that takes the name of an image file . For an application (rather than an applet) an image is created using the Toolkit class as in option 2. 2) Image image=Toolkit.getDefaultToolkit().getImage("MyPicture.jpg");

Answer 32) Objective 1.3) 2) setLayout(new GridLayout(2,2)); Changing the layout manager is the same for an Applet or an application. Answer 1 is wrong though it might have been a reasonable name for the designers to choose. Answers 3 and 4 are incorrect because changing the layout manager always requires an instance of one of the Layout Managers and these are bogus methods. Instead of creating the anonymous instance of the Layout manager as in option 2 you can also create a named instance and pass that as a parameter. This is often what automatic code generators such as Borland/Inprise JBuilder do.

Answer 33)

Page 29: Cracked bits for scjp

Objective 7.2) 3) The code will cause an error at compile time The error is caused because run should have a void not an int return type. Any class that is implements an interface must create a method to match all of the methods in the interface. The Runnable interface has one method called run that has a void return type.The sun compiler gives the error Method redefined with different return type: int run() was defined as void run();

Answer 34) Objective 11.1) 2) public void update(Graphics g) { paint(g); } If not overridden the update method clears the background and calls paint(); By overriding the update method, any previously drawn graphics will not be cleared. This is only a trivial way of preserving any graphics drawn. If the application is resized or the drawing area covered in some way the graphics will be cleared.

Answer 35) Objective 2.2 4) Compile time error The only operator overloading offered by java is the + sign for the String class. A char is a 16 bit integer and cannot be concatenated to a string with the + operator.

Answer 36)

Objective 8.2) 3) if(s.equalsIgnoreCase(s2)) String comparison is case sensitive so using the equals string method will not return a match. Using the==operator just compares where memory address of the references and noCaseMatch was just something I made up to give me a fourth slightly plausible option.

Answer 37)

Objective 9.1) 1) s.setBackground(Color.pink); For speakers of the more British spelt English note that there is no letter u in Color. Also the constants for colors are in lower case.

Answer 38) Objective 13.1) 4) The File class does not support directly changing the current directory.

Page 30: Cracked bits for scjp

This seems rather surprising to me, as changing the current directory is a very common requirement. You may be able to get around this limitation by creating a new instance of the File class passing the new directory to the constructor as the path name.

Answer 39) Objective 9.2) 1)With a fixed font you will see 5 characters, with a proportional it will depend on the width of the characters With a proportional font the letter w will occupy more space than the letter i. So if you have all wide characters you may have to scroll to the right to see the entire text of a TextField.

Answer 40)

Objective 5.8 3) On the line After //Two put super(10); Constructors can only be invoked from within constructors.

Answer 41) Objective 2.8) 3) 10 and 40 when a parameter is passed to a method the method receives a copy of the value. The method can modify its value without affecting the original copy. Thus in this example when the value is printed out the method has not changed the value.

Answer 42) Objective 3.3 4) for(int i=0; i< ia.length;i++) Although you could control the looping with a literal number as with the number 4 used in option 3, it is better practice to use the length property of an array. This provides against bugs that might result if the size of the array changes. This question also checks that you know that arrays starts from zero and not One as option 3 starts from one. Remember that array length is a field and not a function like the string size method.

Answer 43) Objective 3.6 (maybe) 1) Error at compile time This is a slightly sneaky one as it looks like a question about constructors, but it is attempting to test knowledge of the use of the private modifier. A top level class cannot be defined as private. If you didn't notice the modifier private, remember in the exam to be real careful to read every part of the question.

Answer 44)

Page 31: Cracked bits for scjp

Objective 1.11) 3)10 The name of the class might give you a clue with this question, Oct for Octal. Prefixing a number with a zero indicates that it is in Octal format. Thus when printed out it gets converted to base ten. 012 in octal means the first column from the right has a value of 2 and the next along has a value of one times eight. In decimal that adds up to 10.

Answer 45) Objective 3.5) 1) Error at compile time The variable i is created at the level of amethod and will not be available inside the method multi.

Answer 46)

Java2 Objective 10.1) 1) Set The Set interface ensures that its elements are unique, but does not order the elements. In reality you probably wouldn't create your own class using the Set interface. You would be more likely to use one of the JDK classes that use the Set interface such as ArraySet.

Answer 47)

Java2 Objective 10.1) 4) Vector v=new Vector(100); v.addElement("99") A vector can only store objects not primitives. The parameter "99" for the addElement method pases a string object to the Vector. Option 1) creates a vector OK but then uses array syntax to attempt to assign a primitive. Option 2 also creates a vector then uses correct Vector syntax but falls over when the parameter is a primitive instead of an object.

Answer 48)Objective 9.5) 3) The lower part of the word Dolly will be seen at the top of the form The Second parameter to the drawstring method indicates where the baseline of the string will be placed. Thus the 3rd parameter of 10 indicates the Y coordinate to be 10 pixels from the top of the Frame. This will result in just the bottom of the string Dolly showing up or possibly only the descending part of the letter y.

Answer 49) Objective 8.1) 1) Compile time error referring to a cast problem

Page 32: Cracked bits for scjp

This is a bit of a sneaky one as the Math.random method returns a pseudo random number between 0 and 1, and thus option 3 is a plausible Answer. However the number returned is a double and so the compiler will complain that a cast is needed to convert a double to an int.

Answer 50)Objective 4.6)

1) public void ioCall ()throws IOException{ DataInputStream din = new DataInputStream(System.in); din.readChar(); }If a method might throw an exception it must either be caught within the method with a try/catch block, or the method must indicate the exception to any calling method by use of the throws statement in its declaration. Without this, an error will occur at compile time.

Answer 51)Objective 3.10) 3) A compile time error Because only one instance of a static method exists not matter how many instance of the class exists it cannot access any non static variables. The JVM cannot know which instance of the variable to access. Thus you will get an error saying something like

Can't make a static reference to a non static variable

Answer 52)Java2 Objective 8.2)

2) Create an instance of the GridBagConstraints class, set the weightx field and then pass the GridBagConstraints instance with the component to the setConstraints method of the GridBagLayout class. The Key to using the GridBagLayout manager is the GridBagConstraint class. This class is not consistent with the general naming conventions in the java API as you would expect that weightx would be set with a method, whereas it is a simple field (variable).

Answer 53)Objective 13.1) 2) Return the name of the parent directory 3) Delete a file It is surprising that you can't change the current directory. It is not so surprising that you can't tell if a file contains text or binary information.

Answer 54)

Page 33: Cracked bits for scjp

Objective 9.5) 1) public void paint(Graphics g){ int polyX[] = {20,150,150}; int polyY[]= {20,20,120}; g.drawPolygon(polyX, polyY,3); }drawPolygon takes three parameters, the first two are arrays of the X,Y coordinates and the final is an integer specifying the number of vertices (whatever they are).

Answer 55)Objective 6.1)

1) You cannot be certain when garbage collection will run Although there is a Runtime.gc(), this only suggests that the Java Virtual Machine does its garbage collection. You can never be certain when the garbage collector will run. Roberts and Heller is more specific abou this than Boone. This uncertainty can cause consternation for C++ programmers who wish to run finalize methods with the same intent as they use destructor methods.

Answer 56)Java2 Objective 8.2) 4) The fill field of the GridBagConstraints class Unlike the GridLayout manager you can set the individual size of a control such as a button using the GridBagLayout manager. A little background knowledge would indicate that it should be controlled by a setSomethingOrOther method, but it isn't.

Answer 57)Java2 Objective 10.1) ) 4) A collection for storing bits as on-off information, like a vector of bits This is the description given to a bitset in Bruce Eckels "Thinking in Java" book. The reference to unique sequence of bits was an attempt to mislead because of the use of the word Set in the name bitset. Normally something called a set implies uniqueness of the members, but not in this context.

Answer 58)

Objective 3.10) 4)Compile error: Superclass Class1.Base of class Class1.Class1 not found Using the package statement has an effect similar to placing a source file into a different directory. Because the files are in different packages they cannot see each other. The stuff about File1 not having been compiled was just to mislead, java has the equivalent of an "automake",

Page 34: Cracked bits for scjp

whereby if it was not for the package statements the other file would have been automatically compiled.

Answer 59) Objective 5.3) 4) Output of Over.amethod() The names of parameters to an overridden method is not important.

Answer 60)Java2 Objective 8.2) 1) Set the gridy value of the GridBagConstraint class to a value increasing from 1 to 4 Answer 4 is fairly obviously bogus as it is the GridBagConstraint class that does most of the magic in laying out components under the GridBagLayout manager. The fill value of the GridBagConstraint class controls the behavior inside its virtual cell and the ipady field controls the internal padding around a component.

==========================================================Cracked By Charitra Choudhary, INDIAAny Help, Plz Feel Free to mail ([email protected]) MCSE, MCSE, CCNA, Comptia A+, N+, JCP, MCAD, MCSD, MVP==========================================================

Questions

Question 1) What will happen when you attempt to compile and run this code?abstract class Base{ abstract public void myfunc(); public void another(){ System.out.println("Another method"); }}public class Abs extends Base{ public static void main(String argv[]){ Abs a = new Abs(); a.amethod(); } public void myfunc(){ System.out.println("My func"); } public void amethod(){ myfunc(); }}

Page 35: Cracked bits for scjp

1) The code will compile and run, printing out the words "My Func"2) The compiler will complain that the Base class has non abstract methods3) The code will compile but complain at run time that the Base class has non abstract methods4) The compiler will complain that the method myfunc in the base class has no body, nobody at all to looove it

Question 2)

What will happen when you attempt to compile and run this code? public class MyMain{public static void main(String argv){ System.out.println("Hello cruel world"); }}1) The compiler will complain that main is a reserved word and cannot be used for a class2) The code will compile and when run will print out "Hello cruel world"3) The code will compile but will complain at run time that no constructor is defined4) The code will compile but will complain at run time that main is not correctly defined

Question 3) Which of the following are Java modifiers?

1) public2) private3) friendly4) transient4) vagrant

Question 4)What will happen when you attempt to compile and run this code?class Base{ abstract public void myfunc(); public void another(){ System.out.println("Another method"); }}public class Abs extends Base{ public static void main(String argv[]){ Abs a = new Abs(); a.amethod(); } public void myfunc(){

Page 36: Cracked bits for scjp

System.out.println("My func"); } public void amethod(){ myfunc(); }}1) The code will compile and run, printing out the words "My Func"2) The compiler will complain that the Base class is not declared as abstract.3) The code will compile but complain at run time that the Base class has non abstract methods4) The compiler will complain that the method myfunc in the base class has no body, nobody at all to looove it

Question 5)Why might you define a method as native?1) To get to access hardware that Java does not know about2) To define a new data type such as an unsigned integer3) To write optimised code for performance in a language such as C/C++4) To overcome the limitation of the private scope of a method

Question 6)What will happen when you attempt to compile and run this code?class Base{public final void amethod(){ System.out.println("amethod"); }}public class Fin extends Base{public static void main(String argv[]){ Base b = new Base(); b.amethod(); }}1) Compile time error indicating that a class with any final methods must be declared final itself2) Compile time error indicating that you cannot inherit from a class with final methods3) Run time error indicating that Base is not defined as final4) Success in compilation and output of "amethod" at run time.

7) What will happen when you attempt to compile and run this code?public class Mod{public static void main(String argv[]){ } public static native void amethod();

Page 37: Cracked bits for scjp

}1) Error at compilation: native method cannot be static2) Error at compilation native method must return value3) Compilation but error at run time unless you have made code containing native amethod available4) Compilation and execution without error

8) What will happen when you attempt to compile and run this code?private class Base{}public class Vis{

transient int iVal;public static void main(String elephant[]){

}}1)Compile time error: Base cannot be private2)Compile time error indicating that an integer cannot be transient3)Compile time error transient not a data type4)Compile time error malformed main method

9) What happens when you attempt to compile and run these two files in the same directory? //File P1.javapackage MyPackage;class P1{void afancymethod(){ System.out.println("What a fancy method"); }}//File P2.javapublic class P2 extends P1{afancymethod();}1) Both compile and P2 outputs "What a fancy method" when run2) Neither will compile3) Both compile but P2 has an error at run time4) P1 compiles cleanly but P2 has an error at compile time

10) You want to find out the value of the last element of an array. You write the following code. What will happen when you compile and run it.?public class MyAr{public static void main(String argv[]){ int[] i = new int[5]; System.out.println(i[5]);

Page 38: Cracked bits for scjp

}}1) An error at compile time2) An error at run time3) The value 0 will be output4) The string "null" will be output

11) You want to loop through an array and stop when you come to the last element. Being a good java programmer and forgetting everything you ever knew about C/C++ you know that arrays contain information about their size. Which of the following can you use?

1)myarray.length();2)myarray.length;3)myarray.size4)myarray.size();

Question 12)What best describes the appearance of an application with the following code?import java.awt.*;

public class FlowAp extends Frame{

public static void main(String argv[]){ FlowAp fa=new FlowAp(); fa.setSize(400,300); fa.setVisible(true);}FlowAp(){ add(new Button("One")); add(new Button("Two")); add(new Button("Three")); add(new Button("Four")); }//End of constructor

}//End of Application1) A Frame with buttons marked One to Four placed on each edge.2) A Frame with buutons marked One to four running from the top to bottom3) A Frame with one large button marked Four in the Centre4) An Error at run time indicating you have not set a LayoutManager

Question 13)How do you indicate where a component will be positioned using Flowlayout?1) North, South,East,West

Page 39: Cracked bits for scjp

2) Assign a row/column grid reference3) Pass a X/Y percentage parameter to the add method4) Do nothing, the FlowLayout will position the component

Question 14)How do you change the current layout manager for a container1) Use the setLayout method2) Once created you cannot change the current layout manager of a component3) Use the setLayoutManager method4) Use the updateLayout method

Question 15)Which of the following are fields of the GridBagConstraints class?1) ipadx2) fill3) insets4) width

Question 16) What most closely matches the appearance when this code runs?import java.awt.*;

public class CompLay extends Frame{public static void main(String argv[]){ CompLay cl = new CompLay(); }

CompLay(){ Panel p = new Panel(); p.setBackground(Color.pink); p.add(new Button("One")); p.add(new Button("Two")); p.add(new Button("Three")); add("South",p); setLayout(new FlowLayout()); setSize(300,300); setVisible(true); }}1) The buttons will run from left to right along the bottom of the Frame2) The buttons will run from left to right along the top of the frame3) The buttons will not be displayed

Page 40: Cracked bits for scjp

4) Only button three will show occupying all of the frame

Question 17)Which statements are correct about the anchor field?1) It is a field of the GridBagLayout manager for controlling component placement2) It is a field of the GridBagConstraints class for controlling component placement3) A valid setting for the anchor field is GridBagConstraints.NORTH4) The anchor field controls the height of components added to a container

Question 18)What will happen when you attempt to compile and run the following code?public class Bground extends Thread{

public static void main(String argv[]){ Bground b = new Bground();

b.run(); } public void start(){ for (int i = 0; i <10; i++){ System.out.println("Value of i = " + i); } }

}1) A compile time error indicating that no run method is defined for the Thread class2) A run time error indicating that no run method is defined for the Thread class3) Clean compile and at run time the values 0 to 9 are printed out4) Clean compile but no output at runtime

Question 19)10)When using the GridBagLayout manager, each new component requires a new instance of the GridBagConstraints class. Is this statement1) true2) false

Question 20) Which most closely matches a description of a Java Map?1) A vector of arrays for a 2D geographic representation2) A class for containing unique array elements3) A class for containing unique vector elements4) An interface that ensures that implementing classes cannot contain duplicate keys

Page 41: Cracked bits for scjp

Question 21)How does the set collection deal with duplicate elements?1) An exception is thrown if you attempt to add an element with a duplicate value2) The add method returns false if you attempt to add an element with a duplicate value3) A set may contain elements that return duplicate values from a call to the equals method4) Duplicate values will cause an error at compile time

Question 22)What can cause a thread to stop executing?1) The program exits via a call to System.exit(0);2) Another thread is given a higher priority3) A call to the thread's stop method.4) A call to the halt method of the Thread class

Question 23)For a class defined inside a method, what rule governs access to the variables of the enclosing method?1) The class can access any variable2) The class can only access static variables3) The class can only access transient variables4) The class can only access final variables

Question 24)

Under what circumstances might you use the yield method of the Thread class1) To call from the currently running thread to allow another thread of the same priority to run2) To call on a waiting thread to allow it to run3) To allow a thread of higher priority to run4) To call from the currently running thread with a parameter designating which thread should be allowed to run

Question 25)What will happen when you attempt to compile and run the following codepublic class Hope{public static void main(String argv[]){ Hope h = new Hope(); }protected Hope(){ for(int i =0; i <10; i ++){ System.out.println(i); }

Page 42: Cracked bits for scjp

}}1) Compilation error: Constructors cannot be declared protected2) Run time error: Constructors cannot be declared protected3) Compilation and running with output 0 to 104) Compilation and running with output 0 to 9

Question 26)What will happen when you attempt to compile and run the following codepublic class MySwitch{

public static void main(String argv[]){ MySwitch ms= new MySwitch(); ms.amethod(); }

public void amethod(){

int k=10; switch(k){ default: //Put the default at the bottom, not here System.out.println("This is the default output"); break; case 10: System.out.println("ten"); case 20: System.out.println("twenty"); break; } }}1) None of these options2) Compile time errror target of switch must be an integral type3) Compile and run with output "This is the default output"4) Compile and run with output "ten"

Question 27) Which of the following is the correct syntax for suggesting that the JVM performs garbage collection1) System.free();2) System.setGarbageCollection();3) System.out.gc();4) System.gc();

Page 43: Cracked bits for scjp

Question 28)

What will happen when you attempt to compile and run the following codepublic class As{int i = 10;int j;char z= 1;boolean b;public static void main(String argv[]){ As a = new As(); a.amethod(); } public void amethod(){ System.out.println(j); System.out.println(b); }}1) Compilation succeeds and at run time an output of 0 and false2) Compilation succeeds and at run time an output of 0 and true3) Compile time error b is not initialised4) Compile time error z must be assigned a char value

Question 29)

What will happen when you attempt to compile and run the following code with the command line "hello there"public class Arg{String[] MyArg; public static void main(String argv[]){ MyArg=argv; } public void amethod(){ System.out.println(argv[1]); }}1) Compile time error2) Compilation and output of "hello"3) Compilation and output of "there"4) None of the above

Question 30)What will happen when you attempt to compile and run the following codepublic class StrEq{

Page 44: Cracked bits for scjp

public static void main(String argv[]){ StrEq s = new StrEq(); } private StrEq(){ String s = "Marcus"; String s2 = new String("Marcus"); if(s == s2){ System.out.println("we have a match"); }else{ System.out.println("Not equal"); } }}1) Compile time error caused by private constructor2) Output of "we have a match"3) Output of "Not equal"4) Compile time error by attempting to compare strings using ==

Question 31)1) What will happen when you attempt to compile and run the following codeimport java.io.*;

class Base{public static void amethod()throws FileNotFoundException{}}

public class ExcepDemo extends Base{public static void main(String argv[]){ ExcepDemo e = new ExcepDemo();}public static void amethod(){}

protected ExcepDemo(){ try{ DataInputStream din = new DataInputStream(System.in); System.out.println("Pausing"); din.readChar(); System.out.println("Continuing"); this.amethod(); }catch(IOException ioe) {}}

}1)Compile time error caused by protected constructor

Page 45: Cracked bits for scjp

2) Compile time error caused by amethod not declaring Exception3) Runtime error caused by amethod not declaring Exception4) Compile and run with output of "Pausing" and "Continuing" after a key is hit

Question 32)

What will happen when you attempt to compile and run this programpublic class Outer{public String name = "Outer";public static void main(String argv[]){ Inner i = new Inner(); i.showName(); }//End of main

private class Inner{ String name =new String("Inner"); void showName(){ System.out.println(name); } }//End of Inner class

}1) Compile and run with output of "Outer"2) Compile and run with output of "Inner"3) Compile time error because Inner is declared as private4) Compile time error because of the line creating the instance of Inner

Question 33)What will happen when you attempt to compile and run this code//Demonstration of event handlingimport java.awt.event.*;import java.awt.*;

public class MyWc extends Frame implements WindowListener{public static void main(String argv[]){ MyWc mwc = new MyWc(); } public void windowClosing(WindowEvent we){ System.exit(0); }//End of windowClosing

public void MyWc(){ setSize(300,300);

Page 46: Cracked bits for scjp

setVisible(true); }}//End of class1) Error at compile time2) Visible Frame created that that can be closed3) Compilation but no output at run time4) Error at compile time because of comment before import statements

Question 34)Which option most fully describes will happen when you attempt to compile and run the following codepublic class MyAr{public static void main(String argv[]) { MyAr m = new MyAr(); m.amethod(); } public void amethod(){ static int i; System.out.println(i); }}1) Compilation and output of the value 02) Compile time error because i has not been initialized3) Compilation and output of null4) Compile time error

Question 35) Which of the following will compile correctly1) short myshort = 99S;2) String name = 'Excellent tutorial Mr Green';3) char c = 17c;4)int z = 015;

Question 36) Which of the following are Java key words1)double2)Switch3)then4)instanceof

Question 37What will be output by the following line?

Page 47: Cracked bits for scjp

System.out.println(Math.floor(-2.1));1) -22) 2.03) -34) -3.0

Question 38) Given the following main method in a class called Cycle and a command line ofjava Cycle one twowhat will be output?public static void main(String bicycle[]){

System.out.println(bicycle[0]);}1) None of these options2) cycle3) one4) two

Question 39) Which of the following statements are true?1) At the root of the collection hierarchy is a class called Collection2) The collection interface contains a method called enumerator3) The interator method returns an instance of the Vector class4) The set interface is designed for unique elements

Question 40) Which of the following statements are correct?1) If multiple listeners are added to a component only events for the last listener added will be processed2) If multiple listeners are added to a component the events will be processed for all but with no guarantee in the order3) Adding multiple listeners to a comnponent will cause a compile time error4) You may remove as well add listeners to a component.

Question 41)Given the following codeclass Base{}

public class MyCast extends Base{static boolean b1=false;static int i = -1;static double d = 10.1;

Page 48: Cracked bits for scjp

public static void main(String argv[]){ MyCast m = new MyCast(); Base b = new Base();

//Here }}Which of the following, if inserted at the comment //Here will allow the code to compile and run without error

1) b=m;2) m=b;3) d =i;4) b1 =i;

Question 42) Which of the following statements about threading are true1) You can only obtain a mutually exclusive lock on methods in a class that extends Thread or implements runnable2) You can obtain a mutually exclusive lock on any object3) A thread can obtain a mutually exclusive lock on a method declared with the keyword synchronized4) Thread scheduling algorithms are platform dependent

Question 43) Your chief Software designer has shown you a sketch of the new Computer parts system she is about to create. At the top of the hierarchy is a Class called Computer and under this are two child classes. One is called LinuxPC and one is called WindowsPC. The main difference between the two is that one runs the Linux operating System and the other runs the Windows System (of course another difference is that one needs constant re-booting and the other runs reliably). Under the WindowsPC are two Sub classes one called Server and one Called Workstation. How might you appraise your designers work?

1) Give the goahead for further design using the current scheme2) Ask for a re-design of the hierarchy with changing the Operating System to a field rather than Class type3) Ask for the option of WindowsPC to be removed as it will soon be obsolete4) Change the hierarchy to remove the need for the superfluous Computer Class.

Question 44) Objective 4.1)Which of the following statements are true

Page 49: Cracked bits for scjp

1) An inner class may be defined as static2) There are NO circumstances where an inner class may be defined as private3) An anonymous class may have only one constructor4) An inner class may extend another class

Question 45) What will happen when you attempt to compile and run the following codeint Output=10;boolean b1 = false;if((b1==true) && ((Output+=10)==20)){ System.out.println("We are equal "+Output); }else { System.out.println("Not equal! "+Output);}1) Compile error, attempting to peform binary comparison on logical data type2) Compilation and output of "We are equal 10"3) Compilation and output of "Not equal! 20"4) Compilation and output of "Not equal! 10"

Question 46) Given the following variables which of the following lines will compile without error?String s = "Hello";long l = 99;double d = 1.11;int i = 1;int j = 0;1) j= i <<s;2) j= i<<j;3) j=i<<d;4)j=i<<l;

Question 47) What will be output by the following line of code?System.out.println(010|4);1) 142) 03) 64) 12

Question 48) Given the following variables

Page 50: Cracked bits for scjp

char c = 'c';int i = 10;double d = 10;long l = 1;String s = "Hello";Which of the following will compile without error?1)c=c+i; 2)s+=i; 3)i+=s; 4)c+=s;

Question 49)Which of the following will compile without error?1) File f = new File("/","autoexec.bat");2) DataInputStream d = new DataInputStream(System.in);3) OutputStreamWriter o = new OutputStreamWriter(System.out);4) RandomAccessFile r = new RandomAccessFile("OutFile");

Question 50) Given the folowing classes which of the following will compile without error?interface IFace{}class CFace implements IFace{}class Base{}

public class ObRef extends Base{public static void main(String argv[]){ ObRef ob = new ObRef(); Base b = new Base(); Object o1 = new Object(); IFace o2 = new CFace(); }}1)o1=o2;2)b=ob;3)ob=b;4)o1=b;

Question 51)Given the following code what will be the output?class ValHold{ public int i = 10;}public class ObParm{

Page 51: Cracked bits for scjp

public static void main(String argv[]){ ObParm o = new ObParm(); o.amethod(); } public void amethod(){ int i = 99; ValHold v = new ValHold(); v.i=30; another(v,i); System.out.println(v.i);

}//End of amethod

public void another(ValHold v, int i){ i=0; v.i = 20; ValHold vh = new ValHold(); v = vh; System.out.println(v.i+ " "+i); }//End of another}1) 10,0, 302) 20,0,303) 20,99,304) 10,0,20

Question 52)Given the following class definition, which of the following methods could be legally placed after the comment//Here public class Rid{ public void amethod(int i, String s){}

//Here}1)public void amethod(String s, int i){}2)public int amethod(int i, String s){} 3)public void amethod(int i, String mystring){} 4) public void Amethod(int i, String s) {}

Question 53)Given the following class definition which of the following can be legally placed after the comment line//Here ?class Base{

Page 52: Cracked bits for scjp

public Base(int i){}}

public class MyOver extends Base{public static void main(String arg[]){ MyOver m = new MyOver(10); } MyOver(int i){ super(i); } MyOver(String s, int i){ this(i);

//Here }}1)MyOver m = new MyOver();2)super(); 3)this("Hello",10);4)Base b = new Base(10);

Question 54) Given the following class definition, which of the following statements would be legal after the comment //Hereclass InOut{String s= new String("Between");

public void amethod(final int iArgs){ int iam; class Bicycle{ public void sayHello(){

//Here }//End of bicycle class } }//End of amethod public void another(){ int iOther; }}1)System.out.println(s); 2) System.out.println(iOther);3) System.out.println(iam);4) System.out.println(iArgs);

Page 53: Cracked bits for scjp

Question 55)Which of the following are methods of the Thread class?1) yield()2) sleep(long msec)3) go()4) stop()

Question 56)Which of the following methods are members of the Vector class and allow you to input a new element1) addElement2) insert3) append4) addItem

Question 57)Which of the following statements are true?1) Adding more classes via import statements will cause a performance overhead, only import classes you actually use.2) Under no circumstances can a class be defined with the private modifier3) A inner class may under some circumstances be defined with the protected modifier4) An interface cannot be instantiated

Question 58)Which of the following are correct event handling methods

1) mousePressed(MouseEvent e){}2) MousePressed(MouseClick e){}3) functionKey(KeyPress k){}4) componentAdded(ContainerEvent e){}

Question 59) Which of the following are methods of the Collection interface?1) iterator2) isEmpty3) toArray4) setText

Page 54: Cracked bits for scjp

Question 60)Which of the following best describes the use of the synhronized keyword?1) Allows two process to run in paralell but to communicate with each other2) Ensures only one thread at a time may access a class or object3) Ensures that two or more processes will start and end at the same time4) Ensures that two or more Threads will start and end at the same time

Answers

Answer 1)Objective 1.2)1) The code will compile and run, printing out the words "My Func"A class that contains an abstract method must be declared abstract itself, but may contain non abstract methods.

Answer 2)Objective 4.1)4) The code will compile but will complain at run time that main is not correctly definedIn this example the parameter is a string not a string array as needed for the correct main method

Answer 3)Objective 4.3)1) public2) private4) transientThe keyword transient is easy to forget as is not frequently used. Although a method may be considered to be friendly like in C++ it is not a Java keyword.

Answer 4) Objective 1.2)2) The compiler will complain that the Base class is not declared as abstract.If a class contains abstract methods it must itself be declared as abstract

Answer 5)Objective 1.2)1) To get to access hardware that Java does not know about3) To write optimised code for performance in a language such as C/C++

Answer 6)Objective 1.2)4) Success in compilation and output of "amethod" at run time.A final method cannot be ovverriden in a sub class, but apart from that it does not cause any other restrictions.

Answer 7) Objective 1.2)

Page 55: Cracked bits for scjp

4) Compilation and execution without errorIt would cause a run time error if you had a call to amethod though.

Answer 8)Objective 1.2)1)Compile time error: Base cannot be privateA top leve (non nested) class cannot be private.

Answer 9) Objective 1.2)4) P1 compiles cleanly but P2 has an error at compile timeThe package statement in P1.java is the equivalent of placing the file in a different directory to the file P2.java and thus when the compiler tries to compile P2 an error occurs indicating that superclass P1 cannot be found.

Answer 10)Objective 1.1)2) An error at run timeThis code will compile, but at run-time you will get an ArrayIndexOutOfBounds exception. This becuase counting in Java starts from 0 and so the 5th element of this array would be i[4].Remember that arrays will always be initialized to default values wherever they are created.

Answer 11)Objective 1.1)2)myarray.length;The String class has a length() method to return the number of characters. I have sometimes become confused between the two.

Answer 12)Objective 8.2)3) A Frame with one large button marked Four in the CentreThe default layout manager for a Frame is the BorderLayout manager. This Layout manager defaults to placing components in the centre if no constraint is passed with the call to the add method.

Answer 13)Objective 8.2)4) Do nothing, the FlowLayout will position the component

Answer 14)Objective 8.2)1) Use the setLayout method

Answer 15)Objective 8.2)1) ipadx

Page 56: Cracked bits for scjp

2) fill3) insets

Answer 16)Objective 8.2)2) The buttons will run from left to right along the top of the frame

The call to the setLayout(new FlowLayout()) resets the Layout manager for the entire frame and so the buttons end up at the top rather than the bottom.

Answer 17)Objective 8.2)2) It is a field of the GridBagConstraints class for controlling component placement3) A valid settting for the anchor field is GridBagconstraints.NORTH

Answer 18)Objective 7.1)4) Clean compile but no output at runtime

This is a bit of a sneaky one as I have swapped around the names of the methods you need to define and call when running a thread. If the for loop were defined in a method calledpublic void run() and the call in the main method had been to b.start()The list of values from 0 to 9 would have been output.

Answer 19) Objective 8.2)2) false

You can re-use the same instance of the GridBagConstraints when added successive components.

Answer 20)Objective 10.1)4) An interface that ensures that implementing classes cannot contain duplicates

Answer 21)Objective 10.1)2) The add method returns false if you attempt to add an element with a duplicate valueI find it a surprise that you do not get an exception.

Answer 22) Objective 7.1)1) The program exits via a call to exit(0);

Page 57: Cracked bits for scjp

2) The priority of another thread is increased3) A call to the stop method of the Thread class

Java threads are somewhat platform dependent and you should be carefull when making assumptions about Thread priorities. On some platforms you may find that a Thread with higher priorities gets to "hog" the processor.

Answer 23) Objective 4.1)4) The class can only access final variables

Answer 24) Objective 7.1)

1) To call from the currently running thread to allow another thread of the same priority to run

Answer 25)Objective 6.2)

4) Compilation and running with output 0 to 9

Answer 26)Objective 2.1)1) None of these options

Because of the lack of a break statement after the break 10; statement the actual output will be

"ten" followed by "twenty"

Answer 27)Objective 3.1)4) System.gc();

Answer 28)Objective 4.4)1) Compilation succeeds and at run time an output of 0 and falseThe default value for a boolean declared at class level is false, and integer is 0;

Answer 29)Objective 1.2)1) Compile time errorYou will get an error saying something like "Cant make a static reference to a non static variable". Note that the main method is static.

Answer 30)Objective 5.2)

Page 58: Cracked bits for scjp

3) Output of "Not equal"Despite the actual character strings matching, using the == operator will simply compare memory location. Because the one string was created with the new operator it will be in a different location in memory to the other string.

Answer 31)Objective 2.3)4) Compile and run with output of "Pausing" and "Continuing" after a key is hitAn overriden method in a sub class must not throw Exceptions not thrown in the base class. In the case of the method amethod it throws no exceptions and will thus compile without complain. There is no reason that a constructor cannot be protected.

Answer 32)Objective 6.3)4) Compile time error because of the line creating the instance of Inner

This looks like a question about inner classes but it is also a reference to the fact that the main method is static and thus you cannot directly access a non static method. The line causing the error could be fixed by changing it to say Inner i = new Outer().new Inner();Then the code would compile and run producing the output "Inner"

Answer 33)Objective 4.6)1) Error at compile timeIf you implement an interface you must create bodies for all methods in that interface. This code will produce an error saying that MyWc must be declared abstract because it does not define all of the methods in WindowListener. Option 4 is nonsense as comments can appear anywhere. Option 3 suggesting that it might compile but not produce output is ment to mislead on the basis that what looks like a constructor is actually an ordinary method as it has a return type.

Answer 34)Objective 1.2)4) Compile time errorAn error will be caused by attempting to define an integer as static within a method. The lifetime of a field within a method is the duration of the running of the method. A static field exists once only for the class. An approach like this does work with Visual Basic.

Answer 35)Objective 9.5)4)int z = 015;The letters c and s do not exist as literal indicators and a String must be enclosed with double quotes, not single as in this case.

Answer 36)Objective 4.3)

Page 59: Cracked bits for scjp

1)double4)instanceof

Note the upper case S on switch means it is not a keyword and the word then is part of Visual Basic but not Java. Also, instanceof looks like a method but is actually a keyword,

Answer 37)Objective 9.2)4) -3.0

Answer 38) Objective 4.2)3) oneCommand line parameters start from 0 and fromt he first parameter after the name of the compile (normally Java)

Answer 39)Objective 10.1)4) The set is designed for unique elements.Collection is an interface, not a class. The Collection interface includes a method called iterator. This returns an instance of the Iterator class which has some similarities with Enumerators.The name set should give away the purpose of the Set interface as it is analogous to the Set concept in relational databases which implies uniquness.

Answer 40) Objective 8.1)2) If multiple listeners are added to a component the events will be processed for all but with no guarantee in the order4) You may remove as well add listeners to a component.It ought to be fairly intuitive that a component ought to be able to have multiple listeners. After all, a text field might want to respond to both the mouse and keyboard

Answer 41)Objective 5.1)1) b=m;3) d =i;You can assign up the inheritance tree from a child to a parent but not the other way without an explicit casting. A boolean can only ever be assigned a boolean value.

Answer 42)Objective 7.3)2) You can obtain a mutually exclusive lock on any object3) A thread can obtain a mutually exclusive lock on a method declared with the keyword synchronized4) Thread scheduling algorithms are platform dependentYes that says dependent and not independent.

Page 60: Cracked bits for scjp

Answer 43)Objective 6.1)2) Ask for a re-design of the hierarchy with changing the Operating System to a field rather than Class typeOf course there are as many ways to design an object hierarchy as ways to pronounce Bjarne Strousjoup, but this is the sort of answer that Sun will proabably be looking for in the exam.

Answer 44)Objective 4.1)1) An inner class may be defined as static4) An inner class may extend another classA static inner class is also sometimes known as a top level nested class. There is some debate if such a class should be called an inner class. I tend to think it should be on the basis that it is created inside the opening braces of another class. How could an anonymous class have a constructor?. Remember a constructor is a method with no return type and the same name as the class. Inner classes may be defined as private

Answer 45)Objective 5.3)4) Compilation and output of "Not equal! 10"The output will be "Not equal 10". This illustrates that the Output +=10 calculation was never performed because processing stopped after the first operand was evaluated to be false. If you change the value of b1 to true processing occurs as you would expect and the output is "We are equal 20";.

Answer 46)Objective 5.1)2)j= i<<j;4)j=i<<l;

Answer 47)Objective 5.3)4) 12As well as the binary OR objective this questions requires you to understand the octal notaction which means that the leading letter zero (not the letter O)) means that the first 1 indicates the number contains one eight and nothing else. Thus this calculation in decimal mean8|4To convert this to binary means10000100----1100----Which is 12 in decimal

Page 61: Cracked bits for scjp

The | bitwise operator means that for each position where there is a 1, results in a 1 in the same position in the answer.

Answer 48)Objective 5.1)2)s+=i;Only a String acts as if the + operator were overloaded

Answer 49)Objective 10.1)Although the objectives do not specifically mention the need to understand the I/O Classes, feedback from people who have taken the exam indicate that you will get questions on this topic. As you will probably need to know this in the real world of Java programming, get familiar with the basics. I have assigned these questions to Objective 10.1 as that is a fairly vague objective.1) File f = new File("/","autoexec.bat");2) DataInputStream d = new DataInputStream(System.in);3) OutputStreamWriter o = new OutputStreamWriter(System.out);Option 4, with the RandomAccess file will not compile because the constructor must also be passed a mode parameter which must be either "r" or "rw"

Answer 50)Objective 5.1)1)o1=o2;2)b=ob;4)o1=b;

Answer 51)Objective 5.4)4) 10,0,20In the callanother(v,i);A reference to v is passed and thus any changes will be intact after this call.

Answer 52)Objective 6.2)1) public void amethod(String s, int i){}4) public void Amethod(int i, String s) {}Overloaded methods are differentiated only on the number, type and order of parameters, not on the return type of the method or the names of the parameters.

Answer 53)Objective 6.2)

4)Base b = new Base(10);Any call to this or super must be the first line in a constructor. As the method already has a call to this, no more can be inserted.

Page 62: Cracked bits for scjp

Answer 54)Objective 4.1)1)System.out.println(s); 4) System.out.println(iArgs);A class within a method can only see final variables of the enclosing method. However it the normal visibility rules apply for variables outside the enclosing method.

Answer 55)Objective 7.2)1) yield()2) sleep4) stop()Note, the methods stop and suspend have been deprecated with the Java2 release, and you may get questions on the exam that expect you to know this. Check out the Java2 Docs for an explanation

Answer 56)Objective 10.1)1) addElement

Answer 57)Objective 4.1)The import statement allows you to use a class directly instead of fully qualifying it with the full package name, adding more classess with the import statement does not cause a runtime performance overhad. An inner class can be defined with the private modifier.3) An inner class can be defined with the protected modifier4) An interface cannot be instantiated

Answer 58)Objective 4.6)1) mousePressed(MouseEvent e){}4) componentAdded(ContainerEvent e){}

Answer 59)Objective 10.1)1) iterator2) isEmpty3) toArray

Answer 60)Objective 7.3)2) Ensures only one thread at a time may access a class or object

==========================================================

Page 63: Cracked bits for scjp

Cracked By Charitra Choudhary, INDIAAny Help, Plz Feel Free to mail ([email protected]) MCSE, MCSE, CCNA, Comptia A+, N+, JCP, MCAD, MCSD, MVP==========================================================

Q. 1Which colour is used to indicate instance methods in the standard "javadoc" format documentation:blue red purple orangeSelect the most appropriate answer.Q. 2What is the correct ordering for the import, class and package declarations when found in a single file?package, import, class class, import, package import, package, class package, class, importSelect the most appropriate answer.Q. 3Which methods can be legally applied to a string object?equals(String) equals(Object) trim() round() toString()Select all correct answers.Q. 4What is the parameter specification for the public static void main method?String args [] String [] args Strings args [] String argsSelect all correct answers.Q. 5What does the zeroth element of the string array passed to the public static void main method contain?The name of the program The number of arguments The first argument if one is presentSelect the most appropriate answer.Q. 6Which of the following are Java keywords?goto

Page 64: Cracked bits for scjp

malloc extends FALSESelect all correct answersQ. 7What will be the result of compiling the following code:public class Test {public static void main (String args []) {int age;age = age + 1;System.out.println("The age is " + age);}}Compiles and runs with no output Compiles and runs printing out The age is 1 Compiles but generates a runtime error Does not compile Compiles but generates a compile time errorSelect the most appropriate answer.Q. 8Which of these is the correct format to use to create the literal char value a?‘a’ "a" new Character(a) \000aSelect the most appropriate answer.Q. 9What is the legal range of a byte integral type?0 - 65, 535 (–128) – 127 (–32,768) – 32,767 (–256) – 255Select the most appropriate answer.Q. 10Which of the following is illegal:int i = 32; float f = 45.0; double d = 45.0;Select the most appropriate answer.Q. 11What will be the result of compiling the following code:public class Test {static int age;public static void main (String args []) {age = age + 1;System.out.println("The age is " + age);

Page 65: Cracked bits for scjp

}}Compiles and runs with no output Compiles and runs printing out The age is 1 Compiles but generates a runtime error Does not compile Compiles but generates a compile time errorSelect the most appropriate answer.Q. 12Which of the following are correct?128 >> 1 gives 64 128 >>> 1 gives 64 128 >> 1 gives –64 128 >>> 1 gives –64Select all correct answersQ. 13Which of the following return true?"john" == "john" "john".equals("john") "john" = "john" "john".equals(new Button("john"))Select all correct answers.Q. 14Which of the following do not lead to a runtime error?"john" + " was " + " here" "john" + 3 3 + 5 5 + 5.5Select all correct answers.Q. 15Which of the following are so called "short circuit" logical operators?& || && |Select all correct answers.Q. 16Which of the following are acceptable?Object o = new Button("A"); Boolean flag = true; Panel p = new Frame(); Frame f = new Panel(); Panel p = new Applet();Select all correct answers.Q. 17What is the result of compiling and running the following code:

Page 66: Cracked bits for scjp

public class Test {static int total = 10;public static void main (String args []) {new Test();}public Test () {System.out.println("In test");System.out.println(this);int temp = this.total;if (temp > 5) {System.out.println(temp);}}}The class will not compile The compiler reports and error at line 2 The compiler reports an error at line 9 The value 10 is one of the elements printed to the standard output The class compiles but generates a runtime errorSelect all correct answers.Q 18Which of the following is correct:String temp [] = new String {"j" "a" "z"}; String temp [] = { "j " " b" "c"}; String temp = {"a", "b", "c"}; String temp [] = {"a", "b", "c"};Select the most appropriate answer.Q. 19What is the correct declaration of an abstract method that is intended to be public:public abstract void add(); public abstract void add() {} public abstract add(); public virtual add();Select the most appropriate answer.Q. 20Under what situations do you obtain a default constructor?When you define any class When the class has no other constructors When you define at least one constructorSelect the most appropriate answer.Q. 21Given the following code:public class Test {…}Which of the following can be used to define a constructor for this class:

Page 67: Cracked bits for scjp

public void Test() {…} public Test() {…} public static Test() {…} public static void Test() {…}Select the most appropriate answer.Q. 22Which of the following are acceptable to the Java compiler:if (2 == 3) System.out.println("Hi"); if (2 = 3) System.out.println("Hi"); if (true) System.out.println("Hi"); if (2 != 3) System.out.println("Hi"); if (aString.equals("hello")) System.out.println("Hi");Select all correct answers.Q. 23Assuming a method contains code which may raise an Exception (but not a RuntimeException), what is the correct way for a method to indicate that it expects the caller to handle that exception:throw Exception throws Exception new Exception Don't need to specify anythingSelect the most appropriate answer.Q. 24What is the result of executing the following code, using the parameters 4 and 0:public void divide(int a, int b) {try {int c = a / b;} catch (Exception e) {System.out.print("Exception ");} finally {System.out.println("Finally");}Prints out: Exception Finally Prints out: Finally Prints out: Exception No outputSelect the most appropriate answer.Q.25Which of the following is a legal return type of a method overloading the following method:public void add(int a) {…}void int Can be anythingSelect the most appropriate answer.Q.26 Which of the following statements is correct for a method which is overriding the following method:

Page 68: Cracked bits for scjp

public void add(int a) {…}the overriding method must return void the overriding method must return int the overriding method can return whatever it likesSelect the most appropriate answer.Q. 27 Given the following classes defined in separate files:class Vehicle {public void drive() {System.out.println("Vehicle: drive");}}class Car extends Vehicle {public void drive() {System.out.println("Car: drive");}}public class Test {public static void main (String args []) {Vehicle v;Car c;v = new Vehicle();c = new Car();v.drive();c.drive();v = c;v.drive();}}What will be the effect of compiling and running this class Test?Generates a Compiler error on the statement v= c; Generates runtime error on the statement v= c; Prints out: Vehicle: driveCar: driveCar: drivePrints out:Vehicle: driveCar: driveVehicle: driveSelect the most appropriate answer.Q. 28Where in a constructor, can you place a call to a constructor defined in the super class?Anywhere The first statement in the constructor The last statement in the constructor

Page 69: Cracked bits for scjp

You can't call super in a constructorSelect the most appropriate answer.Q. 29Which variables can an inner class access from the class which encapsulates it?All static variables All final variables All instance variables Only final instance variables Only final static variablesSelect all correct answers.Q. 30What class must an inner class extend:The top level class The Object class Any class or interface It must extend an interfaceSelect the most appropriate answer.Q. 31In the following code, which is the earliest statement, where the object originally held in e, may be garbage collected:public class Test { public static void main (String args []) { Employee e = new Employee("Bob", 48); e.calculatePay(); System.out.println(e.printDetails()); e = null; e = new Employee("Denise", 36); e.calculatePay(); System.out.println(e.printDetails()); } }Line 10 Line 11 Line 7 Line 8 NeverSelect the most appropriate answer.Q. 32What is the name of the interface that can be used to define a class that can execute within its own thread?Runnable Run Threadable Thread ExecutableSelect the most appropriate answer.

Page 70: Cracked bits for scjp

Q. 33What is the name of the method used to schedule a thread for execution?init(); start(); run(); resume(); sleep();Select the most appropriate answer.Q. 34Which methods may cause a thread to stop executing?sleep(); stop(); yield(); wait(); notify(); notifyAll() synchronized()Select all correct answers.Q. 35Write code to create a text field able to display 10 characters (assuming a fixed size font) displaying the initial string "hello"::Q. 36Which of the following methods are defined on the Graphics class:drawLine(int, int, int, int) drawImage(Image, int, int, ImageObserver) drawString(String, int, int) add(Component); setVisible(boolean); setLayout(Object);Select all correct answers.Q. 37Which of the following layout managers honours the preferred size of a component:CardLayout FlowLayout BorderLayout GridLayoutSelect all correct answers.Q. 38Given the following code what is the effect of a being 5:public class Test {public void add(int a) {loop: for (int i = 1; i < 3; i++){for (int j = 1; j < 3; j++) {if (a == 5) {break loop;

Page 71: Cracked bits for scjp

}System.out.println(i * j);}}}}Generate a runtime error Throw an ArrayIndexOutOfBoundsException Print the values: 1, 2, 2, 4 Produces no outputSelect the most appropriate answer.Q. 39What is the effect of issuing a wait() method on an objectIf a notify() method has already been sent to that object then it has no effect The object issuing the call to wait() will halt until another object sends a notify() or notifyAll() method An exception will be raised The object issuing the call to wait() will be automatically synchronized with any other objects using the receiving object.Select the most appropriate answer.Q. 40The layout of a container can be altered using which of the following methods:setLayout(aLayoutManager); addLayout(aLayoutManager); layout(aLayoutManager); setLayoutManager(aLayoutManager);Select all correct answers.Q. 41Using a FlowLayout manager, which is the correct way to add elements to a container:add(component); add("Center", component); add(x, y, component); set(component);Select the most appropriate answer.Q. 42Given that a Button can generate an ActionEvent which listener would you expect to have to implement, in a class which would handle this event?FocusListener ComponentListener WindowListener ActionListener ItemListenerSelect the most appropriate answer.Q. 43Which of the following, are valid return types, for listener methods:boolean

Page 72: Cracked bits for scjp

the type of event handled void ComponentSelect the most appropriate answer.Q. 44Assuming we have a class which implements the ActionListener interface, which method should be used to register this with a Button?addListener(*); addActionListener(*); addButtonListener(*); setListener(*);Select the most appropriate answer.Q. 45In order to cause the paint(Graphics) method to execute, which of the following is the most appropriate method to call:paint() repaint() paint(Graphics) update(Graphics) None – you should never cause paint(Graphics) to executeSelect the most appropriate answer.Q. 46Which of the following illustrates the correct way to pass a parameter into an applet:<applet code=Test.class age=33 width=100 height=100> <param name=age value=33> <applet code=Test.class name=age value=33 width=100 height=100> <applet Test 33>Select the most appropriate answer.Q. 47Which of the following correctly illustrate how an InputStreamReader can be created:new InputStreamReader(new FileInputStream("data")); new InputStreamReader(new FileReader("data")); new InputStreamReader(new BufferedReader("data")); new InputStreamReader("data"); new InputStreamReader(System.in);Select all correct answers.Q. 48What is the permanent effect on the file system of writing data to a new FileWriter("report"), given the file report already exists?The data is appended to the file The file is replaced with a new file An exception is raised as the file already exists The data is written to random locations within the fileSelect the most appropriate answer.Q. 49What is the effect of adding the sixth element to a vector created in the following manner:

Page 73: Cracked bits for scjp

new Vector(5, 10);An IndexOutOfBounds exception is raised. The vector grows in size to a capacity of 10 elements The vector grows in size to a capacity of 15 elements Nothing, the vector will have grown when the fifth element was addedSelect the most appropriate answer.Q. 50What is the result of executing the following code when the value of x is 2:switch (x) {case 1:System.out.println(1);case 2:case 3:System.out.println(3);case 4:System.out.println(4);}Nothing is printed out The value 3 is printed out The values 3 and 4 are printed out The values 1, 3 and 4 are printed outSelect the most appropriate answer.Q. 51Consider the following example:class First {public First (String s) {System.out.println(s);}}public class Second extends First {public static void main(String args []) {new Second();}}What is the result of compiling and running the Second class?Nothing happens A string is printed to the standard out An instance of the class First is generated An instance of the class Second is created An exception is raised at runtime stating that there is no null parameter constructor in class First. The class second will not compile as there is no null parameter constructor in the class FirstSelect the most appropriate answer.Q. 52 What is the result of executing the following fragment of code:boolean flag = false;if (flag = true) {System.out.println("true");

Page 74: Cracked bits for scjp

} else {System.out.println("false");}true is printed to standard out false is printed to standard out An exception is raised Nothing happensSelect the most appropriate answer.Q. 53Consider the following classes:public class Test {public static void test() {this.print();}public static void print() {System.out.println("Test");}public static void main(String args []) {test();}}What is the result of compiling and running this class?The string Test is printed to the standard out. A runtime exception is raised stating that an object has not been created. Nothing is printed to the standard output. An exception is raised stating that the method test cannot be found. An exception is raised stating that the variable this can only be used within an instance. The class fails to compile stating that the variable this is undefined.Select all correct answers.Q. 54Examine the following class definition:public class Test {public static void test() {print();}public static void print() {System.out.println("Test");}public void print() {System.out.println("Another Test");}}What is the result of compiling this class:A successful compilation. A warning stating that the class has no main method. An error stating that there is a duplicated method.

Page 75: Cracked bits for scjp

An error stating that the method test() will call one or other of the print() methods.Select the most appropriate answer.Q. 55What is the result of compiling and executing the following Java class:public class ThreadTest extends Thread {public void run() {System.out.println("In run");suspend();resume();System.out.println("Leaving run");}public static void main(String args []) {(new ThreadTest()).start();}}Compilation will fail in the method main. Compilation will fail in the method run. A warning will be generated for method run. The string "In run" will be printed to standard out. Both strings will be printed to standard out. Nothing will happen.Select the most appropriate answer.Q. 56Given the following sequence of Java statementsStringBuffer sb = new StringBuffer("abc"); String s = new String("abc"); sb.append("def"); s.append("def"); sb.insert(1, "zzz"); s.concat(sb); s.trim();Which of the following statements are true:The compiler would generate an error for line 1. The compiler would generate an error for line 2. The compiler would generate an error for line 3. The compiler would generate an error for line 4. The compiler would generate an error for line 5. The compiler would generate an error for line 6. The compiler would generate an error for line 7.Select all correct answers.Q. 57What is the result of executing the following Java class:import java.awt.*;public class FrameTest extends Frame {public FrameTest() {add (new Button("First"));

Page 76: Cracked bits for scjp

add (new Button("Second"));add (new Button("Third"));pack();setVisible(true);}public static void main(String args []) {new FrameTest();}}Select from the following options:Nothing happens. Three buttons are displayed across a window. A runtime exception is generated (no layout manager specified). Only the "first" button is displayed. Only the "second" button is displayed. Only the "third" button is displayed.Select the most appropriate answer.Q. 58Consider the following tags and attributes of tags:CODEBASE ALT NAME CLASS JAVAC HORIZONTALSPACE VERTICALSPACE WIDTH PARAM JARWhich of the above can be used within the <APPLET> and </APPLET> tags?line 1, 2, 3 line 2, 5, 6, 7 line 3, 4, 5 line 8, 9, 10 line 8, 9Select all correct answers.Q. 59Which of the following is a legal way to construct a RandomAccessFile:RandomAccessFile("data", "r"); RandomAccessFile("r", "data"); RandomAccessFile("data", "read"); RandomAccessFile("read", "data");Select the most appropriate answer.Q. 60Carefully examine the following code:public class StaticTest {

Page 77: Cracked bits for scjp

static {System.out.println("Hi there");}public void print() {System.out.println("Hello");}public static void main(String args []) {StaticTest st1 = new StaticTest();st1.print();StaticTest st2 = new StaticTest();st2.print();}}When will the string "Hi there" be printed?Never. Each time a new instance is created. Once when the class is first loaded into the Java virtual machine. Only when the static method is called explicitly.Select the most appropriate answer.Q. 61Consider the following program:public class Test { public static void main (String args []) { boolean a = false; if (a = true)System.out.println("Hello");ElseSystem.out.println("Goodbye");}}What is the result:A. Program produces no output but terminates correctly.B. Program does not terminate.C. Prints out "Hello"D. Prints out "Goodbye"Select the most appropriate answer.Q. 62Examine the following code which includes an inner class:public final class Test4 implements A {class Inner {void test() {if (Test4.this.flag); {sample();}} }private boolean flag = false;public void sample() {System.out.println("Sample");

Page 78: Cracked bits for scjp

}public Test4() {(new Inner()).test();}public static void main(String args []) {new Test4();} }What is the result:A. Prints out "Sample"B. Program produces no output but terminates correctly.C. Program does not terminate.D. The program will not compileSelect the most appropriate answer.Q. 63Carefully examine the following class:public class Test5 { public static void main (String args []) { /* This is the start of a commentif (true) {Test5 = new test5();System.out.println("Done the test");}/* This is another comment */System.out.println ("The end");}}What is the result:A. Prints out "Done the test" and nothing else.B. Program produces no output but terminates correctly.C. Program does not terminate.D. The program will not compile.E. The program generates a runtime exception.F. The program prints out "The end" and nothing else.G. The program prints out "Done the test" and "The end"Select the most appropriate answer.Q. 64The following code defines a simple applet:import java.applet.Applet;import java.awt.*;public class Sample extends Applet {private String text = "Hello World";public void init() {add(new Label(text));}public Sample (String string) {text = string;}

Page 79: Cracked bits for scjp

}It is accessed form the following HTML page:<html><title>Sample Applet</title><body><applet code="Sample.class" width=200 height=200></applet></body></html>What is the result of compiling and running this applet:A. Prints "Hello World".B. Generates a runtime error.C. Does nothing.D. Generates a compile time error.Select the most appropriate answer.Q. 65Examine the following code:public class Calc {public static void main (String args []) {int total = 0;for (int i = 0, j = 10; total > 30; ++i, --j) {System.out.println(" i = " + i + " : j = " + j);total += (i + j);}System.out.println("Total " + total);}}Does this code:A. Produce a runtime errorB. Produce a compile time errorC. Print out "Total 0"D. Generate the following as output:i = 0 : j = 10i = 1 : j = 9i = 2 : j = 8Total 30Please select the most appropriate answer.

Answers to Java Certification Mock Exam1. B 2. A 3. A, B, C, E 4. A, B5. C6. A, C7. D 8. A 9. B 10. B11. B 12. A,B 13. A, B 14. A, B, C, D 15.B, C16. A, E 17. D 18. D 19. A 20. B21. B 22. A, C, D, E 23. B 24. A 25. C26. A 27. C 28. B 29. A, B, C 30. C31. C 32. A 33. B 34. A, B, C, D 35. new TextField("hello", 10)36. A, B, C 37. B 38. D 39. B 40. A

Page 80: Cracked bits for scjp

41. A 42. D 43. C 44. B 45. B46. B 47. A, E 48. B 49. C 50. C51. F 52. A 53. F 54. C 55. D56. D, F 57. F 58. A, E 59. A 60. C61. C 62. A 63. F 64. B 65. C

==========================================================Cracked By Charitra Choudhary, INDIAAny Help, Plz Feel Free to mail ([email protected]) MCSE, MCSE, CCNA, Comptia A+, N+, JCP, MCAD, MCSD, MVP==========================================================

Questions

Q 1. What is the output of the following StringBuffer sb1 = new StringBuffer("Amit"); StringBuffer sb2= new StringBuffer("Amit"); String ss1 = "Amit"; System.out.println(sb1==sb2); System.out.println(sb1.equals(sb2)); System.out.println(sb1.equals(ss1)); System.out.println("Poddar".substring(3)); Ans: a) false false false dar b) false true false Poddar c) Compiler Error d) true true false dar

***** Look carefully at code and answer the following questions ( Q2 to Q8) 1 import java.applet.Applet; 2 import java.awt.*; 3 import java.awt.event.*; 4 public class hello4 extends Applet {

Page 81: Cracked bits for scjp

5 public void init(){ 6 add(new myButton("BBB")); 7 } 8 public void paint(Graphics screen) { 9 } 10 class myButton extends Button{ 11 myButton(String label){ 12 super(label); 13 } 14 public String paramString(){ 15 return super.paramString(); 16 } 17 } 18 public static void main(String[] args){ 19 Frame myFrame = new Frame( 20 "Copyright Amit"); 21 myFrame.setSize(300,100); 22 Applet myApplet = new hello4(); 23 Button b = new Button("My Button"); 24 myApplet.add(b); 25 b.setLabel(b.getLabel()+"New"); 26 // myButton b1 =(new hello4()).new myButton("PARAMBUTTON"); 27 System.out.println(b1.paramString()); 28 myFrame.add(myApplet); 29 myFrame.setVisible(true); 30 myFrame.addWindowListener(new WindowAdapter(){ 31 public void windowClosing(WindowEvent e){ 32 System.exit(0);}}); 33 } 34 } //End hello4 class. Q2. If you run the above program via appletviewer ( defining a HTML file), You see on screen. a) Two buttons b) One button with label as "BBB" c) One button with label as "My ButtonNew" d) One button with label as "My Button"

Q3. In the above code if line 26 is uncommented and program runs as standalone application a) Compile Error b) Run time error c) It will print the the label as PARAMBUTTON for button b1

Q4 In the code if you compile as "javac hello4.java" following files will be generated. a) hello4.class, myButton.class,hello41.class b)hello4.class, hello4$myButton.class,hello4$1.class c)hello4.clas,hello4$myButton.class

Page 82: Cracked bits for scjp

Q5. If above program is run as a standalone application. How many buttons will be displayed a) Two buttons b) One button with label as "BBB" c) One button with label as "My ButtonNew" d) One button with label as "My Button"

Q6. If from line no 14 keyword "public" is removed, what will happen.( Hint :paramString() method in java.awt.Button is a protected method. (Assume line 26 is uncommented) a) Code will not compile. b) Code will compile but will give a run time error. c) Code will compile and no run time error.

Q7. If from line no 14 keyword "public" is replaced with "protected", what will happen.(Hint :paramString() method in java.awt.Button is a protected method.(Assume line 26 is uncommented) a) Code will not compile. b) Code will compile but will give a run time error. c) Code will compile and no run time error.

Q8.If line no 26 is replaced with Button b1 = new Button("PARAMBUTTON").(Hint :paramString() method in java.awt.Button is a protected method.(Assume line 26 is uncommented) a) Code will not compile. b) Code will compile but will give a run time error. c) Code will compile and no run time error.

Q9. What is the output of following if the return value is "the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument" (Assuming written inside main) String s5 = "AMIT"; String s6 = "amit"; System.out.println(s5.compareTo(s6)); System.out.println(s6.compareTo(s5)); System.out.println(s6.compareTo(s6)); Ans a> -32 32 0 b> 32 32 0 c> 32 -32 0

Page 83: Cracked bits for scjp

d> 0 0 0

Q 10) What is the output (Assuming written inside main) String s1 = new String("amit"); String s2 = s1.replace('m','i'); s1.concat("Poddar"); System.out.println(s1); System.out.println((s1+s2).charAt(5)); a) Compile error b) amitPoddar o c) amitPoddar i d) amit i

Q 11) What is the output (Assuming written inside main) String s1 = new String("amit"); System.out.println(s1.replace('m','r')); System.out.println(s1); String s3="arit"; String s4="arit"; String s2 = s1.replace('m','r'); System.out.println(s2==s3); System.out.println(s3==s4); a) arit amit false true b) arit arit false true c) amit amit false true d) arit amit true true

Q12) Which one does not extend java.lang.Number 1)Integer

Page 84: Cracked bits for scjp

2)Boolean 3)Character 4)Long 5)Short

Q13) Which one does not have a valueOf(String) method 1)Integer 2)Boolean 3)Character 4)Long 5)Short

Q.14) What is the output of following (Assuming written inside main) String s1 = "Amit"; String s2 = "Amit"; String s3 = new String("abcd"); String s4 = new String("abcd"); System.out.println(s1.equals(s2)); System.out.println((s1==s2)); System.out.println(s3.equals(s4)); System.out.println((s3==s4)); a) true true true false b) true true true true c) true false true false

Q15. Which checkbox will be selected in the following code ( Assume with main and added to a Frame) Frame myFrame = new Frame("Test"); CheckboxGroup cbg = new CheckboxGroup(); Checkbox cb1 = new Checkbox("First",true,cbg); Checkbox cb2 = new Checkbox("Scond",true,cbg); Checkbox cb3 = new Checkbox("THird",false,cbg); cbg.setSelectedCheckbox(cb3); myFrame.add(cb1); myFrame.add(cb2); myFrame.add(cb3); a) cb1

Page 85: Cracked bits for scjp

b) cb2,cb1 c) cb1,cb2,cb3 d) cb3

Q16) Which checkbox will be selected in the following code ( Assume with main and added to a Frame) Frame myFrame = new Frame("Test"); CheckboxGroup cbg = new CheckboxGroup(); Checkbox cb1 = new Checkbox("First",true,cbg); Checkbox cb2 = new Checkbox("Scond",true,cbg); Checkbox cb3 = new Checkbox("THird",true,cbg); myFrame.add(cb1); myFrame.add(cb2); myFrame.add(cb3); a) cb1 b) cb2,cb1 c) cb1,cb2,cb3 d) cb3

Q17) What will be the output of line 5 1 Choice c1 = new Choice(); 2 c1.add("First"); 3 c1.addItem("Second"); 4 c1.add("Third"); 5 System.out.println(c1.getItemCount()); a) 1 b) 2 c) 3 d) None of the above

Q18) What will be the order of four items added Choice c1 = new Choice(); c1.add("First"); c1.addItem("Second"); c1.add("Third"); c1.insert("Lastadded",2); System.out.println(c1.getItemCount()); a) First,Second,Third,Fourth b) First,Second,Lastadded,Third c) Lastadded,First,Second,Third

Q19) Answer based on following code 1 Choice c1 = new Choice(); 2 c1.add("First"); 3 c1.addItem("Second"); 4 c1.add("Third");

Page 86: Cracked bits for scjp

5 c1.insert("Lastadded",1000); 6 System.out.println(c1.getItemCount()); a) Compile time error b) Run time error at line 5 c) No error and line 6 will print 1000 d) No error and line 6 will print 4

Q20) Which one of the following does not extends java.awt.Component a) CheckBox b) Canvas c) CheckbocGroup d) Label

Q21) What is default layout manager for panels and applets? a) Flowlayout b) Gridlayout c) BorderLayout

Q22) For awt components which of the following statements are true? a) If a component is not explicitly assigned a font, it usese the same font that it container uses. b) If a component is not explicitly assigned a foreground color , it usese the same foreground color that it container uses. c) If a component is not explicitly assigned a backround color , it usese the same background color that it container uses. d) If a component is not explicitly assigned a layout manager , it usese the same layout manager that it container uses.

Q23)java.awt.Component class method getLocation() returns Point (containg x and y cordinate).What does this x and y specify a) Specify the postion of components lower-left component in the coordinate space of the component's parent. b) Specify the postion of components upper-left component in the coordinate space of the component's parent. c) Specify the postion of components upper-left component in the coordinate space of the screen.

Q24. Q. What will be the output of follwing { double d1 = -0.5d; System.out.println("Ceil for d1 " + Math.ceil(d1)); System.out.println("Floor for d1 " +Math.floor(d1)); } Answers: a) Ceil for d1 0 Floor for d1 -1; b) Ceil for d1 0 Floor for d1 -1.0;

Page 87: Cracked bits for scjp

c) Ceil for d1 0.0 Floor for d1 -1.0; d) Ceil for d1 -0.0 Floor for d1 -1.0;

Q25. What is the output of following { float f4 = -5.5f; float f5 = 5.5f; float f6 = -5.49f; float f7 = 5.49f; System.out.println("Round f4 is " + Math.round(f4)); System.out.println("Round f5 is " + Math.round(f5)); System.out.println("Round f6 is " + Math.round(f6)); System.out.println("Round f7 is " + Math.round(f7)); } a)Round f4 is -6 Round f5 is 6 Round f6 is -5 Round f7 is 5 b)Round f4 is -5 Round f5 is 6 Round f6 is -5 Round f7 is 5

Q26. Given Integer.MIN_VALUE = -2147483648 Integer.MAX_VALUE = 2147483647 What is the output of following { float f4 = Integer.MIN_VALUE; float f5 = Integer.MAX_VALUE; float f7 = -2147483655f; System.out.println("Round f4 is " + Math.round(f4)); System.out.println("Round f5 is " + Math.round(f5)); System.out.println("Round f7 is " + Math.round(f7)); } a)Round f4 is -2147483648 Round f5 is 2147483647 Round f7 is -2147483648 b)Round f4 is -2147483648 Round f5 is 2147483647 Round f7 is -2147483655

Q27) 1 Boolean b1 = new Boolean("TRUE"); 2 Boolean b2 = new Boolean("true");

Page 88: Cracked bits for scjp

3 Boolean b3 = new Boolean("JUNK"); 4 System.out.println("" + b1 + b2 + b3); a) Comiler error b) RunTime error c)truetruefalse d)truetruetrue

Q 28) In the above question if line 4 is changed to System.out.println(b1+b2+b3); The output is a) Compile time error b) Run time error c) truetruefalse d) truetruetrue

Q 29. What is the output { Float f1 = new Float("4.4e99f"); Float f2 = new Float("-4.4e99f"); Double d1 = new Double("4.4e99"); System.out.println(f1); System.out.println(f2); System.out.println(d1); } a) Runtime error b) Infinity -Infinity 4.4E99 c) Infinity -Infinity Infinity d) 4.4E99 -4.4E99 4.4E99

Q30 Q. Which of the following wrapper classes can not take a "String" in constructor 1) Boolean 2) Integer 3) Long 4) Character 5) Byte 6) Short

Q31. What is the output of following Double d2 = new Double("-5.5"); Double d3 = new Double("-5.5");

Page 89: Cracked bits for scjp

System.out.println(d2==d3); System.out.println(d2.equals(d3)); a) true true b) false false c) true false d) false true

Q32) Which one of the following always honors the components's preferred size. a) FlowLayout b) GridLayout c) BorderLayout

Q33) Look at the following code import java.awt.*; public class visual extends java.applet.Applet{ static Button b = new Button("TEST"); public void init(){ add(b); } public static void main(String args[]){ Frame f = new Frame("Visual"); f.setSize(300,300); f.add(b); f.setVisible(true); } } What will happen if above code is run as a standalone application a) Displays an empty frame b) Displays a frame with a button covering the entire frame c) Displays a frame with a button large enough to accomodate its label.

Q34 If the code in Q33 is compiled and run via appletviewer what will happen a) Displays an empty applet b) Displays a applet with a button covering the entire frame c) Displays a applet with a button large enough to accomodate its label.

Q35. What is the output public static void main(String args[]){ Frame f = new Frame("Visual"); f.setSize(300,300); f.setVisible(true); Point p = f.getLocation();

Page 90: Cracked bits for scjp

System.out.println("x is " + p.x); System.out.println("y is " + p.y); } a) x is 300 y is 300 b) x is 0 y is 0 c) x is 0 y is 300

Q36) Which one of the following always ignores the components's preferred size. a) FlowLayout b) GridLayout c) BorderLayout

Q37) Consider a directory structure like this (NT or 95) C:\JAVA\12345.msg --FILE \dir1\IO.class -- IO.class is under dir1 Consider the following code import java.io.*; public class IO { public static void main(String args[]) { File f = new File("..\\12345.msg"); try{ System.out.println(f.getCanonicalPath()); System.out.println(f.getAbsolutePath()); }catch(IOException e){ System.out.println(e); } } } What will be the output of running "java IO" from C:\java\dir1 a) C:\java\12345.msg C:\java\dir1\..\12345.msg b) C:\java\dir1\12345.msg C:\java\dir1\..\12345.msg c) C:\java\dir1\..\12345.msg C:\java\dir1\..\12345.msg

Q 38) Suppose we copy IO.class from C:\java\dir1 to c:\java What will be the output of running "java IO" from C:\java. a) C:\java\12345.msg C:\java\..\12345.msg b) C:\12345.msg C:\java\..\12345.msg

Page 91: Cracked bits for scjp

c) C:\java\..\12345.msg C:\java\\..\12345.msg

Q39) Which one of the following methods of java.io.File throws IOException and why a) getCanonicalPath and getAbsolutePath both require filesystem queries. b) Only getCannonicalPath as it require filesystem queries. c) Only getAbsolutePath as it require filesystem queries.

Q40) What will be the output if Consider a directory structure like this (NT or 95) C:\JAVA\12345.msg --FILE \dir1\IO.class -- IO.class is under dir1 import java.io.*; public class IO { public static void main(String args[]) { File f = new File("12345.msg"); String arr[] = f.list(); System.out.println(arr.length); } } a) Compiler error as 12345.msg is a file not a directory b) java.lang.NullPointerException at run time c) No error , but nothing will be printed on screen

Q41) What will be the output Consider a directory structure like this (NT or 95) C:\JAVA\12345.msg --FILE import java.io.*; public class IO { public static void main(String args[]) { File f1 = new File("\\12345.msg"); System.out.println(f1.getPath()); System.out.println(f1.getParent()); System.out.println(f1.isAbsolute()); System.out.println(f1.getName()); System.out.println(f1.exists()); System.out.println(f1.isFile()); } } a) \12345.msg \ true 12345.msg true true b) \12345.msg

Page 92: Cracked bits for scjp

\ true \12345.msg false false c) 12345.msg \ true 12345.msg false false d) \12345.msg \ true 12345.msg false false

Q42) If in question no 41 the line File f1 = new File("\\12345.msg"); is replaced with File f1 = new File("12345.msg"); What will be the output a) 12345.msg \ true 12345.msg true true b) 12345.msg null true 12345.msg true true

c) 12345.msg null false 12345.msg true true d) \12345.msg \ true 12345.msg false false

Page 93: Cracked bits for scjp

ANSWERS :-

1) a)2) b)3) c)4) b)5) C)6) a)As you can not override a method with weaker access privileges7) c)As you can access a protected variable in the same package.8) a) Because protected variables and methods can not be accssed in another package directly. They can only be accessed if the class is subclassed and instance of subclass is used. 9) a)10) d)As String is imutable.so s1 is always "amit". and s2 is "aiit".11) a) s3==s4 is true because java points both s3 and s4 to same memory location in string pool12) 2) and 3)13) 3)14) a)15) d) As in a CheckboxGroup only one can be selected16) d) As in a CheckboxGroup only one can be selected17) c)18) b)19) d)20) c)21) a)22) a),b),c)23) b)24) d) as 0.0 is treated differently from -0.025) b)26) a) //Reason If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE. If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE. // From JDK api documentation 27) c)28) a) As there is no method to support Boolean + Boolean Boolean b1 = new Boolean("TRUE"); Think ----->System.out.println(b1); // Is this valid or not?29) b)30) 4)31) d)32) a) 33) b) Reason- Frame uses Border Layout which places the button to CENTRE (By default) and ignores Button's preferred size.

Page 94: Cracked bits for scjp

34) c) Reason- Applet uses FlowLayout which honors Button's preferred size. 35) b) Because postion is always relative to parent container and in this. case Frame f is the topemost container36) b)37) a) as getCanonicalPath Returns the canonical form of this File object's pathname. The precise definition of canonical form is system-dependent, but it usually specifies an absolute pathname in which all relative references and references to the current user directory have been completely resolved. WHERE AS getAbsolutePath Returns the absolute pathname of the file represented by this object. If this object represents an absolute pathname, then return the pathname. Otherwise, return a pathname that is a concatenation of the current user directory, the separator character, and the pathname of this file object.38) b)39) b)40) b)41) d)42) c)

==========================================================Cracked By Charitra Choudhary, INDIAAny Help, Plz Feel Free to mail ([email protected]) MCSE, MCSE, CCNA, Comptia A+, N+, JCP, MCAD, MCSD, MVP==========================================================

Question 1 What will happen if you compile/run this code?

1: public class Q1 extends Thread2: {3: public void run()4: {5: System.out.println("Before start method");6: this.stop(); 7: System.out.println("After stop method");8: }9: 10: public static void main(String[] args)11: {12: Q1 a = new Q1();13: a.start();14: }15: }

A) Compilation error at line 7.B) Runtime exception at line 7.C) Prints "Before start method" and "After stop method".D) Prints "Before start method" only.

Page 95: Cracked bits for scjp

Question 2What will happen if you compile/run the following code?

1: class Test2: {3: static void show()4: {5: System.out.println("Show method in Test class");6: }7:}8:9: public class Q2 extends Test10: {11: static void show()12: {13: System.out.println("Show method in Q2 class");14: }15: public static void main(String[] args)16: {17: Test t = new Test();18: t.show();19: Q2 q = new Q2();20: q.show();21: 22: t = q; 23: t.show();24:25: q = t; 26: q.show();27: }28: }

A) prints "Show method in Test class" "Show method in Q2 class" "Show method in Q2 class" "Show method in Q2 class" B) prints "Show method in Test class" "Show method in Q2 class" "Show method in Test class" "Show method in Test class"

C) prints "Show method in Test class" "Show method in Q2 class"

Page 96: Cracked bits for scjp

"Show method in Test class" "Show method in Q2 class" D) Compilation error.

Question 3 The following code will give1: class Test2: {3: void show()4: {5: System.out.println("non-static method in Test");6: }7: }8: public class Q3 extends Test9: {10: static void show()11: {12: System.out.println("Overridden non-static method in Q3");13: }14: 15: public static void main(String[] args)16: {17: Q3 a = new Q3();18: }19: }

A) Compilation error at line 3.B) Compilation error at line 10.C) No compilation error, but runtime exception at line 3.D) No compilation error, but runtime exception at line 10.

Question No :4 The following code will give

1: class Test2: {3: static void show()4: {5: System.out.println("Static method in Test");6: }7: }

Page 97: Cracked bits for scjp

8: public class Q4 extends Test9: {10: void show()11: {12: System.out.println("Overridden static method in Q4");13: }14: public static void main(String[] args)15: {16: }17: }

A) Compilation error at line 3.B) Compilation error at line 10.C) No compilation error, but runtime exception at line 3.D) No compilation error, but runtime exception at line 10.

Question No :5 The following code will print

1: int i = 1;2: i <<= 31;3: i >>= 31;4: i >>= 1;5:6: int j = 1;7: j <<= 31;8: j >>= 31;9: 10: System.out.println("i = " +i );11: System.out.println("j = " +j);

A) i = 1 j = 1

B) i = -1 j = 1 C) i = 1 j = -1 D) i = -1 j = -1

Page 98: Cracked bits for scjp

Question No :6 The following code will print

1: Double a = new Double(Double.NaN);2: Double b = new Double(Double.NaN);3: 4: if( Double.NaN == Double.NaN )5: System.out.println("True");6: else7: System.out.println("False");8: 9: if( a.equals(b) )10: System.out.println("True");11: else12: System.out.println("False");

A) True True B) True False C) False True D) False False

Question No :7 1: if( new Boolean("true") == new Boolean("true")) 2: System.out.println("True");3: else4: System.out.println("False");

A) Compilation error.B) No compilation error, but runtime exception.C) Prints "True".D) Prints "False".

Question No :8

Page 99: Cracked bits for scjp

1: public class Q82: {3: int i = 20;4: static 5: {6: int i = 10;7: 8: }9: public static void main(String[] args)10: {11: Q8 a = new Q8();12: System.out.println(a.i);13: }14: }

A) Compilation error, variable "i" declared twice.B) Compilation error, static initializers for initialization purpose only.C) Prints 10.D) Prints 20.

Question No :9 The following code will give

1: Byte b1 = new Byte("127");2:3: if(b1.toString() == b1.toString())4: System.out.println("True");5: else6: System.out.println("False");

A) Compilation error, toString() is not avialable for Byte.B) Prints "True".C) Prints "False".

Question No :10 What will happen if you compile/run this code?

1: public class Q102: {3: public static void main(String[] args)

Page 100: Cracked bits for scjp

4: {5: int i = 10;6: int j = 10;7: boolean b = false;8: 9: if( b = i == j)10: System.out.println("True");11: else12: System.out.println("False");13: }14: }

A) Compilation error at line 9 .B) Runtime error exception at line 9.C) Prints "True".D) Prints "Fasle".

Question 11 What will happen if you compile/run the following code?

1: public class Q11 2: { 3: static String str1 = "main method with String[] args"; 4: static String str2 = "main method with int[] args"; 5: 6: public static void main(String[] args) 7: { 8: System.out.println(str1); 9: } 10: 11: public static void main(int[] args) 12: { 13: System.out.println(str2); 14: } 15: }

A) Duplicate method main(), compilation error at line 6. B) Duplicate method main(), compilation error at line 11. C) Prints "main method with main String[] args". D) Prints "main method with main int[] args".

Question 12 What is the output of the following code?

Page 101: Cracked bits for scjp

1: class Test 2: { 3: Test(int i) 4: { 5: System.out.println("Test(" +i +")"); 6: } 7: } 8: 9: public class Q12 10: { 11: static Test t1 = new Test(1); 12: 13: Test t2 = new Test(2); 14: 15: static Test t3 = new Test(3); 16: 17: public static void main(String[] args) 18: { 19: Q12 Q = new Q12(); 20: } 21: }

A) Test(1) Test(2) Test(3)

B) Test(3) Test(2) Test(1) C) Test(2) Test(1) Test(3) D) Test(1) Test(3) Test(2)

Question 13 What is the output of the following code?

1: int i = 16; 2: int j = 17; 3:

Page 102: Cracked bits for scjp

4: System.out.println("i >> 1 = " + (i >> 1)); 5: System.out.println("j >> 1 = " + (j >> 1));

A) Prints "i >> 1 = 8" "j >> 1 = 8" B) Prints "i >> 1 = 7" "j >> 1 = 7"

C) Prints "i >> 1 = 8" "j >> 1 = 9"

D) Prints "i >> 1 = 7" "j >> 1 = 8"

Question 14 What is the output of the following code?

1: int i = 45678; 2: int j = ~i; 3: 4: System.out.println(j);

A) Compilation error at line 2. ~ operator applicable to boolean values only. B) Prints 45677. C) Prints -45677. D) Prints -45679.

Question 15 What will happen when you invoke the following method?

1: void infiniteLoop() 2: { 3: byte b = 1; 4: 5: while ( ++b > 0 ) 6: ; 7: System.out.println("Welcome to Java"); 8: } A) The loop never ends(infiniteLoop). B) Prints "Welcome to Java".

Page 103: Cracked bits for scjp

C) Compilation error at line 5. ++ operator should not be used for byte type variables. D) Prints nothing.

Question 16 In the following applet, how many Buttons will be displayed? 1: import java.applet.*; 2: import java.awt.*; 3: 4: public class Q16 extends Applet 5: { 6: Button okButton = new Button("Ok"); 7: 8: public void init() 9: { 10: add(okButton); 11: add(okButton); 12: add(okButton); 13: add(okButton); 14: 15: add(new Button("Cancel")); 16: add(new Button("Cancel")); 17: add(new Button("Cancel")); 18: add(new Button("Cancel")); 19: 20: setSize(300,300); 21: } 22: }

A) 1 Button with label "Ok" and 1 Button with label "Cancel" . B) 1 Button with label "Ok" and 4 Buttons with label "Cancel" . C) 4 Buttons with label "Ok" and 1 Button with label "Cancel" . D) 4 Buttons with label "Ok" and 4 Buttons with label "Cancel" .

Question 17 In the following, which is correct Container-Default layout combination?

A) Applet - FlowLayout B) Applet - BorderLayout C) Applet - CardLayout D) Frame - Flowlayout E) Frame - BorderLayout

Page 104: Cracked bits for scjp

F) Frame - CardLayout G) Panel - FlowLayout H) Panel - BorderLayout.

Question 18 What is the output of the following code?

1: String str = "Welcome"; 2: 3: str.concat(" to Java!"); 4: 5: System.out.println(str);

A) Strings are immutable, compilation error at line 3. B) Strings are immutable, runtime exception at line 3. C) Prints "Welcome". D) Prints "Welcome to Java!".

Question 19 What is the output of the following code?

1: class MyClass 2: { 3: static int maxElements; 4: 5: MyClass(int maxElements) 6: { 7: this.maxElements = maxElements; 8: } 9: 10: } 11: 12: public class Q19 13: { 14: public static void main(String[] args) 15: { 16: 17: MyClass a = new MyClass(100); 18: MyClass b = new MyClass(100); 19: 20: if(a.equals(b)) 21: System.out.println("Objects have the same values");

Page 105: Cracked bits for scjp

22: else 23: System.out.println("Objects have different values"); 24: } 25: }

A) Compilation error at line 20. equals() method was not defined. B) Compiles fine, runtime exception at line 20. C) Prints "Objects have the same values". D) Prints "Objects have different values";

Question 20 1: import java.applet.*; 2: import java.awt.*; 3: 4: public class Q20 extends Applet 5: { 6: Button okButton = new Button("Ok"); 7: 8: public void init() 9: { 10: setLayout(new BorderLayout()); 11: 12: add("South", okButton); 13: add("North", okButton); 14: add("East", okButton); 15: add("West", okButton); 16: add("Center", okButon); 17: 18: setSize(300,300); 19: } 20: }

The above Applet will display

A) Five Buttons with label "Ok" at Top, Bottom, Right, Left and Center of the Applet. B) Only one Button with label "Ok" at the Top of the Applet. C) Only one Button with label "Ok" at the Bottom of the applet. D) Only one Button with label "Ok" at the Center of the Applet.

Question 21 What will happen if you compile/run the following code? 1: public class Q21

Page 106: Cracked bits for scjp

2: { 3: int maxElements; 4: 5: void Q21() 6: { 7: maxElements = 100; 8: System.out.println(maxElements); 9: } 10: 11: Q21(int i) 12: { 13: maxElements = i; 14: System.out.println(maxElements); 15: } 16: 17: public static void main(String[] args) 18: { 19: Q21 a = new Q21(); 20: Q21 b = new Q21(999); 21: } 22: }

A) Prints 100 and 999. B) Prints 999 and 100. C) Compilation error at line 3, variable maxElements was not initialized. D) Compillation error at line 19.

Question 22 What will happen if run the following code? 1: Boolean[] b1 = new Boolean[10]; 2: 3: boolean[] b2 = new boolean[10]; 4: 6: System.out.println("The value of b1[1] = " +b1[1]); 7: System.out.println("The value of b2[1] = " +b2[1]); A) Prints "The value of b1[1] = false" "The value of b2[1] = false". B) Prints "The value of b1[1] = null" "The value of b2[1] = null".

C) Prints "The value of b1[1] = null" "The value of b2[1] = false".

Page 107: Cracked bits for scjp

D) Prints "The value of b1[1] = false" "The value of b2[1] = null".

Question 23 Which of the following are valid array declarations/definitions? 1: int iArray1[10]; 2: int iArray2[]; 3: int iArray3[] = new int[10]; 4: int iArray4[10] = new int[10]; 5: int []iArray5 = new int[10]; 6: int iArray6[] = new int[]; 7: int iArray7[] = null; A) 1. B) 2. C) 3. D) 4. E) 5. F) 6. G) 7.

Question 24 What is the output for the following lines of code? 1: System.out.println(" " +2 + 3); 2: System.out.println(2 + 3); 3: System.out.println(2 + 3 +""); 4: System.out.println(2 + "" +3); A) Compilation error at line 3 B) Prints 23, 5, 5 and 23. C) Prints 5, 5, 5 and 23. D) Prints 23, 5, 23 and 23.

Question 25 The following declaration(as a member variable) is legal. static final transient int maxElements = 100; A) True. B) False.

Page 108: Cracked bits for scjp

Question 26 What will happen if you compile/run the following lines of code? 1: int[] iArray = new int[10]; 2: 3: iArray.length = 15; 4: 5: System.out.println(iArray.length); A) Prints 10. B) Prints 15. C) Compilation error, you can't change the length of an array. D) Runtime exception at line 3.

Question 27 What will happen if you compile/run the folowing lines of code? 1: Vector a = new Vector(); 2: 3: a.addElement(10); 4: 5: System.out.println(a.elementAt(0)); A) Prints 10. B) Prints 11. C) Compilation error at line 3. D) Prints some garbage.

Question 28 What will happen if you invoke the following method? 1: public void check() 2: { 3: System.out.println(Math.min(-0.0,+0.0)); 4: System.out.println(Math.max(-0.0,+0.0)); 5: System.out.println(Math.min(-0.0,+0.0) == Math.max(0.0,+0.0)); 6: } A) prints -0.0, +0.0 and false. B) prints -0.0, +0.0 and true. C) prints 0.0, 0.0 and false. D) prints 0.0, 0.0 and true.

Question 29 What will happen if you compile/run this code? 1: int i = 012; 2: int j = 034; 3: int k = 056;

Page 109: Cracked bits for scjp

4: int l = 078; 5: 6: System.out.println(i); 7: System.out.println(j); 8: System.out.println(k); A) Prints 12,34 and 56. B) Prints 24,68 and 112. C) Prints 10, 28 and 46. D) Compilation error.

Question 30 When executed the following line of code will print System.out.println(-1 * Double.NEGATIVE_INFINITY); A) -Infinity B) Infinity C) NaN D) -NaN

ANSWERSQuestion No: 1 D. After the execution of stop() method, thread won't execute any more statements.

Question No: 2 D. Explicit casting is required at line 25.

Question No: 3 B. You cann't override an non-static method with static method.

Question No: 4 B. You cann't override a static method with non-static method.

Question No: 5 D.

Question No: 6 C.

Question No: 7

Page 110: Cracked bits for scjp

D.

Question No: 8 D. Here the variable '"i" defined in static initializer is local to that block only. The statements in the static initializers will be executed (only once) when the class is first created.

Question No: 9 C.

Question No: 10 C. Conditional operators have high precedence than assignment operators.

Question No 11 C. Here the main method was overloaded, so it won't give compilation error.

Question No 12 D. No matter where they declared, static variables will be intitialized before non-static variables.

Question No 13 A. 16 >> 1 is 8 and 17 >> 1 also 8.

Question No 14 D. Java allows you to use ~ operator for integer type variables. The simple way to calculate is ~i = (- i) - 1.

Question No 15 B. Here the variable 'b' will go upto 127. After that overflow will occur, so 'b' will be set to -ve value, the loop ends and prints "Welcome to Java"

Question No 16 B.

Question No 17 A, E and G. For Applets and Panels FlowLayout is the default one, BorderLayout is default for Window and Frames.

Question No 18 C. Strings are immutable. So str.concat("to Java!") will not append anything to str. Infact it will create another string "Welcome to Java!" and leaves it.

Question No 19 D. equals() method was available in base class Object. So it won't give any compilation error.

Page 111: Cracked bits for scjp

Here MyClass is a user-defined class, so the user has to implement equals() method according to his requirments.

Question No 20 D.

Question No 21 D. Constructors should not return any value. Java won't allow to indicate with void. In this case void Q21() is an ordinary method which has the same name of the Class.

Question No 22 C. By default objects will be initialized to null and primitives to their corresponding default vaulues. The same rule applies to array of objects and primitves. Question No 23 B,C,E and G. You can't specify the array dimension in type specification(left hand side), so A and D are invalid. In line 6 the array dimension is missing(right hand side) so F is invalid. You can intialize an array with null. so G is valid. Question No 24 B. Question No 25 A.

Question No 26 C. Once array is created then it is not possible to change the length of the array. Question No 27 C. You can't add primitives to Vector. Here 10 is int type primitive.

Question No 28 B. The order of floating/double values is -Infinity --> Negative Numbers/Fractions --> -0.0 --> +0.0 --> Positive Numbers/Fractions --> Infinity. Question No 29 D. Here integers are assinged by octal values. Octal numbers will contain digits from 0 to 7. 8 is illegal digit for an octal value, so you get compilation error.

Question No 30 B. Compile and see the result.

==========================================================

Page 112: Cracked bits for scjp

Cracked By Charitra Choudhary, INDIAAny Help, Plz Feel Free to mail ([email protected]) MCSE, MCSE, CCNA, Comptia A+, N+, JCP, MCAD, MCSD, MVP==========================================================

QUESTIONS :- 1.Which statement about the garbage collection mechanism are true? A.Garbage collection require additional programe code in cases where multiple threads are running. B.The programmer can indicate that a referance through a local variable is no longer of interest. C.The programmer has a mechanism that explicity and immediately frees the memory used by Java objects. D.The garbage collection mechanism can free the memory used by Java Object at explection time. E.The garbage collection system never reclaims memory from objects while are still accessible to running user thread.

2.Give the following method: 1) public void method(){ 2) String a,b; 3) a=new String("hello world"); 4) b=new String("game over"); 5) System.out.println(a+b+"ok"); 6) a=null; 7) a=b; 8) System.out.println(a); 9) }In the absence of compiler optimization,which line is the earliest point the object a refered is definitely elibile to be garbage collected? A.3 B.5 C.6 D.7 E.9

3.In the class java.awt.AWTEvent,which is the parent class upon which jdk1.1 awt events are based there is a method called getID(), which phrase most accerrately describes in significance of the reture value of this method? A.It is a reference to the object directly affected by the cause of the event. B.It is an indication of the nature of the cause of the event. C.It is an indication of the position of the mouse when it caused the event. D.In the case of a mouse click,it is an indication of the text under the mouse at the time of the event.

Page 113: Cracked bits for scjp

E.It tells the state of certain keys on the keybord at the time of the event. F.It is an indication of the time at which the event occurred.

4. Which statement about listener is true? A.Most component allow multiple listeners to be added. B.If mutiple listener be add to a single component,the event only affected one listener. C.Component don't allow multiple listeners to be add. D.The listener mechanism allows you to call an addListener method as many times as is needed,specifying as many different listeners as your design requires.

5.Give the following code: public class Example{ public static void main(String args[]){ int I=0; do{ System.out.println("Doing it for I is:"+ I ); }while(--i); System.out.println("Finish"); } } Which will be output: A.Doing it for I is 3 B.Doing it for I is 1 C.Doing it for I is 2 D.Doing it for I is 0 E.Doing if for I is -1 F.Finish

6.Give the code fragment: 1) switch(x){ 2) case 1: System.out.println("Test 1"); break; 3) case 2: 4) case 3:System.out.println("Test 2"); break; 5) default: System.out.println("end"); 6) }which value of x would cause "Test 2" to the output: A.1 B.2 C.3 D.default

Page 114: Cracked bits for scjp

7.Give incompleted method: 1) 2) { if(unsafe()) {//do something...} 3) else if(safe()){//do the other...} 4} }The method unsafe() will throw an IOException,which completes the method of declaration when added at line one? A.public IOException methodName() B.public void methodName() C.public void methodName() throw IOException D.public void methodName() throws IOException F.public void methodName() throws Exception8.Give the code fragment:

8. if(x>4){ System.out.println("Test 1");} else if(x>9) { System.out.println("Test 2");} else { System.out.println("Test 3");}Which range of value of x would produce of output "Test 2"? A.x<4 B.x>4 C.x>9 D.None

9.Give the following method: public void example(){ try{ unsafe(); System.out.println("Test 1"); }catch(SafeException e){System.out.println("Test 2"); }finally{System.out.println("Test 3");} System.out.println("Test 4"); }Which will display if method unsafe() run normally? A.Test 1 B.Test 2 C.Test 3 D.Test 4

10.Which method you define as the starting point of new thread in a class from which new the thread can be excution? A.public void start() B.public void run() C.public void int() D.public static void main(String args[]) E.public void runnable()

Page 115: Cracked bits for scjp

11.What wight cause the current thread to stop excutings? A.thread of higher priority become ready. B.method sleep() be called. C.method stop() be called D.method suspend() be called. E.method wait() be called 12.Which modifier should be applied to a method for the lock of object this to be obtained prior to excution any of the mehod body? A.synchronized B.abstract C.final D.static E.public

13.The following code is entire contents of a file called Example.java,causes precisely one error during compilation: 1) class SubClass extends BaseClass{ 2) } 3) class BaseClass{ 4) String str; 5) public BaseClass(){ 6) System.out.println("ok");} 7) public BaseClass(String s){ 8) str=s; 9) public class Example{ 10) public void method(){ 11) SubClass s=new SubClass("hello"); 12) BaseClass b=new BaseClass("world"); 13) } 14) } 15) } 16) }Which line would be cause the error? A.9 B.10 C.11 D.12

14.Which statement is correctly declare a variable a which is suitable for refering to an array of 30 string empty object? A.String []a B.String a[] D.char a[][] E.String a[50] F.Object a[50]

15.Give the following java sourse fragement: //point x public class Interesting{ //do something }which statement is correctly Java syntax ant point x? A.import java.awt.*; B.package mypackage C.static int PI=3.14

Page 116: Cracked bits for scjp

D.public class MyClass{//do other thing...} E.class MyClass{//do something...}

16.Give this class outline: class Example{ private int x; //rest of class body... }Assuming that x invoked by the code java Example,which statement can made this.x be accessible in main() method of Example.java: A.Change private int x to public int x B.change private int x to static int x C.Change private int x to protected int x D.change private int x to final int x

17.The piece of preliminary analsis work describes a class that will be used frequently in many unrelated parts of a project: "The polygon object is a drawable,A polygon has vertex information stored in a vector,a color,length and width."Which Data type would be used? A.Vector B.int C.String D.Color E.Date

18.A class design requires that a member variable should be accessible only by same package,which modifer word should be used: A.protected B.public C.no modifer D.private

19.Which declares for a native method in a java class corrected? A.public native void method(){ } B.public native void method(); C.public native method(); D.public void method(){native;} E.public void native method();

20.Which modifer should be applied to a declaration of a class member variable for the value of variable to remain constant after the creation of the object?(short answer)

Page 117: Cracked bits for scjp

21.Which is the main() method's return of a application? A.String B.byte C.char D.void

22.Which is corrected argument of main() method of a applicaton? A.String args B.String ar[] C.Char args[][] D.StringBuffer arg[]

23."The Employee object is a person,An Employee has appointment store in a vector,a hire date and a number of dependents." short anwser:use shortest statement define a class of Employee.

24.Give the following class defination inseparate source files: public class Example{ public Example(){//do something} protected Example(){// do something} protected void method(){//do something} } public class Hello extends Example{// member method and member variable}Which methods are corrected added to the class Hello? A.public void Example(){} B.public void method(){} C.protected void method(){} D.private void method() E.private otherMethod(){}

25. Float s=new Float(0.9F); Float t=new Float(0.9F); Double u=new Double(0.9);Which expression's result is true? A.s==t; B.s.equal(t); C.s==u D.t.equal(u)

26.Give following class: class AClass{ private long

Page 118: Cracked bits for scjp

val; public AClass(long v){val=v;} public static void main(String args[]){ AClass x=new AClass(10L); AClass y=new AClass(10L); AClass z=y; long a=10L; int b=10; } }Which expression's result is true? A.a= =b; B.a= =x; C.y= =z; D.x= =y; E.a= =10.0;

27.A socket object has been created and connected to a standard internet sevice on a remote network server.Which construction give the most suitable means for reading ASCII data one line at a time from the socket? A.InputStream in=s.getInputStream(); B.DataInputStream in=new DataInputstream(s.getInputStream()); C.ByteArrayInputStream in=new ByteArrayInputStream(s.getInputStream()); D.BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream())); E.BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()),"8859-1");

28.String s="Example String"; Which operation is legal? A.s>>>=3; B.int =s.length(); C.s[3]="x"; D.String short s=s.trim(); E.String t="root"+s;

29.Give: String str="goodby"; Which operation is legal? A.char c=s[3]; B.int i=s.length(); C.s>>=2; D.String lower s=s.toLowerCase(); E.s+="long

ago";

Page 119: Cracked bits for scjp

30.What use to position a Button in a Frame,width of Button is affected by the Frame size,which Layout Button will be set to? A.FlowLayout; B.GridLayout; C.North of BorderLayout D.South of BorderLayout D.Ease or West of BorderLayout

31.What use to position a Button in a Frame,size of Button is not affected by the Frame size,which Layout Button will be set to? A.FlowLayout; B.GridLayout; C.North of BorderLayout D.South of BorderLayout D.Ease or West of BorderLayout

32.An AWT GUI under exposure condition,which one or more method will be invok when it redraw? A.paint(); B.update(); C.repaint(); D.drawing();

33.Select valid identifier of Java: A.userName B.%passwd C.3d_game D.$charge E.this

34.Which are Java keyword? A.goto B.null C.FALSE D.native E.const

35.Run a corrected class:java -cs AClass a b c Which statement is true? A.args[0]="-cs"; B.args[1]="a b c"; C.args[0]="java"; D.args[0]="a"; E.args[1]='b';36.Give the following java

Page 120: Cracked bits for scjp

class: public class Example{ static int x[]=new int[15]; public static void main(String args[]){ System.out.println(x[5]); } }Which statement is corrected? A.When compile,some error will occur. B.When run,some error will occur. C.Output is zearo. D.Output is null.37.Give the following java class: public class Example{ public static void main(String args[]){ static int x[]=new int[15]; System.out.println(x[5]); } }Which statement is corrected? A.When compile,some error will occur. B.When run,some error will occur. C.Output is zearo. D.Output is null.38. Short answer: The decimal value of i is 12,the octal i value is:39.short answer: The decimal value of i is 7,the hexadecimal is:

40.Which is the range of char? A.2-7~27-1 B.0~216-1 C.0~216 D.0~28

41.Which is the range of int type? A.2-16~2 16-1 B.2-31~ 2 31-1 C.2-32~2 32-1 D.2-64~2 64-1

42.Give the following class: public class Example{ String str=new String("good"); char ch[]={'a','b','c'}; public static void main(String args[]){ Example ex=new Example(); ex.change(ex.str,ex.ch); System.out.println(ex.str+" and "+ex.ch); } public void change(String str,char ch[]){ str="test ok";ch[0]="g"; } } Which is the output: A.good and abc B.good and gbc C.test ok and abc D.test ok and gbc

Page 121: Cracked bits for scjp

43.Which code fragments would correctly identify the number of arguments passed via command line to a Javaapplication, excluding the name of the class that is being invoked? A.int count = args.length; B.int count = args.length - l; C.int count=0; while (args [count] !=null) count ++; D.int count=0; while (!(args[count].equals(""))) count ++;

44.FilterOutputStream is the parent class for BufferedOutputStream, DataOutputStream and PrintStream. Which classes are a valid argument for the constructor of a FilterOutputStream? A.InputStream B.OutputStream C.File D.RandomAccessFile E.StreamTokenizer

45.Given a TextArea using a proportional pitch font and constructed like this: TextArea t = new TextArea("12345", 5, 5); Which statement is true? A.the displayed width shows exactly five characters one ach line unless otherwise constrained B.The displayed height is five lines unless otherwise constrained. C.The maximum number of characters in a line will be five. D.The user will be able to edit the character string E.The displayed string can use multiple fonts

46.Given a TextArea using a proportional pitch font and constructed like this: List l=new List(5,true); Which statement is true? A.the displayed item exactly five line unless otherwise constrained B.The displayed item is five lines init.but can displayed more than five Item by C.The maximum number of item in a list will be five.

Page 122: Cracked bits for scjp

D.The list is multiple mode 47.Given this skeleton of a class currently under construction: public class Example { int x, y,z; public Example(int a,int b) { //lots of complex computation x=a;y=b; } public Example(int a, int b,int c) { // do everything the same as single argument // version of constructor //including assignment x = a,y=b z=c; } } What is the most concise way to code the "do everything..."part of the constructor taking two arguments? (short answer)

48.Which correctly create a two dimensional array of integers? A.int a[][] = new int[10,10] B.int a[10][10] = new int[][]; C.int a[][] = new int [10][10]; D.int []a[] = new int [10][10]; E.int []a[] = new int[10][10];

49.Which are correct class declarations? Assume in each case that the text constitutes the entire contents of a file called Fred.java on a system with a case-significant file system. A.public class Fred { public int x = 0; public Fred (int x) { this.x = x; } } B.public class fred public int x = 0; public fred (int x) { this.x = x; } } C.public class Fred extends MyBaseClass, MyOtherBaseClass { public int x = 0;

Page 123: Cracked bits for scjp

public Fred (int xval) { x = xval; } } D.protected class Fred { private int x = 0; private Fred (int xval) { x = xval; } } E.import java.awt.*; public class Fred extends Object { int x; private Fred (int xval) { x = xval; } } 50.A class design requires that a particular member variable must be accessible for direct access by any subclasses of this class, but otherwise not by classes which are not members of the same package. What should be done to achieve this? A.The variable should be marked public B.The variable should be marked private C.The variable should be marked protected D.The variable should have no special access modifier E.The variable should be marked private and an accessor method provided 51.Which correctly create an array of five empty Strings? A.String a [] = new String [5]; for (int i = 0; i < 5; a[i++] = ""); B.String a [] = {"", "", "", "", ""}; C.String a [5]; D.String [5] a; E.String [] a = new String [5]; for (int i = 0; i < 5; a[i++] = null);52.Which cannot be added to a Container? A.an Applet B.a Component C.a Container D.a MenuComponent E.a panel53.Which is the return value of Event listener's method? A.String B.AWTEvent C.void D.int54.If we implements MouseEventListener,which is corrected argument of it's method?(short answer)55.Use the oprator ">>" and ">>>".Which statement is true? A.1010 0000 0000 0000 0000 0000 0000 0000>>4 give 0000 1010 0000 0000 0000 0000 0000 0000 B.1010 0000 0000 0000 0000 0000 0000 0000>>4 give 1111 1010 0000 0000 0000 0000 0000 0000 A.1010 0000 0000 0000 0000 0000 0000 0000>>>4 give

Page 124: Cracked bits for scjp

0000 1010 0000 0000 0000 0000 0000 0000 A.1010 0000 0000 0000 0000 0000 0000 0000>>>4 give 1111 1010 0000 0000 0000 0000 0000 000056.56. Give following fragment. outer:for(int i=0;i<3;i++) inner:for(int j=0;j<3;j++){ if(j>1) break outer; System.out.println(j+"and"+i); } Which will be output? A.0 and 0 B.0 and 1 C.0 and 2 D.0 and 3 E.1 and 0 F.1 and 1 G.1 and 2 H.1 and 3 I.2 and 0 J.2 and 1 K.2 and 2 L.2 and 357.FilterInputStream is the parent class for BufferedInputStream, DataInputStream and PrintStream. Which classes are a valid argument for the constructor of a FilterOutputStream? A.InputStream B.OutputStream C.File D.RandomAccessFile E.StreamTokenizer 58.Which is the main()method return? A.String B.void C.char D.int59.Look the inheritance ralation: person | | | man womanIn a sourse of java have the following line: person p=new man();What statement are corrected? A.The expression is illegal. B.Compile corrected but running wrong. C.The expression is legal. D.Will construct a person's object.60.60.Look the inheritance ralation: person | | | man womanIn a sourse of java have the following line: woman w=new man();What statement are corrected? A.The expression is illegal. B.Compile corrected but running wrong. C.The expression is legal. D.Will construct a woman's object.

Basic Java

Page 125: Cracked bits for scjp

Q1 Given the following class, which statements can be inserted at position 1 without causing the code to fail compilation?Public class Test { int a, b=0;

static int c;public void m(){ int d;

int e=0;// Position 1

} }(a) a++(b) b++(c) c++(d) d++(e) e++

Q2 Which statement are true concerning the effect of the >> and >>> operators?(a) For non-negative values of the left operand, the >> and >>> operators

will have the same effect(b) The result of (-1 >> 1) is 0(c) The result of (-1 >>> 1) is –1(d) The value returned by >>> will never be negative as long as the value

of the right operand is equal to or greater than 1(e) When using the >> operator, the leftmost bit of the bit representation of

the resulting value will always as the same bit value as the leftmost bit of the bit representation of the left operand

Q3 What is wrong with the following code?Class MyException extends Exception{}Public class Test {

public void foo() {try{ bar(); }finally { baz(); } catch (MyException e) {} }

public void bar () throws MyException { throw new MyException(); }public void baz () throws RuntimeException { throw new RuntimeException(); }

(a) Since the method foo() does not catch the exception generated by the method baz(), it must declare the RuntimeException in its throws clause

(b) A try block cannot be followed by both a catch and a finally block(c) An empty catch block is not allowed(d) A catch block cannot follow a finally block(e) A finally block must always follow one or more catch blocks

Q4 What will be written to the standard output when the following program is run?Public class Test {

Public static void main(String args [])

Page 126: Cracked bits for scjp

{ String word = “restructure”; System.out.println(word.substring(2,3));} }

(a) est(b) es(c) str(d) st(e) s

Q5 Given that a static method doIt() in a class Work represents work to be done, what block of code will succeed in starting a new thread that will do the work?(a) Runnable r = new Runnable(){ Public void run(){ Work.doIt(); } };

Thread t new Thread( r );t.start();

(b) Thread t new Thread(){ public void start(){Work.doIt(); }};t.start();

(c) Runnable r = new Runnable() { Public void run(){ Work.doIt(); } }; r.start();

(d) Thread t new Thread( new Work()) ; t.start();(e) Runnable t = new Runnable() { Public void run(){ Work.doIt(); } }; t.run();

Q6 Write a line of code that declares a variable named layout of type LayoutManager and initializes it with a new object, which when used with a container can lay out components in a rectangular grid of equal-sized rectangles, 3 components wide and 2 components high(a) LayoutManager layout = new Map(2,3);(b) LayoutManager layout = new Paint(2,3);(c) LayoutManager layout = new GridLayout(2,3);(d) All of the above

Q7 What will be the result of compiling and running the following code?Public class Test {

static int a;int b;Public Test1{ Int c; c = a ; a++; b += c;}public static void main(String args[] ){ new Test1(); }}

(a) The code will fail to compile, since the constructor is trying to access static members

(b) The code will fail to compile, since the constructor is trying to use static member variable a before it has been initialized

(c) The code will fail to compile, since the constructor is trying to use static member variable b before it has been initialized

Page 127: Cracked bits for scjp

(d) The code will fail to compile, since the constructor is trying to use local variable c before it has been initialized

(e) The code will compile, and run without any problems.Q8 What will be written to the standard output when the following program is

run?Public class Test{ Public static void main(String args[]) { System.out.println(9 ^ 2); } }(a) 81(b) 7(c) 11(d) 0(e) false

Q9 Which statements are true concerning the default layout manager for containers in the java.awt package?(a) Objects instantiated from Panel do not have a default layout manager(b) Objects instantiated from Panel have FlowLayout as default layout

manager(c) Objects instantiated from Applet have BorderLayout as default layout

manager(d) Objects instantiated from Dialog have BorderLayout as default layout

manager(e) Objects instantiated from Window have the same default layout

manager as instances of AppletQ10

Which declarations will allow a class to be started as a standalone program?(a) Public void main(String args[])(b) Public void static main(String args[])(c) Public static main(String[] argv)(d) Final Public static void main(String[] array)(e) Public static void main(String args[])

Q11 Under which circumstances will a thread stop?(a) The method waitforId() in class MediaTracker is called(b) The run() method that the Thread is executing ends(c) The call to the start() method of the Thread object returns(d) The suspend() method is called on the Thread object(e) The wait() method is called on the Thread object

Q12

When creating a class that associates a set of keys with a set of values, which of these interfaces is most applicable?(a) Collection(b) Set(c) Sortedset(d) Map

Q13

What does the value returned by the method getID() found in class java.awt.AWTEvent uniquely identify?(a) The particular event instance(b) The source of the event

Page 128: Cracked bits for scjp

(c) The set of events that were triggered by the same action(d) The type of event(e) The type of component from which the event originated

Q14

What will be written to the standard output when the following program is run?Class Base{

int i;Base() { Add(1); }void add(int v) { i += v ;}void print() { System.out.println(i); }

Class Extension extends Base{Extensions() { add(2);}void add (int v) { i += v*2; }

Public class Test{Public static void main(String args[]) { bogo(new Extension());}static void bogo(Base b) { b.add(8); b.print(); }

}(a) 9(b) 18(c) 20(d) 21(e) 22

Q15

Which lines of code are valid declarations of a native method when occurring within the declaration of the following class?Public class Test{ // insert declaration of a native method here }(a) native public void setTemperature(int kelvin);(b) private native void setTemperature(int kelvin);(c) protected int native getTemperature();(d) public abstract native void setTemperature(int kelvin);(e) native int setTemperature(int kelvin) ()

Q16

How does the weighty property of the GridBagConstraints objects used in grid bag layout affect the layout of the components?(a) If affects which grid cell the components end up in(b) If affects how the extra vertical space is distributed(c) If affects the alignment of each components(d) If affects whether the components completely fill their allotted display

area verticallyQ17

Which statement can be inserted at the indicated position in the following code to make the program write 1 on the standard output when run?Public class Test{Int a = 1 ;Int b = 1 ;Int c = 1 ;Class Inner{Int a = 2 ;Int get() {

Page 129: Cracked bits for scjp

int c = 3 ;// insert statement herereturn c;} }

Test () {Inner I = new Inner()System.out.println(i.get());}public static void main(String args[]){ new Test(); }

}(a) C = b;(b) C = this.a;(c) C = this.b;(d) C = Test.this.a;(e) C = c;

Q18

Which is the earliest line in the following code after which the object created on the line marked (0) will be candidate for being garbage collected assuming no compiler optimizations are done?Public class Test{

Static String f(){Static a = “hello”;Static b = “bye” ; // (0)Static c = b + “!” ; // (1)Static d = b ;b= a; // (2)d= a; // (3)return c ; // (4)}public static void main(String args[]) {String msg = f();System.out.println(msg); // (5)} }

(a) The line marked (1)(b) The line marked (2)(c) The line marked (3)(d) The line marked (4)(e) The line marked (5)

Q19

Which methods from the String and StringBuffer classes modify the object on which they are called?(a) The charAt() method of the String class(b) The toUpperCase() method of the String class(c) The replace() method of the String class(d) The reverse() method of the StringBuffer class(e) The length() method of the StringBuffer class

Page 130: Cracked bits for scjp

Q20 Which statements, when inserted at the indicated position in the following code, will cause a runtime exception when attempting to run the program?Class A {}Class B extends A{}Class C extends A{}Public class Test {

Public static void main(String args[]) {A x = new A();B y = new B();C z = new C();// insert statement here ;} }

(a) x = y;(b) z = x ;(c) y = (B) x ;(d) z = (C ) y;(e) y = (A) y;

Q21 Which of these are keywords in Java?(a) Default(b) NULL(c) String(d) Throws(e) Long

Q22

It is desirable that a certain method within a certain class only be accessed by classes that are defined within the same package as the class of the method. How can such restrictions be enforced?(a) Mark the method with the keyword public(b) Mark the method with the keyword protected(c) Mark the method with the keyword private(d) Mark the method with the keyword package(e) Do not mark the method with any accessibility modifiers

Q23

Which code fragments will succeed in initializing a two dimensional array named tab with a size that will cause the expression tab[3][2] to access a valid element?(a) Int[] [] tab = { {0,0,0}, {0,0,0}};(b) Int tab[] [] = new int[4][]; for(int I=0, I<tab.length; I++) tab[I] = new int[3];(c) Int tab[][]= {

0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

(d) Int tab [3][2];(e) Int [] tab[]= { {0,0,0}, {0,0,0},{0,0,0},{0,0,0}};

Q24

What will be the result of attempting to run the following program?Public class Test{

Public static void main(String args[])

Page 131: Cracked bits for scjp

{ String[][][] arr = { {{},null}, {{ “1”,”2”}, {“1”, null, “3”}}, {}, { {“1”,null} } }; System.out.println (arr.length + arr[1][2].length);} }

(a) The program will terminate with an ArrayIndexOutOfBoundException(b) The program will terminate with an NullPointerException(c) 4 will be written to standard output(d) 6 will be written to standard output(e) 7 will be written to standard output

Q25

Which expressions will evaluate to true if preceded by the following code?String a = “hello”;String b = new String(a);String c = a;Char[] d = {‘h’,’e’,’l’,’l’,’o’};

(a) (a == “Hello”)(b) (a == b)(c) (a == c)(d) a.equals(b)(e) a.equals(d)

Q26

Which statements concerning the following code are true?Class A {

public A() {}public A(int I) { this(); }}

class B extends A {public boolean B(String msg) { return false; }}

class C extends B {private C() {super (); }public C(String msg) { this();}public C(int I) {}

}

(a) The code will fail to compile(b) The constructor in A that takes an int as an argument will never be

called as a result of constructing an object of class B or C(c) Class C has three constructors(d) Objects of class B cannot be constructed(e) At most one of the constructors of each class is called as a result of

constructing an object of class CQ27

Given two collection objects referenced by col1 an col2, which of these statements are true?(a) The operation col1.retainAll(col2) will not modify the col1 object(b) The operation col1.removeAll(col2) will not modify the col2 object(c) The operation col1.addAll(col2) will return a new modify collection

object, containing elements from both col1 and col2

Page 132: Cracked bits for scjp

(d) The operation col1.containsAll(col2) will not modify the col1 objectQ28

Which statements concerning the relations between the following classes are true?Class Foo{

Int num;Baz comp = new Baz();}

class Bar {boolean flag ;}

class Baz extends Foo{Bar thing = new Bar();Double limit ;}

(a) A Bar is a Baz(b) A Foo has a Bar(c) A Baz is a Foo(d) A Foo is a Baz(e) A Baz has a Bar

Q29 Which statements concerning the value of a member variable are true, when no explicit assignments have been made?(a) The value of an int is undetermined(b) The value of all numeric types is zero(c) The compiler may issue an error if the variable is used before it is

initialized(d) The value of a String variable is “” (empty string)(e) The value of all object variables is null

Q30 Which statements describe guaranteed behavior of the garbage collection and finalization mechanisms?(a) Objects are deleted when they can no longer be accessed through any

reference(b) The finalize() method will eventually be called on every object(c) The finalize() method will never be called more than once on an object(d) The object will not be garbage collected as long as it is possible for an

active part of the program to access it through a reference(e) The garbage collector will use a mark and sweep algorithm

Q31

Which code fragments will succeed in printing the last argument given on the command line to the standard output, and exit gracefully with no output if no arguments are given?(a) Public static void main(String args[]){

If (args.length!=0)System.out.println(args[args.length-1]);

}(b) Public static void main(String args[]) {

Try { System.out.println(args[args.length]) ; }Catch (ArrayIndexOutOfBoundsException e) {}

Page 133: Cracked bits for scjp

}(c) Public static void main(String args[]) {

Int ix = args.length;String last = args[ix];If (ix > 0) System.out.println(last);}

(d) Public static void main(String args[]) {Int ix = args.length-1;If (ix > 0) System.out.println(args[ix]);}

(e) Public static void main(String args[]) {Try { System.out.println(args[args.length-1]) ; }Catch (NullPointerException e) {}}

Q32

Which of the following statements concerning the collection interfaces are true?(a) Set extends Collection(b) All methods defined in Set are also defined in Collection(c) List extends Collection(d) All method defined in List are also defined in Collection(e) Map extends Collection

Q33

The range of short is(a) –2 7 to 2 7 –1(b) –2 8 to 2 8

(c) –2 15 to 2 15 -1(d) –2 16 to 2 16 –1(e) 0 to 2 16 –1

Q34

What is the name of the method that threads can use to pause their execution until signalled to continue by another thread?(a) Wait(b) Suspend(c) Stop(d) All of the above

Q35

Given the following class definitions, which expression identifies whether the object referred to by obj was created by instantiating class B rather than classes A, C and D?Class A {}Class B extends A {}Class C extends B {}Class D extends A {}(a) Obj instanceof B(b) Obj instanceof A && ! (obj instanceof C)(c) Obj instanceof B && ! (obj instanceof C)(d) !(obj instanceof C || obj instanceof D)(e) !(obj instanceof A) && ! (obj instanceof C) && ! (obj instanceof D)

Q3 What will be written to the standard output when the following program is

Page 134: Cracked bits for scjp

6 run?Public class Test {

Public static void main(String args[]){Double d = -2.9;Int i = (int) d;i *= (int) Math.ceil(d);i *= (int) Math.abs(d);System.out.println(i);} }

(a) –12(b) 18(c) 8(d) 12(e) 27

Q37

What will be written to the standard output when the following program is runPublic class Test{

Int a;Int b;Public void f() {

A = 0;B = 0 ;Int [] c = { 0 };G(b,c);System.out.println(a+” “ + b + “ “ + c[0] + “ “ );}

Public void g(int b, int [] c) {A = 1;B = 1 ;C[0] = 1;}

Public static void main(String args[]) {Test obj = new Test();Obj.f();}

}(a) 0 0 0(b) 0 0 1(c) 0 1 0(d) 1 0 0(e) 1 0 1

Q38

Which statements concerning the effect of the statement gfx.drawRect (5,5,10,10) are true, given that gfx is a reference to a valid Graphics object?(a) The rectangle drawn will have a total width of 5 pixels(b) The rectangle drawn will have a total height of 6 pixels

Page 135: Cracked bits for scjp

(c) The rectangle drawn will have a total width of 10 pixels(d) The rectangle drawn will have a total height of 11 pixels(e) None of the above

Q39 Given the following code, which code fragments, when inserted at the indicated location, will succeed in making the program display a button spanning the whole window area?Import java.awt. ;Public class Test{

public static void main(String args[]) {Window win = new Frame();Button but = new Button(“button”);// insert code fragment herewin.setSize(200,200);win.setVisible(true);

} }(a) Win.setLayout(new BorderLayout());

Win.add(but);(b) Win.setLayout(new GridLayout(1,1));

Win.add(but);(c) Win.setLayout(new BorderLayout( ));

Win.add(but.BorderLayout.CENTER);(d) Win.add(but);(e) Win.setLayout(new FlowLayout());

Win.add(but);Q40

Which method implementations will write the given string to a file named “file”, using UTF8 encoding?(a) Public void write(String msg) throws IOException{

FileWriter fw = new FileWriter(new File(“file”));Fw.write(msg);Fw.close();}

(b) Public void write(String msg) throws IOException{OutputStreamWriter osw = new OutputStreamWriter(new

FileOutputStream(“file”), “UTF8);Osw.write(msg);Osw.close();}

(c) Public void write(String msg) throws IOException{FileWriter fw = new FileWriter(new File(“file”));Fw.setEncoding(“UTF8);Fw.write(msg);Fw.close();}

(d) Public void write(String msg) throws IOException{FilterWriter fw = new FilterWriter(new FileWriter(“file”),”UTF8”);Fw.write(msg);

Page 136: Cracked bits for scjp

Fw.close();}

(e) Public void write(String msg) throws IOException{OutputStreamWriter osw = new OutputStreamWriter(new

OutputStream(new File(“file”)), UTF8); Osw.write(msg);

Osw.close();}

Q41

Which are the valid identifiers?(a) _class(b) $value$(c) zer@(d) angstrom(e) 2much

Q42

What will be the output of attempting to compile and run the following program?Public class Test{

Public static void main(String args[]) {Int counter = 0;L1:For(int i = 10; I<0;I++){L2:Int j = 0;While(j<10) {

If (j > 1) break L2;If ( i == j ) {

Counter ++ ;Continue L1;}

}counter - - ;}System.out.println(counter);}

}(a) The program will fail to compile(b) The program will not terminate normally(c) The program will write 10 to the standard output(d) The program will write 0 to the standard output(e) The program will write 9 to the standard output

Q43

Given the following definition, which definitions are valid?Interface I {

void setValue(int val);Int getValue(); }

(a) Class A extends I {Int value;

Page 137: Cracked bits for scjp

Void setValue(int val) {value = val;}Int getValue(){return value;} }

(b) Interface B extends I {void increment(); }

(c) Abstract class C implements I {Int getValue(); { return 0; }Abstract void increment(); }

(d) Interface D implements I {void increment(); }

(e) Class E implements I {Int value ;Public void setValue(int val) {value = val ;} }

Q44

Which statements concerning the methods notify() and notifyAll() are true?(a) Instances of class Thread have a method called notify()(b) A call to the method notify() will wake the thread that currently owns the

monitor of the object(c) The method notify() is synchronized(d) The method notifyAll() is defined in class Thread(e) When there is more than one thread waiting to obtain the monitor of an

object, there is no way to be sure which thread will be notified by the notify() method

Q45

Which statements concerning the correlation between the inner and outer instances of non-static inner classes are true?(a) Member variables of the outer instances are always accessible to inner

instances, regardless of their accessibility modifiers(b) Member variables of the outer instances can never be referred to using

only the variable name within the inner instance(c) More than one inner instance can be associated with the same outer

instance(d) All variables from the outer instance that should be accessible in the

inner instance must be declared final(e) A class that is declared final cannot have any inner classes

Q46

What will be the result of attempting to compile and run the following code?Public class Test{

Public static void main(String args[]) {Int I = 4;Float f = 4.3;Double d = 1.8;Int c = 0;If ( I == f ) c++;If ((int) ( f + d )) == ((int) f + (int) d)) c +=2;System.out.println( c );} }

(a) The code will fail to compile(b) 0 will be written to the standard output(c) 1 will be written to the standard output

Page 138: Cracked bits for scjp

(d) 2 will be written to the standard output(e) 3 will be written to the standard output

Q47

Which operators will always evaluate all the operands?(a) | |(b) +(c) &&(d) ? :(e) %

Q48

Which statements concerning the switch construct are true?(a) All switch statements must have a default label(b) There must be exactly one label for each code segment in a switch

statement(c) The keyword continue can never occur within the body of a switch

statement(d) No case label may follow a default label within a single switch

statement(e) A character literal can be used as a value for a case label

Q49

Which modifiers and return types would be valid in the declaration of a working main() method for a Java standalone application?(a) Private(b) Final(c) Static(d) Int(e) Abstract

Q50 What will be the appearance of an applet with the following init() method?Public void init() { Add(new Button(“hello”)); }(a) Nothing appears in the applet(b) A button will cover the whole area of the object(c) A button will appear in the top left corner of the applet(d) A button will appear, centered in the top region of the applet(e) A button will appear in the center of the applet

Q51 Which statements concerning the event model of the AWT are true?(a) At most one listener of each type can be registered with a component(b) Mouse motion listeners can be registered on a List instance(c) There exists a class named ContainerEvent in package java.awt.event(d) There exists a class named MouseMotionEvent in package

java.awt.event(e) There exists a class named ActionAdapter in package java.awt.event

Q52

Which statements are true, given the code new FileOutputStream(“data” , true) for creating an object of class FileOutputStream?(a) FileOutputStream has no constructors matching the given arguments(b) An IOException will be thrown if a file named “data” already exists(c) An IOException will be thrown if a file named “data” does not already

exist(d) If a file named “data’ exists, its contents will be reset and overwritten

Page 139: Cracked bits for scjp

(e) If a file named “data’ exists, its output will be appended to its current contents

Q53

Given the following code, write a line of code that, when inserted at the indicated location, will make the overriding method in Extension invoke the overridden method in class Base on the current objectClass Base{

Public void print() {System.out.println(“base”);} }

Class Extension extends Base{Public void print() {

System.out.println(“extension”);// insert line of implementation here} }

public Class Test{public static void main(String args[]) {

Extension ext = new Extention();ext.print();} }

(a) Super.print();(b) Super.Test();(c) Ext.print();(d) None of the above

Q54

Given that file is a reference to a File object that represents a directory, which code fragments will succeed in obtaining a list of the entries in the directory?(a) Vector filelist = ((Directory) file).getList();(b) String[] filelist = file.directory;(c) Enumeration filelist = file.contents();(d) String[] filelist = file.list();(e) Vector filelist = (new Directory(file)).files();

Q55

What will be written to the standard output when the following program is run?Public class Test{

Public static void main)String args[]) {String space = “ “;String composite = space + “hello” + space + space ;Composite.concat(“world”);String trimmed = composite.trim();System.out.println(trimmed.length());} }

(a) 5(b) 6(c) 7(d) 12(e) 13

Page 140: Cracked bits for scjp

Q56

Given the following code, which statement concerning the objects referenced through the member variables i, j, k are true, given that any thread may call the methods a, b, c at any time?Class Counter{

Int v = 0;Synchronized void inc() { v++; }Synchronized void dec() { v- -; }}

public class Test{Counter I, j, k ;Public synchronized void a() {

i.inc();System.out.println(“a”);i.dec();

}Public synchronized void b() {

i.inc(); j.inc(); k.inc();System.out.println(“b”);i.dec(); j.dec(); k.dec();

}Public void c() {

k.inc();System.out.println(“c”);k.dec();

}}

(a) i.v is guaranteed always to be 0 or 1(b) j.v is guaranteed always to be 0 or 1(c) k.v is guaranteed always to be 0 or 1(d) j.v will always be greater than or equal to k.v at any given time(e) k.v will always be greater than or equal to j.v at any given time

Q57

Which statements concerning casting and conversion are true?(a) Conversion from int to long does not need a cast(b) Conversion from byte to short does not need a cast(c) Conversion from float to long does not need a cast(d) Conversion from short to char does not need a cast(e) Conversion from boolean to int using a cast is not possible

Q58

Given the following code, which method declarations, when inserted at the indicated position will not cause the program to fail compilation?Public class Test {

Public ling sum (long a, long b) { return a + b; }// insert new method declaration here

}

Page 141: Cracked bits for scjp

(a) Public int sum( int a, int b) { return a + b ; }(b) Public int sum( long a, long b) { return 0 ; }(c) Abstract int sum();(d) Private long sum(long a , long b) {return a + b ; }(e) Public long sum(long a , int b) {return a + b ; }

Q59

The 8859-1-character code for the uppercase letter A is 565. Which of these code fragments declare and initialize a variable of type char with this value?(a) Char ch = 65;(b) Char ch = ‘\65’;(c) Char ch = ‘\0041’;;(d) Char ch = ‘A’;(e) Char ch = “A” ;

Q60

Given the following code, which of these constructors could be added to the MySubclass without causing a compile time error?Class MySuper{

Int number ;MySuper(int i ) {number = i ;}}

class MySub extends MySuper {int count;MySub(int cnt, int sum) {

Super(num);Count = cnt ;

}// insert additional constructor here

}(a) MySub() { }(b) MySub( int cnt) { count = cnt; }(c) MySub( int cnt) { super(); count = cnt; }(d) MySub( int cnt) { count = cnt; super(cnt); }(e) MySub( int cnt) { this(cnt , cnt); }

Page 142: Cracked bits for scjp

Q61 Which of these statements are true?(a) A super() or this() call must always be provided explicitly as the first

statement in the body of a constructor(b) If both a subclass and its superclass do not have any declared

constructors, the implicit default constructor of the subclass will call super() when run

(c) If neither super() or this() is declared as the first statement in the body of a constructor, then this() will implicitly be inserted as the first statement

(d) If super() is the first statement in the body of constructor, then this() can be declared as the second statement

(e) Calling super() as the first statement in the body of a constructor of a subclass will always work, since all superclasses have a default constructor?

Q62

What will the following program print when run?Public class MyClass {

Public static void main(String args[]) {B b = new B(“Test”);

}}class A {

A() { this(“1”, “2”);}A(String s, String t) { this( s + t );}A(String s) { System.out.println(s);}}

class B extends A {B(String s) { System.out.println(s);}B(String s, String t) { this( t + s + “3” );}B() {super(“4”); };}

(a) It will simply print Test(b) It will print Test followed by Test(c) It will print 123 followed by Test(d) It will print 12 followed by Test(e) It will print 4 followed by Test

Q63

Given the following variable declaration within the definition of an interface which of these declarations are equivalent to it?Int answer = 42;(a) Public static int answer = 42;(b) Public final int answer = 42;(c) static final int answer = 42;(d) Public int answer = 42;(e) All of the above

Q64

What is wrong, if anything, with the following code?Abstract class MyClass implements Interface1, Interface2 {

Void f() { } ;

Page 143: Cracked bits for scjp

Void g() { } ;}

interface Interface1 {int VAL_A = 1 ;int VAL_B = 2 ;void f() ;void g() ;}

interface Interface2 {int VAL_B = 3 ;int VAL_C = 4 ;void g() ;void h() ;}

(a) Interface1 and Interface2 do not match, therefore MyClass cannot implement them both

(b) MyClass only implements Interface1. Implementation for void h() from Interface2 is missing

(c) The declarations of void g() in the two interfaces clash(d) The declarations of int VAL_B in the two interfaces clash(e) Nothing is wrong in the code, it will compile without errors

Q65

Given the following program, which statement is true?Public class Test {

Public static void main(String args[]){A[] arrA ;B[] arrB ;arrA = new A[10];arrB = new B[20];arrA = arrB; // (1)arrB = (B[]) arrA ; // (2)arrA = new A[10];arrB = (B[]) arrA; // (3)}

}class A { }class B extends A { }(a) The program will fail to compile, owing to the line labeled (1)(b) The program will throw a lava.lang.ClassCastException at the line

labeled (2)(c) The program will throw a lava.lang.ClassCastException at the line

labeled (3)(d) The program will compile and run without problems, even if the (B[])

cast in the lines labeled (2) and (3) were removed(e) The program will compile and run without problems, but would not do

so if the (B[]) cast in the lines labeled (2) and (3) were removedQ6 Which is the first line that will cause compilation to fail in the following

Page 144: Cracked bits for scjp

6 program?Class Test {

Public static void main(String args{}){Test a ;SubTest b ;A = new test(); // (1)B = new SubTest (); // (2)A = b ; // (3)B = a ; // (4)A = new SubTest(); // (5)B = new Test(); // (6)}

}class SubTest extends Test { }(a) Line labeled (1)(b) Line labeled (2)(c) Line labeled (3)(d) Line labeled (4)(e) Line labeled (5)(f) Line labeled (6)

Q67

Given three classes A,B and C where B is a subclass of A and C is a subclass of B, which one of these boolean expressions correctly identifies when an object o has actually been instantiated from class B as opposed from A or C?(a) ( o instanceof B ) && ( !( o instanceof A ))(b) ( o instanceof B ) && ( !( o instanceof C ))(c) !(( o instanceof A ) || ( o instanceof B )(d) ( o instanceof B )(e) ( o instanceof B ) && !(( o instanceof A )) || (o instanceof C))

Q68

What will be the result of attempting to compile and run the following program?Public class Polymorphism {

Public static void main(String args[]) {A ref1 = new C();B ref2 = (B) ref1;System.out.println(ref2.f());}

}class A { int f() {return 0; } }class B extends A { int f() {return 1; } }class C extends B { int f() {return 2; } }(a) The program will fail to compile(b) The program will compile without errors, but will throw a

ClassCastException when run(c) The program will compile without errors, and print 0 when run(d) The program will compile without errors, and print 1 when run

Page 145: Cracked bits for scjp

(e) The program will compile without errors, and print 2 when runQ69

Given the following code, which statements are true?Public interface HeavenlyBody{ String describe(); }Class Star implements HeveanlyBody{

String starName;Public String describe() { return “star” + starName; }}

class Planet{String name;Star orbiting;Public String describe() {

Return “planet” + name + “orbiting” + orbiting.describe();}

}(a) The code will fail to compile(b) The use of aggregation is justified, since planet has-a star(c) The code will fail to compile if the name starName is replaced with the

name bodyName throughout the Star class definition(d) the code will fail to compile if the name starName is replaced with the

name name throughout the Star class definition(e) An instance of Planet is a valid instance of a HeavenlyBody

Q70

What will happen if you register more than one ActionListener in a button component?(a) The program will fail to compile(b) The program will issue a runtime exception during execution(c) All the registered action listeners will be notified when the button is

clicked(d) The last registered action listeners will be notified when the button is

clicked(e) The first registered action listeners will be notified when the button is

clicked

Page 146: Cracked bits for scjp

A1 A2 A3 A4 A5 A6 A7 A8 A9 A10A,B,C,E

A,B,E D E A C E C B,D D,E

A11 A12 A13 A14 A15 A16 A17 A18 A19 A20B D D E A,B B A,D C D C

A21 A22 A23 A24 A25 A26 A27 A28 A29 A30D,E D,E B,E A C,D B,C B,D C,E B,E C,D

A31 A32 A33 A34 A35 A36 A37 A38 A39 A40A A,B,C C A C C E D A,B,C B

A41 A42 A43 A44 A45 A46 A47 A48 A49 A50A,B,D A B A,E A,C A B,E E B,C D

A51 A52 A53 A54 A55 A56 A57 A58 A59 A60B,C E A D A A,B A,B,E A,E D E

A61 A62 A63 A64 A65 A66 A67 A68 A69 A70B D E E C D B E B C

Advance JAVA

Q1 JAVA Swing are(a) Methods(b) Class(c) Components(d) Libraries

Q2 Difference between AWT and JFC Classes are:(a) AWT classes are more functional than JFC classes and reside in the

java.awt package(b) JFC classes are more functional, start with the letter J and reside in the

java.awt.swing package(c) JFC classes use the AWT peer mechanism, start with the letter J and

reside in the java.awt.swing package(d) None of the above

Q3 The content pane can be accessed by calling :(a) The getContentPane on Jframe() from JFC(b) The getFrame() on Frame() class from AWT(c) The textfield on JtextField() from JFC(d) Cannot be accessed

Q4 To present contents in a Tabbed Pane format :(a) The TabbedPane class is used(b) The JtabbedPane class is used(c) The addTab() method is used

Page 147: Cracked bits for scjp

(d) None of the aboveQ5 The Jlabel class has properties of:

(a) Displaying text message(b) Icon to the text message(c) Position of the text message and icon(d) All of the above

Q6 Anonymous inner classes are(a) A heavyweight listener and is generally avoided(b) Never used in JAVA programming(c) A useful way to add a lightweight listener to a component(d) The class definition begins and ends with {( … )}; combination

Q7 The JtoggleButtons class announces state changes by sending ItemEvents to ItemListenters(a) True(b) False

Q8 The Jcheckbox class is similar to JToggleButton(c) True(a) False

Q9 The JcomboBox class is like the java.awt.Choice class(d) True(a) False

Q10

The JSlider class(a) Is unlike the java.awt.Scrollbar class(b) Enhances the java.awt.Scrollbar class(c) Both the classes are different in their functionality(d) None of the above

Page 148: Cracked bits for scjp

Q11 The JToolBar class(a) Is a rectangular area that can be detached from the window in which it

resides and placed on the desktop or any other region of the window(b) Cannot be detached from the window in which it resides(c) Is a rectangular area that cannot contain other components(d) None the above

Q12

JAVA is(a) A write once run anywhere language(b) A write once run once compiler(c) A machine dependent programming language(d) A write once and compile at runtime language

Q13

Java based clients are(a) Heavily dependent on hardware and software maintenance(b) Expensive software requiring configurations(c) Thin clients(d) None of the above

Q14

Relational Database Management Systems (RDBMS) has been the pioneering vision of(a) Microsoft(b) IBM(c) Bill Clinton(d) Dr. E.F Codd

Q15

Data stored in RDBMS are retrieved through(a) Natural Query Language(b) Structured Query Language (SQL)(c) Both the above(d) None of the above

Q16

All RDBMS and DBMS systems support SQL to retrieve data(a) True(b) False

Q17

In a two tier model(a) The database developer creates an application front-end and access

data through a socket connection to the server(b) The database developer creates an application front-end and access

data through a socket connection on the same computer(c) No socket connection is used to access data from the server database(d) There is no concept of front end and back end database connectivity

Q18

The formatting and display of the data is the responsibility of :(a) Server application(b) Client application(c) Third Party vendor(d) A combination of the above

Q19

Macro Programs written for simple data manipulation are called(a) Applications(b) Functions(c) Stored procedures

Page 149: Cracked bits for scjp

(d) PackagesQ20

________ executes stored procedures automatically when some event occurs(a) Remote Procedure Calls(b) Triggers(c) Remote Method Invocation(d) All the above

Page 150: Cracked bits for scjp

Q21 Two tier database models have limitations like:(a) Simple library functions for manipulation of server database(b) New Versions could be easily incorporated without recompiling or

redistribution(c) Universal vendor provided libraries(d) Large client side runtimes applications, driving up the cost

Q22

In a three tier database design, the client communicates with:(a) The database server directly(b) An intermediate server that provides a layer of abstraction from the

database(c) Client side libraries for database access(d) Data reply procedure calls

Q23

The JDBC API is designed to allow developers to:(a) Create database front ends without having to continually rewrite their

code(b) Rewrite their code using various vendor developed libraries(c) Access proprietary third party solutions(d) Create one time write and forget applications

Q24

JDBC provides a multi interfaced API that is uniform and database dependent(a) True(b) False

Q25

The Java interface drivers(a) Access the database servers for fetching the data from the database

table(b) Are mapped to the corresponding library routine calls of the database

serer(c) Take care of the translation of the standard JDBC calls into the specific

calls required by the database it supports(d) There is no concept of drivers in Java

Q26

JDBC is(a) Derived from Microsoft’s Open Database Connectivity specification

(ODBC)(b) Developed in Java and based on X/Open SQL Command Level

Interface(c) Non compliant with ODBC drivers(d) Developed by Microsoft in conjunction with ODBC calls

Q27

The JDBC API has ______________ and _______________ interface(a) Application Layer and Client Layer(b) Client Layer and Business Layer(c) Middleware Layer and Firmware Layer(d) Application Layer and Driver Layer

Q28

The main interfaces for a Driver Layer are:(a) Driver, Connection, Statement and ResultSet(b) Application, Connection, Statement and ResultSet(c) DriverManager, Connection, Statement and ResultSet

Page 151: Cracked bits for scjp

(d) ApplicationManager, Connection, Statement and ResultSetQ29

The DriverManager is responsible for:(a) Loading and unloading drivers, making connection through drivers,

logging and database login timeouts(b) Loading and making connection through drivers, database login

timeouts(c) Unloading and disconnecting through drivers, logout and login timeouts(d) None of the above

Q30

Every JDBC program must have at least _______ implementations of the JDBC driver(a) 0(b) 10(c) 1(d) 3

Page 152: Cracked bits for scjp

Answers:A1 A2 A3 A4 A5 A6 A7 A8 A9 A1

0C B A B D C A A A B

A11 A12 A13 A14 A15 A16 A17 A18 A19 A20

A A C D B A A B C B

A21 A22 A23 A24 A25 A26 A27 A28 A29 A30

D B A B C B D A A C

Page 153: Cracked bits for scjp

1. Which statement are characteristics of the >> and >>> operators.

A. >> performs a shift B. >> performs a rotate C. >> performs a signed and >>> performs an unsigned shift D. >> performs an unsigned and >>> performs a signed shift E. >> should be used on integrals and >>> should be used on floating point types

C.

2. Given the following declaration

String s = "Example";

Which are legal code?

A. s >>> = 3; B. s[3] = "x"; C. int i = s.length(); D. String t = "For " + s; E. s = s + 10;

CDE.

3. Given the following declaration

String s = "hello";

Which are legal code?

A. s >> = 2; B. char c = s[3]; C. s += "there"; D. int i = s.length(); E. s = s + 3;

CDE.

4. Which statements are true about listeners?

Page 154: Cracked bits for scjp

A. The return value from a listener is of boolean type. B. Most components allow multiple listeners to be added. C. A copy of the original event is passed into a listener method. D. If multiple listeners are added to a single component, they all must all be friends to each other. E. If the multiple listeners are added to a single component, the order [in which listeners are called is guaranteed].

BC.

5. What might cause the current thread to stop executing.

A. An InterruptedException is thrown. B. The thread executes a wait() call. C. The thread constructs a new Thread. D. A thread of higher priority becomes ready. E. The thread executes a waitforID() call on a MediaTracker.

ABDE.

6. Given the following incomplete method.

1. public void method(){ 2. 3. if (someTestFails()){ 4. 5. } 6. 7.}

You want to make this method throw an IOException if, and only if, the method someTestFails() returns a value of true. Which changes achieve this?

A. Add at line 2: IOException e; B. Add at line 4: throw e; C. Add at line 4: throw new IOException(); D. Add at line 6: throw new IOException();

Page 155: Cracked bits for scjp

E. Modify the method declaration to indicate that an object of [type] Exception might be thrown.

DE. (E suppose they mean the method declaration for someTestFails.)

7. Which modifier should be applied to a method for the lock of the object this to be obtained prior to executing any of the method body?

A. final B. static C. abstract D. protected E. synchronized

E.

8. Which are keywords in Java?

A. NULL B. true C. sizeof D. implements E. instanceof

DE.

9. Consider the following code:

Integer s = new Integer(9); Integer t = new Integer(9); Long u = new Long(9);

Which test would return true?

A. (s==u) B. (s==t) C. (s.equals(t)) D. (s.equals(9)) E. (s.equals(new Integer(9))

Page 156: Cracked bits for scjp

CE.

10. Why would a responsible Java programmer want to use a nested class?

Don't know the answers. But here are some reasons from Exam Cram.

a.To keep the code for a very specialized class in close association with the class it works with.b. To support a new user interface that generates custom events.c. To impress the boss with his/her knowledge of Java by using nested classes all over theplace.

AB.

11. You have the following code. Which numbers will cause "Test2" to be printed?

switch(x){

case 1: System.out.println("Test1"); case 2:

case 3: System.out.println("Test2"); break; } System.out.println("Test3"); }

A. 0 B. 1 C. 2 D. 3 E. 4

BCD.11. You have the following code. Which numbers will cause "Test3" to be printed?

Page 157: Cracked bits for scjp

switch(x){

case 1: System.out.println("Test1"); case 2:

case 3: System.out.println("Test2"); break; default: System.out.println("Test3"); }

A. 1 B. 2 C. 3 D. 4 E. none

D

12. Which statement declares a variable a which is suitable for referring to an array of 50 string objects?

A. char a[][]; B. String a[]; C. String []a; D. Object a[50]; E. String a[50); F. Object a[];

BCF.

13. What should you use to position a Button within an application frame so that the width of the Button is affected by the Frame size but the height is not affected.

A. FlowLayout B. GridLayout C. Center area of a BorderLayout

Page 158: Cracked bits for scjp

D. East or West of a BorderLayout E. North or South of a BorderLayout

E.

14. What might cause the current thread to stop executing?

A. An InterruptedException is thrown B. The thread executes a sleep() call C. The thread constructs a new Thread D. A thread of higher priority becomes ready (runnable) E. The thread executes a read() call on an InputStream

ABDE.

Non-runnable states:

* Suspended: caused by suspend(), waits for resume() * Sleeping: caused by sleep(), waits for timeout * Blocked: caused by various I/O calls or by failing to get a monitor's lock, waits for I/O or for the monitor's lock * Waiting: caused by wait(), waits for notify() or notifyAll() * Dead: Caused by stop() or returning from run(), no way out

From Certification Study Guide p. 227

15. Consider the following code:

String s = null;

Which code fragments cause an object of type NullPointerException to be thrown?

A. if((s!=null) & (s.length()>0)) B. if((s!=null) &&(s.length()>0)) C. if((s==null) | (s.length()==0)) D. if((s==null) || (s.length()==0))

AC.

Page 159: Cracked bits for scjp

16. Consider the following code:

String s = null;

Which code fragments cause an object of type NullPointerException to be thrown?

A. if((s== null) & (s.length()>0)) B. if((s==null) &&(s.length()>0)) C. if((s!=null) | (s.length()==0)) D. if((s!=null) || (s.length()==0))

ABCD.

17. Which statement is true about an inner class?

A. It must be anonymous B. It can not implement an interface C. It is only accessible in the enclosing class D. It can only be instantiated in the enclosing class E. It can access any final variables in any enclosing scope.

E.

18. Which statements are true about threads?

A. Threads created from the same class all finish together B. A thread can be created only by subclassing Java.Lang.Thread. C. Invoking the suspend() stops a thread so that it cannot be restarted D. The Java Interpreter's natural exit occurs when no non daemon threads remain alive E. Uncoordinated changes to shared data by multiple threads may result in the data being read, or left, in an inconsistent state.

DE.

19. Consider the following code:

Page 160: Cracked bits for scjp

1. public void method(String s){ 2. String a,b; 3. a = new String("Hello"); 4. b = new String("Goodbye"); 5. System.out.println(a + b); 6. a = null; 7. a = b; 8. System.out.println(a + b); 9. }

Where is it possible that the garbage collector will run the first time?

A. Just before line 5 B. Just before line 6 C. Just before line 7 D. Just before line 8 E. Never in this method

C.

20. Which code fragments would correctly identify the number of arguments passed via the command line to a Java application, excluding the name of the class that is being invoked?

A. int count = args.length; B. int count = args.length - 1; C. int count = 0; while (args[count] != null) count ++; D. int count = 0; while (!(args[count].equals(""))) count ++;

A.

21. Which are keywords in Java?

A. sizeof B. abstract C. native D. NULL

Page 161: Cracked bits for scjp

E. BOOLEAN

BC.

22. Which are correct class declarations? Assume in each case text constitutes the entire contents of a file called Fred.java on a system with a case-significant system.

A. public class Fred { public int x = 0; public Fred (int x) { this.x = x; } }

B. public class fred { public int x = 0; public fred (int x) { this.x = x; } }

C. public class Fred extends MyBaseClass, MyOtherBaseClass { public int x = 0; public Fred (int xval) { x = xval; } }

D. protected class Fred { private int x = 0; private Fred (int xval) { x = xval; } }

E. import java.awt.*; public class Fred extends Object { int x; private Fred (int xval) { x = xval; } }

Page 162: Cracked bits for scjp

AE.

22. Which are correct class declarations? Assume in each case text constitutes the entire contents of a file called Fred.java on a system with a case-significant system.

A. public class Fred { public int x = 0; public Fred (int x) { this.x = x; } }

B. public class fred { public int x = 0; public fred (int x) { this.x = x; } }

C. public class Fred extends MyBaseClass, MyOtherBaseClass { public int x = 0; public Fred (int xval) { x = xval; } }

D. protected class Fred { private int x = 0; private Fred (int xval) { x = xval; } }

E. import java.awt.*; public class Fred extends Object { int x; private Fred (int xval) { x = xval; } }

AE.

Page 163: Cracked bits for scjp

//Do car in the place of fred

B is wrong because of case-sensitivity. C is wrong because multiple inheritance is not supported in Java. D is wrong because a class can only be public, abstract, final or default (with no access modifier).

23. Which are correct class declarations? Assume in each case text constitutes the entire contents of a file called Test.java on a system with a case-significant system.

A. public class Test { public int x = 0; public Test (int x) { this.x = x; } }

B. public class Test extends MyClass, MyOtherClass { public int x = 0; public Test (int xval) { x = xval; } }

C. import java.awt.*; public class Test extends Object { int x; private Test (int xval) { x = xval; } }

D. protected class Test { private int x = 0; private Test (int xval) { x = xval; } }

AC.

Page 164: Cracked bits for scjp

24. A class design requires that a particular member variable must be accesible for direct access by any subclasses of this class, otherwise not by classes which are not members of the same package. What should be done to achieve this?

A. The variable should be marked public B. The variable should be marked private C. The variable should be marked protected D. The variable should have no special access modifier E. The variable should be marked private and an accessor method provided

C.

25. Which correctly create an array of five empty Strings?

A. String a [] = new String [5]; for (int i = 0; i < 5; a[i++] = "");

B. String a [] = {"", "", "", "", "", ""};

C. String a [5]; D. String [5] a; E. String [] a = new String[5]; for (int i = 0; i < 5; a[i++] = null);

AB.

26. Which cannot be added to a Container?

A. an Applet B. a Component C. a Container D. a Menu E. a Panel

D.

26. Which cannot be added to a Container?

Page 165: Cracked bits for scjp

A. an Applet B. a Panel C. a Container D a Container E. a MenuItem

E.

27. FilterOutputStream is the parent class for BufferedOutputStream, DataOutputStream and PrintStream. Which classes are a valid argument for the constructor of a FilterOutputStream?

A. InputStream B. OutputStream C. File D. RandomAccessFile E. StreamTokenizer

B.

28. FilterInputStream is the parent class for BufferedInputStream and DataInputStream. Which classes are a valid argument for the constructor of a FilterInputStream?

A. File B. InputStream C. OutputStream D. FileInputStream E. RandomAccessFile

B.

29. Given the following method body:

{ if (atest()) { unsafe(): } else { safe();

Page 166: Cracked bits for scjp

} }

The method "unsafe" might throw an AWTException (which is not a subclass of RunTimeException). Which correctly completes the method of declaration when added at line one?

A. public AWTException methodName() B. public void methodname() C. public void methodName() throw AWTException D. public void methodName() throws AWTException E. public void methodName() throws Exception

DE.

30. Given a TextArea using a proportional pitch font and constructed like this:

TextField t = new TextArea("12345", 5, 5);

Which statement is true?

A. The displayed width shows exactly five characters on each line unless otherwise constrained. B. The displayed height is five lines unless otherwise constrained. C. The maximum number of characters in a line will be five. D. The user will be able to edit the character string. E. The displayed string can use multiple fonts.

BD.

31. Given this skeleton of a class currently under construction:

public class Example { int x, y;

public Example(int a){ //lots of complex computation

Page 167: Cracked bits for scjp

x = a; }

public Example(int a, int b) { /*do everything the same as single argument version of constructor including assignment x = a */ y = b; } }

What is the most concise way to code the "do everything..." part of the constructor taking two arguments?

Answer:

this(a);

32. Given this skeleton of a class currently under construction:

public class Example { int x, y;

public Example(int a, int b){ //lots of complex computation x = a; }

public Example(int a, int b, long c) { /*do everything the same as the two argument version of constructor including assignment x = a */ y = b; } }

What is the most concise way to code the "do everything..." part of the constructor taking two arguments?

Answer:

this(a, b);

Page 168: Cracked bits for scjp

Warning! A similar question will appear with at least two classes, then it is super("arguments"); that you should use.

33. Which correctly create a two dimensional array of integers?

A. int a [][] = new int [10,10]; B. int a [10][10] = new int [][]; C. int a [][] = new int [10][10]; D. int []a[] = new int [10][10]; E. int [][]a = new int [10][10];

CDE.

34. Given the following method body:

{ if (sometest()) { unsafe(); } else { safe(); } }

The method "unsafe" might throw an IOException (which is not a subclass of RunTimeException). Which correctly completes the method of declaration when added at line one?

A. public void methodName() throws Exception B. public void methodname() C. public void methodName() throw IOException D. public void methodName() throws IOException E. public IOException methodName()

AD.

35. What would be the result of attempting to compile and run the following piece of

Page 169: Cracked bits for scjp

code?

public class Test { static int x;

public static void main(String args[]){ System.out.println("Value is " + x); } }

A. The output "Value is 0" is printed. B. An object of type NullPointerException is thrown. C. An "illegal array declaration syntax" compiler error occurs. D. A "possible reference before assignment" compiler error occurs. E. An object of type ArrayIndexOutOfBoundsException is thrown.

A.

35. What would be the result of attempting to compile and run the following piece of code?

public class Test { static int[] x = new int[10];

public static void main(String args[]){ System.out.println("Value is " + x[5]); } }

A. The output "Value is 0" is printed. B. An object of type NullPointerException is thrown. C. An "illegal array declaration syntax" compiler error occurs. D. A "possible reference before assignment" compiler error occurs. E. An object of type ArrayIndexOutOfBoundsException is thrown.

A.

36. What would be the result of attempting to compile and run the following piece of

Page 170: Cracked bits for scjp

code?

public class Test { public int x;

public static void main(String args[]){ System.out.println("Value is " + x); } }

A. The output "Value is 0" is printed. B. Non-static variable x cannot be referenced from a static context.. C. An "illegal array declaration syntax" compiler error occurs. D. A "possible reference before assignment" compiler error occurs. E. An object of type ArrayIndexOutOfBoundsException is thrown.

B.

37. What would be the result of attempting to compile and run the following piece of code?

public class Test {

public static void main(String args[]){ int x; System.out.println("Value is " + x); } }

A. The output "Value is 0" is printed. B. An object of type NullPointerException is thrown. C. An "illegal array declaration syntax" compiler error occurs. D. A "possible reference before assignment" compiler error occurs. E. An object of type ArrayIndexOutOfBoundsException is thrown.

Page 171: Cracked bits for scjp

D. Compiler says variable x might not have been initialized.

38. What should you use to position a Button within an application Frame so that the size of the Button is NOT affected by the Frame size?

A. a FlowLayout B. a GridLayout C. the center area of a BorderLayout D. the East or West area of a BorderLayout E. The North or South area of a BorderLayout

A.

For the following six questions you will be presented with a picture in the real test, showing the relationship and quite long text, but don't be afraid the questions are quite easy.

39. We have the following organization of classes.

class Parent {} class DerivedOne extends Parent {} class DerivedTwo extends Parent {}

Which of the following statements is correct for the following expression?

Parent p = new Parent(); DerivedOne d1 = new DerivedOne(); DerivedTwo d2 = new DerivedTwo(); p = d1;

A. Illegal both at compile and runtime. B. Legal at compile time, but may fail at runtime. C. Legal at both compile and runtime. D. .... E. ....

C.

Page 172: Cracked bits for scjp

39. We have the following organization of classes.

class Parent {} class DerivedOne extends Parent {} class DerivedTwo extends Parent {}

A methods declares three variables as shown bellow and assign them non null values. Which of the following statements is correct for the following expression?

Parent p; DerivedOne d1; DerivedTwo d2; p = d1;

A. Illegal both at compile and runtime. B. Legal at compile time, but may fail at runtime. C. Legal at both compile and runtime. D. .... E. ....

C.

40. We have the following organization of classes.

class Parent {} class DerivedOne extends Parent {} class DerivedTwo extends Parent {}

Which of the following statements is correct for the following expression?

Parent p = new Parent(); DerivedOne d1 = new DerivedOne(); DerivedTwo d2 = new DerivedTwo(); d2 = d1;

A. Illegal both at compile and runtime. B. Legal at compile time, but may fail at runtime. C. Legal at both compile and runtime. D. .... E. ....

A.

Page 173: Cracked bits for scjp

41. We have the following organization of classes.

class Parent {} class DerivedOne extends Parent {} class DerivedTwo extends Parent {}

Which of the following statements is correct for the following expression?

Parent p = new Parent(); DerivedOne d1 = new DerivedOne(); DerivedTwo d2 = new DerivedTwo(); d1 = (DerivedOne)d2;

A. Illegal both at compile and runtime. B. Legal at compile time, but may fail at runtime. C. Legal at both compile and runtime. D. .... E. ....

A. Illegal both at compile and runtime. You cannot assign an object to a sibling reference, even with casting.

43. We have the following organization of classes.

class Parent {} class DerivedOne extends Parent {} class DerivedTwo extends Parent {}

Which of the following statements is correct for the following expression?

Parent p = new Parent(); DerivedOne d1 = new DerivedOne(); DerivedTwo d2 = new DerivedTwo(); d1 = (DerivedOne)p;

A. Illegal both at compile and runtime. B. Legal at compile time, but may fail at runtime. C. Legal at both compile and runtime. D. .... E. ....

Page 174: Cracked bits for scjp

B.

44. We have the following organization of classes.

class Parent {} class DerivedOne extends Parent {} class DerivedTwo extends Parent {}

Which of the following statements is correct for the following expression?

Parent p = new Parent(); DerivedOne d1 = new DerivedOne(); DerivedTwo d2 = new DerivedTwo(); d1 = p;

A. Illegal both at compile and runtime. B. Legal at compile time, but may fail at runtime. C. Legal at both compile and runtime. D. .... E. ....

A.

45. We have the following organization of classes.

class Parent {} class DerivedOne extends Parent {} class DerivedTwo extends Parent {}

Which of the following statements is correct for the following expression?

Parent p = new Parent(); DerivedOne d1 = new DerivedOne(); DerivedTwo d2 = new DerivedTwo(); p = (Parent)d1;

A. Illegal both at compile and runtime. B. Legal at compile time, but may fail at runtime. C. Legal at both compile and runtime. D. .... E. ....

Page 175: Cracked bits for scjp

C.

46. What would you use when you have duplicated values that needs to be sorted?

A. Map B. Set C. Collection D. List E. Enumeration

D.

47. What kind of reader do you use to handle ASCII code?

A. BufferedReader B. ByteArrayReader C. PrintWriter D. InputStreamReader E. ?????

D.

InputStreamReader and FileReader automatically converts from a particular character encoding to Unicode. From Core Java Advanced Features p. 820.

48. How can you implement encapsulation in a class?

A. Make all variables protected and only allow access via methods. B. Make all variables private and only allow access via methods. C. Ensure all variables are represented by wrapper classes. D. Ensure all variables are accessed through methods in an ancestor class.

B.

Page 176: Cracked bits for scjp

49. What is the return-type of the methods that implement the MouseListener interface?

A. boolean B. Boolean C. void D. Pont

C.

50. What is true about threads that stop executing?

A. When a running thread's suspend() method is called, then it is indefinitely possible for the thread to start. B. The interpreter stops when the main method stops. C. A thread can stop executing when another thread is in a runnable state. D. ...... E. ......

C. {It is doubtable answer it might be A}

51. For which of the following code will produce "test" as output on the screen?

A. int x=10.0; if (x=10.0) { System.out.println("test"); }

B. int x=012; if (x=10.0) { System.out.println("test"); }

C. int x=10f; if (x=10.0) { System.out.println("test"); }

Page 177: Cracked bits for scjp

D. int x=10L; if (x=10.0) { System.out.println("test"); }

B.

52. Given this class ?

class Loop { public static void main (String [] args){ int x=0; int y=0, outer: for (x=0; x<100;x++) { middle: for (y=0;y<100y++) {

System.out.printl("x=" + x + "; y=" + y);

if (y==10){

<<<>>>} } } }//main }//class

The question is which code must replace the <<<>>> to finish the outer loop? A. continue middle; B. break outer; C. break middle; D. continue outer; E. none of these...

B.

53. What does it mean when the handleEvent() returns the true boolean?

A. The event will be handled by the component. B. The action() method will handle the event. C. The event will be handled by the super.handleEvent(). D. Do nothing.

Page 178: Cracked bits for scjp

A.

54. What is the target in an Event?

A. The Object() where the event came from. B. The Object() where the event is destined for. C. What the Object() that generated the event was doing.

A.

55. What is the statement to assign a unicode constant CODE with 0x30a0?

Answer:

public static final char CODE='\u30a0';

56. The following code resides in the source?

class StringTest {

public static void main (String [] args){ // // String comparing // String a,b; StringBuffer c,d; c = new StringBuffer ("Hello"); a = new String("Hello"); b = a; d = c;

if (<<>>) {} } }//class

Which of the following statement return true for the <<>> line in StringTest.class?

A. b.equals(a) B. b==a

Page 179: Cracked bits for scjp

C. d==c D. d.equals(c)

ABCD.

57. Which are valid identifiers?

A. %fred B. *fred C. thisfred D. 2fred E. fred

CE.

57. Which are valid identifiers?

A. Employee B. _Employee C. %something D. *something E. thisemployee

A.B.E.

58. We have the following class X.

public class X {

public void method();

}

<<>>

Which of the following statement return true for the <<>> line in StringTest.class?

A. abstract void method() ; B. class Y extends X {} C. package java.util; D. abstract class z { }

BD.

Page 180: Cracked bits for scjp

59. Which code fragments would correctly identify the number of arguments passed via the command line to a Java Application?

A. int count = args.length; B. int count = 0; while args[count] !=null) count++; C. int count = 0; while (!(args[count].equals(""))) count++; D. int count = args.length - 1;

A.

60. Given a TextField that is constructed like this:

TextField t = new TextField(30);

Which statement is true?

A. The displayed width is 30 columns. B. The displayed string can use multiple fonts. C. The user will be able to edit the character string. D. The displayed line will show exactly thirty characters. E. The maximum number of characters in a line will be thirty.

AC.

61. What does the java runtime option -cs do?

A. check source with debug report B. clear classes that are existing when starting compilation. C. check if the source is newer when loading classes.

C.

62. When is an action invoked?

A. TextField Enter

Page 181: Cracked bits for scjp

B. TextArea Enter C. Scrollbar D. MouseDown E. Button

AE.

63. What error does the following code generate?

class SuperClass{

SuperClass(String s){} }

class SubClass extends SuperClass{ SubClass(){} }

......

SubClass s1 = new SubClass("The"); SuperClass s = new SubClass("The");

A. java.lang.ClassCastException B. Wrong number of arguments in constructor C. Incompatible type for =. Can't convert SubClass to SuperClass. D. No constructor matching SuperClass found in class SuperClass.

BD.

64. How do you declare a native method called myMethod in Java?

Answer:

public native void myMethod();

65. What should you use to position a component within an application frame so that the components height is affected by the Framesize?

Page 182: Cracked bits for scjp

A. FlowLayout B. GridLayout C. Center area of a BorderLayout D. East or West of a BorderLayout E. North or South of a BorderLayout

D. C.

66. What should you use to position a component within an application frame so that the components width is affected by the Framesize?

A. FlowLayout B. GridLayout C. Center area of a BorderLayout D. East or West of a BorderLayout E. North or South of a BorderLayout

E.C.

67. What should you use to position a Button within an application frame so that the height of the Button is affected by the Frame size but the width is not affected.

A. FlowLayout B. GridLayout C. Center area of a BorderLayout D. East or West of a BorderLayout E. North or South of a BorderLayout

D.

68. Which are keywords in Java?

A. NULL B. sizeof C. friend D. extends E. synchronized

DE.

Page 183: Cracked bits for scjp

69. Which is the advantage of encapsulation?

A. Only public methods are needed. B. No exceptions need to be thrown from any method. C. Making the class final causes no consequential changes to other code. D. It changes the implementation without changing the interface and causes no consequential changes to other code. E. It changes the interface without changing the implementation and causes no consequential changes to other code.

D.

70. What can contain objects that have a unique key field of String type, if it is required to retrieve the objects using that key field as an index?

A. Map B. Set C. List D. Collection E. Enumeration

A.

71. Which statement is true about a non-static inner class?

A. It must implement an interface. B. It is accessible from any other class. C. It can only be instantiated in the enclosing class. D. It must be final if it is declared in a method scope. E. It can access private instance variables in the enclosing object.

E.

72. Which declares an abstract method in an abstract Java class?

A. public abstract method();

Page 184: Cracked bits for scjp

B. public abstract void method(); C. public void abstract Method(}; D. public void method() {abstract;/} E. public abstract void method() {/} F. public void abstract Method();

B.

73. Which statements on the<<< call>>> line are valid expressions?

public class SuperClass { public int x; int y; public void m(int a) {} Superclass(){ } } class SubClass extends SuperClass{ private float f; void m2() { return; } SubClass() { } } class T { public static void main (String [] args) { int i; float g; SubClass b = SubClass(); <<< calls >>> } }

A. b.m2(); B. g=b.f; C. i=b.x; D. i=b.y; E. b.m(6);

ACDE.

74. Type 7 in hexadecimal form.

Answer:

0x7

Page 185: Cracked bits for scjp

75. Type 7 in octal form.

Answer:

07

76. What is the range of an integer?

A. -128–127 B. -32 768 – 32 767 C. -231 – 231 -1 D. -232 – 232 -1

C.

77. What is the range of a char?

A. ‘\u0000’ – ‘\uFFFF’ B. -32 768 – 32 767 C. -128 – 127 D. -231 – 231 -1

A.

78. What is the range of a char?

A. 0 – 215-1 B. -32 768 – 32 767 C. - 2 16 – 216-1 D. 0 – 216-1

D.

78. What is the range of a char?

A. 0 – 216-1 B. 0 – 232 -1 C. - 2 16 – 216-1 D. 0 – 216-1

D.

Page 186: Cracked bits for scjp

79. Which method contains the code-body of a thread?

A. start() B. run() C. init() D. suspend() E. continue()

B.

80. What can you place first in this file?

//What can you put here?

public class Apa{}

A. class a implements Apa B. protected class B {} C. private abstract class{} D. import java.awt.*; E. package dum.util; F. private int super = 1000;

ADE.

81. What is the output of the following code?

outer: for(int i=1; i<3; i++){ inner: for(int j=1; j<3; j++){ if (j==2){ continue outer; } System.out.println(i+" and "+j); } }

A. 1 and 1 B. 1 and 2 C. 2 and 1 D. 2 and 2 E. 2 and 3

Page 187: Cracked bits for scjp

F. 3 and 2 G. 3 and 3

AC.

82. What is the output of the following code?

outer: for(int i=1; i<2; i++){ inner: for(int j=1; j<2; j++){ if (j==2){ continue outer; } System.out.println(i " and " j); } }

A. 1 and 1 B. 1 and 2 C. 2 and 1 D. 2 and 2 E. 2 and 3 F. 3 and 2 G. 3 and 3

A.

82. What is the output of the following code?

outer: for(int x=0; i<2; x++){ inner: for(int a=0; a<2; a++){ if (a==1){ continue outer; } System.out.println(a +" and "+x); } }

A. 0 and 0 B. 0 and 1 C. 2 and 1 D. 1 and 2 E. 1 and 2 F. 2 and 1 G. 1 and 3

Page 188: Cracked bits for scjp

A.B.

83. How do you declare a native method?

A. public native method(); B. public native void method(); C. public void native method(); D. public void native() {} E. public native void method() {}

B.

84. Given the following code, what is the output when a exception other than a NullPointerException is thrown?

try{

//some code } catch(NullPointerException e) { System.out.println("thrown 1"); } finally { System.out.println("thrown 2"); } System.out.println("thrown 3");

A thrown 1 B thrown 2 C thrown 3 D none

B.

85. You have been given a design document for a employee system for implementation in Java. It states. bla bla bla

choose between the following words:

Page 189: Cracked bits for scjp

public class object extends Employee Person plus at least five more

How should you name the class?

Answer:

public class Employee extends Person

86. You have been given a design document for a polygon system for implementation in Java. It states.

A polygon is drawable, is a shape. You must access it. It should have values in a vector bla bla

Which variables should you use?

choose between the following words:

public object vector drawable color plus some more

Answer:

vector, color (not sure)

87. You have been given a design document for a polygon system for implementation in Java. It states. A polygon is a Shape. You must access it. It has a vector and corners bla bla

Page 190: Cracked bits for scjp

choose between the following words: What will you write when defining the class?

public class Polygon object extends Shape plus some more

Answer:

public class Polygon extends Shape

88. What is true about the garbage collection?

A. The garbage collector is very unpredictable. B. The garbage collector is predictable. C. D. E.

A.

87. What is true about a thread?

A The only way you can create a thread is to subclass java.lang.Thread B If a Thread with higher priority than the currently running thread is created, the thread with the higher priority runs. C. D. E.

B (not sure)

88. What happens when you compile the following code?

public classTest {

public static void main(String args[] ) {

Page 191: Cracked bits for scjp

int x; System.out.println(x); }

A. Error at compile time. Malformed main method B. Clean compile C. Compiles but error at runtime. X is not initialized D. E. Compile error. Variable x may not have been initialized.

E.

89.What happens hen you run the following program with the command:

java Prog cat dog mouse

public class Prog {

public static void main(String args[]) { System.out.println(args[0]) ; }

A. Error at compile time. ArrayIndexOutOfBoundsException thrown B. Compile with no output C. Compile and output of dog D. Compile and output of cat E. Compile and output of mouse

D.89.What happens hen you run the following program with the command:

java Prog cat

public class Prog {

public static void main(String args[]) { System.out.println(args[0]) ; }

A. Error at compile time. ArrayIndexOutOfBoundsException thrown B. Compile with no output

Page 192: Cracked bits for scjp

C. Compile and output of dog D. Compile and output of cat E. Compile and output of mouse

D.

90. Which number for the argument must you use for the code to print cat?

With the command:

java Prog dog cat mouse

public class Prog {

public static void main(String args[]) { System.out.println(args[?]) ; } }

A. 0 B. 1 C. 2 D. 3 E. none of these

B.

91. Which number for the argument must you use for the code to print cat? With the command:

java Prog cat dog mouse

public class Prog {

public static void main(String args[]) { System.out.println(args[?]) ; } }

A. 0 B. 1 C. 2

Page 193: Cracked bits for scjp

D. 3 E. none of these

A.

92. You have the following code:

....... String s; s = "Hello"; t = " " + "my"; s.append(t); s.toLowerCase(); s+= " friend"; System.out.println(s);

What will be printed?

Answer:

hello my friend

93. What will happen when you attempt to compile and run this code?

public class MySwitch{

public static void main(String argv[]) { MySwitch ms = new MySwitch(); ms.amethod(); }

public void amethod() {

char k=10;

switch(k){ default: System.out.println("This is the default output");

break; case 10: System.out.println("ten"); break;

Page 194: Cracked bits for scjp

case 20: System.out.println("twenty"); break; } } }

A. None of these options B. Compile time error target of switch must be an integral type C. Compile and run with output "This is the default output" D. Compile and run with output "ten"

D.

94. What will happen when you attempt to compile and run the following code?

public class MySwitch{

public static void main(String argv[]) { MySwitch ms = new MySwitch(); ms.amethod(); }

public void amethod() {

int k=10; switch (k){ default: //Put the default at the bottom, not here System.out.println("This is the default output"); break; case 10: System.out.println("ten"); case 20: System.out.println("twenty"); break; } } }

A. None of these options B. Compile time error target of switch must be an integral type C. Compile and run with output "This is the default output

Page 195: Cracked bits for scjp

D. Compile and run with output "ten"

A.

95. Which of the following statements are true? A. For a given component, events will be processed in the order that the listeners were added B. Using the Adapter approach to event handling means creating blank method bodies for all event methods C. A component may have multiple listeners associated with it D. Listeners may be removed once added

CD.

Button for instance has the methods addActionListener (ActionListener a) and removeActionListener(ActionListener a).

96. Which of the following statements are true? A. Directly subclassing Thread gives you access to more functionality of the Java threading capability than using the Runnable interface B. Using the Runnable interface means you do not have to create an instance of the Thread class and can call run directly C. Both using the Runnable interface and subclassing of Thread require calling start to begin execution of a Thread D. The Runnable interface requires only one method to be implemented, this method is called run

CD.

97. If you want subclasses to access, but not to override a superclass member method, what keyword should precede the name of the superclass method?

Answer:

final

Page 196: Cracked bits for scjp

98. If you want a member variable to not be accessible outside the current class at all, what keyword should precede the name of the variable when declaring it?

Answer:

private

99. Which of the following are correct methods for initializing the array "dayhigh" with 7 values?

A. int dayhigh = { 24, 23, 24, 25, 25, 23, 21 }; B. int dayhigh[] = { 24, 23, 24, 25, 25, 23, 21 }; C. int[] dayhigh = { 24, 23, 24, 25, 25, 23, 21 }; D. int dayhigh [] = new int [24, 23, 24, 25, 25, 23, 21]; E. int dayhigh = new [24, 23, 24, 25, 25, 23, 21] ;

BC.

100. Assume that val bas been defined as an int for the code below.

if(val > 4){ System.out.println("Test A"); }

else if(val > 9){ System.out.println("Test B"); } else System.out.println("Test C");

Which values of val will result in "Test C" being printed: A. val < 0 B val between 0 and 4 C val between 4 and 9 D val > 9 E val = 0 F no values for val will be satisfactory

ABE.

Page 197: Cracked bits for scjp

100. Assume that val bas been defined as an int for the code below.

if(val > 4){ System.out.println("Test A"); }

else if(val > 9){ System.out.println("Test B"); } else System.out.println("Test C");

Which values of val will result in "Test C" being printed: A. val < 0 B val between 0 and 4 C val between 4 and 9 D val > 9 E val = 10 or morethen 10 F no values for val will be satisfactory

AB

101. Consider the code below.

void myMethod(){ try{ fragile() ; } catch(NullPointerException npex){

System.out.println("NullPointerException thrown "); ) catch(Exception ex){ System.out.println("Exception thrown "); } finally{ System.out.println("Done with exceptions "); } System.out.println("myMethod is done"); }

What is printed to standard output if fragile() throws an IllegalArgumentException?

A. "NullPointerException thrown"

Page 198: Cracked bits for scjp

B. "Exception thrown" C. "Done with exceptions" D. "myMethod is done" E. Nothing is printed

BCD.

102. A class design requires that a particular member variable must be accessible for direct access by classes which are members of the same package. What should be done to achieve this?

A. The variable should be marked public B. The variable should be marked private C. The variable should be marked protected D. The variable should have no special access modifier E. The variable should be marked private and an accessor method provided

D.

103. Which method do you call to run a Thread?

A. start() B. init() C. begin() D. run()

A.

104. Which statements on the <<< call >>> line are valid expressions?

public class SuperClass {

public int x; int y; public void m1( int a ) { }

SuperClass( ) { }

Page 199: Cracked bits for scjp

}

class SubClass extends SuperClass {

private float f; void m2(int c) { int x; return; } SubClass() { } }

class T {

public static void main( String [] args) { int i; float g; SubClass b = new SubClass( ); <<< calls >>> } }

A. b.m2(); B. g=b.f; C. I=b.x; D. I=b.y; E. b.m1(6); F. g=b.x;

testa.

105. What is the range of a byte?

A. -128–127 B. -32 768 – 32 767 C. -231 – 231 -1 D. -232 – 232 -1

A.

106. What is the range of a byte?

Page 200: Cracked bits for scjp

A. -27 – 27 -1 B. -2 15 – 215 -1 C. -231 – 231 -1 D. -263 – 263 -1

A.

107. What would be the result of attempting to compile and run the following piece of code?

public class Test { public static void main (String args[]) { int x[] = new int[10]; System.out.println("Value is " + x[5]); } }

A. The output "Value is 0" is printed. B. An object of type NullPointerException is thrown. C. An "illegal array declaration syntax" compiler error occurs. D. A "possible reference before assignment" compiler error occurs. E. An object of type ArrayIndexOutOfBoundsException is thrown.

A.

108. Which interface should you use if you want no duplicates, no order and no particular retrieval system?

A. Map B. Set C. List D. Collection E. Enumeration

B.

109. Which are keywords in Java?

Page 201: Cracked bits for scjp

A. NULL B. TRUE C. sizeof D. implements E. synchronized

DE.

110. Consider the code fragment below:

outer: for(int i=0; i < 2; i++){ inner: for(j = 0; j < 2; j++){ if(j==1) continue outer; System.out.println("i = " + i ", j = " + j); }}

Which of the following will be printed to standard output?

A. i = 0, j = 0 B. i = 1, j = 0 C. i = 2, j = 0 D. i = 0, j = 1 E. i = 1, j = 1 F. i = 2, j = 1 G. i = 0, j = 2 H. i = 1, j = 2 I. i = 2, j = 2

AB.

111. Consider the code fragment below:

outer: for(int i=1; i < 3; i++){ inner: for(j = 1; j < 3; j++){ if(j==2) continue outer; System.out.println("i = " + i ", j = " + j); }}

Which of the following will be printed to standard output?

A. i = 1, j = 1

Page 202: Cracked bits for scjp

B. i = 1, j = 2 C. i = 1, j = 3 D. i = 2, j = 1 E. i = 2, j = 2 F. i = 2, j = 3 G. i = 3, j = 1 H. i = 3, j = 2

AD.

112. What is the modifier for events in EventListeners?

A. public B. none C. private D. .....

B.

113. You want the program to print 3 to the output. Which of the following values for x will do this?

Code:

switch(x){

case(1): System.out.println("1"); case(2): case(3): System.out.println("2"); default: System.out.println("3"); }

A 1 B 2 C 3 D 4

ABCD.

Page 203: Cracked bits for scjp

114. You want the program to print 3 to the output. Which of the following values for x will do this?

Code:

switch(x){

case(1): System.out.println("1"); case(2): case(3): System.out.println("3"); break; default: System.out.println("Default"); }

A 1 B 2 C 3 D 4

ABC.

115. A question about the GridbagLayout. One alternative.

116. You have been given a design document for an employee system for implementation in Java. It states.

An Employee has a vector of bla bla, dates for meetings, number of dependants (what is this???)

A. Vector B. Int C. Date D. Object E. New employee e;

Which variables should you use?

Answer:

Page 204: Cracked bits for scjp

A, B, C. (Not sure. Don't remember exactly how the question was posed)

117. You have been given a design document for a polygon system for implementation in Java. It states. A polygon is drawable. You must access it. It has a vector and corners bla bla

choose between the following words: What will you write when defining the class?

public class Polygon object extends Shape drawable plus some more

Answer:

public class Polygon implements drawable

118. A question about stacks. Only one correct answer.

A. (Is it possible to have stack objects in a String) Code contained + "" + stack2 + "" + B. (Is it possible to write stack1 = stack2;) C. Prints bla bla bla D. Prints bla bla E. Prints bla bla

119. Threads: Which statements are true about threads stopping to execute?

A. All threads in the same class stop at the same time B. The suspend() method stops the thread so that you can not start it again C. D.

C or D.

Page 205: Cracked bits for scjp

120. Which statements are true about garbage collection? A. Garbage collection is predictable. B. You can mark a variable or an object, (telling the system) so that it can be garbage collected C. ..... D. .....

C or D.(not sure)

121. Consider the following code. What will be on the output. No Exception is thrown.

public class Mock2ExceptionTest{

public static void main(String [] args){

Mock2ExceptionTest e = new Mock2ExceptionTest(); e.trythis(); }

public void trythis(){

try{

System.out.println("1"); problem(); System.out.println("1b"); }

catch(Exception x){ System.out.println("3");

}

finally{ System.out.println("4");

} System.out.println("5"); }

Page 206: Cracked bits for scjp

public void problem()throws Exception{

//throw not any Exception(); } }

A. 1 B 1b C. 3 D. 4 E. 5

ABDE.

No exception is thrown and everything except 3 will be printed.

121b. Consider the following code. What will be on the output. No Exception is thrown.

public class Mock3ExceptionTest{

public static void main(String [] args){

Mock3ExceptionTest e = new Mock3ExceptionTest(); e.trythis(); }

public void trythis(){

try{

System.out.println("1"); problem(); System.out.println("1b"); }

catch(Exception x){ System.out.println("3");

}

finally{ System.out.println("4");

Page 207: Cracked bits for scjp

} System.out.println("5"); }

public void problem()throws Exception{

throw new Exception(); } }

A. 1 B 1b C. 3 D. 4 E. 5

ACDE.

122. What can you put where the X is?

X

Public class A{}

A. import java.awt.*; B. package bla.bla; C. class bla{} D. public abstract final method(); E. public final int x = 1000;

ABC.

123. What are the characteristics of a totally encapsulated class? One answer.

A. methods not private B. variables not public C. ...... D. all modifying of the object should be made through methods

D.

Page 208: Cracked bits for scjp

124. Consider the following code:

public class TBMock1{

public static void main(String[]args){

Integer n = new Integer(7); Integer k = new Integer(7); Long i = new Long(7); } }

Which return true?

A. n==i

B. n==k

C. n.equals(k)

D. n.equals(7)

E. n.equals(new Integer(7))

CE.

125. Write 7 in hexadecimal. Do not use more than four characters and do no assignment.

Answer:

0x7, 0x07

126. Consider the classes defined below:

import java.io.*;

class Super{

void method (int x, int b) }

Page 209: Cracked bits for scjp

class Sub extends Super{}

How will a correct method in Sub look like?

A. int method(int x, int b) B. void method (int x) throws Exception C. void anotherMethod(int x) D. ........

BC.

127. Consider the classes defined below:

import java.io.*;

class Super{

int method1 (int x, long b) throws IOException {//code } }

public class Sub extends Super{}

Which of the following are legal method declarations to add to the class Sub? Assume that each method is the only one being added.

A. public static void main (String args[]){} B. float method2(){} C. long method1 (int c, long d) {} D. int method1(int c, long d) throws ArithmeticException{} E. int method1 (int c, long d) throws FileNotFoundException{}

ABE.

128. What does the method getID do?

A. returns a value which shows the nature of the event B. ....... C. ... D. .....

A.

Page 210: Cracked bits for scjp

129. Which object will be created when you implement a KeyListener? Unsure about how the question was formulated!!

Answer:

Answered KeyEvent

130 Which of these will create an array that can be used for 50 Strings?

A. char a[][] B. String a[] C. String[]a; D. String a[5]; E. ...

BC. (not sure)

131 How can you declare a legal inner class?

A class x{} B C myInterface (String x){ D myInterface () {

132. One Superclass and one Subclass. One was public and one was default. How do you create a new instance?? Unsure of the formulation of the question.

A. new Inner() B. new Outer().new Inner() C. ..... D. ......

B.

133. Claims about adapters and listeners

Page 211: Cracked bits for scjp

134. Which are legal identifiers

A. niceIdentifier B. 2Goodbajs C. %hejpådig D. _goddag E. Hello2

ADE.

135. Which statement is true about a non-static inner class?

A. It must implement an interface. B. It is accessible from any other class. C. It can only be instantiated in the enclosing class. D. It must be final if it is declared in a method scope. E. It can access any final variables in the enclosing class

E.

136. A question with some wrong code. What must you do to correct. I changed to the static modifier.

137. Consider the following code:

String s = "Svenne"; int i = 1;

What can you do?

A String t = s>>i; B Long x = 12; String s = s + x; C. ..... D. ......

B.

Page 212: Cracked bits for scjp

138. Assume that val has been defined as an int for the code below.

if(val > 4){ System.out.println("Test A"); }

else if(val > 9){ System.out.println("Test B"); } else System.out.println("Test C");

Which values of val will result in "Test C" being printed: A. val < 0 B val between 0 and 4 C val between 4 and 9 D val > 9 E val = 10 F no values for val will be satisfactory

AB.

139. You are going to read some rows one by one from a file that is stored locally on your hard drive. How do you do it?

A. BufferedReader B. InputStreamReader C. One reader with "8859-1" as an argument D. Don't remember E. FileReader

E. (Don't remember if E was an alternative.)

140. What is a correct argument list for a public static void main method?

A. (String argv []) B. (String arg ) C. (String [] fish) D. (String args) E. (String args{})

Made up alternatives C-E by myself.

Page 213: Cracked bits for scjp

AC.

141. Consider the following code:

What will be printed?

public class AB{

public static void main (String[] args){

int x = 1;

if (0 < x--){

System.out.println(x); } }

A. 0 B. 1 C. 2 D. Nothing E. An IllegalArgumentException will be thrown

A.

141b. Consider the following code:

What will be printed?

public class AB{

public static void main (String[] args){

int x = 1;

if (0 < x--){

System.out.println(x); } }

A. 0

Page 214: Cracked bits for scjp

B. 1 C. 2 D. Nothing E. An IllegalArgumentException will be thrown

D.

142. Which of the following are valid definitions of an application's main ( ) method?

A. public static void main( ); B. public static void main( String args ); C. public static void main( String args [] ); D. public static void main( Graphics g ); E. public static boolean main( String args [] );

C.

143. Which of the following are Java keywords?

A array B boolean C Integer D protect E super

BE.

144. After the declaration:

char[] c = new char[100];

what is the value of c[50]?

A. 50 B. 49 C. '\u0000' D. '\u0020' E. "" F. cannot be determined G. always null until a value is assigned

C.

Page 215: Cracked bits for scjp

145. Which identifiers are valid?

A. _xpoints B. U2 C. blabla$ D set-flow E. something

ABCE.

146. Represent the number 6 as a hexadecimal literal.

Answer:

0x6, 0x06, 0X6, 0X06

147. Which of the following statements assigns "Hello Java" to the String variable s?

A. String s = "Hello Java"; B. String s [] = "Hello Java"; C. new String s = "Hello Java"; D. String s = new String ("Hello Java");

AD.

148. An integer, x has a binary value (using 1 byte) of 10011100. What is the binary value of z after these statements:

int y = 1 << 7 ; int z = x & y;

A. 1000 0001 B. 1000 0000 C. 0000 0001 D. 1001 1101 E. 1001 1100

B.

Page 216: Cracked bits for scjp

149. The statement ...

String s = "Hello" + "Java";

yields the same value for s as ...

String s = "Hello"; String s2 = "Java"; s.concat( s2 );

A. True B. False

B.

150. If you compile and execute an application with the following code in its main()method:

String s = new String("Computer");

if ( s == "Computer" ) System.out.println ("Equal A"); if( s.equals( "Computer" ) ) System.out.println ("Equal B");

A. It will not compile because the String class does not support the = = operator. B. It will compile and run, but nothing is printed. C. "Equal A" is the only thing that is printed. D. "Equal B" is the only thing that is printed. E. Both "Equal A" and "Equal B" are printed.

D.

151. Given the variable declarations below:

byte myByte; int myInt; long myLong; char myChar; float myFloat; double myDouble;

Page 217: Cracked bits for scjp

Which one of the following assignments would need an explicit cast?

A. myInt = myByte; B. myInt = myLong; C. myByte = 3; D. myInt = myChar; E. myFloat = myDouble; F. myFloat = 3; G. my Double = 3.0;

BE.

152. Consider this class example:

class MyPoint { void myMethod(){ int x, y; x = 5; y = 3; System.out.print("(" + x + ", " + y + ")"); switchCoords(x,y); System.out.print("(" + x + ", " + y + ")"); }

void switchCoords(int x,int y){ int temp; temp = x; x = y; y = temp; System.out.print("(" + x + ", " + y + ")"); } }

What is printed to standard output if myMethod() is executed?

A. (5, 3) (5, 3) (5, 3) B. (5, 3) (3, 5) (3, 5) C. (5, 3) (3, 5) (5, 3)

C.

Page 218: Cracked bits for scjp

153. To declare an array of 31 floating point numbers representing snowfall for each day of March in Gnome, Alaska, which declarations would be valid?

A. double snow[] = new double[31]; B. double snow[31] = new array[31]; C. double snow[31] = new array; D. double[] snow = new double[31];

AD.

154. If arr[] contains only positive integer values, what does this function do?

public int guessWhat(int arr[]){ int x = 0; for(int i = 0; i < arr.length; i++) x = x < arr[i] ? arr[i] : x; return x; }

A. Returns the index of the highest element in the array B. Returns true/false if there are any elements that repeat in the array C. Returns how many even numbers are in the array D. Returns the highest element in the array E. Returns the number of question marks in the array

D.

155. Consider the code below:

arr[0] = new int[4]; arr[1] = new int[3]; arr[2] = new int[2]; arr[3] = new int[l]; for(int n = 0; n < 4; n++) System.out.println ( /*What will work here? */);

Which statement below, when inserted as the body of the for loop, would print the number of values in each row?

Page 219: Cracked bits for scjp

A. arr[n].length(); B. arr.size; C. arr.size -1; D. arr[n] [size] ; E. arr[n].length;

E.

156. Which of the following are legal declarations of a two-dimensional array of integers?

A. int[5][5] a = new int[][]; B. int a = new int[5,5]; C. int[]a[] = new int [5][5]; D. int[][]a = new [5]int[5];

C.

157. Given the variables defined below:

int one = 1; int two = 2; char initial = '2'; boolean flag = true;

Which of the following are valid? A. if ( one ){} B. if( one = two ){} C. if( one == two ) {} D. if( flag ){} E. switch ( one ) { } F. switch ( flag ) { } G. switch ( initial ) { }

CDEG.

158. If val = 1 in the code below:

switch (val){ case 1: System.out.println("P"); case 2: case 3: System.out.println("Q") ; break;

Page 220: Cracked bits for scjp

case 4: System.out.println("R"); default: System.out.println ("S"); }

A. P B. Q C. R D. S

AB.

159. What exception might a wait() method throw?

Answer:

InterruptedException

160. For the code:

m = 0; while( m++ < 2 ) System.out.println(m);

Which of the following are printed to standard output?

A. 0 B. 1 C. 2 D. 3 E. Nothing and an exception is thrown

BC.

161. For the code:

m = 0; while( ++m < 2 ) System.out.println(m);

Which of the following are printed to standard output?

A. 0 B. 1

Page 221: Cracked bits for scjp

C. 2 D. 3 E. Nothing and an exception is thrown

B.

162. Consider the following code sample:

class Tree{} class Pine extends Tree{} class Oak extends Tree{} public class Forest { public static void main (String [] args){ Tree tree = new Pine():

if( tree instanceof Pine ) System.out.println ("Pine");

if( tree instanceof Tree ) System.out.println ("Tree");

if( tree instanceof Oak ) System.out.println ( "Oak" );

else System.out.println ("Oops "); } }

Select all choices that will be printed:

A. Pine B. Tree C. Forest D. Oops E. Nothing will be printed

ABD.

163. Which of the following statements about Java's garbage collection are true?

A. The garbage collector can be invoked explicitly using a Runtime object.

Page 222: Cracked bits for scjp

B. The finalize method is always called before an object is garbage collected. C. Any class that includes a finalize method should invoke its superclass' finalize method. D. Garbage collection behaviour is very predictable.

BC.

164. What line of code would begin execution of a thread named myThread?

Answer:

myThread.start();

165. Which methods are required to implement the interface Runnable?

A. wait() B. run() C. stop() D. update() E. resume()

B.

166. What class defines the wait() method?

Answer:

Object.

for yield(), sleep(#), start(), run() it is Thread for wait(), notify(), notifyAll() it is Object

167. 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. E. The thread's sleep() method was invoked.

Page 223: Cracked bits for scjp

ABCE.

168. Which method below can change a String object, s ?

A. equals( s ) B. substring( s ) C. concat( s ) D. toUpperCase ( s ) E. none of the above will change s

E.

169. If s1 is declared as:

String sl = "phenobarbital";

What will be the value of s2 after the following line of code:

String s2 = s1.substring( 3, 5 );

A. null B. "eno" C. "enoba" D. "no"

D.

170. What method(s) from the java.lang.Math class might method() be if the statement method( -4.4 )== -4; is true.

A. round() B. min() C. trunc() D. abs() E. floor() F. ceil()

AF.

Page 224: Cracked bits for scjp

171. Which methods does java.lang.Math include for trigonometric computations?

A. sin( ) B. cos( ) C. tan ( ) D. aSin ( ) E. Cos ( ) F. aTan( ) G. toDegree ( )

ABC.

172. This piece of code:

TextArea ta = new TextArea ( 10, 3 );

Produces (select all correct statements):

A. a TextArea with 10 rows and up to 3 columns B. a TextArea with a variable number of columns not less than 10 and 3 rows C. a TextArea that may not contain more than 30 characters D. a TextArea that can be edited

AD.

173. In the list below, which subclass(es) of Component cannot be directly instantiated:

A. Panel B. Dialog C. Container D. Frame

C.

174. Of the five Component methods listed below, only one is also a method of the class MenuItem. Which one?

A. setVisible (boolean b)

Page 225: Cracked bits for scjp

B. setEnabled (boolean b) C. getSize () D. setForeground (Color c) E. setBackground (Color c)

B.

175. If a font with variable width is used to construct the string text for a column, the initial size of the column is:

A. determined by the number of characters in the string, multiplied by the width of a character in this font B. determined by the number of characters in the string, multiplied by the average width of a character in this font C. exclusively determined by the number of characters in the string D. undetermined

B.

176. Which of the following methods from the java.awt.Graphics class could be used to draw the outline of a rectangle with a single method call? Select all.

A. fillRect() B. drawRect() C. fillPolygon() D. drawPolygon() E. drawLine()

BD.

177. Of the following AWT classes, which one(s) are responsible for implementing the components layout? Select all.

A. LayoutManager B. GridBagLayout C. ActionListener

Page 226: Cracked bits for scjp

D. WindowAdapter E. FlowLayout

BE.

178. A component that should resize vertically but not horizontally should be placed in:

A. BorderLayout in the North or South location B. FlowLayout as the first component C. BorderLayout in the East or West location D. BorderLayout in the Center location E. GridLayout

C.

179. What type of object is the parameter for all methods of the MouseListener interface?

Answer:

MouseEvent

180. What type of object is the parameter for all methods of the MouseMotionListener interface?

Answer:

MouseEvent

181. What type of object is the parameter for all methods of the KeyListener interface?

Answer:

KeyEvent

182. What type of object is the parameter for all methods of the ActionListener interface?

Page 227: Cracked bits for scjp

Answer:

ActionEvent

183. Which of the following statements about event handling in JDK 1.1 and later are true? Select all.

A. A class can implement multiple listener interfaces B. If a class implements a listener interface, it only has to overload the methods it uses C. All of the MouseMotionAdapter class methods have a void return type

AC.

184. Which of the following describe the sequence of method calls that result in a component being redrawn?

A. invoke paint() directly B. invoke update which calls paint() C. invoke repaint() which � D. invoke repaint() which invokes paint() directly

C.

185. Choose all valid forms of the argument list for the FileOutputStream constructor shown below:

A. FileOutputStream(FileDescriptor fd) B. FileOutputStream(String n, boolean b) C. FileOutputStream(boolean a) D. FileOutputStream() E. FileOutputStream(File f)

ABE.

186. A "mode" argument such as "r" or "rw" is required in the constructor for the class(es):

Page 228: Cracked bits for scjp

A. DataInputStream B. InputStream C. RandomAccessFile D. File E. None of the above

C.

187. A directory can be created using a method from the class(es):

A. File B. DataOutput C. Directory D. FileDescriptor E. FileOutputStream

A.

188. If raf is a RandomAccessFile, what is the result of compiling and executing the following code?

raf.seek(raf.length());

A. The code will not compile. B. An IOException will be thrown. C. The file pointer will be positioned immediately before the last character of the file. D. The file pointer will be positioned immediately after the last character of the file.

D.

189. Consider the following code: What will be printed?

public class ExceptionTest{

public static void main(String [] args){

ExceptionTest e = new ExceptionTest(); e.trythis();

Page 229: Cracked bits for scjp

}

public void trythis(){

try{

System.out.println("1"); problem(); }

catch (RuntimeException x){

System.out.println("2"); return; }

catch(Exception x){ System.out.println("3"); return; }

finally{ System.out.println("4"); } System.out.println("5"); }

public void problem()throws Exception{

throw new Exception(); } }

1 2 3 4 5

ACD.

190. Consider the following code: What will be printed?

Page 230: Cracked bits for scjp

public class ExceptionTest2{

public static void main(String[] args){

ExceptionTest2 e = new ExceptionTest2(); e.divide(4, 0);}

public void divide(int a, int b){

try{ int c = a/b; } catch(ArithmeticException e){

System.out.println("ArithmeticException"); }

catch(RuntimeException e){

System.out.println("RuntimeException"); }

catch(Exception e){

System.out.println("Exception"); }

finally{

System.out.println("Finally"); } } }

ArithmeticException RuntimeException Exception Finally

A. ArithmeticException D. Finally.

191. Consider the following code: What will be printed?

public class ExceptionTestMindQ{

Page 231: Cracked bits for scjp

public static void main(String [] args){

ExceptionTestMindQ e = new ExceptionTestMindQ(); e.trythis(); }

public void trythis(){

try{

System.out.println("Innan testet"); problem(); }

catch (NullPointerException x){

System.out.println("Nullpointer");

}

catch(Exception x){ System.out.println("Exception"); return; }

finally{ System.out.println("finally"); } System.out.println("mymethod is done"); }

public void problem()throws IllegalArgumentException{

throw new IllegalArgumentException(); } }

Innan testet Nullpointer´ Exception finally mymethod is done

A. Innan testet C. exception D. finally.

Page 232: Cracked bits for scjp

192. Consider the following code: What will be printed?

public class exceptiontest101{

public static void main(String[]args){

exceptiontest101 e = new exceptiontest101(); e.myMethod(); } void myMethod(){ try{ fragile() ; } catch(NullPointerException npex){

System.out.println("NullPointerException thrown "); } catch(Exception ex){ System.out.println("Exception thrown "); } finally{ System.out.println("Done with exceptions "); } System.out.println("myMethod is done"); }

public void fragile() { throw new IllegalArgumentException(); } }

NullpointerException thrown Exception thrown Done with exceptions D.myMethod is done

B. Exception thrown C. Done with exceptions D. myMethod is done

193. What is the range of a short?

A. –128 – 127 B. -32 768 – 32 767

Page 233: Cracked bits for scjp

C. -231 – 231 -1 D. -263 – 263 -1

B.

194. What is the range of a short?

-128 – 127 -231 – 231 –1 C. -215 – 215 -1 D. -263 – 263 -1

C.

195. What is the range of a long?

-128 – 127 -231 – 231 –1 C. -215 – 215 -1 D. -263 – 263 -1

D.

196. Consider the following code: What will be printed?

public class Access{

int i = 10; int j; char z = 823; char q = '1'; boolean b; static int k = 9;

public static void main(String arg[]){

Access a = new Access(); a.amethod(); System.out.println(k); }

public void amethod(){

Page 234: Cracked bits for scjp

System.out.println(j); System.out.println(b); System.out.println(z); System.out.println(q); } }

0 true 823 1 9 null false 823 1 9 false 823 1 9 0 0 false ? 1 9 true 823 1 9 0

D.

197. Consider the following code: What will be printed?

public class amethod{

public static void main(String arg[]){

String s = "Hello"; char c ='H'; s+=c; System.out.println(s);

}

}

A. Nothing will be printed because of a compilation error. B. HelloH C. Hhello D. Hello\u345 Hello

B.

198. Consider the following code: What will be printed?

public class Arg{

Page 235: Cracked bits for scjp

String [] MyArg; public static void main(String arg[]){ MyArg[] = arg[]; } public void amethod(){ System.out.println(arg[1]); } } null 0 Nothing will be printed. Compilation error. Compiles just fine, but a RuntimeException will be thrown.

C.

199. Consider the following code: What will be printed? public class Arg2{ static String [] MyArg = new String[2]; public static void main(String arg2[]){ arg2 = MyArg; System.out.println(arg2[1]); }

}

null 0 Nothing will be printed. Compilation error. Compiles just fine, but a RuntimeException will be thrown.

A.

200. Consider the following code: What will be printed?

public class Arraytest{ public static void main(String kyckling[]){ Arraytest a = new Arraytest(); int i[] = new int[5]; System.out.println(i[4]); a.amethod(); Object o[] = new Object[5]; System.out.println(o[2]);

}

Page 236: Cracked bits for scjp

void amethod(){ int K[] = new int[4]; System.out.println(K[3]); } }

A. null null null B. null 0 0 C. 0 0 null D. 0 null 0

C.

201. Consider the following code: What will be printed?

class Arraytest2{

public static void main(String[]args){ int [] arr = {1, 2, 3}; for(int i = 0; i < 2; i++){ arr[i] = 0; }

for(int i = 0; i < 3; i++){ System.out.println(arr [i]); } } }

1 2 3 0 0 3 0 2 3 0 0 0

B.

202. Consider the following code: What will be printed?

public class ArrayTest3{

public static void main(String[]args){

int [][] a = new int[5][5];

Page 237: Cracked bits for scjp

System.out.println(a[4][4]); } }

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

C.

203. Consider the following code: What will be printed?

public class booleanFlag{ public static void main(String[] args){ test(); test2(); }

public static void test(){

//boolean flag = false;

if(flag=true){

System.out.println("true");

}

else {

System.out.println("false"); }}

public static void test2(){ boolean flag = false; if(flag==true){

System.out.println("true"); }

else { System.out.println("false"); } }

Page 238: Cracked bits for scjp

}

true true true false false true false false Compilation error. Cannot resolve symbol: variable flag.

E.

204. Consider the following code: What will be printed? class CeilTest{ static float k = 3.2f; public static void main(String[]args){ System.out.println("Ceil for 3.2 is: " + Math.ceil(k) + "Floor for 3.2 is: " + Math.floor(k));} }

Ceil for 3.2 is : 4.0 Floor for 3.2 is : 3.0 Ceil for 3.2 is : 3.0 Floor for 3.2 is : 4.0 Ceil for 3.2 is : 4 Floor for 3.2 is : 3 Ceil for 3.2 is : 3 Floor for 3.2 is : 4 Compiler error. Variable k cannot be reached.

A.

205. Consider the following code: What will be printed?

public class DoubleTest{ public static void main(String[]args){ Float i = new Float(0.9f); Float j = new Float(0.9f); if(i.equals(j)) System.out.println("i.equals(j)"); if(i==j) System.out.println("i==j"); float s = 10.0f; int t = 10; long x = 10; char u = 10; if(s==t) System.out.println("s==t"); if(x==u)

Page 239: Cracked bits for scjp

System.out.println("x==u"); }}

i.equals(j) i==j s==t x==u B. i==j s==t x==u C. i.equals(j) s==t x==u i.equals(j) x==u

C. What makes the difference here is the new operator. You get fooled and think that s = = t and x = = u would return false.

206. Consider the following code: What will be printed?

public class Equal{

public static void main(String kyckling[]){

int Output = 10;

boolean b1 = false;

if((b1==true) && ((Output+=10)==20)) { System.out.println("We are equal " + Output); } else {System.out.println("Not equal! " + Output); } }}

A. Nothing will be printed. You must use the word args instead of kyckling in the main method. We are equal 10 Not equal 10 We are equal 20 Not equal 20

C.

207. Consider the following code: What will be printed?

public class EqualsTest{

Page 240: Cracked bits for scjp

public static void main(String []args){ if ("john" == "john") System.out.println("\"john\" == \"john\""); if("john".equals("john")); System.out.println("\"john\".equals(\"john\")"); Boolean flag = new Boolean(true); boolean flagga = true; } }

john == john "john" == "john" "john".equals "john" john == john john.equals john john.equals john "john" == "john" "john".equals "john"

B.

208. Consider the following code: What will be printed?

public class EqualsTest2{

public static void main(String[]args){ byte A = (byte)4096;

if (A == 4096) System.out.println("Equal");

else System.out.println("Not Equal");

System.out.println(A);

int B = (int)4096;

if (B == 4096) System.out.println("Equal");

else System.out.println("Not Equal");

System.out.println(A);

}

}

Page 241: Cracked bits for scjp

Not Equal Not Equal 0 Not Equal Equal 0 Equal Not Equal 4096 Equal Equal 4096

B.

A byte can store values from –128-127. Therefore the variable A will not be able to store 4096.

209. Consider the following code: What will be printed?

class ExampleInteger extends Object{

public static void main(String[] args){

ExampleInteger e = new ExampleInteger(); e.Result(30); }

public void Increment(Integer N){ N = new Integer(N.intValue() + 1); }

public void Result(int x){

Integer X = new Integer(x); Increment(X); System.out.println("New value is " + X); } }

New value is 30 New value is 31 New value is 1 New value is null

A.

210. Consider the following code: What will be printed?

public class Hope{

Page 242: Cracked bits for scjp

public static void main(String[]args) { Hope h = new Hope(); } protected Hope(){ for(int i = 0; i < 10; i++){

System.out.println(i);}

}}

0 1 2 3 4 5 6 7 8 9 Compiler error. Constructor cannot be protected. 1 2 3 4 5 6 7 8 9 10

211. Consider the following code: What will be printed? public class Init{ public static void main(String arg[]){ int[]a = new int[5]; String s[] = new String[5]; for (int i = 0; i System.out.println(a[1]); } System.out.println(s[3]);} }

0 null 0 null 0 null 0 null 0 null 0 0 0 0 0 null null null null null 0 null 0 0 0 0 0 null Nothing will be printed due to Compilation Error.

D.

212. Consider the following code: What will be printed?

public class Init2{ public static void main(String arg[]){ int[]a = new int[5]; String s[] = new String[5]; String t[]; String u; System.out.println(a[1]);

Page 243: Cracked bits for scjp

System.out.println(s[3]); System.out.println(t[3]); System.out.println(u); }

}

0 null null null 0 0 0 0 null null null null null null null null null 0 0 0 Nothing will be printed: Variable t and u may not have been initialized.

E.

213. Consider the following code: What will happen when you try to compile it?

public class InnerClass{ public static void main(String[]args) {} public class MyInner{ }}

It will compile fine. It will not compile, because you cannot have a public inner class. It will compile fine, but you cannot add any methods, because then it will fail to compile.

A.

214. Consider the following code: What will be printed?

public class charTest2{ public static void main(String[] args){ int y = 020; char b = '\u0010'; if(b==y) System.out.println("Char 'u0010' = 16.0"); } }

Page 244: Cracked bits for scjp

A. Nothing will be printed. B. Compilation error. The char variable cannot be assigned this way. C. Char 'u0010' = 16.0 Compilation error. The int variable cannot be assigned this way. Compilation error. The char variable cannot be assigned this way. The int variable cannot be assigned this way.

C.

215. If you're stupid and program like this. What will happen?

public class LoseInformationCast2{

public static void main(String[]args){

byte b = (byte)259; short s = (short)b;

System.out.println("short s =" + s + " byte b = " + b);

} }

short s = 3 + byte b = 3 short s = 3 byte b = 3 short s = 3 byte b = 259 Nothing will be printed. Illegal explicit cast.

B.

216. If you're stupid and program like this. What will happen?public class LoseInformationCast{ public static void main(String[]args){ short s = 259; byte b = (byte)s; System.out.println("short s =" + s + "= byte b = " + b);

Page 245: Cracked bits for scjp

} }

short s = 259 + byte b = 3 short s = 259 = byte b = 3 short s = 3 byte b = 259 Nothing will be printed. Illegal explicit cast.

B.

217. Consider the following code: What will be printed? public class maze{ public static void main(String[]args){ int x = 4; if(x<=7){ if(x==5) System.out.println("2"); System.out.println("1"); }

else if (x==17) System.out.println("3");

else if (x==18) System.out.println("4"); System.out.println("0");

}

}

Nothing will be printed. 0 1 0 Compilation Error. You can not use two else if statements in this way. 2 1 3 4 0

C.

218. Consider the following code: What will be printed? public class maze2{ public static void main(String[]args){

Page 246: Cracked bits for scjp

int x= 4; if(x<=7){ if(x==5){ System.out.println("2"); System.out.println("1"); } }

else if (x==17) System.out.println("3"); else if (x==18){ System.out.println("4"); System.out.println("0"); }

}

}

Nothing will be printed. 0 1 0 Compilation Error. You can not use two else if statements in this way. 2 1 3 4 0

A.

219. Consider the following code: What will be printed? public class maze3{ public static void main(String[]args){ int x= 4; if(x<=7){ if(x==5){ System.out.println("2"); System.out.println("1"); } } else if (x==17) System.out.println("3"); else if (x==18){ System.out.println("4"); } System.out.println("0");

Page 247: Cracked bits for scjp

}

}

Nothing will be printed. 0 1 0 Compilation Error. You can not use two else if statements in this way. 2 1 3 4 0

B.

220. Consider the following code: What will be printed? public class MyAr{ public static void main(String args[]){ MyAr m = new MyAr(); m.amethod(); } public void amethod(){ int i = 12; System.out.println(i); } }

12 null Error you cannot initialize a non-static variable in the main method. 0

A.

221. Consider the following code: What will be printed? public class MyAr{ public static void main(String args[]){ MyAr m = new MyAr(); m.amethod(); }

public void amethod(){

Page 248: Cracked bits for scjp

static int i; System.out.println(i); } }

A. 1 null Syntax error: illegal start of expression. You cannot define an integer as static inside a non-static method 0 Syntax error: illegal start of expression. Error you cannot define an integer as non-static inside a static method.

C.

222. Consider the following code: What will be printed? public class MyAr{ public static void main(String args[]){ MyAr m = new MyAr(); m.amethod(); } public void amethod(){ int i; System.out.println(i); } }

A. 1 null Error. Variable i might not have been initialized. 0 Error you cannot define an integer as non-static inside a static method.

C.

223. Consider the following code: What will be printed? public class newIntegerLong{ public static void main(String[]args){ Integer nA = new Integer(4096); Long nB = new Long(4096); if(nA.equals(nB)) System.out.println("LongEqualsInteger.");

Page 249: Cracked bits for scjp

if(nA.intValue() == nB.longValue()){ System.out.println("If you create new primitive values of Long(4096) and Integer(4096), then == true.");

}}}

LongEqualsInteger. If you create new primitive values of Long(4096) and Integer(4096), then == true. LongEqualsInteger. If you create new primitive values of Long(4096) and Integer(4096), then == true. If you create new primitive values of Long(4096) and Integer(4096), then == true. Nothing will be printed.

B.

224. Consider the following code: What will be printed?

public class Q{ public static void main(String arg[]){ int anar[] = new int[]{1,2,3}; System.out.println(anar[1]); int i = 9; switch(i){ default: System.out.println("default"); case 0: System.out.println("zero"); break; case 1: System.out.println("one"); case 2: System.out.println("two"); } boolean b=true; boolean b2 = true; if (b==b2){ System.out.println("So true"); } } }

Page 250: Cracked bits for scjp

2 default so true 2 default zero so true 1 default zero so true 0 default so true 2 default zero two 2 default zero two so true

B.

225. Consider the following code: What will be printed? public class Scope{ private int i; public static void main(String arg[]){ Scope s = new Scope(); s.amethod(); }

public static void amethod(){ System.out.println(i); }

}

0 null Error. Non-static variable i cannot be referenced from a static context. Error. Variable I may not have been initialized.

C.

Consider the following code: What will be printed? public class StringBuf{ public static void main(String args[]){ StringBuffer sb = new StringBuffer("abc "); String s = new String(" a b c"); String st = "ABCDE"; sb.append("def ");//nu är s = abc def sb.insert(1, " zzz ");//nu är s = a zzz bc def String i = s.concat(st); s = s.trim(); System.out.println(s); System.out.println(sb);

Page 251: Cracked bits for scjp

System.out.println(st.indexOf("C")); System.out.println(st.indexOf('A')); System.out.println(st.indexOf('A', 2)); System.out.println(st.indexOf('G')); System.out.println(i); } }

What will be printed?

abc azzz bc def 2 0 -1 -1 a b cABCDE

a b c abc def zzz 2 0 -1 -1 a b c ABCDE

C. abc abcdefzzz 2 0 1 -1 a b c ABCDE

D. a b c a zzz bc def 2 0 -1 -1 a b cABCDE

Page 252: Cracked bits for scjp

D.

227. Consider the following code: What will be printed?

public class StringBufferTest{

public static void main(String[]args){

StringBuffer sb1 = new StringBuffer("Anna"); StringBuffer sb2 = new StringBuffer("Anna");

if (sb1.equals(sb2))

System.out.println("Equals");

else

System.out.println("StringBuffer Equals not");

String s1 = new String("Anna"); String s2 = new String("Anna");

if (s1.equals(s2))

System.out.println("String Equals");

else

System.out.println("Equals not"); } }

Equals Equals not

StringBuffer Equals not String Equals

Equals String Equals D. StringBuffer Equals not Equals not

B.

Page 253: Cracked bits for scjp

228. Consider the following code: What will be printed?

public class StringBufferTest2{ public static void main(String[]args){ String a, b; StringBuffer c, d; c = new StringBuffer("Kalle"); a = new String("Kalle"); b = a; d = c; StringBuffer e = new StringBuffer("Kalle"); String f = new String("Kalle"); if(b.equals(a)) System.out.println("b.equals(a)"); if(b==a) System.out.println("b==a"); if(d.equals(c)) System.out.println("d.equals(c)"); if(d==c) System.out.println("d==c"); if(f.equals(a)) System.out.println("f.equals(a)"); if(f==a) System.out.println("f==a"); else System.out.println("f!=a"); if(e.equals(c)) System.out.println("e.equals(c)"); else System.out.println("e.equalsnot(c)"); if(e==c) System.out.println("e==c"); else System.out.println("e!=c"); } }

A. b.equals(a) b==a d.equals(c) d==c f.equals(a) f!=a e.equalsnot(c)

Page 254: Cracked bits for scjp

e!=c

B. b.equals(a) b==a d.equals(c) d==c f!=a e.equalsnot(c) e!=c

C. b.equals(a) d.equals(c) f.equals(a) f==a e.equals(c) e!=c

D. b==a d==c f.equals(a) f!=a e.equalsnot(c) e==c

E. b.equals(a) b==a d.equals(c) d==c f.equals(a) e.equals(c) e!=c

A.

229. Consider the following code: What will be printed? public class StringTest{ public static void main(String[] args){ String s = "Kalle och Matte"; int i = s.length(); int j = args.length; System.out.println(i + " " + j); }}

Page 255: Cracked bits for scjp

13 13 13 0 15 0 15 13 15 null 15 + + 0 13 + + 0

C.

230. Check and run this code and you will see how the round method in the Java.lang.math class will behave when you have –4.5 and 4.5. It will round up. You will also see how substring(); floor(); and ceil(); behave. import java.lang.Math; public class Substr{ public static void main(String[]args){ String s1 = ("Kalle Bengtsson"); String s2 = s1.substring(0,5); System.out.println(s2); s1 = ("phenobarbital"); s2 = s1.substring(3,5); System.out.println(s2);

long i = Math.round(-4.4); System.out.println("Math.round(-4.4) = " + i);

long j = Math.round(4.5); System.out.println("Math.round(4.5) = " + j);

long k = Math.round(-4.5); System.out.println("Math.round(-4.5) = " + k);

int l = (int)(Math.ceil(-4.4)); System.out.println("Math.ceil(-4.4) = " + l);

int m = (int)Math.ceil(-4.5); System.out.println("Math.ceil(-4.5) = " + m);

int n = (int)Math.ceil(4.4); System.out.println("Math.ceil(4.4) = " + n);

int o = (int)Math.floor(-4.4); System.out.println("Math.floor(-4.4) = " + o);

Page 256: Cracked bits for scjp

int p = (int)Math.floor(4.4); System.out.println("Math.floor(4.4) = " + p);

int q = (int)Math.floor(4.5); System.out.println("Math.floor(4.5) = " + q); } }

231. Consider the following code: What will be printed? public class Testa { Integer a = 10; Integer b = 20; Integer c = 10; public static void main (String[] args){ if (a==c){ System.out.println("Fel"); }

if (a.equals(c)){ System.out.println("rätt"); } } }

Fel rätt rätt Fel None will be printed. A NullPointerException will be thrown. None will be printed. Compilation error. Incompatible types and a non-static variable cannot be referenced from a static context.

Consider the following code: What will be printed?

public class Testb { static Integer a = 10; static Integer b = 20; static Integer c = 10; public static void main (String[] args){

Page 257: Cracked bits for scjp

if (a==c){ System.out.println("Fel"); }

if (a.equals(c)){ System.out.println("rätt"); }

} }

Fel rätt rätt Fel None will be printed. A NullPointerException will be thrown. None will be printed. Compilation error. Incompatible types and a non-static variable cannot be referenced from a static context. None will be printed. Compilation error. Incompatible types.

F.

232. Consider the following code: What will be printed?

public class Testc {

static Integer a = new Integer(10); static Integer b; static Integer c = new Integer(10);

public static void main (String[] args){

if (a==c){ System.out.println("Fel"); }

if (a.equals(c)){ System.out.println("rätt"); }

} }

Page 258: Cracked bits for scjp

Fel rätt rätt Fel None will be printed. A NullPointerException will be thrown. None will be printed. Compilation error. Incompatible types and a non-static variable cannot be referenced from a static context. None will be printed. Compilation error. Incompatible types.

B.

233. Consider the following code: What will be printed?

class Unchecked{ public static void main(String[]args){ try{ method(); } catch (Exception e) { System.out.println("Fångar Exception"); } } static void method(){ try{ method1(); System.out.println("Testar method1"); }

catch (ArithmeticException ae) { System.out.println("Fångar ArithmeticException"); } finally{ System.out.println("Kör finally"); } System.out.println("I method() utanför finally"); }

static void wrench(){ throw new NullPointerException(); } }

Page 259: Cracked bits for scjp

A. Kör finally. I method() utanför finally. Fångar Exception. Kör finally. Fångar Exception. None. Kör finally.

B.

234. Consider the following code: What will be printed?

class Unchecked1{ public static void main(String[]args){ } void method(){ try{ metod1(); System.out.println("Testar metod1"); } catch (ArithmeticException ae) { System.out.println("Fångar ArithmeticException"); } finally{ System.out.println("Kör finally"); } System.out.println("I method() utanför finally"); }

void metod1(){ throw new NullPointerException(); } }

Kör finally. I method() utanför finally. Fångar Exception. Kör finally. Fångar Exception. None. Kör finally.

C. (Strange but that´s it).

Originally created by Thomas Leuthard.

Updated by Sasa.

Page 260: Cracked bits for scjp

Kept alive by you.

1. Which statement are characteristics of the >> and >>> operators.

A. >> performs a shift B. >> performs a rotate C. >> performs a signed and >>> performs an unsigned shift D. >> performs an unsigned and >>> performs a signed shift E. >> should be used on integrals and >>> should be used on floating point types

C.

2. Given the following declaration

String s = "Example";

Which are legal code?

A. s >>> = 3; B. s[3] = "x"; C. int i = s.length(); D. String t = "For " + s; E. s = s + 10;

CDE.

3. Given the following declaration

String s = "hello";

Which are legal code?

A. s >> = 2; B. char c = s[3]; C. s += "there"; D. int i = s.length(); E. s = s + 3;

CDE.

Page 261: Cracked bits for scjp

4. Which statements are true about listeners?

A. The return value from a listener is of boolean type. B. Most components allow multiple listeners to be added. C. A copy of the original event is passed into a listener method. D. If multiple listeners are added to a single component, they all must all be friends to each other. E. If the multiple listeners are added to a single component, the order [in which listeners are called is guaranteed].

BC.

5. What might cause the current thread to stop executing.

A. An InterruptedException is thrown. B. The thread executes a wait() call. C. The thread constructs a new Thread. D. A thread of higher priority becomes ready. E. The thread executes a waitforID() call on a MediaTracker.

ABDE.

6. Given the following incomplete method.

1. public void method(){ 2. 3. if (someTestFails()){ 4. 5. } 6. 7.}

You want to make this method throw an IOException if, and only if, the method someTestFails() returns a value of true. Which changes achieve this?

A. Add at line 2: IOException e; B. Add at line 4: throw e;

Page 262: Cracked bits for scjp

C. Add at line 4: throw new IOException(); D. Add at line 6: throw new IOException(); E. Modify the method declaration to indicate that an object of [type] Exception might be thrown.

DE. (E suppose they mean the method declaration for someTestFails.)

7. Which modifier should be applied to a method for the lock of the object this to be obtained prior to executing any of the method body?

A. final B. static C. abstract D. protected E. synchronized

E.

8. Which are keywords in Java?

A. NULL B. true C. sizeof D. implements E. instanceof

DE.

9. Consider the following code:

Integer s = new Integer(9); Integer t = new Integer(9); Long u = new Long(9);

Which test would return true?

A. (s==u) B. (s==t) C. (s.equals(t)) D. (s.equals(9))

Page 263: Cracked bits for scjp

E. (s.equals(new Integer(9))

CE.

10. Why would a responsible Java programmer want to use a nested class?

Don't know the answers. But here are some reasons from Exam Cram.

To keep the code for a very specialized class in close association with the class it works with. To support a new user interface that generates custom events. To impress the boss with his/her knowledge of Java by using nested classes all over the place.

AB.

11. You have the following code. Which numbers will cause "Test2" to be printed?

switch(x){

case 1: System.out.println("Test1"); case 2:

case 3: System.out.println("Test2"); break; } System.out.println("Test3"); }

A. 0 B. 1 C. 2 D. 3 E. 4

BCD.

Page 264: Cracked bits for scjp

12. Which statement declares a variable a which is suitable for referring to an array of 50 string objects?

A. char a[][]; B. String a[]; C. String []a; D. Object a[50]; E. String a[50); F. Object a[];

BCF.

13. What should you use to position a Button within an application frame so that the width of the Button is affected by the Frame size but the height is not affected.

A. FlowLayout B. GridLayout C. Center area of a BorderLayout D. East or West of a BorderLayout E. North or South of a BorderLayout

E.

14. What might cause the current thread to stop executing?

A. An InterruptedException is thrown B. The thread executes a sleep() call C. The thread constructs a new Thread D. A thread of higher priority becomes ready (runnable) E. The thread executes a read() call on an InputStream

ABDE.

Non-runnable states:

Page 265: Cracked bits for scjp

* Suspended: caused by suspend(), waits for resume() * Sleeping: caused by sleep(), waits for timeout * Blocked: caused by various I/O calls or by failing to get a monitor's lock, waits for I/O or for the monitor's lock * Waiting: caused by wait(), waits for notify() or notifyAll() * Dead: Caused by stop() or returning from run(), no way out

From Certification Study Guide p. 227

15. Consider the following code:

String s = null;

Which code fragments cause an object of type NullPointerException to be thrown?

A. if((s!=null) & (s.length()>0)) B. if((s!=null) &&(s.length()>0)) C. if((s==null) | (s.length()==0)) D. if((s==null) || (s.length()==0))

AC.

16. Consider the following code:

String s = null;

Which code fragments cause an object of type NullPointerException to be thrown?

A. if((s==null) & (s.length()>0)) B. if((s==null) &&(s.length()>0)) C. if((s!=null) | (s.length()==0)) D. if((s!=null) || (s.length()==0))

ABCD.

17. Which statement is true about an inner class?

A. It must be anonymous B. It can not implement an interface

Page 266: Cracked bits for scjp

C. It is only accessible in the enclosing class D. It can only be instantiated in the enclosing class E. It can access any final variables in any enclosing scope.

E.

18. Which statements are true about threads?

A. Threads created from the same class all finish together B. A thread can be created only by subclassing Java.Lang.Thread. C. Invoking the suspend() stops a thread so that it cannot be restarted D. The Java Interpreter's natural exit occurs when no non daemon threads remain alive E. Uncoordinated changes to shared data by multiple threads may result in the data being read, or left, in an inconsistent state.

DE.

19. Consider the following code:

1. public void method(String s){ 2. String a,b; 3. a = new String("Hello"); 4. b = new String("Goodbye"); 5. System.out.println(a + b); 6. a = null; 7. a = b; 8. System.out.println(a + b); 9. }

Where is it possible that the garbage collector will run the first time?

A. Just before line 5 B. Just before line 6 C. Just before line 7 D. Just before line 8 E. Never in this method

C.

Page 267: Cracked bits for scjp

20. Which code fragments would correctly identify the number of arguments passed via the command line to a Java application, excluding the name of the class that is being invoked?

A. int count = args.length; B. int count = args.length - 1; C. int count = 0; while (args[count] != null) count ++; D. int count = 0; while (!(args[count].equals(""))) count ++;

A.

21. Which are keywords in Java?

A. sizeof B. abstract C. native D. NULL E. BOOLEAN

BC.

22. Which are correct class declarations? Assume in each case text constitutes the entire contents of a file called Fred.java on a system with a case-significant system.

A. public class Fred { public int x = 0; public Fred (int x) { this.x = x; } }

B. public class fred { public int x = 0; public fred (int x) {

Page 268: Cracked bits for scjp

this.x = x; } }

C. public class Fred extends MyBaseClass, MyOtherBaseClass { public int x = 0; public Fred (int xval) { x = xval; } }

D. protected class Fred { private int x = 0; private Fred (int xval) { x = xval; } }

E. import java.awt.*; public class Fred extends Object { int x; private Fred (int xval) { x = xval; } }

AE.

B is wrong because of case-sensitivity. C is wrong because multiple inheritance is not supported in Java. D is wrong because a class can only be public, abstract, final or default (with no access modifier).

23. Which are correct class declarations? Assume in each case text constitutes the entire contents of a file called Test.java on a system with a case-significant system.

A. public class Test { public int x = 0; public Test (int x) { this.x = x;

Page 269: Cracked bits for scjp

} }

B. public class Test extends MyClass, MyOtherClass { public int x = 0; public Test (int xval) { x = xval; } }

C. import java.awt.*; public class Test extends Object { int x; private Test (int xval) { x = xval; } }

D. protected class Test { private int x = 0; private Test (int xval) { x = xval; } }

AC.

24. A class design requires that a particular member variable must be accesible for direct access by any subclasses of this class, otherwise not by classes which are not members of the same package. What should be done to achieve this?

A. The variable should be marked public B. The variable should be marked private C. The variable should be marked protected D. The variable should have no special access modifier E. The variable should be marked private and an accessor method provided

C.

Page 270: Cracked bits for scjp

25. Which correctly create an array of five empty Strings?

A. String a [] = new String [5]; for (int i = 0; i < 5; a[i++] = "");

B. String a [] = {"", "", "", "", "", ""};

C. String a [5]; D. String [5] a; E. String [] a = new String[5]; for (int i = 0; i < 5; a[i++] = null);

AB.

26. Which cannot be added to a Container?

A. an Applet B. a Component C. a Container D. a Menu E. a Panel

D.

27. FilterOutputStream is the parent class for BufferedOutputStream, DataOutputStream and PrintStream. Which classes are a valid argument for the constructor of a FilterOutputStream?

A. InputStream B. OutputStream C. File D. RandomAccessFile E. StreamTokenizer

B.

28. FilterInputStream is the parent class for BufferedInputStream and DataInputStream. Which classes are a valid argument for the constructor of a FilterInputStream?

Page 271: Cracked bits for scjp

A. File B. InputStream C. OutputStream D. FileInputStream E. RandomAccessFile

B.

29. Given the following method body:

{ if (atest()) { unsafe(): } else { safe(); } }

The method "unsafe" might throw an AWTException (which is not a subclass of RunTimeException). Which correctly completes the method of declaration when added at line one?

A. public AWTException methodName() B. public void methodname() C. public void methodName() throw AWTException D. public void methodName() throws AWTException E. public void methodName() throws Exception

DE.

30. Given a TextArea using a proportional pitch font and constructed like this:

TextField t = new TextArea("12345", 5, 5);

Which statement is true?

A. The displayed width shows exactly five characters on each line unless otherwise constrained.

Page 272: Cracked bits for scjp

B. The displayed height is five lines unless otherwise constrained. C. The maximum number of characters in a line will be five. D. The user will be able to edit the character string. E. The displayed string can use multiple fonts.

BD.

31. Given this skeleton of a class currently under construction:

public class Example { int x, y;

public Example(int a){ //lots of complex computation x = a; }

public Example(int a, int b) { /*do everything the same as single argument version of constructor including assignment x = a */ y = b; } }

What is the most concise way to code the "do everything..." part of the constructor taking two arguments?

Answer:

this(a);

32. Given this skeleton of a class currently under construction:

public class Example { int x, y;

public Example(int a, int b){ //lots of complex computation

Page 273: Cracked bits for scjp

x = a; }

public Example(int a, int b, long c) { /*do everything the same as the two argument version of constructor including assignment x = a */ y = b; } }

What is the most concise way to code the "do everything..." part of the constructor taking two arguments?

Answer:

this(a, b);

Warning! A similar question will appear with at least two classes, then it is super("arguments"); that you should use.

33. Which correctly create a two dimensional array of integers?

A. int a [][] = new int [10,10]; B. int a [10][10] = new int [][]; C. int a [][] = new int [10][10]; D. int []a[] = new int [10][10]; E. int [][]a = new int [10][10];

CDE.

34. Given the following method body:

{ if (sometest()) { unsafe(); } else { safe(); } }

Page 274: Cracked bits for scjp

The method "unsafe" might throw an IOException (which is not a subclass of RunTimeException). Which correctly completes the method of declaration when added at line one?

A. public void methodName() throws Exception B. public void methodname() C. public void methodName() throw IOException D. public void methodName() throws IOException E. public IOException methodName()

AD.

35. What would be the result of attempting to compile and run the following piece of code?

public class Test { static int x;

public static void main(String args[]){ System.out.println("Value is " + x); } }

A. The output "Value is 0" is printed. B. An object of type NullPointerException is thrown. C. An "illegal array declaration syntax" compiler error occurs. D. A "possible reference before assignment" compiler error occurs. E. An object of type ArrayIndexOutOfBoundsException is thrown.

A.

36. What would be the result of attempting to compile and run the following piece of code?

public class Test { public int x;

Page 275: Cracked bits for scjp

public static void main(String args[]){ System.out.println("Value is " + x); } }

A. The output "Value is 0" is printed. B. Non-static variable x cannot be referenced from a static context.. C. An "illegal array declaration syntax" compiler error occurs. D. A "possible reference before assignment" compiler error occurs. E. An object of type ArrayIndexOutOfBoundsException is thrown.

B.

37. What would be the result of attempting to compile and run the following piece of code?

public class Test {

public static void main(String args[]){ int x; System.out.println("Value is " + x); } }

A. The output "Value is 0" is printed. B. An object of type NullPointerException is thrown. C. An "illegal array declaration syntax" compiler error occurs. D. A "possible reference before assignment" compiler error occurs. E. An object of type ArrayIndexOutOfBoundsException is thrown.

D. Compiler says variable x might not have been initialized.

Page 276: Cracked bits for scjp

38. What should you use to position a Button within an application Frame so that the size of the Button is NOT affected by the Frame size?

A. a FlowLayout B. a GridLayout C. the center area of a BorderLayout D. the East or West area of a BorderLayout E. The North or South area of a BorderLayout

A.

For the following six questions you will be presented with a picture in the real test, showing the relationship and quite long text, but don't be afraid the questions are quite easy.

39. We have the following organization of classes.

class Parent {} class DerivedOne extends Parent {} class DerivedTwo extends Parent {}

Which of the following statements is correct for the following expression?

Parent p = new Parent(); DerivedOne d1 = new DerivedOne(); DerivedTwo d2 = new DerivedTwo(); p = d1;

A. Illegal both at compile and runtime. B. Legal at compile time, but may fail at runtime. C. Legal at both compile and runtime. D. .... E. ....

C.

40. We have the following organization of classes.

class Parent {}

Page 277: Cracked bits for scjp

class DerivedOne extends Parent {} class DerivedTwo extends Parent {}

Which of the following statements is correct for the following expression?

Parent p = new Parent(); DerivedOne d1 = new DerivedOne(); DerivedTwo d2 = new DerivedTwo(); d2 = d1;

A. Illegal both at compile and runtime. B. Legal at compile time, but may fail at runtime. C. Legal at both compile and runtime. D. .... E. ....

A.

41. We have the following organization of classes.

class Parent {} class DerivedOne extends Parent {} class DerivedTwo extends Parent {}

Which of the following statements is correct for the following expression?

Parent p = new Parent(); DerivedOne d1 = new DerivedOne(); DerivedTwo d2 = new DerivedTwo(); d1 = (DerivedOne)d2;

A. Illegal both at compile and runtime. B. Legal at compile time, but may fail at runtime. C. Legal at both compile and runtime. D. .... E. ....

A. Illegal both at compile and runtime. You cannot assign an object to a sibling reference, even with casting.

43. We have the following organization of classes.

Page 278: Cracked bits for scjp

class Parent {} class DerivedOne extends Parent {} class DerivedTwo extends Parent {}

Which of the following statements is correct for the following expression?

Parent p = new Parent(); DerivedOne d1 = new DerivedOne(); DerivedTwo d2 = new DerivedTwo(); d1 = (DerivedOne)p;

A. Illegal both at compile and runtime. B. Legal at compile time, but may fail at runtime. C. Legal at both compile and runtime. D. .... E. ....

B.

44. We have the following organization of classes.

class Parent {} class DerivedOne extends Parent {} class DerivedTwo extends Parent {}

Which of the following statements is correct for the following expression?

Parent p = new Parent(); DerivedOne d1 = new DerivedOne(); DerivedTwo d2 = new DerivedTwo(); d1 = p;

A. Illegal both at compile and runtime. B. Legal at compile time, but may fail at runtime. C. Legal at both compile and runtime. D. .... E. ....

A.

45. We have the following organization of classes.

Page 279: Cracked bits for scjp

class Parent {} class DerivedOne extends Parent {} class DerivedTwo extends Parent {}

Which of the following statements is correct for the following expression?

Parent p = new Parent(); DerivedOne d1 = new DerivedOne(); DerivedTwo d2 = new DerivedTwo(); p = (Parent)d1;

A. Illegal both at compile and runtime. B. Legal at compile time, but may fail at runtime. C. Legal at both compile and runtime. D. .... E. ....

C.

46. What would you use when you have duplicated values that needs to be sorted?

A. Map B. Set C. Collection D. List E. Enumeration

D.

47. What kind of reader do you use to handle ASCII code?

A. BufferedReader B. ByteArrayReader C. PrintWriter D. InputStreamReader E. ?????

D.

Page 280: Cracked bits for scjp

InputStreamReader and FileReader automatically converts from a particular character encoding to Unicode. From Core Java Advanced Features p. 820.

48. How can you implement encapsulation in a class?

A. Make all variables protected and only allow access via methods. B. Make all variables private and only allow access via methods. C. Ensure all variables are represented by wrapper classes. D. Ensure all variables are accessed through methods in an ancestor class.

B.

49. What is the return-type of the methods that implement the MouseListener interface?

A. boolean B. Boolean C. void D. Pont

C.

50. What is true about threads that stop executing?

A. When a running thread's suspend() method is called, then it is indefinitely possible for the thread to start. B. The interpreter stops when the main method stops. C. A thread can stop executing when another thread is in a runnable state. D. ...... E. ......

C.

Page 281: Cracked bits for scjp

51. For which of the following code will produce "test" as output on the screen?

A. int x=10.0; if (x=10.0) { System.out.println("test"); }

B. int x=012; if (x=10.0) { System.out.println("test"); }

C. int x=10f; if (x=10.0) { System.out.println("test"); }

D. int x=10L; if (x=10.0) { System.out.println("test"); }

B.

52. Given this class ?

class Loop { public static void main (String [] args){ int x=0; int y=0, outer: for (x=0; x<100;x++) { middle: for (y=0;y<100y++) {

System.out.printl("x=" + x + "; y=" + y);

if (y==10){

<<<>>>} } }

Page 282: Cracked bits for scjp

}//main }//class

The question is which code must replace the <<<>>> to finish the outer loop? A. continue middle; B. break outer; C. break middle; D. continue outer; E. none of these...

B.

53. What does it mean when the handleEvent() returns the true boolean?

A. The event will be handled by the component. B. The action() method will handle the event. C. The event will be handled by the super.handleEvent(). D. Do nothing.

A.

54. What is the target in an Event?

A. The Object() where the event came from. B. The Object() where the event is destined for. C. What the Object() that generated the event was doing.

A.

55. What is the statement to assign a unicode constant CODE with 0x30a0?

Answer:

public static final char CODE='\u30a0';

56. The following code resides in the source?

class StringTest {

Page 283: Cracked bits for scjp

public static void main (String [] args){ // // String comparing // String a,b; StringBuffer c,d; c = new StringBuffer ("Hello"); a = new String("Hello"); b = a; d = c;

if (<<>>) {} } }//class

Which of the following statement return true for the <<>> line in StringTest.class?

A. b.equals(a) B. b==a C. d==c D. d.equals(c)

ABCD.

57. Which are valid identifiers?

A. %fred B. *fred C. thisfred D. 2fred E. fred

CE.

58. We have the following class X.

public class X {

public void method();

}

Page 284: Cracked bits for scjp

<<>>

Which of the following statement return true for the <<>> line in StringTest.class?

A. abstract void method() ; B. class Y extends X {} C. package java.util; D. abstract class z { }

BD.

59. Which code fragments would correctly identify the number of arguments passed via the command line to a Java Application?

A. int count = args.length; B. int count = 0; while args[count] !=null) count++; C. int count = 0; while (!(args[count].equals(""))) count++; D. int count = args.length - 1;

A.

60. Given a TextField that is constructed like this:

TextField t = new TextField(30);

Which statement is true?

A. The displayed width is 30 columns. B. The displayed string can use multiple fonts. C. The user will be able to edit the character string. D. The displayed line will show exactly thirty characters. E. The maximum number of characters in a line will be thirty.

AC.

61. What does the java runtime option -cs do?

Page 285: Cracked bits for scjp

A. check source with debug report B. clear classes that are existing when starting compilation. C. check if the source is newer when loading classes.

C.

62. When is an action invoked?

A. TextField Enter B. TextArea Enter C. Scrollbar D. MouseDown E. Button

AE.

63. What error does the following code generate?

class SuperClass{

SuperClass(String s){} }

class SubClass extends SuperClass{ SubClass(){} }

......

SubClass s1 = new SubClass("The"); SuperClass s = new SubClass("The");

A. java.lang.ClassCastException B. Wrong number of arguments in constructor C. Incompatible type for =. Can't convert SubClass to SuperClass. D. No constructor matching SuperClass found in class SuperClass.

BD.

Page 286: Cracked bits for scjp

64. How do you declare a native method called myMethod in Java?

Answer:

public native void myMethod();

65. What should you use to position a component within an application frame so that the components height is affected by the Framesize?

A. FlowLayout B. GridLayout C. Center area of a BorderLayout D. East or West of a BorderLayout E. North or South of a BorderLayout

D.

66. What should you use to position a component within an application frame so that the components width is affected by the Framesize?

A. FlowLayout B. GridLayout C. Center area of a BorderLayout D. East or West of a BorderLayout E. North or South of a BorderLayout

E.

67. What should you use to position a Button within an application frame so that the height of the Button is affected by the Frame size but the width is not affected.

A. FlowLayout B. GridLayout C. Center area of a BorderLayout D. East or West of a BorderLayout E. North or South of a BorderLayout

D.

Page 287: Cracked bits for scjp

68. Which are keywords in Java?

A. NULL B. sizeof C. friend D. extends E. synchronized

DE.

69. Which is the advantage of encapsulation?

A. Only public methods are needed. B. No exceptions need to be thrown from any method. C. Making the class final causes no consequential changes to other code. D. It changes the implementation without changing the interface and causes no consequential changes to other code. E. It changes the interface without changing the implementation and causes no consequential changes to other code.

D.

70. What can contain objects that have a unique key field of String type, if it is required to retrieve the objects using that key field as an index?

A. Map B. Set C. List D. Collection E. Enumeration

A.

71. Which statement is true about a non-static inner class?

A. It must implement an interface. B. It is accessible from any other class.

Page 288: Cracked bits for scjp

C. It can only be instantiated in the enclosing class. D. It must be final if it is declared in a method scope. E. It can access private instance variables in the enclosing object.

E.

72. Which declares an abstract method in an abstract Java class?

A. public abstract method(); B. public abstract void method(); C. public void abstract Method(}; D. public void method() {abstract;/} E. public abstract void method() {/}

B.

73. Which statements on the<<< call>>> line are valid expressions?

public class SuperClass { public int x; int y; public void m(int a) {} Superclass(){ } } class SubClass extends SuperClass{ private float f; void m2() { return; } SubClass() { } } class T { public static void main (String [] args) { int i; float g; SubClass b = SubClass(); <<< calls >>> } }

A. b.m2(); B. g=b.f; C. i=b.x; D. i=b.y;

Page 289: Cracked bits for scjp

E. b.m(6);

ACDE.

74. Type 7 in hexadecimal form.

Answer:

0x7

75. Type 7 in octal form.

Answer:

07

76. What is the range of an integer?

A. -128–127 B. -32 768 – 32 767 C. -231 – 231 -1 D. -232 – 232 -1

C.

77. What is the range of a char?

A. \u0000 – \uFFFF B. -32 768 – 32 767 C. -128 – 127 D. -231 – 231 -1

A.

78. What is the range of a char?

A. 0 – 215-1 B. -32 768 – 32 767 C. - 2 16 – 216-1 D. 0 – 216-1

Page 290: Cracked bits for scjp

D.

79. Which method contains the code-body of a thread?

A. start() B. run() C. init() D. suspend() E. continue()

B.

80. What can you place first in this file?

//What can you put here?

public class Apa{}

A. class a implements Apa B. protected class B {} C. private abstract class{} D. import java.awt.*; E. package dum.util; F. private int super = 1000;

ADE.

81. What is the output of the following code?

outer: for(int i=1; i<3; i++){ inner: for(int j=1; j<3; j++){ if (j==2){ continue outer; } System.out.println(i+" and "+j); } }

A. 1 and 1 B. 1 and 2 C. 2 and 1 D. 2 and 2 E. 2 and 3

Page 291: Cracked bits for scjp

F. 3 and 2 G. 3 and 3

AC.

82. What is the output of the following code?

outer: for(int i=1; i<2; i++){ inner: for(int j=1; j<2; j++){ if (j==2){ continue outer; } System.out.println(i " and " j); } }

A. 1 and 1 B. 1 and 2 C. 2 and 1 D. 2 and 2 E. 2 and 3 F. 3 and 2 G. 3 and 3

A.

83. How do you declare a native method?

A. public native method(); B. public native void method(); C. public void native method(); D. public void native() {} E. public native void method() {}

B.

84. Given the following code, what is the output when a exception other than a NullPointerException is thrown?

try{

//some code

Page 292: Cracked bits for scjp

} catch(NullPointerException e) { System.out.println("thrown 1"); } finally { System.out.println("thrown 2"); } System.out.println("thrown 3");

A thrown 1 B thrown 2 C thrown 3 D none

BC.

85. You have been given a design document for a employee system for implementation in Java. It states. bla bla bla

choose between the following words:

public class object extends Employee Person plus at least five more

How should you name the class?

Answer:

public class Employee extends Person

86. You have been given a design document for a polygon system for implementation in Java. It states.

A polygon is drawable, is a shape. You must access it. It should have values in a vector

Page 293: Cracked bits for scjp

bla bla

Which variables should you use?

choose between the following words:

public object vector drawable color plus some more

Answer:

vector, color (not sure)

87. You have been given a design document for a polygon system for implementation in Java. It states. A polygon is a Shape. You must access it. It has a vector and corners bla bla

choose between the following words: What will you write when defining the class?

public class Polygon object extends Shape plus some more

Answer:

public class Polygon extends Shape

88. What is true about the garbage collection?

A. The garbage collector is very unpredictable. B. The garbage collector is predictable. C. D.

Page 294: Cracked bits for scjp

E.

A.

87. What is true about a thread?

A The only way you can create a thread is to subclass java.lang.Thread B If a Thread with higher priority than the currently running thread is created, the thread with the higher priority runs. C. D. E.

B (not sure)

88. What happens when you compile the following code?

public classTest {

public static void main(String args[] ) { int x; System.out.println(x); }

A. Error at compile time. Malformed main method B. Clean compile C. Compiles but error at runtime. X is not initialized D. E. Compile error. Variable x may not have been initialized.

E.

89.What happens hen you run the following program with the command:

java Prog cat dog mouse

public class Prog {

public static void main(String args[]) { System.out.println(args[0]) ;

Page 295: Cracked bits for scjp

}

A. Error at compile time. ArrayIndexOutOfBoundsException thrown B. Compile with no output C. Compile and output of dog D. Compile and output of cat E. Compile and output of mouse

D.

90. Which number for the argument must you use for the code to print cat?

With the command:

java Prog dog cat mouse

public class Prog {

public static void main(String args[]) { System.out.println(args[?]) ; } }

A. 0 B. 1 C. 2 D. 3 E. none of these

B.

91. Which number for the argument must you use for the code to print cat? With the command:

java Prog cat dog mouse

public class Prog {

public static void main(String args[]) { System.out.println(args[?]) ; }

Page 296: Cracked bits for scjp

}

A. 0 B. 1 C. 2 D. 3 E. none of these

A.

92. You have the following code:

....... String s; s = "Hello"; t = " " + "my"; s.append(t); s.toLowerCase(); s+= " friend"; System.out.println(s);

What will be printed?

Answer:

hello my friend

93. What will happen when you attempt to compile and run this code?

public class MySwitch{

public static void main(String argv[]) { MySwitch ms = new MySwitch(); ms.amethod(); }

public void amethod() {

char k=10;

switch(k){ default: System.out.println("This is the default output");

Page 297: Cracked bits for scjp

break; case 10: System.out.println("ten"); break; case 20: System.out.println("twenty"); break; } } }

A. None of these options B. Compile time error target of switch must be an integral type C. Compile and run with output "This is the default output" D. Compile and run with output "ten"

D.

94. What will happen when you attempt to compile and run the following code?

public class MySwitch{

public static void main(String argv[]) { MySwitch ms = new MySwitch(); ms.amethod(); }

public void amethod() {

int k=10; switch (k){ default: //Put the default at the bottom, not here System.out.println("This is the default output"); break; case 10: System.out.println("ten"); case 20: System.out.println("twenty"); break; } } }

Page 298: Cracked bits for scjp

A. None of these options B. Compile time error target of switch must be an integral type C. Compile and run with output "This is the default output D. Compile and run with output "ten"

A.

95. Which of the following statements are true? A. For a given component, events will be processed in the order that the listeners were added B. Using the Adapter approach to event handling means creating blank method bodies for all event methods C. A component may have multiple listeners associated with it D. Listeners may be removed once added

CD.

Button for instance has the methods addActionListener (ActionListener a) and removeActionListener(ActionListener a).

96. Which of the following statements are true? A. Directly subclassing Thread gives you access to more functionality of the Java threading capability than using the Runnable interface B. Using the Runnable interface means you do not have to create an instance of the Thread class and can call run directly C. Both using the Runnable interface and subclassing of Thread require calling start to begin execution of a Thread D. The Runnable interface requires only one method to be implemented, this method is called run

CD.

Page 299: Cracked bits for scjp

97. If you want subclasses to access, but not to override a superclass member method, what keyword should precede the name of the superclass method?

Answer:

final

98. If you want a member variable to not be accessible outside the current class at all, what keyword should precede the name of the variable when declaring it?

Answer:

private 99. Which of the following are correct methods for initializing the array "dayhigh" with 7 values? A. int dayhigh = { 24, 23, 24, 25, 25, 23, 21 }; B. int dayhigh[] = { 24, 23, 24, 25, 25, 23, 21 }; C. int[] dayhigh = { 24, 23, 24, 25, 25, 23, 21 }; D. int dayhigh [] = new int [24, 23, 24, 25, 25, 23, 21]; E. int dayhigh = new [24, 23, 24, 25, 25, 23, 21] ;

BC. 100. Assume that val bas been defined as an int for the code below.

if(val > 4){ System.out.println("Test A"); } else if(val > 9){ System.out.println("Test B"); } else System.out.println("Test C"); Which values of val will result in "Test C" being printed: A. val < 0 B val between 0 and 4 C val between 4 and 9 D val > 9 E val = 0 F no values for val will be satisfactory

Page 300: Cracked bits for scjp

ABE.Q-1 int b1 = << 31; int b2 = << 31; b1 >>> = 31; b1 >>> =1; b2 >> = 31; b2 >> = 1;

Ans: (a) b1 all zeros & b2 all zeros (b) b1 all zeros & b2 all ones (c) b1 all ones & b2 all zeros (d) b1 all ones & b2 all ones

Q-2 Which of following expressions throws "Null Pointer Exception" given String S=null;

Ans: (a) if (S1 = null & s.length ( ) > o) (b) if (S1 = null & s.length ( ) > o) (c) if (S == null / s.length ( ) ==o) (d) if (S == null ll s.length ( ) ==o)

Q-3 How can you define an array of 10 by 10 with all zeros ?(a) int a[][]=new [10,10](b) int a[10][10] = new int[][](c) int a[][]=new int[10][10](d) int []a[]=new int[10][10](e) int a[][]=new int[][]

Q-4 Which of the following operations can be done on String String s = "abcdef";(a)s>>>=4;(b)s[3]=a;(c)s=s.trim();(d)s=s.toUppercase();(e)s.equals("xyz");(f)s.append("xyz");(g)s.subString(3);

Q-5 Following can be placed at Point1

// Point1public class Xyz{}

(a) import java.awt.*;(b) public class Abc{ }(c) package my.util.*;

Page 301: Cracked bits for scjp

(d) import lang.util.*;(e) protected class pqr{ }

Q-6 In order to read a file line by line which is most preffered way(a) FileInputStream fis = new FileInputStream("a.dat");(b) DataInputStream dis = new DataInputStream(new FileInputStream("a.dat",r));(c) DataInputStream dis = new DataInputStream(new FileInputStream("a.dat"));(d) BufferedReader br = new BufferedReader(new FileReader("file");

Q-7 Intially "old.dat" file consists of 10 bytes of data after the following operation what is the length of the file "old.dat" ?

FileOutputStream fos = new FileOutputStream("old.dat");DataOutputStream dos = new DataOutputStream(fos);dos.write(bye);

(a) 8(b) 14(c) 4(d) 20(e) none

Q-8 Which is the valid argument passed to constructor of FilterInputStream(a) FileInputStream(b) BufferedInputStream(c) File(d) RandomAccessFile(e) DataInputStream

Q-9 Following cannot be added to a Container(a)Component(b)Panel(c)MenuItem(d)Container

Q-10 If following method may throw IOException How do you declare the method in a proper way

(a) public void IOException{ }(b) void method throw IOException{ }(c) public void method throws IOException{ }

Q-11 What will be the output for the following codeOuter: for(int i=1;i<3;i++) {

for(int j=1;j<3;j++){if(j==2){ continue Outer; }

Page 302: Cracked bits for scjp

System.out.println(" i : "+i+" j : "+j);}

}(a) i=0 j=0(b) i=1 j=0(c) i=0 j=1(d) i=1 j=1(e) i=2 j=1(f) i=1 j=2(g) i=2 j=0(h) i=0 j=2(b) i=2 j=2

Q-12 For what values of x the "Point 3" only will be printedif(x>4) { System.out.println("Point1"); }else if(x>9 ) { System.out.println("Point 3"); }else { System.out.println("Point 3"); }

(a) x is less than zero(b) between 0 and 4(c) greater than 4(d) none

Q-13 How can you represent 7 in Hexadecimal ___

Q-14 What is return type of method in Actionlistener

Q-15 What is the arguments passed for methods in MouseMotionListener ?

Q-16 For the following code snippet which expression will result true ?Integer A = new Integer(10);Integer B = new Integer(10);Float f = new Float(10.0f);int x = 10;long y = 10L;Integer c = b;(a) if(c==b) (b) if(a==b)(c) if(a.equals(10));(d) if(x==a)(e) if(x==y)

Q-17 Parent| |

Derived1 Derived2

Page 303: Cracked bits for scjp

Parent p1;Derived1 d1;Derived2 d2;

All of above given class are not null;

(a) compile error(b) runtime error(c) compiles and runs without Exception

Q-18

class Abc{int x,y,z;public Abc(int a , int b) {

x= a;y= b;

}public Abc(int a, int b, int c) {

//point 1z =c;

}}In order to initialize x and y in second constructor write shortest possible way at point 1

Q-19

What is output of following codeclass StackTest{

static Stack s1,s2;public static void main(String a[]){

s1 = new Stack();s1.push(new Integer(100));amethod(s1);System.out.println(" s1 is " + s1 + "\n s2 is " + s2);

}public static void amethod(Stack s1){

s2=s1;}

}(a) s1 is [100]

s2 is [](b) s1 is [100]

s2 is [100](c) compile error

Page 304: Cracked bits for scjp

(d) runtime error

Q-20 If you resize a component horizontally you need to add the component

(a) to the north and south of BorderLayout(b) to the east and west of BorderLayout(c) to the FlowLayout(d) to east and north of BorderLayout

Q-21 Which are the correct class declarations ? Assume in each case text constitutes of a file called Car.java on a system with a case significant FileSystem.

(a) public class Fred{(b) public class fred{(c) public class Fred extends Abc,Xyz{(d) public class Fred extends Objec{

Q-22 valid java keywords

q-23 legal identifiers

Q-24 after creating thread which method make that thread eligible to run _____ .

Q-25 what is range of char 0 to (2 raiseto 16) -1

Q-26 At which line in following code object created at line 3 becomes garbage collected

Q-27 Which interface impose no order, no restrictions and no content duplication ?(a) Set(b) Map(c) List(d) Collection

Q-28 When you resize window row changes its height vericatically . what is to be given(a) weightx(b) gridx(c) gridy(d) weighty

Q-29 what constraints effects size of GridbagLayout.(a) fill(b) gridx(c) gridy(d) anchor

Q-30 Specify true or false(a) it is in programmers hand to explicitly invoke garbage collection and frees

Page 305: Cracked bits for scjp

memorywhen required.

Page 306: Cracked bits for scjp

Preparation Topics

Questions are:

1. What is the return type of main() method?

2. What is the range of int primitive type in Java?

3. What is the argument type of all the methods in Mouse Listener interface?

4. What is the range of Char primitive type in Java?

5. Select the valid Java identifiers from the list.

6. Select from the list those, which are NOT Java keywords.

7. How to add a button in a frame so that height of the button is dependent on the frame, but width is not?

8. How will you represent the number 7 as an octal literal, using not more than four characters?

9. What modifier you should use if you don't want the method to be overridden in a subclass?

10. equals() on wrapper class. How it works?

11. Which is the earliest point in the given method, where Garbage Collection can be done?

12. What is the exact behavior of passing "references to objects" as method parameters?

13. Immutability of String

14. Explicit casting during object reference assignment.

15. Short circuit operators, compare them with logical & and |

16. "while" loop. Question to test that it may not get executed even once if the condition is false in the beginning itself.

17. Labeled "Continue". Question to test that where flow goes when "continue" with a label is encountered?

18. "switch" statement. Question to test the "fall-through" nature of "switch" structure.

19. "If(){} else if(){}" to test mutual exclusiveness of code blocks

20. Signature of a subclass: importance of "extends".

21. Thread: What will stop it from executing?

22. What does the getid() method of AWT subclass return?

Page 307: Cracked bits for scjp

23. What are the possible signatures of methods in the given options, allowed in a subclass, given a method in superclass.

24. Characteristics of Garbage Collection in Java

25. Which all keywords from the given list needed to declare instance variables of the given class definition?

26. Given a class definition, what is allowed above it in the code? From the list package, import, other class signature etc.

27. Which element of args array of main will contain the specific command line argument?

28. Class, subclass definitions and calling. Syntax error line identification.

29. What all from the given list a container can contain?

30. Event handling and multiple listeners for a component.

31. Valid declaration type for a two dimensional array.

32. Constructor argument for FilterInputStream

33. A constructor calling this() in the same class.

34. Two ways to construct Threads. (1. extends and 2. implements)

35. Which collection can have ordered items but repetitions allowed?

36. Gridbaglayout parameter characteristics.(weightx and weighty)

37. Adapter classes for event handling.

38. Array declaration (without initialization) in main() what will be printed if array elements are to be printed?

39. With an instance variable of a class without the class getting instantiated getting referred in main.

40. What is the return type of listener?

41. Exception handling: To test that finally always gets executed.

42. What will be the output, when a frame declaration and description without using a separate class for that, is done in main()?

43. Compare and contrast of >> and >>>

44. In a case sensitive operating system, what are the valid class signatures given the source code file name?

45. Valid inner class declaration and instantiation at same place.

46. "Throws" and "throw" syntax.

Page 308: Cracked bits for scjp

47. Final contents of a string after concat, toUppercase etc. without assigning to other string or overwriting, and then finally with += operator.

48. Ideal conditions for total encapsulation.

49. Math object’s floor, ceil and round.

50. Default scope of class (package level or friendly as it is called without a modifier).

51. How to declare a native method?

52. At a given point (place) in code, which all assignment statements valid, from the given list?

53. Access of variables between inner and outer classes(which variables can the inner class access)

54. Name of the method used to schedule a Thread for execution.

55. From the given list, which all are valid abstract class signatures.

56. From a given list, which statement is true about a non-static inner class?

57. From the list given, what can cause a thread to stop execution?

58. The modifier “synchronized” for object locking.

59. Casting questions to see when the code produces a runtime error and when a compile error