SCJP认证套题解析
- 格式:doc
- 大小:100.50 KB
- 文档页数:31
Module2-类、接口以及枚举一、选择题:Question1Given:11.public interface Status{12./*insert code here*/int MY_V ALUE=10;13.}Which three are valid on line12?(Choose three.)A.finalB.staticC.nativeD.publicE.privateF.abstractG.protectedQuestion2Given:10.class Foo{11.static void alpha(){/*more code here*/}12.void beta(){/*more code here*/}13.}Which two are true?(Choose two.)A.Foo.beta()is a valid invocation of beta().B.Foo.alpha()is a valid invocation of alpha().C.Method beta()can directly call method alpha().D.Method alpha()can directly call method beta().Question3Click the Exhibit button.11.class Payload{12.private int weight;13.public Payload(int wt){weight=wt;}14.public Payload(){}15.public void setWeight(mt w){weight=w;}16.public String toString{return Integer.toString(weight);}17.}18.19.public class TestPayload{20.static void changePayload(Payload p){21./*insert code here*/22.}23.24.public static void main(String[]args){25.Payload p=new Payload();26.p.setWeight(1024);27.changePayload(p);28.System.out.println("The value of p is"+p);29.}30.}Which statement,placed at line21,causes the code to print“The value of p is420.”?A.p.setWeight(420);B.p.changePayload(420);C.p=new Payload(420);D.Payload.setWeight(420);E.p=Payload.setWeight(420);F.p=new Payload();p.setWeight(420);Question4Click the Exhibit button.1.public class Item{2.private String desc;3.public String getDescription(){return desc;}4.public void setDescription(String d){desc=d;}5.6.public static void modifyDesc(Item item,String desc){7.item=new Item();8.item.setDescription(desc);9.}10.public static void main(String[]args){11.Item it=new Item();12.it.setDescription("Gobstopper");13.Item it2=new Item();14.it2.setDescription("Fizzylifting");15.modifyDesc(it,"Scrumdiddlyumptious");16.System.out.println(it.getDescription());17.System.out.println(it2.getDescription());18.}19.}What is the outcome of the code?pilation fails.B.GobstopperFizzyliftingC.GobstopperScrumdiddlyumptiousD.ScrumdiddlyumptiousFizzylifltngE.ScrumdiddlyumptiousScrumdiddlyumptiousQuestion5Given:11.public class ItemTest{12.private final in t id;13.public ItemTest(int id){this.id=id;}14.public void updateId(int newId){id=newId;}15.16.public static void main(String[]args){17.ItemTest fa=new ItemTest(42);18.fa.updateId(69);19.System.out.println(fa.id);20.}21.}What is the result?pilation fails.B.An exception is thrown at runtime.C.The attribute id in the Item object remains unchanged.D.The attribute id in the Item object is modified to the new value.E.A new Item object is created with the preferred value in the id attribute.Question6Click the Exhibit button.10.class Inner{11.private int x;12.public void setX(int x){this.x=x;}13.public int getX(){return x;}14.}15.16.class Outer{17.private Inner y;18.public void setY(Inner y){this.y=y;}19.public Inner getY(){return y;}20.}21.22.public class Gamma{23.public static void main(String[]args){24.Outer o=new Outer();25.Inner i=new Inner();26.int n=10;27.i.setX(n);28.o.setY(i);29.//insert code here30.System.out.println(o.getY().getX());31.}32.}Which three code fragments,added individually at line29,produce the output100?(Choose three.)A.n=100;B.i.setX(100);C.o.getY().setX(100);D.i=new Inner();i.setX(100);E.o.setY(i);i=new Inner();i.setX(100);F.i=new Inner();i.setX(100);o.setY(i);Question7Click the Exhibit button.10.class Foo{11.private int x;12.public Foo(int x){this.x=x;}13.public void setX(int x){this.x=x;}14.public int getX(){return x;}15.}16.17.public class Gamma{18.19.static Foo fooBar(Foo foo){20.foo=new Foo(100);21.return foo;22.}23.24.public static void main(String[]args){25.Foo foo=new Foo(300);26.System.out.print(foo.getX()+"-");27.28.Foo fooFoo=fooBar(foo);29.System.out.print(foo.getX()+"-");30.System.out.print(fooFoo.getX()+"-");31.32.foo=fooBar(fooFoo);33.System.out.print(foo.getX()+"-");34.System.out.prmt(fooFoo.getX());35.}36.}What is the output of this program?A.300-100-100-100-100B.300-300-100-100-100C.300-300-300-100-100D.300-300-300-300-100Question8Given:1.interface DoStuff2{2.float getRange(int low,int high);}3.4.interface DoMore{5.float getAvg(int a,int b,int c);}6.7.abstract class DoAbstract implements DoStuff2,DoMore{} 8.9.class DoStuff implements DoStuff2{10.public float getRange(int x,int y){return3.14f;}}11.12.interface DoAll extends DoMore{13.float getAvg(int a,int b,int c,int d);}What is the result?A.The file will compile without error.pilation fails.Only line7contains an error.pilation fails.Only line12contains an error.pilation fails.Only line13contains an error.pilation fails.Only lines7and12contain errors.pilation fails.Only lines7and13contain errors.pilation fails.Lines7,12,and13contain errors. Question9Click the Exhibit button.1.public class A{2.3.private int counter=0;4.5.public static int getInstanceCount(){6.return counter;7.}8.9.public A(){10.counter++;11.}12.13.}Given this code from Class B:25.A a1=new A();26.A a2=new A();27.A a3=new A();28.System.out.printIn(A.getInstanceCount());What is the result?pilation of class A fails.B.Line28prints the value3to System.out.C.Line28prints the value1to System.out.D.A runtime error occurs when line25executes.pilation fails because of an error on line28.Question10Given:1.public class A{2.public void doit(){3.}4.public String doit(){5.return“a”;6.}7.public double doit(int x){8.return1.0;9.}10.}What is the result?A.An exception is thrown at runtime.pilation fails because of an error in line7.pilation fails because of an error in line4.pilation succeeds and no runtime errors with class A occur. Question11Given:10.class Line{11.public static class Point{}12.}13.14.class Triangle{15.//insert code here16.}Which code,inserted at line15,creates an instance of the Point class defined in Line?A.Point p=new Point();B.Line.Point p=new Line.Point();C.The Point class cannot be instatiated at line15.D.Line1=new Line();1.Point p=new1.Point();Question12Click the Exhibit button.10.interface Foo{11.int bar();12.}13.14.public class Beta{15.16.class A implements Foo{17.public int bar(){return1;}18.}19.20.public int fubar(Foo foo){return foo.bar();}21.22.public void testFoo(){23.24.class A implements Foo{25.public int bar(){return2;}26.}27.28.System.out.println(fubar(new A()));29.}30.31.public static void main(String[]argv){32.new Beta().testFoo();33.}34.}Which three statements are true?(Choose three.)pilation fails.B.The code compiles and the output is2.C.If lines16,17and18were removed,compilation would fail.D.If lines24,25and26were removed,compilation would fail.E.If lines16,17and18were removed,the code would compile and the output would be2.F.If lines24,25and26were removed,the code would compile and the output would be1.Question13Given:1.public interface A{2.String DEFAULT_GREETING=“Hello World”;3.public void method1();4.}A programmer wants to create an interface calledB that has A as its parent.Which interface declaration is correct?A.public interface B extends A{}B.public interface B implements A{}C.public interface B instanceOf A{}D.public interface B inheritsFrom A{}Question14Given:1.class TestA{2.public void start(){System.out.println(”TestA”);}3.}4.public class TestB extends TestA{5.public void start(){System.out.println(”TestB”);}6.public static void main(String[]args){7.((TestA)new TestB()).start();8.}9.}What is the result?A.TestAB.TestBpilation fails.D.An exception is thrown at runtime.Question15Given:11.public abstract class Shape{12.int x;13.int y;14.public abstract void draw();15.public void setAnchor(int x,int y){16.this.x=x;17.this.y=y;18.}19.}and a class Circle that extends and fully implements the Shape class. Which is correct?A.Shape s=new Shape();s.setAnchor(10,10);s.draw();B.Circle c=new Shape();c.setAnchor(10,10);c.draw();C.Shape s=new Circle();s.setAnchor(10,10);s.draw();D.Shape s=new Circle();s->setAnchor(10,10);s->draw();E.Circle c=new Circle();c.Shape.setAnchor(10,10);c.Shape.draw();Question16Given:10.abstract public class Employee{11.protected abstract double getSalesAmount();12.public double getCommision(){13.return getSalesAmount()*0.15;14.}15.}16.class Sales extends Employee{17.//insert method here18.}Which two methods,inserted independently at line17,correctly complete the Sales class?(Choose two.)A.double getSalesAmount(){return1230.45;}B.public double getSalesAmount(){return1230.45;}C.private double getSalesAmount(){return1230.45;}D.protected double getSalesAmount(){return1230.45;} Question17Given:10.interface Data{public void load();}11.abstract class Info{public abstract void load();} Which class correctly uses the Data interface and Info class?A.public class Employee extends Info implements Data{ public void load(){/*do something*/}}B.public class Employee implements Info extends Data{ public void load(){/*do something*/}}C.public class Employee extends Info implements Data{ public void load(){/*do something*/}public void Info.load(){/*do something*/}}D.public class Employee implements Info extends Data{ public void Data.load(){/*d something*/}public void load(){/*do something*/}}E.public class Employee implements Info extends Data{ public void load(){/*do something*/}public void Info.load(){/*do something*/}}F.public class Employee extends Info implements Data{ public void Data.load(){/*do something*/}public void Info.load(){/*do something*/}}Question18Given:11.public abstract class Shape{12.private int x;13.private int y;14.public abstract void draw();15.public void setAnchor(int x,int y){16.this.x=x;17.this.y=y;18.}19.}Which two classes use the Shape class correctly?(Choose two.)A.public class Circle implements Shape{private int radius;}B.public abstract class Circle extends Shape{private int radius;}C.public class Circle extends Shape{private int radius;public void draw();}D.public abstract class Circle implements Shape{private int radius;public void draw();}E.public class Circle extends Shape{private int radius;public void draw(){/*code here*/}}F.public abstract class Circle implements Shape{private int radius;public void draw(){/code here*/}}Question19Which two classes correctly implement both the ng.Runnable and the ng.Clonable interfaces?(Choose two.)A.public class Sessionimplements Runnable,Clonable{public void run();public Object clone();}B.public class Sessionextends Runnable,Clonable{public void run(){/do something*/}public Object clone(){/make a copy*/}}C.public class Sessionimplements Runnable,Clonable{public void run(){/do something*/}public Object clone(){/*make a copy*/}}D.public abstract class Sessionimplements Runnable,Clonable{public void run(){/do something*/}public Object clone(){/*make a copy*/}}E.public class Sessionimplements Runnable,implements Clonable{public void run(){/do something*/}public Object clone(){/make a copy*/}}Question20Given:10.class One{11.public One(){System.out.print(1);}12.}13.class Two extends One{14.public Two(){System.out.print(2);}15.}16.class Three extends Two{17.public Three(){System.out.print(3);}18.}19.public class Numbers{20.public static void main(String[]argv){new Three();}21.}What is the result when this code is executed?A.1B.3D.321E.The code rims with no output.Question21Given classes defined in two different files:1.package packageA;2.public class Message{3.String getText(){return“text”;}4.}and:1.package packageB;2.public class XMLMessage extends packageA.Message{3.String getText(){return“<msg>text</msg>”;}4.public static void main(String[]args){5.System.out.println(new XMLMessage().getText());6.}7.}What is the result of executing XMLMessage.main?A.textB.<msg>text</msg>C.An exception is thrown at runtime.pilation fails because of an error in line2of XMLMessage.pilation fails because of an error in line3of XMLMessage. Question22Given:11.interface DeclareStuff{12.public static final int EASY=3;13.void doStuff(int t);}14.public class TestDeclare implements DeclareStuff{15.public static void main(String[]args){16.int x=5;17.new TestDeclare().doStuff(++x);18.}19.void doStuff(int s){20.s+=EASY+++s;21.System.out.println("s"+s);22.}23.}What is the result?A.s14C.s10pilation fails.E.An exception is thrown at runtime.Question2341.Given:10.class One{11.public One foo(){return this;}12.}13.class Two extends One{14.public One foo(){return this;}15.}16.class Three extends Two{17.//insert method here18.}Which two methods,inserted individually,correctly complete the Three class?(Choose two.)A.public void foo(){}B.public int foo(){return3;}C.public Two foo(){return this;}D.public One foo(){return this;}E.public Object foo(){return this;}Question24Given:10.class One{11.void foo(){}12.}13.class Two extends One{14.//insert method here15.}Which three methods,inserted individually at line14,will correctly complete class Two?(Choose three.)A.int foo(){/*more code here*/}B.void foo(){/*more code here*/}C.public void foo(){/*more code here*/}D.private void foo(){/*more code here*/}E.protected void foo(){/*more code here*/}Question25Click the Exhibit button.1.public interface A{2.public void doSomething(String thing);3.}1.public class AImpl implements A{2.public void doSomething(String msg){}3.}1.public class B{2.public A doit(){3.//more code here4.}5.6.public String execute(){7.//more code here8.}9.}1.public class C extends B{2.public AImpl doit(){3.//more code here4.}5.6.public Object execute(){7.//more code here8.}9.}Which statement is true about the classes and interfaces in the exhibit?pilation will succeed for all classes and interfaces.pilation of class C will fail because of an error in line2.pilation of class C will fail because of an error in line6.pilation of class AImpl will fail because of an error in line2. Question26Click the Exhibit button.11.class Person{12.String name="No name";13.public Person(String nm){name=nm;}14.}15.16.class Employee extends Person{17.String empID=“0000”;18.public Employee(String id){empID=id;}19.}20.21.public class EmployeeTest{22.public static void main(String[]args){23.Employee e=new Employee(”4321”);24.System.out.println(e.empID);25.}26.}What is the result?A.4321B.0000C.An exception is thrown at runtime.pilation fails because of an error in line18.Question27Given:1.public class Plant{2.private String name;3.public Plant(String name){=name;}4.public String getName(){return name;}5.}1.public class Tree extends Plant{2.public void growFruit(){}3.public void dropLeaves(){}4.}Which is true?A.The code will compile without changes.B.The code will compile if public Tree(){Plant();}is added to the Tree class.C.The code will compile if public Plant(){Tree();}is added to the Plant class.D.The code will compile if public Plant(){this(”fern”);}is added to the Plant class.E.The code will compile if public Plant(){Plant(”fern”);}is added to the Plant class.Question28Click the Exhibit button.11.public class Bootchy{12.int bootch;13.String snootch;14.15.public Bootchy(){16.this(”snootchy”);17.System.out.print(”first“);18.}19.20.public Bootchy(String snootch){21.this(420,"snootchy");22.System.out.print("second");23.}24.25.public Bootchy(int bootch,String snootch){26.this.bootch=bootch;27.this.snootch=snootch;28.System.out.print("third");29.}30.31.public static void main(String[]args){32.Bootchy b=new Bootchy();33.System.out.print(b.snootch+""+b.bootch);34.}35.}What is the result?A.snootchy420third second firstB.snootchy420first second thirdC.first second third snootchy420D.third second first siiootchy420E.third first second snootchy420F.first second first third snootchy420 Question29Given:1.interface TestA{String toString();}2.public class Test{3.public static void main(String[]args){4.System.out.println(new TestA(){5.public String toString(){return"test";}6.});7.}8.}What is the result?A.testB.nullC.An exception is thrown at runtime.pilation fails because of an error in line1.pilation fails because of an error in line4.pilation fails because of an error in line5.Question30Given:10.interface Foo{int bar();}11.public class Sprite{12.public int fubar(Foo foo){return foo.bar();}13.public void testFoo(){14.fubar(15.//insert code here16.);17.}18.}Which code,inserted at line15,allows the class Sprite to compile?A.Foo{public int bar(){return1;}}B.new Foo{public int bar(){return1;}}C.new Foo(){public int bar(){return1;}}D.new class Foo{public int bar(){return1;}}Question31Given:10.class Line{11.public class Point{public int x,y;}12.public Point getPoint(){return new Point();}13.}14.class Triangle{15.public Triangle(){16.//insert code here17.}18.}Which code,inserted at line16,correctly retrieves a local instance of a Point object?A.Point p=Line.getPoint();B.Line.Point p=Line.getPoint();C.Point p=(new Line()).getPoint();D.Line.Point p=(new Line()).getPoint();Question32A JavaBeans component has the following field:11.private boolean enabled;Which two pairs of method declarations follow the JavaBeans standard for accessing this field?(Choose two.)A.public void setEnabled(boolean enabled)public boolean getEnabled()B.public void setEnabled(boolean enabled)public void isEnabled()C.public void setEnabled(boolean enabled)public boolean isEnabled()D.public boolean setEnabled(boolean enabled)public boolean getEnabled()Question33A programmer is designing a class to encapsulate the information about an inventory item.A JavaBeans component is needed todo this.The Inventoryltem class has private instance variables to store the item information:10.private int itemId;11.private String name;12.private String description;Which method signature follows the JavaBeans naming standards for modifying the itemld instance variable?A.itemID(int itemId)B.update(int itemId)C.setItemId(int itemId)D.mutateItemId(int itemId)E.updateItemID(int itemId)Question34Given:10.class Nav{11.public enum Direction{NORTH,SOUTH,EAST,WEST}12.}13.public class Sprite{14.//insert code here15.}Which code,inserted at line14,allows the Sprite class to compile?A.Direction d=NORTH;B.Nav.Direction d=NORTH;C.Direction d=Direction.NORTH;D.Nav.Direction d=Nav.Direction.NORTH;Question35Given:1.package sun.scjp;2.public enum Color{RED,GREEN,BLUE}1.package sun.beta;2.//insert code here3.public class Beta{4.Color g=GREEN;5.public static void main(String[]argv)6.{System.out.println(GREEN);}7.}The class Beta and the enum Color are in different packages. Which two code fragments,inserted individually at line2of the Beta declaration,will allow this code to compile?(Choose two.)A.import sun.scjp.Color.*;B.import static sun.scjp.Color.*;C.import sun.scjp.Color;import static sun.scjp.Color.*;D.import sun.scjp.*;import static sun.scjp.Color.*;E.import sun.scjp.Color;import static sun.scjp.Color.GREEN; Question36Given:11.public class Ball{12.public enum Color{RED,GREEN,BLUE};13.public void foo(){14.//insert code here15.{System.out.println(c);}16.}17.}Which code inserted at line14causes the foo method to print RED, GREEN,and BLUE?A.for(Color c:Color.values())B.for(Color c=RED;c<=BLUE;c++)C.for(Color c;c.hasNext();c.next())D.for(Color c=Color[0];c<=Color[2];c++)E.for(Color c=Color.RED;c<=Color.BLUE;c++)Question37Given:11.public enum Title{12.MR("Mr."),MRS("Mrs."),MS("Ms.");13.private final String title;14.private Title(String t){title=t;}15.public String format(String last,String first){16.return title+""+first+""+last;17.}18.}19.public static void main(String[]args){20.System.out.println(Title.MR.format("Doe","John"));21.}What is the result?A.Mr.John DoeB.An exception is thrown at runtime.pilation fails because of an error in line12.pilation fails because of an error in line15.pilation fails because of an error in line20.Question38Given:10.public class Fabric11.public enum Color{12.RED(0xff0000),GREEN(0x00ff00),BLUE(0x0000ff);13.private final int rgb;14.Color(int rgb){this.rgb=rgb;}15.public int getRGB(){return rgb;}16.};17.public static void main(String[]argv){18.//insert code here19.}20.}Which two code fragments,inserted independently at line18,allow the Fabric class to compile?(Choose two.)A.Color skyColor=BLUE;B.Color treeColor=Color.GREEN;C.Color purple=new Color(0xff00ff);D.if(RED.getRGB()<BLUE.getRGB()){}E.Color purple=Color.BLUE+Color.RED;F.if(Color.RED.ordinal()<Color.BLUE.ordinal()){} Question39Given:11.public class Test{12.public enum Dogs{collie,harrier,shepherd};13.public static void main(String[]args){14.Dogs myDog=Dogs.shepherd;15.switch(myDog){16.case collie:17.System.out.print("collie");18.case default:19.System.out.print("retriever");20.case harrier:21.System.out.print("harrier");22.}23.}24.}What is the result?A.harrierB.shepherdC.retrieverpilation fails.E.retriever harrierF.An exception is thrown at runtime.Question40Given:12.public class Test{13.public enum Dogs{collie,harrier};14.public static void main(String[]args){15.Dogs myDog=Dogs.collie;16.switch(myDog){17.case collie:18.System.out.print("collie");19.case harrier:20.System.out.print("harrier");21.}22.}23.}What is the result?A.collieB.harrierpilation fails.D.collie harrierE.An exception is thrown at runtime.二、拖拽题:Question1:。
35道SCJP考试真题精解例题1:Choose the three valid identifiers from those listed below.A. IDoLikeTheLongNameClassB. $byteC. constD. _okE. 3_case解答:A, B, D点评:Java中的标示符必须是字母、美元符($)或下划线(_)开头。
关键字与保留字不能作为标示符。
选项C中的const是Java的保留字,所以不能作标示符。
选项E中的3_case以数字开头,违反了Java的规则。
例题2:How can you force garbage collection of an object?A. Garbage collection cannot be forcedB. Call System.gc().C. Call System.gc(), passing in a reference to the object to be garbage collected.D. Call Runtime.gc().E. Set all references to the object to new values(null, for example).解答:A点评:在Java中垃圾收集是不能被强迫立即执行的。
调用System.gc()或Runtime.gc()静态方法不能保证垃圾收集器的立即执行,因为,也许存在着更高优先级的线程。
所以选项B、D不正确。
选项C的错误在于,System.gc()方法是不接受参数的。
选项E中的方法可以使对象在下次垃圾收集器运行时被收集。
例题3:以下是引用片段:Consider the following class:1. class Test(int i) {2. void test(int i) {3. System.out.println(“I am an int.”);4. }5. void test(String s) {6. System.out.println(“I am a string.”);7. }8.9. public static void main(String args[]) {10. Test t=new Test();11. char ch=“y”;12. t.test(ch);13. }14. }Which of the statements below is true?(Choose one.)A. Line 5 will not compile, because void methods cannot be overridden.B. Line 12 will not compile, because there is no version of test() that rakes a char argument.C. The code will compile but will throw an exception at line 12.D. The code will compile and produce the following output: I am an int.E. The code will compile and produce the following output: I am a String.解答:D点评:在第12行,16位长的char型变量ch在编译时会自动转化为一个32位长的int型,并在运行时传给void test(int i)方法。
SCJP 6.0 認證教戰手冊黃彬華著碁峰出版書名:SCJP 6.0 認證教戰手冊作者:黃彬華完全擬真試題 201-244(共 244 題)第201題Given:1.import java.util.*;2.class A{}3.class B extends A{}4.public class Test{5.public static void main(Strang[] args){6.List<A> listA = new LinkedList<A>();7.List<B> listB = new LinkedList<B>();8.List<Obect> listO = new LinkedList<Obect>();9.//insert code here10.}11.public static void m1(List<? extends A> list){}12.public static void m2(List<A> list){}Place a result onto each method call to indicate what would happen if the method call were inserted at line 9. Note: Results can be used more than once.Method Calls Resultm1(listA); m2(listA); Does not compile.m1(listB); m2(listB); Compiles and runs without error.m1(listO); m2(listO); An exception is thrown atruntime.答案:m1(listA);Compiles and runs without error.m1(listB);Compiles and runs without error.m1(listO);Does not compile.m2(listA);Compiles and runs without error.m2(listB);Does not compile.m2(listO);Does not compile.參考:12-3 泛型第202題Given:NumberNames nn = new NumberNames();nn.put("one", 1);System.out.println(nn.getNames());Place the code into position to create a class that maps from Strings to integer values. The result of execution must be [one]. Some options may be used more than once.public class NumberNames{private HashMap< Place here , Place here > map =SCJP 6.0 認證教戰手冊黃彬華著碁峰出版public void put(String name, int value){map.put( Place here , Place here );}public Place here getNames(){return map.keySet();}}CodeSet<int> Set<Integer> HashSetSet<Integer, String> Set<int, String> Set<String, Integer>Set<String, int> Set<String> NumberNamesString Integer int >>() namevalue map答案:public class NumberNames{private HashMap< String , Integer > map =new HashMap< String , Integer>() ;public void put(String name, intvalue){ map.put( name , value );}public Set<String>getNames(){ returnmap.keySet();}}參考:12-5-1 HashMap第203題 Given:5.import java.util.*;6.public class SortOf{7.public static void main(String[] args){8.ArrayList<Integer> a = new ArrayList<Integer>();9. a.add(1); a.add(5); a.add(3);10.Collections.sort(a);11. a.add(2);12.Collections.reverse(a);13.System.out.println(a);14.}15.}What is the result?A.[1, 2, 3, 5]2D.[5, 3, 2, 1]E.[1, 3, 5, 2]pilation fails.G.An exception is thrown at runtime.答案:C參考:12-2-2 Collections 類別、12-4-5 List 集合第204題Given:11.public class Person{12.private name;13.public Person(String name){ = name;15.}16.public int hashCode(){17.return 420;18.}19.}Which statement is true?A.The time to find the value from HashMap with a Person key depends on the size of the map.B.Deleting a Person key from a HashMap will delete all map entries for all keys of type Person.C.Inserting a second Person object into a HashSet will cause the first Person object to be removed asa duplicate.D.The time to determine whether a Person object is contained in a HashSet is constant and does NOTdepend on the size of the map.答案:A參考:12-4-2 equals()、hashCode()方法的改寫第205題Given:12.import java.util.*;13.public class Explorer2{14.public static void main(String[] args){15.TreeSet<Integer> s = new TreeSet<Integer>();16.TreeSet<Integer> subs = new TreeSet<Integer>();17.for(int i=606; i<613; i++)18.if(i%2 == 0) s.add(i);19.subs = (TreeSet)s.subSet(608, true, 611, true);20.s.add(629);21.System.out.println(s + " " + subs);22.}23.}What is the result?pilation fails.B.An exception is thrown at runtime.C.[608, 610, 612, 629] [608, 610]D.[608, 610, 612, 629] [608, 610, 629]E.[606, 608, 610, 612, 629] [608, 610]F.[606, 608, 610, 612, 629] [608, 610, 629]答案:E參考:12-4-4 子集檢視第206題Given:1.public class Drink implements Comparable{2.public String name;3.public int compareTo(Object o){4.return 0;5.}6.}and:20.Drink one = new Drink();21.Drink two = new Drink(); = "Coffee"; = "Tea";24.TreeSet set = new TreeSet();25.set.add(one);26.set.add(two);A programmer iterates over the TreeSet and prints the name of each Drink object.What is the result?A.TeaB.CoffeeC.Coffee Teapilation fails.E.The code runs with no output.F.An exception is thrown at runtime.答案:B參考:12-4-3 SortedSet 集合第207題A programmer must create a generic class MinMax and the type parameter of MinMax must implement Comparable. Which implementation of MinMax will compile?A.class MinMax<E extendsComparable<E>>{ E min = null;E max = null;public MinMax(){}public void put(E value){/* store min or max */}B.class MinMax<E implementsComparable<E>>{ E min = null;E max = null;public MinMax(){}public void put(E value){/* store min or max */}C.class MinMax<E extendsComparable<E>>{ <E> E min = null;<E> E max = null;public MinMax(){}public <E> void put(E value){/* store min or max */}D.class MinMax<E implementsComparable<E>>{ <E> E min = null;<E> E max = null;public MinMax(){}public <E> void put(E value){/* store min or max */}答案:A參考:12-3 泛型第208題Given:1.import java.util.*;2.public class Example{3.public static void main(String[] args){4.//insert code here5.set.add(new Integer(2));6.set.add(new Integer(1)),7.System.out.println(set);8.}9.}Which code, inserted at line 4, guarantees that this program will output [1, 2]?A.Set set = new TreeSet();B.Set set = new HashSet();C.Set set = new SortedSet();D.List set = new SortedList();E.Set set = new LinkedHashSet();答案:A參考:12-4-3 SortedSet 集合第209題Given:1.import java.util.*;2.public class TestSet{3.enum Example{ONE, TWO, THREE}4.public static void main(String[] args){5.Collection coll = new ArrayList();6.coll.add(Example.THREE);7.coll.add(Example.THREE);8.coll.add(Example.THREE);9.coll.add(Example.TWO);10.coll.add(Example.TWO);11.coll.add(Example.ONE)12.Set set = new HashSet(coll);13.}14.}Which statement is true about the set variable on line 12?A.The set variable contains all six elements from the coll collection, and the order is guaranteed tobe preserved.B.The set variable contains only three elements from the coll collection, and the order is guaranteed tobe preserved.C.The set variable contains all six elements from the coll collection, but the order is NOT guaranteed tobe preserved.D.The set variable contains only three elements from the coll collection, but the order is NOTguaranteed to be preserved.答案:D參考:12-4-1 Set 集合、12-4-5 List 集合第210題Given:11.public class Person{12.private String name, comment;13.private int age;14.public Person(String n, int a, String c){ = n; age = a; comment = c;16.}17.public boolean equals(Object o){18.if (!(0 instanceof Person)) return false;19.Person p = (Person)o;20.return age == p.age && name.equals();21.}22.}What is the appropriate definition of the hashCode method in class Person?A.return super.hashCode();B.return name.hashcode() + age * 7;C.return name.hashCode() + comment.hashCode() / 2;D.return name.hashCode() + comment.hashCode() / 2- age * 3;答案:D參考:12-4-2 equals()、hashCode()方法的改寫第211題Given:11.public class Key{12.private long id1,13.private long id2;14.15.//class Key methods16.}A programmer is developing a class Key, that will be used as a key in a standard java.util.HashMap. Which two methods should be overridden to assure that Key works correctly as a key? (Choose two.)A.public int hashCode()B.public void hashCode()C.public int compareTo(Object o)D.public boolean equals(Object o)E.public boolean compareTo(Key k)答案:AD參考:12-4-2 equals()、hashCode()方法的改寫第212題Given:3.import java.util.*;4.public class Hancock{5.//insert code here6.list.add("foo");7.}8.}Which two code fragments, inserted independently at line 5, will compile without warnings? (Choose two.)A.public void addStrings(List list){B.public void addStrings(List<String> list){C.public void addStrings(List<? super String> list){D.public void addStrings(List<? extends String> list){答案:BC參考:12-4-2 equals()、hashCode()方法的改寫第213題Given a class whose instances, when found in a collection of objects, are sorted by using the compareTo() method, which two statements are true? (choose two.)A.The class implements parable.B.The class implements parator.C.The interface used to implement sorting allows this class to define only one sort sequence.D.The interface used to implement sorting allows this class to define many different sort sequences. 答案:AC參考:12-4-3 SortedSet 集合第214題Given:12.import java.util.*;13.public class Explorer3{14.public static void main(String[] args){15.TreeSet<Integer> s = new TreeSet<Integer>();16.TreeSet<Integer> subs = new TreeSet<Integer>();17.for(int i=606; i<613; i++)18.if(i%2 == 0) s.add(i);19.subs = (TreeSet)s.subSet(608, true, 611, true);20.subs.add(629);21.System.out.println(s + " " + subs);22.}23.}What is the result?pilation fails.B.An exception is thrown at runtime.C.[608, 610, 612, 629] [608, 610]D.[608, 610, 612, 629] [608, 610, 629]E.[606, 608, 610, 612, 629] [608, 610]F.[606, 608, 610, 612, 629] [608, 610, 629]答案:B參考:12-4-4 子集檢視第215題Given:1.import java.util.*;2.3.public class LetterASort{4.public static void main(String[] args){5.ArrayList<String> strings = new ArrayList<String>();6.strings.add("aAaA");7.strings.add("AaA");8.strings.add("aAa");9.strings.add("AAaa");10.Collections.sort(strings);11.for(String s : strings){System.out.print(s + " ");}12.}13.}What is the result?pilation fails.B.aAaA aAa AAaa AaAC.AAaa AaA aAa aAaAD.AaA AAaa aAaA aAaE.aAa AaA aAaA AAaaF.An exception is thrown at runtime.答案:C參考:12-2-2 Collections 類別、12-4-5 List 集合第216題Given:1.import java.util.*,2.public class TestGenericConversion{3.public static void main(String[] args){4.List list = new LinkedList();5.list.add("one");6.list.add("two");7.System.out.print(((String)list.get(O)).length());8.}9.}Refactor this class to use generics without changing the code's behavior.1. import java.util.*,2. public class TestGenericConversion{3. public static void main(String[] args){4. Place here5. list.add("one");6. list.add("two");7. Place here8. }9. }CodeList list = new LinkedList();System.out.print(list.get(0).length());List<String> list = new LinkedList<String>();System.out.print(list.get<String>(0).length()); List<String> list = new LinkedList(); System.out.print(<String>list.get(0).length());List list = new LinkedList<String>(); System.out.print((List<String>)list.get(0).length());1.import java.util.*,2.public class TestGenericConversion{3.public static void main(String[] args){4.List<String> list = new LinkedList<String>();5.list.add("one");6.list.add("two");7.System.out.print(list.get(0).length());8.}9.}參考:12-3 泛型SCJP 6.0 認證教戰手冊黃彬華著碁峰出版第217題Place the code into the GenericB class definition to make the class compile successfully.答案:參考:12-3 泛型10SCJP 6.0 認證教戰手冊黃彬華著碁峰出版第218題Place the code elements in position so that the Flags2 class will compile and make appropriate use of the wait/notify mechanism. Note You may reuse code elements.class Flags2{private boolean isReady = false;public Place here void produce(){isReady = true;Place here ;}public Place here voidconsume(){ while(!isReady){try{Placehere ; }catch(Exceptionex){}}isReady = Place here ;}}Code Elementssynchronizedtruefalsewait()volatilesynchronized()notifyAll()synchronize答案:class Flags2{private boolean isReady = false;public synchronized void produce(){isReady = true;notifyAll() ;}public synchronized voidconsume(){ while(!isReady){try{wait() ; }catch(Exception ex){}}isReady = false ;}}參考:13-5 執行緒的互動處理第219題 Given:1.public class Threads2 implements Runnable{114.System.out.println("run.");5.throw new RuntimeException("Problem");6.}7.public static void main(String[] args){8.Thread t = new Thread(new Threads2());9.t.start();10.System.out.println("End of method.");11.}12.}Which two can be results? (Choose two.)ng.RuntimeException: ProblemB.run.ng.RuntimeException: ProblemC.End of method.ng.RuntimeException: ProblemD.End of method.run.ng.RuntimeException: ProblemE.run.ng.RuntimeException: ProblemEnd of method.答案:DE參考:13-2 Java 執行緒與 Thread 類別第220題Which factor or factorsA.It is possible for more than two threads to deadlock at once.B.The JVM implementation guarantees that multiple threads cannot enter into a deadlocked state.C.Deadlocked threads release once their sleep() method's sleep duration has expired.D.Deadlocking can occur only when the wait(), notify() and notifyAll() methods are used incorrectly.E.It is possible for a single-threaded application to deadlock if synchronized blocks are used incorrectly.F.If a piece of code is capable of deadlocking, you cannot eliminate the possibility of deadlocking byinserting invocations of Thread.yield().答案:AF參考:13-5 執行緒的互動處理第221題Given:7.void waitForSignal(){8.Object obj = new Object();9.synchronized(Thread.currentThread()){10.obj.wait();11.obj.notify();12.}13.}Which statement is true?A.This code can throw an InterruptedException.B.This code can throw an IllegalMonitorStateException.C.This code can throw a TimeoutException after ten minutes.D.Reversing the order of obj.wait() and obj.notify() might cause this method to complete normally.E. A call to notify() or notifyAll() from another thread might cause this method to complete normally.F.This code does NOT compile unless "obj.wait()" is replaced with "((Thread) obj).wait()".答案:B參考:13-5 執行緒的互動處理第222題Given:10.public class Starter extends Thread{11.private int x = 2;12.public static void main(String[] args) throws Exception{13.new Starter().makeItSo();14.}15.public Starter(){16.x = 5;17.start();18.}19.public void makeItSo() throws Exception{20.join();21.x = x - 1;22.System.out.println(x);23.}24.public void run(){x *= 2;}25.}What is the output if the main() method is run?A. 4B. 5C.8D.9pilation fails.F.An exception is thrown at runhime.G.It is impossible to determine for certain.答案:D參考:13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第223題Given:11.class PingPong2{12.synchronized void hit(long n){13.for(int i=1; i<3; i++)14.System.out.print(n + "-" + i + " ");15.}16.}17.public dass Tester implements Runnable{18.static PingPong2 pp2 = new PingPong2();19.public static void main(String[] args){20.new Thread(new Tester()).start();21.new Thread(new Tester()).start();22.}23.public void run(){pp2.hit(Thread.currentThread.getId());}24.}Which statement is true?A.The output could be 5-1 6-1 6-2 5-2B.The output could be 6-1 6-2 5-1 5-2C.The output could be 6-1 5-2 6-2 5-1D.The output could be 6-1 6-2 5-1 7-1答案:B參考:13-4 執行緒的同步性與安全性第224題Given:1.public class Threads4{2.public static void main(String[] args){3.new Threads4.go();4.}5.public void go(){6.Runnable r = new Runnable(){7.public void run(){8.System.out.print("foo");9.}10.};11.Thread t = new Thread(r);12.t.start();13.t.start();14.}15.}What is the result?pilation fails.B.An exception is thrown at runtime.C.The code executes normally and prints "foo";D.The code executes normally, but nothing is printed.答案:B參考:13-4 執行緒的同步性與安全性第225題Given:10.Runnable r = new Runnable(){11.public void run(){12.try{13.Thread.sleep(1000);14.}catch(InterruptedException e){15.System.out.println("interrupted");16.}17.System.out.println("ran");18.}19.};20.Thread t = new Thread(r);21.t.start();22.System.out.println("started");23.t.sleep(2000):24.System.out.println("interrupting");25.t.interrupt();26.System.out.println("ended");Assume that sleep(n) executes in exactly n milliseconds. and all other code executes in an insignificant amount of time.Place the fragments in the output area to show the result of running this code.答案:第226題Which two statements are true? (Choose two.)A. It is possible to synchronize static methods.15SCJP 6.0 認證教戰手冊黃彬華著碁峰出版B.When a thread has yielded as a result of yield(), it releases its locks.C.When a thread is sleeping as a result of sleep(), it releases its locks.D.The Object.wait() method can be invoked only from a synchronized context.E.The Thread.sleep() method can be invoked only from a synchronized context.F.When the thread scheduler receives a notify() request, and notifies a thread, that thread immediatelyreleases its lock.答案:AD參考:13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面、13-5 執行緒的互動處理第227題Given:1.public class TestOne implements Runnable{2.public static void main (String[] args)throws Exception{3.Thread t = new Thread(new TestOne());4.t.start();5.System.out.pririt("Started");6.t.join();7.System.out.print("Complete");8.}9.public void run(){10.for(int i=0; i<4; i++){11.System.out.print(i);12.}13.}14.}What can be a result?pilation fails.B.An exception is thrown at runtime.C.The code executes and prints "StartedComplete".D.The code executes and prints "StartedComplete0123".E.The code executes and prints "Started0123Complete".答案:E參考:13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第228題Which three will compile and run without exception? (Choose three.)A.private synchronized Object o;B.void go(){synchronized(){/* code here */}C.public synchronized void go(){/* code here */}D.private synchronized(this) void go(){/* code here */}E.void go(){synchronized(Object.class){/* code here */}F.void go(){Object o = new Object();synchronized(o){/* code here */}答案:CEF參考:13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面、13-5 執行緒的互動處理第229題Given:1.public class TestFive{2.private int x;3.public void foo(){4.int current = x;5.x = current + 1;6.}7.public void go(){8.for(int i=0; i<5; i++){9.new Thread(){10.public void run(){11. foo();12. System.out.print(x + ", ");13.}}.start();14.}}Which two changes, taken together, would guarantee the output: 1, 2, 3, 4, 5, ? (Choose two.)A.move the line 12 print statement into the foo() methodB.change line 7 to public synchronized void go(){C.change the variable declaration on line 2 to private volatile int x;D.wrap the code inside the foo() method with a synchronized(this) blockE.wrap the for loop code inside the go() method with a synchronized block synchronized(this){//for loopcode here}答案:AD參考:8-5-4 匿名內部類別、13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第230題Given that t1 is a reference to a live thread, which is true?A.The Thread.sleep() method can take t1 as an argument.B.The Object.notify() method can take t1 as an argument.C.The Thread.yield() method can take t1 as an argument.D.The Thread.setPriority() method can take t1 as an argument.E.The Object.notify() method arbitrarily chooses which thread to notify.答案:E參考:13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面、13-5 執行緒的互動處理第231題Given:11.Runnable r = new Runnable(){12.public void run(){13.System.out.print("Cat");14.}15.};16.Thread t = new Thread(r){17.public void run(){18.System.outprint("Dog");19.}20.};21.t.start();What is the result?A.CatB.Dogpilation fails.D.The code runs with no output.E.An exception is thrown at runtime.答案:B參考:8-5-4 匿名內部類別、13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第232題Given:1.public class Threads5{2.public static void main(String[] args){3.new Thread(new Runnable(){4.public void run(){5.System.out.print("bar");6.}}).start();7.}8.}What is the result?pilation fails.B.An exception is thrown at runtime.C.The code executes normally and prints "bar".D.The code executes normally, but nothing prints.答案:C參考:8-5-4 匿名內部類別、13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第233題Given:1.public class Threads1{2.int x = 0;3.public class Runner implements Runnable{4.public void run(){S.int current = 0;6.for(int i=0; i<4; i++){7.current = x;8.System.out.print(current + ", ");9.x = current + 2;10.}11.}12.}13.14.public static void main(String[] args){15.new Threads1().go();16.}17.18.public void go(){19.Runnable rl = new Runner();20.new Thread(r1).start();21.new Thread(r1).start();22.}23.}Which two are possible results? (Choose two.)A.0, 2, 4, 4, 6, 8, 10, 6,B.0, 2, 4, 6, 8, 10, 2, 4,C.0, 2, 4, 6, 8, 10, 12, 14,D.0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14,E.0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14,答案:AC參考:8-5-4 匿名內部類別、13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第234題Given:foo and bar are public references available to many other threads, foo refers to a Thread and bar is an Object. The thread foo is currently executing bar.wait().From another thread, what provides the most reliable way to ensure that foo will stop executing wait()?A.foo.notify();B.bar.notify();C.foo.notifyAll();D.Thread.notify();E.bar.notifyAll();F.Object.notify();答案:E參考:13-5 執行緒的互動處理第235題Given:11.public class PingPong implements Runnable{12.synchronized void hit(long n){13.for(int i=1; i<3; i++)14.System.out.print(n + "-" + i + " ");15.}16.public static void main(String[] args){17.new Thread(new PingPong()).start();18.new Thread(new PingPong()).start();19.}20.public void run(){21.hit(Thread.currentThread().getId);22.}23.}Which two statements are true? (Choose two.)A.The output could be 8-1 7-2 8-2 7-1B.The output could be 7-1 7-2 8-1 6-1C.The output could be 8-1 7-1 7-2 8-2D.The output could be 8-1 8-2 7-1 7-2答案:CD參考:13-4 執行緒的同步性與安全性第236題Given:1.class Computation extends Thread{2.3.private int num;4.private boolean isComplete;5.private int result;6.7.public Computation(int num){this.num = num;}8.9.public synchronized void run(){10.result = num * 2;11.isComplete = true;12.notify();13.}14.15.public synchronized int getResult(){16.while(!isComplete){17.try{18.wait();19.}catch(InterruptedException e){}20.}21.return result;22.}23.24.public static void main(String[] args){putation[] computations = new Computation[4];26.for(int i=0; i<computations.length; i++){putations[i] = new Computation(i);putations[i].start();29.}30.for(Computation c : computations)31.System.out.print(c.getResult() + " ");32.}33.}What is the result?A.The code will deadlock.B.The code may run with no output.C.An exception is thrown at runtime.D.The code may run with output "0 6".E.The code may run with output "2 0 6 4".F.The code may run with output "0 2 4 6".答案:F參考:13-4 執行緒的同步性與安全性第237題Place the code elements into the class so that the code compiles and prints "Run. Run. doIt. " in exactly that order. Note that there may be more than one correct solution.class TesTwo extends Thread{public static void main(String[] a) throwsException{ TesTwo t = new TesTwo();t.start();Place herePlace herePlace here}public voidrun(){ System.out.print("Run. ");}public voiddoIt(){ System.out.print("doIt. ");}}Code Elementst.start();t.join();t.pause(10);run();t.run();t.doIt(); doIt();答案:class TesTwo extends Thread{public static void main(String[] a) throws21SCJP 6.0 認證教戰手冊黃彬華著碁峰出版t.run();t.join();t.doIt();}public voidrun(){ System.out.print("Run. ");}public voiddoIt(){ System.out.print("doIt. ");}}參考:13-2 Java 執行緒與 Thread 類別第238題Which two code fragments will execute the method doStuff() in a separate thread? (Choose two.)A.new Thread(){public voidrun(){doStuff();} };B.new Thread(){public voidstart(){doStuff();} };C new Thread(){public voidstart(){doStuff();} }.run();D.new Thread(){public voidrun(){doStuff();} }.start();E.new Thread(newRunnable(){ public voidrun(){doStuff();} }).run();F.new Thread(newRunnable(){ public voidrun(){doStuff();}}).start();答案:DF參考:8-5-4 匿名內部類別、13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第239題 Given:22SCJP 6.0 認證教戰手冊黃彬華著碁峰出版4.System.out.println("sleep");5.}6.}What is the result?pilation fails.B.An exception is thrown at runtime.C.The code executes normally and prints "sleep".D.The code executes normally, but nothing is printed.答案:C參考:13-2 Java 執行緒與 Thread 類別第240題Place a Class on each method that is declared in the class.參考:13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面、13-5 執行緒的互動處理第241題Given:1.public class Threads3 implements Runnable{2.public void run(){3.System.out.print("running");4.}5.public static void main(String[] args){6.Thread t = new Thread(new Threads3());7.t.run();11.}23What is the result?pilation fails.B.An exception is thrown at runtime.C.The code executes and prints "running".D.The code executes and prints "runningrunning".E.The code executes and prints "runningrunningrunning".答案:E參考:13-3 Runnable 介面第242題Given:public classNamedCounter{ privatefinal String name; privateint count;public NamedCounter(String name){ = name;}public String getName(){return name;}public void increment(){count++;}public int getCount(){return count;}public void reset(){count = 0;}Which three changes should be made to adapt this class to be used safely by multiple threads? (Choose three.)A.declare reset() using the synchronized keywordB.declare getName() using the synchronized keywordC.declare getCount() using the synchronized keywordD.declare the constructor using the synchronized keywordE.declare increment() using the synchronized keyword答案:ACE參考:13-3 Runnable 介面第243題Given that Triangle implements Runnable, and:31.void go() throws Exception{32.Thread t = new Thread(new Triangle());33.t.start();34.for(int x=1; x<100000; x++){35.//insert code here36.if(x%100 == 0) System.out.print("g");37.}}38.public void run(){39.try{40.for(int x=1; x<100000; x++){41.//insert the same code here42.if(x%100 == 0) System.out.print("t");43.}24。
SUN认证Java2程序员考试(SCJP) 试题解析(2)SUN认证Java2程序员考试(SCJP) 试题解析(2) which of the following lines of code will pile without error?a.int i=0;if (i) {system.out.println(“hi”);}b.boolean b=true;boolean b2=true;if(b==b2) {system.out.println(“so true”); }c.int i=1;int j=2;if(i==1|| j==2)system.out.println(“ok”);d.int i=1;int j=2;if (i==1 &| j==2)system.out.println(“ok”);解答:b, c点评:选项a错,因为if语句后需要一个boolean类型的表达式。
逻辑操作有^、&、| 和 &&、||,但是“&|”是非法的,所以选项d不正确。
例题5:which two demonstrate a "has a" relationship? (choose two) a. public interface person { }public class employee extends person{ }b. public interface shape { }public interface rectandle extends shape { }c. public interface colorable { }public class shape implements colorable{ }d. public class species{ }public class animal{private species species;}e. interface ponent{ }class container implements ponent{private ponent[] children;}解答:d, e点评:在java中代码重用有两种可能的方式,即组合(“has a”关系)和继承(“is a”关系)。
英文SCJP模拟题200道附答案,因为目录分隔符不正确。
3)执行此代码时,不会在硬盘上创建文件。
4)如果文件已经存在,运行时将引发异常。
5)代码无法编译,因为这不是文件类的有效构造函数。
问题7:关于随机访问文件类,下列哪项陈述是正确的?1)如果使用\模式创建时指定的文件不存在,则会引发IOException。
2)这个类有一个允许从硬盘上删除文件的方法。
3)可以将这个类与DataInputStream类结合使用。
4)当与\模式一起使用时,如果指定的文件不存在,它将在磁盘驱动器上创建。
5)有读和写主词的方法(例如,readInt(),writeInt(),等等)。
考虑下面这段代码,并从下面选择正确的语句。
1.字符串s =新字符串(\ 2 . s . replace(“d”、“q”);3.系统输出打印输入。
1)代码编译失败,在第2行报告了一个错误。
字符串是不可变的,因此replace()方法毫无意义。
2)代码编译正确,并显示文本\ 3)代码编译正确,并显示文本\4)代码编译,但是在执行第2行时会引发异常。
5)代码编译,但是在第3行抛出异常。
Q9下列哪个关键字可以应用到界面的变量或方法中。
1)静态2)私有3)同步4)受保护5)公共Q10真或假。
只有框架可以包含菜单栏或下拉菜单。
1)真2)假。
Q11考虑以下代码,选择正确的语句:1.甲级2.受保护的int方法(){ 3。
} 4。
} 5。
6.B类扩展了A{ 7。
int方法(){ 8。
} 9。
}1)代码无法编译,因为您不能重写一个比其父方法更私有的方法。
2)代码无法编译,因为方法()被声明为受保护的,因此对任何子类都不可用。
3)代码编译正确,但是在运行时抛出一个空指针异常。
4)代码无法编译。
但是,可以通过在第7行前加上访问限定符\来正确编译5)代码无法编译。
但是,可以通过在第7行前加上访问限定符\ Q12真或假来进行正确编译。
可抛出类是Java语言中所有异常的超类。
JAVA认证历年真题:SCJP认证套题解析(3)41、Which of the following statements are legal?A. long l = 4990;B. int i = 4L;C. float f = 1.1;D. double d = 34.4;E. double t = 0.9F.(ade)题目:下面的哪些声明是合法的。
此题的考点是数字的表示法和基本数据类型的类型自动转换,没有小数点的数字被认为是int型数,带有小数点的数被认为是double型的数,其它的使用在数字后面加一个字母表示数据类型,加l或者L是long型,加d或者D是double,加f或者F是float,可以将低精度的数字赋值给高精度的变量,反之则需要进行强制类型转换,例如将int,short,byte赋值给long 型时不需要显式的类型转换,反之,将long型数赋值给byte,short,int型时需要强制转换(int a=(int)123L;)。
42、public class Parent {int change() {…}}class Child extends Parent {}Which methods can be added into class Child?A. public int change(){}B. int chang(int i){}C. private int change(){}D. abstract int chang(){}(ab)题目:哪些方法可被加入类Child。
这个题目的问题在第35题中有详尽的叙述。
需要注意的是答案D的内容,子类可以重写父类的方法并将之声明为抽象方法,但是这引发的问题是类必须声明为抽象类,否则编译不能通过,而且抽象方法不能有方法体,也就是方法声明后面不能带上那两个大括号({}),这些D都不能满足。
43、class Parent {String one, two;public Parent(String a, String b){one = a;two = b;}public void print(){ System.out.println(one); }}public class Child extends Parent {public Child(String a, String b){super(a,b);}public void print(){System.out.println(one + " to " + two);}public static void main(String arg[]){Parent p = new Parent("south", "north");Parent t = new Child("east", "west");p.print();t.print();}}Which of the following is correct?A. Cause error during compilation.B. southeastC. south to northeast to westD. south to northeastE. southeast to west(e)题目:下面的哪些正确。
Java Certification Mock ExamQ. 1Which colour is used to indicate instance methods in the standard "javadoc" format documentation:A. blueB. redC. purpleD. orangeSelect the most appropriate answer.Q. 2What is the correct ordering for the import, class and package declarations when found in a single file?A. package, import, classB. class, import, packageC. import, package, classD. package, class, importSelect the most appropriate answer.Q. 3Which methods can be legally applied to a string object?A. equals(String)B. equals(Object)C. trim()D. round()E. toString()Select all correct answers.Q. 4What is the parameter specification for the public static void main method?A. String args []B. String [] argsC. Strings args []D. String argsSelect all correct answers.Q. 5What does the zeroth element of the string array passed to the public static void main method contain?A. The name of the programB. The number of argumentsC. The first argument if one is presentSelect the most appropriate answer.Q. 6Which of the following are Java keywords?A. gotoB. mallocC. extendsD. 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);}}A. Compiles and runs with no outputB. Compiles and runs printing out The age is 1C. Compiles but generates a runtime errorD. Does not compileE. 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’B. "a"C. new Character(a)D. \000aSelect the most appropriate answer.Q. 9What is the legal range of a byte integral type?A. 0 - 65, 535B. (–128) – 127C. (–32,768) – 32,767D. (–256) – 255Select the most appropriate answer.Q. 10Which of the following is illegal:A. int i = 32;B. float f = 45.0;C. double d = 45.0;Select the most appropriate answer.Q. 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);}}A. Compiles and runs with no outputB. Compiles and runs printing out The age is 1C. Compiles but generates a runtime errorD. Does not compileE. Compiles but generates a compile time errorSelect the most appropriate answer.Q. 12Which of the following are correct?A. 128 >> 1 gives 64B. 128 >>> 1 gives 64C. 128 >> 1 gives –64D. 128 >>> 1 gives –64Select all correct answersQ. 13Which of the following return true?A. "john" == "john"B. "john".equals("john")C. "john" = "john"D. "john".equals(new Button("john"))Select all correct answers.Q. 14Which of the following do not lead to a runtime error?A. "john" + " was " + " here"B. "john" + 3C. 3 + 5D. 5 + 5.5Select all correct answers.Q. 15Which of the following are so called "short circuit" logical operators?A. &B. ||C. &&D. |Select all correct answers.Q. 16Which of the following are acceptable?A. Object o = new Button("A");B. Boolean flag = true;C. Panel p = new Frame();D. Frame f = new Panel();E. Panel p = new Applet();Select all correct answers.Q. 17What is the result of compiling and running the following code:public class Test {static int total = 10;public static void main (String args []) {new Test();}public Test () {System.out.println("In test");System.out.println(this);int temp = this.total;if (temp > 5) {System.out.println(temp);}}}A. The class will not compileB. The compiler reports and error at line 2C. The compiler reports an error at line 9D. The value 10 is one of the elements printed to the standard outputE. The class compiles but generates a runtime errorSelect all correct answers.Q 18Which of the following is correct:A. String temp [] = new String {"j" "a" "z"};B. String temp [] = { "j " " b" "c"};C. String temp = {"a", "b", "c"};D. String temp [] = {"a", "b", "c"};Select the most appropriate answer.Q. 19What is the correct declaration of an abstract method that is intended to be public:A. public abstract void add();B. public abstract void add() {}C. public abstract add();D. public virtual add();Select the most appropriate answer.Q. 20Under what situations do you obtain a default constructor?A. When you define any classB. When the class has no other constructorsC. 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:A. public void Tes t() {…}B. public Test() {…}C. public static Test() {…}D. public static void Test() {…}Select the most appropriate answer.Q. 22Which of the following are acceptable to the Java compiler:A. if (2 == 3) System.out.println("Hi");B. if (2 = 3) System.out.println("Hi");C. if (true) System.out.println("Hi");D. if (2 != 3) System.out.println("Hi");E. if (aString.equals("hello")) System.out.println("Hi");Select all correct answers.Q. 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:A. throw ExceptionB. throws ExceptionC. new ExceptionD. 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");}A. Prints out: Exception FinallyB. Prints out: FinallyC. Prints out: ExceptionD. 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) {…}A. voidB. intC. Can be anythingSelect the most appropriate answer.Q.26Which of the following statements is correct for a method which is overriding the following method:public void add(int a) {…}A. the overriding method must return voidB. the overriding method must return intC. the overriding method can return whatever it likesSelect the most appropriate answer.Q. 27Given the following classes defined in separate files:class Vehicle {public void drive() {System.out.println("Vehicle: drive");}}class Car extends Vehicle {public void drive() {System.out.println("Car: drive");}}public class Test {public static void main (String args []) {Vehicle v;Car c;v = new Vehicle();c = new Car();v.drive();c.drive();v = c;v.drive();}}What will be the effect of compiling and running this class Test?A. Generates a Compiler error on the statement v= c;B. Generates runtime error on the statement v= c;C. Prints out:Vehicle: driveCar: driveCar: driveD. Prints 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?A. AnywhereB. The first statement in the constructorC. The last statement in the constructorD. 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?A. All static variablesB. All final variablesC. All instance variablesD. Only final instance variablesE. Only final static variablesSelect all correct answers.Q. 30What class must an inner class extend:A. The top level classB. The Object classC. Any class or interfaceD. 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:1. public class Test {2. public static void main (String args []) {3. Employee e = new Employee("Bob", 48);4. e.calculatePay();5. System.out.println(e.printDetails());6. e = null;7. e = new Employee("Denise", 36);8. e.calculatePay();9. System.out.println(e.printDetails());10. }11. }A. Line 10B. Line 11C. Line 7D. Line 8E. 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?A. RunnableB. RunC. ThreadableD. ThreadE. ExecutableSelect the most appropriate answer.Q. 33What is the name of the method used to schedule a thread for execution?A. init();B. start();C. run();D. resume();E. sleep();Select the most appropriate answer.Q. 34Which methods may cause a thread to stop executing?A. sleep();B. stop();C. yield();D. wait();E. notify();F. notifyAll()G. synchronized()Select all correct answers.Q. 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:A. drawLine(int, int, int, int)B. drawImage(Image, int, int, ImageObserver)C. drawString(String, int, int)D. add(Component);E. setVisible(boolean);F. setLayout(Object);Select all correct answers.Q. 37Which of the following layout managers honours the preferred size of a component:A. CardLayoutB. FlowLayoutC. BorderLayoutD. 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;}System.out.println(i * j);}}}}A. Generate a runtime errorB. Throw an ArrayIndexOutOfBoundsExceptionC. Print the values: 1, 2, 2, 4D. Produces no outputSelect the most appropriate answer.Q. 39What is the effect of issuing a wait() method on an objectA. If a notify() method has already been sent to that object then it has no effectB. The object issuing the call to wait() will halt until another object sends a notify() or notifyAll() methodC. An exception will be raisedD. 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:A. setLayout(aLayoutManager);B. addLayout(aLayoutManager);C. layout(aLayoutManager);D. setLayoutManager(aLayoutManager);Select all correct answers.Q. 41Using a FlowLayout manager, which is the correct way to add elements to a container:A. add(component);B. add("Center", component);C. add(x, y, component);D. set(component);Select the most appropriate answer.Q. 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?A. FocusListenerB. ComponentListenerC. WindowListenerD. ActionListenerE. ItemListenerSelect the most appropriate answer.Q. 43Which of the following, are valid return types, for listener methods:A. booleanB. the type of event handledC. voidD. 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?A. addListener(*);B. addActionListener(*);C. addButtonListener(*);D. setListener(*);Select the most appropriate answer.Q. 45In order to cause the paint(Graphics) method to execute, which of the following is the mostappropriate method to call:A. paint()B. repaint()C. paint(Graphics)D. update(Graphics)E. 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: A. tags?A. line 1, 2, 3B. line 2, 5, 6, 7C. line 3, 4, 5D. line 8, 9, 10E. line 8, 9Select all correct answers.Q. 59Which of the following is a legal way to construct a RandomAccessFile:A. RandomAccessFile("data", "r");B. RandomAccessFile("r", "data");C. RandomAccessFile("data", "read");D. RandomAccessFile("read", "data");Select the most appropriate answer.Q. 60Carefully examine the following code:public class StaticTest {static {System.out.println("Hi there");}public void print() {System.out.println("Hello");}public static void main(String args []) {StaticTest st1 = new StaticTest();st1.print();StaticTest st2 = new StaticTest();st2.print();}}When will the string "Hi there" be printed?A. Never.B. Each time a new instance is created.C. Once when the class is first loaded into the Java virtual machine.D. Only when the static method is called explicitly.Select the most appropriate answer.Q. 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");}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;}}It is accessed form the following HTML page: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. B2. A3. A, B, C, E4. A, B5. C6. A, C7. D8. A9. 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. A41. 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。
一些SCJP考试题含答案Leading the way in IT testing and certification tools,QUESTION NO: 92 Given:1. String foo = “blue”;2. Boolean[]bar = new Boolean [1];3. if (bar[0]) {4. foo = “green”;5. }What is the result?A. Foo has the value of “”B. Foo has the value of null.C. Foo has the value of “blue”D. Foo has the value of “green”E. An exception is thrown.F. The code will not compile.Answer: FQUESTION NO: 93Exhibit:1. public class X {2. public static void main (String[]args) {3. String s1 = new String (“true”);4. Boolean b1 = new Boolean (true);5. if (s2.equals(b1)) {6. System.out.printIn(“Equal”);7. }8. }9. }What is the result?A. The program runs and prints nothing.B. The program runs and prints “Equal”C. An error at line 5 causes compilation to fail.D. The program runs but aborts with an exception.Answer: AQUESTION NO: 94Given:1. public class Foo {2. public static void main (String []args) {3. int i = 1;4. int j = i++;5. if ((i>++j) && (i++ ==j)) {6. i +=j;7. }9. }What is the final value of i?A. 1B. 2C. 3D. 4E. 5Answer: BQUESTION NO: 95Exhibit:1. public class X {2. public static void main (String[]args) {3. string s = new string (“Hello”);4. modify(s);5. System.out.printIn(s);6. }7.8. public static void modify (String s) {9. s += “world!”;10. }11. }What is the result?E. The program runs and prints “Hello”F. An error causes compilation to fail.G. The program runs and prints “Hello world!”H. The program runs but aborts with an exception. Answer: AQUESTION NO: 96Which two are equivalent? (Choose Two)A. 16>4B. 16/2C. 16*4D. 16>>2E. 16/2^2F. 16>>>2Answer: D, EQUESTION NO: 97Exhibit:1. public class X {2. public static void main (String[]args) {3. int [] a = new int [1]4. modify(a);5. System.out.printIn(a[0]);7.8. public static void modify (int[] a) {9. a[0] ++;10. }11. }What is the result?A. The program runs and prints “0”B. The program runs and prints “1”C. The program runs but aborts with an exception.D. An error “possible undefined variable” at line 4 causes compilation to fail.E. An error “possible undefined variable” at line 9 causes compilation to fail. Answer: BQUESTION NO: 98Given:13. public class Foo {14. public static void main (String [] args) {15. StringBuffer a = new StringBuffer (“A”);16. StringBuffer b = new StringBuffer (“B”);17. operate (a,b);18. system.out.printIn,a + “,” +b-;19. )20. static void operate (StringBuffer x, StringBuffer y) {21. y.append {x};22. y = x;23. )24. }What is the result?A. The code compiles and prints “A,B”.B. The code compiles and prints “A, BA”.C. The code compiles and prints “AB, B”.D. The code compiles and prints “AB, AB”.E. The code compiles and prints “BA, BA”.F. The code does not compile because “+” cannot be overloaded for stringBuffer. Answer: BQUESTION NO: 99Given:1. public class X {2. public static void main (String[] args) {3. byte b = 127;4. byte c = 126;5. byte d = b + c;6. }7. }Which statement is true?A. Compilation succeeds and d takes the value 253.B. Line 5 contains an error that prevents compilation.C. Line 5 throws an exception indicating “Out of range”D. Line 3 and 4 contain error that prevent compilation.E. The compilation succeeds and d takes the value of 1.Answer: BQUESTION NO: 100Given:1. public class WhileFoo {2. public static void main (String []args) {3. int x= 1, y = 6;4. while (y--) {x--;}5. system.out.printIn(“x=” + x “y =” + y);6. }7. }What is the result?A. The output is x = 6 y = 0B. The output is x = 7 y = 0C. The output is x = 6 y = -1D. The output is x = 7 y = -1E. Compilation will fail.Answer: EQUESTION NO: 101Which statement is true?A. The Error class is a untimeException.B. No exceptions are subclasses of Error.C. Any statement that may throw an Error must be enclosed in a try block.D. Any statement that may throw an Exception must be enclosed in a try block.E. Any statement that may thro a runtimeException must be enclosed in a try block. Answer: DQUESTION NO: 102Exhibit:1. int I=1, j=02.3. switch(i) {4. case 2:5. j+=6;6.7. case 4:8. j+=1;9.10. default:11. j +=2;12.13. case 0:14. j +=4;15. }16.What is the value of j at line 16?A. 0B. 1C. 2D. 4E. 6Answer: AEQUESTION NO: 103Given:1. switch (i) {2. default:3. System.out.printIn(“Hello”);4. )What is the acceptable type for the variable i?A. ByteB. LongC. FloatD. DoubleE. ObjectF. A and BG. C and DAnswer: AQUESTION NO: 104You need to store elements in a collection that guarantees that no duplicates are stored. Which twointerfaces provide that capability? (Choose Two)A. Java.util.MapB. Java.util.SetC. Java.util.ListD. Java.util.StoredSetE. Java.util.StoredMapF. Java.util.CollectionAnswer: B, DQUESTION NO: 105Which statement is true for the class java.util.ArrayList?A. The elements in the collection are ordered.B. The collection is guaranteed to be immutable.C. The elements in the collection are guaranteed to be unique.D. The elements in the collection are accessed using a unique key.E. The elements in the collections are guaranteed to be synchronized.Answer: AQUESTION NO: 106Exhibit:1. public class X implements Runnable(2. private int x;3. private int y;4.5. public static void main(String[]args)6. X that = new X();7. (new Thread(that)).start();8. (new Thread(that)).start();9. )10.11. public void run() (12. for (;;) (13. x++;14. y++;15. System.out.printIn(“x=” + x + “, y = ” + y);16. )17. )18. )What is the result?A. Errors at lines 7 and 8 cause compilation to fail.B. The program prints pairs of values for x and y that might not always be the same on the same line(for example, “x=2, y=1”).C. The program prints pairs of values for x and y that are always the same on the same line (for example, “x=1, y=1”.In addition, each value appears twice (for example, “x=1, y=1” followed by “x=1, y=1”).D. The program prints pairs of values for x and y that are always the same on the same line (for example, “x=1, y=1”. In addition, each value appears only for once (for example, “x=1, y=1”followed by “x=2, y=2”).Answer: DQUESTION NO: 107Given:1. public class SyncTest {2. private int x;3. private int y;4. public synchronized void setX (int i) (x=1;)5. public synchronized void setY (int i) (y=1;)6. public synchronized void setXY(int 1)(set X(i); setY(i);)7. public synchronized Boolean check() (return x !=y;)8. )Under which conditions will check () return true when called from a different class?A. Check() can never return true.B. Check() can return true when setXY is called by multiple threads.C. Check() can return true when multiple threads call setX and setY separately.D. Check() can only return true if SyncTest is changed to allow x and y to be set separately. Answer: AQUESTION NO: 108Which is a method of the MouseMotionListener interface?A. Public void mouseDragged(MouseEvent)B. Public boolean mouseDragged(MouseEvent)C. Public void mouseDragged(MouseMotionEvent)D. Public boolean MouseDragged(MouseMotionEvent)E. Public boolean mouseDragged(MouseMotionEvent)Answer: AQUESTION NO: 109Given:1. String foo = “base”;2. foo.substring(0,3);3. foo.concat(“ket”);4. foo += “ball”;5.Type the value of foo at line 8.Answer: BASEBALLQUESTION NO 110Given:1. public class Test {2. public static void leftshift(int i, int j) {3. i<<=j;4. }5. public static void main(String args[]) {6. int i = 4, j = 2;7. leftshift(i, j);8. System.out.printIn(i);9. }10. }What is the result?A. 2B. 4C. 8D. 16E. The code will not compile.Answer: BQUESTION NO 111Given:1. public class Foo {2. private int val;3. public foo(int v) (val = v;) }4. public static void main (String [] args) {5. Foo a = new Foo (10);6. Foo b = new Foo (10);7. Foo c = a;8. int d = 10;9. double e = 10.0;10. }11. }Which three logical expression evaluate to true? (Choose Three)A. (a ==c)B. (d ==e)C. (b ==d)D. (a ==b)E. (b ==c)F. (d ==10.0)Answer: A, B, FQUESTION NO 112Exhibit:1. public class X {2. private static int a;3.5. public static void main (String[] args) {6. modify (a);7. }8.9. public static void modify (int a) {10. a++;11. }12. }What is the result?A. The program runs and prints “0”B. The program runs and prints “1”C. The program runs but aborts with an exception.D. En error “possible undefined variable” at line 5 causes compilation to fail.F. En error “possible undefined variable” at line 10 causes compilation to fail. Answer: AQUESTION NO 113Exhibit:1. public class Test {2. public static void replaceJ(string text) {3. text.replace (‘j’, ‘l’);4. }5.6. public static void main(String args[]) {7. string text = new String (“java”)8. replaceJ(text);9. system.out.printIn(text);10. }11. }What is the result?A. The program prints “lava”B. The program prints “java”C. An error at line 7 causes compilation to fail.D. Compilation succeeds but the program throws an exception. Answer: BQUESTION NO 114Which two are equivalent? (Choose Two)A. 3/2B. 3<2C. 3*4D. 3<<2E. 3*2^2F. 3<<<2Answer: C, DQUESTION NO 115What is the numerical range of a char?A. 0 . . . 32767B. 0 . . . 65535C. ?256 . . . 255D. ?32768 . . . 32767E. Range is platform dependent.Answer: BQUESTION NO 116Given:1. public class Test {2. public static void main (String []args) {3. unsigned byte b = 0;4. b--;5.6. }7. }What is the value of b at line 5?A. -1B. 255C. 127D. Compilation will fail.E. Compilation will succeed but the program will throw an exception at line 4.Answer: DQUESTION NO 117Given:1. public class Foo {2. public void main (String [] args) {3. system.out.printIn(“Hello World.”);4. }5. }What is the result?A. An exception is thrown.B. The code does no compile.C. “Hello World.” Is printed to the terminal.D. The program exits without printing anything.Answer: AQUESTION NO 118Given:1. //point X2. public class foo (3. public static void main (String[]args) throws Exception {4. java.io.printWriter out = new java.io.PrintWriter (5. new java.io.outputStreamWriter (System.out), true;6. out.printIn(“Hello”);7. }8. }Which statement at PointX on line 1 allows this code to compile and run?A. Import java.io.*;B. Include java.io.*;C. Import java.io.PrintWriter;D. Include java.io.PrintWriter;E. No statement is needed.Answer: EQUESTION NO 119Which will declare a method that is available to all members of the same package and can be referencedwithout an instance of the class?A. Abstract public void methoda();B. Public abstract double methoda();C. Static void methoda(double d1){}D. Public native double methoda() {}E. Protected void methoda(double d1) {}Answer: CQUESTION NO 120Which type of event indicates a key pressed on a ponent?A. KeyEventB. KeyDownEventC. KeyPressEventD. KeyTypedEventE. KeyPressedEventAnswer: AQUESTION NO 121Exhibit:1. import java.awt.*;2.3. public class X extends Frame {4. public static void main (String [] args) {5. X x = new X();6. x.pack();7. x.setVisible(true);8. }9.10. public X() {11. setLayout (new BordrLayout());12. Panel p = new Panel ();13. add(p, BorderLayout.NORTH);14. Button b = new Button (“North”);15. p.add(b):16. Button b = new Button (“South”);17. add(b1, BorderLayout.SOUTH):18. }19. }Which two statements are true? (Choose Two)A. The buttons labeled “North” and “South” will have the s ame width.B. The buttons labeled “North” and “South” will have the same height.C. The height of the button labeled “North” can very if the Frame is resized.D. The height of the button labeled “South” can very if the Frame is resized.E. The width of the button labeled “North” is constant even if the Frame is resized.F. The width of the button labeled “South” is constant even if the Frame is resized. Answer: B, EQUESTION NO 122How can you create a listener class that receives events when the mouse is moved?A. By extending MouseListener.B. By implementing MouseListener.C. By extending MouseMotionListener.D. By implementing MouseMotionListener.E. Either by extending MouseMotionListener or extending MouseListener.F. Either by implementing MouseMotion Listener or implementing MouseListener.Answer: DQUESTION NO 123Which statement is true?A. A grid bag layout can position components such that they span multiple rows and/or columns.B. The “North” region of a border layout is the proper place to locat e a menuBar component in a Frame.C. Components in a grid bag layout may either resize with their cell, or remain centered in that cell attheir preferred size.D. A border layout can be used to position a component that should maintain a constant size evenwhen the container is resized.Answer: AQUESTION NO 124You want a class to have access to members of another class in the same package. Which is the mostrestrictive access modifier that will accomplish that will accomplish this objective?A. PublicB. PrivateC. ProtectedD. TransientE. No access modifier is required.Answer: EQUESTION NO 125Which two statements are true regarding the creation of a default constructor? (Choose Two)A. The default constructor initializes method variables.B. The default constructor invokes the no-parameter constructor of the superclass.C. The default constructor initializes the instance variables declared in the class.D. If a class lacks a no-parameter constructor,, but has other constructors, the compiler creates a default constructor.E. The compiler creates a default constructor only when there are no other constructors for the class.Answer: C, EQUESTION NO 126Given:1. public class OuterClass {2. private double d1 1.0;3. //insert code here4. }You need to insert an inner class declaration at line2. Which two inner class declarations are valid?(Choose Two)A. static class InnerOne {public double methoda() {return d1;}}B. static class InnerOne {static double methoda() {return d1;}}C. private class InnerOne {public double methoda() {return d1;}}D. protected class InnerOne {static double methoda() {return d1;}}E. public abstract class InnerOne {public abstract double methoda();}Answer: C, EQUESTION NO 127Which two declarations prevent the overriding of a method? (Choose Two)A. Final void methoda() {}B. Void final methoda() {}C. Static void methoda() {}D. Static final void methoda() {}E. Final abstract void methoda() {}Answer: A, DQUESTION NO 128Given:1. public class Test {2. public static void main (String args[]) {3. class Foo {4. public int i = 3;5. }6. Object o = (Object) new Foo();7. Foo foo = (Foo)o;8. System.out.printIn(foo. i);9. }10. }What is the result?A. Compilation will fail.B. Compilation will succeed and the progr am will print “3”C. Compilation will succeed but the program will throw a ClassCastException at line 6.D. Compilation will succeed but the program will throw a ClassCastException at line 7. Answer: BQUESTION NO 129Which two create an instance of an array? (Choose Two)A. int[] ia = new int [15];B. float fa = new float [20];C. char*+ ca = “Some String”;D. Object oa = new float[20];E. Int ia [][] = (4, 5, 6) (1, 2, 3)Answer: A, DQUESTION NO 130Given:1. public class ExceptionTest {2. class TestException extends Exception {}3. public void runTest () throws TestException {}4. public void test () /* Point X*/ {5. runTest ();6. }7. }At point X on line 4, which code can be added to make the code compile?A. Throws Exception.B. Catch (Exception e).C. Throws RuntimeException.D. Catch (TestException e).E. No code is necessary.Answer: BQUESTION NO 131Exhibit:1. public class SwitchTest {2. public static void main (String []args) {3. System.out.PrintIn(“value =” +switchIt(4));4. }5. public static int switchIt(int x) {6. int j = 1;7. switch (x) {8. case 1: j++;9. case 2: j++;10. case 3: j++;11. case 4: j++;12. case 5: j++;13. default:j++;14. }15. return j + x;16. }17. }What is the output from line 3?A. Value = 3B. Value = 4C. Value = 5D. Value = 6E. Value = 7F. Value = 8Answer: FQUESTION NO 132Which four types of objects can be thrown using the throw statement? (Choose Four)A. ErrorB. EventC. ObjectD. ExceptionE. ThrowableF. RuntimeExceptionAnswer: A, D, E, FQUESTION NO 133Given:1. public class ForBar {2. public static void main(String []args) {3. int i = 0, j = 5;4. tp: for (;;) {5. i ++;6. for(;;)7. if(i > --j) break tp;8. }9. system.out.printIn(“i = ” + i + “, j = “+ j);10. }11. }What is the result?A. The program runs and prints “i=1, j=0”B. The program runs and prints “i=1, j=4”C. The program runs and prints “i=3, j=4”D. The program runs and prints “i=3, j=0”E. An error at line 4 causes compilation to fail.F. An error at line 7 causes compilation to fail.Answer: AQUESTION NO 134Which two can directly cause a thread to stop executing? (Choose Two)A. Exiting from a synchronized block.B. Calling the wait method on an object.C. Calling the notify method on an object.D. Calling the notifyAll method on an object.E. Calling the setPriority method on a thread object.Answer: B, EQUESTION NO 135Given:1. public class Foo implements Runnable (2. public void run (Thread t) {3. system.out.printIn(“Running.”);4. }5. public static void main (String[] args) {6. new thread (new Foo()).start();7. )8. )What is the result?A. An exception is thrown.B. The program exists without printing anything.C. An error at line 1 causes compilation to fail.D. An error at line 6 causes the compilation to fail.E. “Running” is printed and the program exits. Answer: CQUESTION NO 136Which constructs a DataOutputStream?A. New dataInputStream(“in.txt”);B. New dataInputStream(new file(“in.txt”));C. New dataInputStream(new writer(“in.txt”));D. New dataInputSt ream(new FileWriter(“in.txt”));E. New dataInputStream(new InputStream(“in.txt”));F. New dataInputStream(new FileInputStream(“in.txt”)); Answer: FQUESTION NO 137Which can be used to decode charS for output?A. Java.io.InputStream.B. Java.io.EncodedReader.C. Java.io.InputStreamReader.D. Java.io.InputStreamWriter.E. Java.io.BufferedInputStream.Answer: CQUESTION NO 138Given:1. public class Test {2. public static void main (String [] args) {3. string foo = “blue”;4. string bar = foo;5. foo = “green”;6. System.out.printIn(bar);7. }8. }What is the result?A. An exception is thrown.B. The code will not compile.C. The program prints “null”D. The program prints “blue”E. The program prints “green”Answer: DQUESTION NO 139Which code determines the int value foo closest to a double value bar?A. Int foo = (int) Math.max(bar);B. Int foo = (int) Math.min(bar);C. Int foo = (int) Math.abs(bar);D. Int foo = (int) Math.ceil(bar);E. Int foo = (int) Math.floor(bar);F. Int foo = (int) Math.round(bar);Answer: FQUESTION NO 140Which two demonstrate encapsulation of data? (Choose Two)A. Member data have no access modifiers.B. Member data can be modified directly.C. The access modifier for methods is protected.D. The access modifier to member data is private.E. Methods provide for access and modification of data.Answer: D, EQUESTION NO 141Exhibit:1. class A {2. public String toString () {3. return “4”;4. }5. }6. class B extends A {7. 8. public String toString () {8. return super.toString() + “3”;9. }10. }11. public class Test {12. public static void main(String[]args) {13. System.out.printIn(new B());14. }15. }What is the result?A. Compilation succeeds and 4 is printed.B. Compilation succeeds and 43 is printed.C. An error on line 9 causes compilation to fail.D. An error on line 14 causes compilation to fail.E. Compilation succeeds but an exception is thrown at line 9.Answer: BQUESTION NO 142Which two statements are true? (Choose Two)A. An anonymous inner class can be declared inside of a methodB. An anonymous inner class constructor can take arguments in some situation.C. An anonymous inner class that is a direct subclass that is a direct subclass of Object can implementmultiple interfaces.D. Even if a class Super does not implement any interfaces, it is still possible to define an anonymousinner class that is an immediate subclass of Super that implements a single interface.E. Event if a class Super does not implement any interfaces, it is still possible to define an anonymousinner class that is an immediate subclass of Super that implements multiple interfaces. Answer: A, BQUESTION NO 143Given:1. public class MethodOver {2. private int x, y;3. private float z;4. public void setVar(int a, int b, float c){5. x = a;6. y = b;7. z = c;8. }9. }Which two overload the setVar method? (Choose Two)A. void setVar (int a, int b, float c){x = a;y = b;z = c;}B. public void setVar(int a, float c, int b) {setVar(a, b, c);}C. public void setVar(int a, float c, int b) {this(a, b, c);}D. public void setVar(int a, float b){x = a;z = b;}E. public void setVar(int ax, int by, float cz) {x = ax;y = by;z = cz;}Answer: B, DQUESTION NO 144Which statements about static inner classes are true? (Choose Two)A. A static inner class requires a static initializer.B. A static inner class requires an instance of the enclosing class.C. A static inner class has no reference to an instance of the enclosing class.D. A static inner class has access to the non-static members of the outer class.E. Static members of a static inner class can be referenced using the class name of the static inner class.Answer: C, EQUESTION NO 145Given:1. public class X {2. public object m () {3. object o = new float (3.14F);4. object [] oa = new object [1];5. oa[0]= o;6. o = null;7. oa[0] = null;9. return o;9. }10. }When is the float object created in line 3, eligible for garbage collection?A. Just after line 5.B. Just after line 6.C. Just after line 7.D. Just after line 8(that is, as the method returns).Answer: CQUESTION NO 146Which two interfaces provide the capability to store objects using a key-value pair? (Choose Two)A. Java.util.Map.B. Java.util.Set.C. Java.util.List.D. Java.util.StoredSet.E. Java.util.StoredMap.F. Java.util.Collection.Answer: A, EQUESTION NO 147Which interface does java.util.Hashable implement?A. Java.util.Map.B. Java.util.List.C. Java.util.Hashable.D. Java.util.Collection. Answer: A。
1. Which of the following range of short is correct?A. -27 -- 27-1B. 0 -- 216-1C. ?215 -- 215-1D. ?231 -- 231-1翻译下面哪些是short型的取值范围。
答案C 解析短整型的数据类型的长度是16 bits,有符号。
另外需要说明的是java中所有的整(Integral)数(包括byte,short,int,long)全是有符号的。
2. Which declarations of identifiers are legal?A. $personsB. TwoUsersC. *pointD. thisE. _endline翻译下面哪些是合法的标识符。
答案A,B,E 解析Java的标识符可以以一个Unicode字符,下滑线(_),美元符($)开始,后续字符可以是前面的符号和数字,没有长度限制,大小写敏感,不能是保留字。
3. Which statement of assigning a long type variable to a hexadecimal value is correct?A. long number = 345L;B. long number = 0345;C. long number = 0345L;D. long number = 0x345L翻译哪些是将一个十六进制值赋值给一个long型变量。
答案D 解析十六进制数以0x开头,long型数以L(大小写均可,一般使用大写,因为小写的l和数字1不易区分)。
4.Which of the following fragments might cause errors?A. String s = "Gone with the wind";String t = " good ";String k = s + t;B. String s = "Gone with the wind";String t;t = s[3] + "one";C. String s = "Gone with the wind";String standard = s.toUpperCase();D. String s = "home directory";String t = s - "directory";翻译下面的哪些程序片断可能导致错误。
答案B,D 解析A:String类型可以直接使用+进行连接运算。
B:String是一种Object,而不是简单的字符数组,不能使用下标运算符取其值的某个元素,错误。
C:toUpperCase()方法是String对象的一个方法,作用是将字符串的内容全部转换为大写并返回转换后的结果(String类型)。
D:String类型不能进行减(-)运算,错误。
5. Which are syntactically valid statement at// point x?class Person {private int a;public int change(int m){ return m; }}public class Teacher extends Person {public int b;public static void main(String arg[]){Person p = new Person();Teacher t = new Teacher();int i;// point x}}A. i = m;B. i = b;C. i = p.a;D. i = p.change(30);E. i = t.b.翻译在// point x处的哪些申明在句法上合法的。
答案D,E 解析A:m没有被申明过,不能使用。
B:虽然b是类Teacher的public成员变量,但是在静态方法中不能使用类中的非静态成员。
C:a是类Person的private成员,在类外不能直接引用。
D:change(int m)方法是public方法,并且返回一个int型值,可以通过类的实例变量p引用并赋值给一个int型变量。
E:b是类Teacher的public成员变量,且是int型,可以通过类的实例变量t引用并赋值给一个int型变量。
6. Which layout manager is used when the frame is resized the buttons's position in the Frame might be changed?A. BorderLayoutB. FlowLayoutC. CardLayoutD. GridLayout翻译当Frame的大小被改变时Frame中的按钮的位置可能被改变时使用的哪一个布局管理器。
答案B 解析A:该布局管理器将容器划分为五个部分,容器大小的改变不会影响其中的组件的位置而是影响他们的大小。
B:该布局管理器根据放入其中的组件的最合适大小调整组件的位置,根据组件放入的顺序安排,一行不能容纳时放入下一行,因此容器的大小改变可能改变组件的位置。
C:该布局管理器显示放入该容器的当前页中的组件,一次显示一个,容器大小的改变不能影响其中组件的位置。
D:该布局管理器将容器划分为固定的网格,组件加入后占据一个单元,各组件的相对位置不会因为容器的大小变化而变化,改变的只是组件的大小。
7. Given the following code fragment:1) public void create() {2) Vector myVect;3) myVect = new Vector();4) }Which of the following statements are true?A. The declaration on line 2 does not allocate memory space for the variable myVect.B. The declaration on line 2 allocates memory space for a reference to a Vector object.C. The statement on line 2 creates an object of class Vector.D. The statement on line 3 creates an object of class Vector.E. The statement on line 3 allocates memory space for an object of class Vector翻译给出下面的代码片断。
下面的哪些陈述为true(真)?A. 第二行的声明不会为变量myVect分配内存空间。
B. 第二行的声明分配一个到Vector对象的引用的内存空间。
C. 第二行语句创建一个Vector类对象。
D. 第三行语句创建一个Vector类对象。
E. 第三行语句为一个Vector类对象分配内存空间。
答案A,D,E 解析SL-275中指出:要为一个新对象分配空间必须执行new Xxx()调用,new调用执行以下的操作:1.为新对象分配空间并将其成员初始化为0或者null。
2.执行类体中的初始化。
(例如在类中有一个成员声明int a=10;在第一步后a=0 ,执行到第二步后a=10)3.执行构造函数。
4.变量被分配为一个到内存堆中的新对象的引用。
8. Which of the following answer is correct to express the value 8 in octal number?A. 010B. 0x10C. 08D. 0x8翻译下面的哪些答案可以用以表示八进制值8。
答案A 解析八进制值以0开头,以0x开头的为十六进制值,八进制中不能出现数字8,最大只有7。
9. Which are not Java keywords?A. TRUEB. sizeofC. constD. superE. void翻译哪些不是Java关键字。
答案A,B 解析A:不是,Java中有true,但是这也不是关键字而是字面量(literal)。
B:不是,Java中不需要这个操作符,所有的类型(原始类型)的大小都是固定的。
C、D、E都是,需要说明的是const是java中未被使用的关键字。
10. Which of the following statements are true?A. The equals() method determines if reference values refer to the same object.B. The == operator determines if the contents and type of two separate objects match.C. The equals() method returns true only when the contents of two objects match.D. The class File overrides equals() to return true if the contents and type of two separate obj ects match.翻译下面的哪些叙述为真。
A. equals()方法判定引用值是否指向同一对象。
B. == 操作符判定两个分立的对象的内容和类型是否一致。
C. equals()方法只有在两个对象的内容一致时返回true。
D. 类File重写方法equals()在两个分立的对象的内容和类型一致时返回true。
答案A,D 解析严格来说这个问题的答案是不确定的,因为equals()方法是可以被重载的,但是按照java语言的本意来说:如果没有重写(override)新类的equals(),则该方法和 == 操作符一样在两个变量指向同一对象时返回真,但是java推荐的是使用equals()方法来判断两个对象的内容是否一样,就像String类的equals()方法所做的那样:判定两个String对象的内容是否相同,而==操作符返回true的唯一条件是两个变量指向同一对象。
从这个意义上来说选择给定的答案。
从更严格的意义来说正确答案应该只有d。
11. Which statements about inheritance are true?A. In Java programming language only allows single inheritance.B. In Java programming language allows a class to implement only oneinterface.C. In Java programming language a class cannot extend a class and implementa interface together.D. In Java programming language single inheritance makes code morereliable.翻译下面关于继承的哪些叙述是正确的。