SUN公司SCJP题库
SCJP题库 带达内考点分析②

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:。
Sunjava认证考试真题答案

Sunjava认证考试真题答案Sun java认证考试真题答案SUN认证是给网络设计界建立的一套认证标准,Sun公司推出了Java以及Solaris技术认证方案。
以下是店铺整理的关于Sun java认证考试真题答案,希望大家认真阅读!1. What gets printed when the following programis compiled and run?class Test {public static void main(String args[]) {int i;do {i++;} while (i < 0);System.out.println(i);}}Select 1 correct answer:A. The program does not compile as i is not initialized.B. The program compiles but does not run.C. The program compiles and runs but does not print anything.D. The program prints 0.E. The program prints 1.答案:A:如果没有初始化便使用基本变量类型,会导致编译时异常,程序不能编译。
2. What gets printed when the following programis compiled and run?public class XYZ {public static void main(String args[]) {int i,j,k;for (i = 0; i < 3; i++){for(j=1; j < 4; j++){for(k=2; k<5; k++){if((i == j) && (j==k))System.out.println(i);} } } } }Select 1 correct answer:A. 0B. 1C. 2D. 3E. 4答案:C3. Given the following code :class Base{}public class MyCast extends Base{static boolean b1=false;static int i = -1;static double d = 10.1;public static void main(String argv[]){MyCast m = new MyCast();Base b = new Base();//Here}}Which of the following, if ed at the comment //Herewill allow the code to compile and run without error?Select 2 correct answers:A. b = m;B. m = b;C. d = i;D. b1 = i;解析:A 从子类型到父类型的转换是扩展引用转换,不需要在运行时采取特殊的动作,不会在运行时抛出异常。
SUN认证Java2程序员考试(SCJP) 试题解析(2)

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认证试题及答案

转载对题目和答案谨做参考Q1A method is ...1) an implementation of an abstraction.2) an attribute defining the property of a particular abstraction.3) a category of objects.4) an operation defining the behavior for a particular abstraction.5) a blueprint for making operations.Q2An object is ...1) what classes are instantiated from.2) an instance of a class.3) a blueprint for creating concrete realization of abstractions.4) a reference to an attribute.5) a variable.Q3Which line contains a constructor in this class definition?public class Counter { // (1)int current, step;public Counter(int startValue, int stepValue) { // (2)set(startValue);setStepValue(stepValue);}public int get() { return current; } // (3)public void set(int value) { current = value; } // (4)public void setStepValue(int stepValue) { step = stepValue; } // (5) }1) Code marked with (1) is a constructor2) Code marked with (2) is a constructor3) Code marked with (3) is a constructor4) Code marked with (4) is a constructor5) Code marked with (5) is a ConstructorQ4Given that Thing is a class, how many objects and reference variables are created by the following code?Thing item, stuff;item = new Thing();Thing entity = new Thing();1) One object is created2) Two objects are created3) Three objects are created4) One reference variable is created5) Two reference variables are created6) Three reference variables are created.Q5An instance member…1) is also called a static member2) is always a variable3) is never a method4) belongs to a single instance, not to the class as a whole5) always represents an operationQ6How do objects pass messages in Java?1) They pass messages by modifying each other's member variables2) They pass messages by modifying the static member variables of each other's classes3) They pass messages by calling each other's instance member methods4) They pass messages by calling static member methods of each other's classes.Q7Given the following code, which statements are true?class A {int value1;}class B extends A {int value2;}1) Class A extends class B.2) Class B is the superclass of class A.3) Class A inherits from class B.4) Class B is a subclass of class A.5) Objects of class A have a member variable named value2.Q8If this source code is contained in a file called SmallProg.java, what command should be used to compile it using the JDK?public class SmallProg {public static void main(String args[]) { System.out.println("Good luck!"); }}1) java SmallProg2) avac SmallProg3) java SmallProg.java4) javac SmallProg.java5) java SmallProg mainQ9Given the following class, which statements can be inserted at position 1 without causing the code to fail compilation?public class Q6db8 {int a;int b = 0;static int c;public void m() {int d;int e = 0;// Position 1}}1) a++;2) b++;3) c++;4) d++;5) e++;Q10Which statements are true concerning the effect of the >> and >>> operators?1) For non-negative values of the left operand, the >> and >>> operators will have the same effect.2) The result of (-1 >> 1) is 0.3) The result of (-1 >>> 1) is -1.4) The value returned by >>> will never be negative as long as the value of the right operand is equal to or greater than 1.5) When using the >> operator, the leftmost bit of the bit representation of the resulting value will always be the same bit value as the leftmost bit of the bit representation of the left operand.Q11What is wrong with the following code?class MyException extends Exception {}public class Qb4ab {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();}}1) Since the method foo() does not catch the exception generated by the method baz(), it must declare the RuntimeException in its throws clause.2) A try block cannot be followed by both a catch and a finally block.3) An empty catch block is not allowed.4) A catch block cannot follow a finally block.5) A finally block must always follow one or more catch blocks.Q12What will be written to the standard output when the following program is run?public class Qd803 {public static void main(String args[]) {String word = "restructure";System.out.println(word.substring(2, 3));}}1) est2) es3) str4) st5) sQ13Given 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?CODE BLOCK A:Runnable r = new Runnable() { public void run() {Work.doIt();}};Thread t = new Thread(r);t.start();CODE BLOCK B:Thread t = new Thread() {public void start() {Work.doIt();}};t.start();CODE BLOCK C:Runnable r = new Runnable() { public void run() {Work.doIt();}};r.start();CODE BLOCK D:Thread t = new Thread(new Work()); t.start();CODE BLOCK E:Runnable t = new Runnable() { public void run() {Work.doIt();}};t.run();1) Code block A.2) Code block B.3) Code block C.4) Code block D.5) Code block E.Q14Write 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.Q15public class Q275d {static int a;int b;public Q275d() {int c;c = a;a++;b += c;}public static void main(String args[]) {new Q275d();}}1) The code will fail to compile, since the constructor is trying to access static members.2) The code will fail to compile, since the constructor is trying to use static member variable a before it has been initialized.3) The code will fail to compile, since the constructor is trying to use member variable b before it has been initialized.4) The code will fail to compile, since the constructor is trying to use local variable c before it has been initialized.5) The code will compile and run without any problems.Q16What will be written to the standard output when the following program is run?public class Q63e3 {public static void main(String args[]) {System.out.println(9 ^ 2);}}1) 812) 73) 114) 05) falseQ17Which statements are true concerning the default layout manager for containers in the java.awt package?1) Objects instantiated from Panel do not have a default layout manager.2) Objects instantiated from Panel have FlowLayout as default layout manager.3) Objects instantiated from Applet have BorderLayout as default layout manager.4) Objects instantiated from Dialog have BorderLayout as default layout manager.5) Objects instantiated from Window have the same default layout manager as instances of Applet.Q18Which declarations will allow a class to be started as a standalone program?1) public void main(String args[])2) public void static main(String args[])3) public static main(String[] argv)4) final public static void main(String [] array)5) public static void main(String args[])Q19Under which circumstances will a thread stop?1) The method waitforId() in class MediaTracker is called.2) The run() method that the thread is executing ends.3) The call to the start() method of the Thread object returns.4) The suspend() method is called on the Thread object.5) The wait() method is called on the Thread object.Q20When creating a class that associates a set of keys with a set of values, which of these interfaces is most applicable?1) Collection2) Set3) SortedSet4) MapQ21What does the value returned by the method getID() found in class java.awt.AWTEvent uniquely identify?1) The particular event instance.2) The source of the event.3) The set of events that were triggered by the same action.4) The type of event.5) The type of component from which the event originated.Q22What 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 {Extension() {add(2);}void add(int v) {i += v*2;}}public class Qd073 {public static void main(String args[]) {bogo(new Extension());}static void bogo(Base b) {b.add(8);b.print();}}1) 92) 183) 204) 215) 22Q23Which lines of code are valid declarations of a native method when occurring within the declaration of the following class?public class Qf575 {// insert declaration of a native method here}1) native public void setTemperature(int kelvin);2) private native void setTemperature(int kelvin);3) protected int native getTemperature();4) public abstract native void setTemperature(int kelvin);5) native int setTemperature(int kelvin) {}Q24How does the weighty property of the GridBagConstraints objects used in grid bag layout affect the layout of the components?1) It affects which grid cell the components end up in.2) It affects how the extra vertical space is distributed.3) It affects the alignment of each component.4) It affects whether the components completely fill their allotted display area vertically.Q25Which statements 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 Q4a39 {int a = 1;int b = 1;int c = 1;class Inner {int a = 2;int get() {int c = 3;// insert statement herereturn c;}}Q4a39() {Inner i = new Inner();System.out.println(i.get());}public static void main(String args[]) {new Q4a39();}}1) c = b;2) c = this.a;3) c = this.b;4) c = Q4a39.this.a;5) c = c;Q26Which is the earliest line in the following code after which the object created on the line marked (0) will be a candidate for being garbage collected, assuming no compiler optimizations are done?public class Q76a9 {static String f() {String a = "hello";String b = "bye"; // (0)String c = b + "!"; // (1)String 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)}}1) The line marked (1).2) The line marked (2).3) The line marked (3).4) The line marked (4).5) The line marked (5).Q27Which methods from the String and StringBuffer classes modify the object on which they are called?1) The charAt() method of the String class.2) The toUpperCase() method of the String class.3) The replace() method of the String class.4) The reverse() method of the StringBuffer class.5) The length() method of the StringBuffer class.Q28Which 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 Q3ae4 {public static void main(String args[]) {A x = new A();B y = new B();C z = new C();// insert statement here}}1) x = y;2) z = x;3) y = (B) x;4) z = (C) y;5) y = (A) y;Q29Which of these are keywords in Java?1) default2) NULL3) String4) throws5) longQ30It is desirable that a certain method within a certain class can only be accessed by classes that are defined within the same package as the class of the method. How can such restrictions be enforced?1) Mark the method with the keyword public.2) Mark the method with the keyword protected.3) Mark the method with the keyword private.4) Mark the method with the keyword package.5) Do not mark the method with any accessibility modifiers.Q31Which 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?CODE FRAGMENT A:int[][] tab = {{ 0, 0, 0 },{ 0, 0, 0 }};CODE FRAGMENT B:int tab[][] = new int[4][];for (int i=0; iCODE FRAGMENT C:int tab[][] = {0, 0, 0, 0,0, 0, 0, 0,0, 0, 0, 0,0, 0, 0, 0};CODE FRAGMENT D:int tab[3][2];CODE FRAGMENT E:int[] tab[] = { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0} };1) Code fragment A.2) Code fragment B.3) Code fragment C.4) Code fragment D.5) Code fragment E.Q32What will be the result of attempting to run the following program?public class Qaa75 {public static void main(String args[]) {String[][][] arr = {{ {}, null },{ { "1", "2" }, { "1", null, "3" } },{},{ { "1", null } }};System.out.println(arr.length + arr[1][2].length);}}1) The program will terminate with an ArrayIndexOutOfBoundsException.2) The program will terminate with a NullPointerException.3) 4 will be written to standard output.4) 6 will be written to standard output.5) 7 will be written to standard output.Q33Which 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' };1) (a == "Hello")2) (a == b)3) (a == c)4) a.equals(b)5) a.equals(d)Q34Which 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) {}}1) The code will fail to compile.2) 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.3) Class C has three constructors.4) Objects of class B cannot be constructed.5) At most one of the constructors of each class is called as a result of constructing an object of class C.Q35Given two collection objects referenced by col1 and col2, which of these statements are true?1) The operation col1.retainAll(col2) will not modify the col1 object.2) The operation col1.removeAll(col2) will not modify the col2 object.3) The operation col1.addAll(col2) will return a new collection object,containing elements from both col1 and col2.4) The operation col1.containsAll(Col2) will not modify the col1 object.Q36Which statements concerning the relationships 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;}1) A Bar is a Baz.2) A Foo has a Bar.3) A Baz is a Foo.4) A Foo is a Baz.5) A Baz has a Bar.Q37Which statements concerning the value of a member variable are true, when no explicit assignments have been made?1) The value of an int is undetermined.2) The value of all numeric types is zero.3) The compiler may issue an error if the variable is used before it is initialized.4) The value of a String variable is "" (empty string).5) The value of all object variables is null.Q38Which statements describe guaranteed behavior of the garbage collection and finalization mechanisms?1) Objects are deleted when they can no longer be accessed through any reference.2) The finalize() method will eventually be called on every object.3) The finalize() method will never be called more than once on an object.4) An 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.5) The garbage collector will use a mark and sweep algorithm.Q39Which 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?CODE FRAGMENT A:public static void main(String args[]) {if (args.length != 0)System.out.println(args[args.length-1]);}CODE FRAGMENT B:public static void main(String args[]) {try { System.out.println(args[args.length]); }catch (ArrayIndexOutOfBoundsException e) {}}CODE FRAGMENT C:public static void main(String args[]) {int ix = args.length;String last = args[ix];if (ix != 0) System.out.println(last);}CODE FRAGMENT D:public static void main(String args[]) {int ix = args.length-1;if (ix > 0) System.out.println(args[ix]);}CODE FRAGMENT E:public static void main(String args[]) {try { System.out.println(args[args.length-1]); }catch (NullPointerException e) {}}1) Code fragment A.2) Code fragment B.3) Code fragment C.4) Code fragment D.5) Code fragment E.Q40Which of these statements concerning the collection interfaces are true?1) Set extends Collection.2) All methods defined in Set are also defined in Collection.3) List extends Collection.4) All methods defined in List are also defined in Collection.5) Map extends Collection.Q41What is the name of the method that threads can use to pause their execution until signalled to continue by another thread?Fill in the name of the method (do not include a parameter list).Q42Given 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 {}1) obj instanceof B2) obj instanceof A && ! (obj instanceof C)3) obj instanceof B && ! (obj instanceof C)4) obj instanceof C || obj instanceof D5) (obj instanceof A) && ! (obj instanceof C) && ! (obj instanceof D)Q43What will be written to the standard output when the following program is run?public class Q8499 {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);}}1) 122) 183) 84) 125) 27Q44What will be written to the standard output when the following program is run?public class Qcb90 {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[]) {Qcb90 obj = new Qcb90();obj.f();}}1) 0 0 02) 0 0 13) 0 1 04) 1 0 05) 1 0 1Q45Which 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?1) The rectangle drawn will have a total width of 5 pixels.2) The rectangle drawn will have a total height of 6 pixels.3) The rectangle drawn will have a total width of 10 pixels.4) The rectangle drawn will have a total height of 11 pixels.Q46Given 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 Q1e65 {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);}}1) win.setLayout(new BorderLayout()); win.add(but);2) win.setLayout(new GridLayout(1, 1)); win.add(but);3) win.setLayout(new BorderLayout()); win.add(but, BorderLayout.CENTER);4) win.add(but);5) win.setLayout(new FlowLayout()); win.add(but);Q47Which method implementations will write the given string to a file named "file", using UTF8 encoding?IMPLEMENTATION A:public void write(String msg) throws IOException {FileWriter fw = new FileWriter(new File("file"));fw.write(msg);fw.close();}IMPLEMENTATION B:public void write(String msg) throws IOException {OutputStreamWriter osw =new OutputStreamWriter(new FileOutputStream("file"), "UTF8");osw.write(msg);osw.close();}IMPLEMENTATION C:public void write(String msg) throws IOException { FileWriter fw = new FileWriter(new File("file"));fw.setEncoding("UTF8");fw.write(msg);fw.close();}IMPLEMENTATION D:public void write(String msg) throws IOException { FilterWriter fw = FilterWriter(new FileWriter("file"), "UTF8"); fw.write(msg);fw.close();}IMPLEMENTATION E:public void write(String msg) throws IOException { OutputStreamWriter osw = new OutputStreamWriter(new OutputStream(new File("file")), "UTF8");osw.write(msg);osw.close();}1) Implementation A.2) Implementation B.3) Implementation C.4) Implementation D.5) Implementation E.Q48Which are valid identifiers?1) _class2) $value$3) zer@4) ¥ngstr5) 2muchuqQ49What will be the result of attempting to compile and run the following program?public class Q28fd {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 > i) break l2;if (i == j) {counter++;continue l1;}}counter--;}System.out.println(counter);}}1) The program will fail to compile.2) The program will not terminate normally.3) The program will write 10 to the standard output.4) The program will write 0 to the standard output.5) The program will write 9 to the standard output.Q50Given the following interface definition, which definitions are valid?interface I {void setValue(int val);int getValue();}DEFINITION A:(a) class A extends I {int value;void setValue(int val) { value = val; }int getValue() { return value; }}DEFINITION B:(b) interface B extends I {void increment();}DEFINITION C:(c) abstract class C implements I {int getValue() { return 0; }abstract void increment();}DEFINITION D:(d) interface D implements I {void increment();}DEFINITION E:(e) class E implements I {int value;public void setValue(int val) { value = val; } }1) Definition A.2) Definition B.3) Definition C.4) Definition D.5) Definition E.Q51Which statements concerning the methods notify() and notifyAll() are true?1) Instances of class Thread have a method called notify().2) A call to the method notify() will wake the thread that currently owns the monitor of the object.3) The method notify() is synchronized.4) The method notifyAll() is defined in class Thread.5) 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.Q52Which statements concerning the correlation between the inner and outer instances of non-static inner classes are true?1) Member variables of the outer instance are always accessible to inner instances, regardless of their accessibility modifiers.2) Member variables of the outer instance can never be referred to using only the variable name within the inner instance.3) More than one inner instance can be associated with the same outer instance.4) All variables from the outer instance that should be accessible in the inner instance must be declared final.5) A class that is declared final cannot have any inner classes.Q53What will be the result of attempting to compile and run the following code?public class Q6b0c {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);}}1) The code will fail to compile.2) 0 will be written to the standard output.3) 1 will be written to the standard output.4) 2 will be written to the standard output.5) 3 will be written to the standard output.Q54Which operators will always evaluate all the operands?1) ||2) +3) &&4) ? :5) %Q55Which statements concerning the switch construct are true?1) All switch statements must have a default label.2) There must be exactly one label for each code segment in a switch statement.3) The keyword continue can never occur within the body of a switch statement.4) No case label may follow a default label within a single switch statement.5) A character literal can be used as a value for a case label.Q56Which modifiers and return types would be valid in the declaration of a working main() method for a Java standalone application?1) private2) final3) static4) int5) abstractQ57What will be the appearance of an applet with the following init() method?public void init() {add(new Button("hello"));}1) Nothing appears in the applet.2) A button will cover the whole area of the applet.3) A button will appear in the top left corner of the applet.4) A button will appear, centered in the top region of the applet.5) A button will appear in the center of the applet.Q58Which statements concerning the event model of the AWT are true?1) At most one listener of each type can be registered with a component.2) Mouse motion listeners can be registered on a List instance.3) There exists a class named ContainerEvent in package java.awt.event.4) There exists a class named MouseMotionEvent in package java.awt.event.5) There exists a class named ActionAdapter in package java.awt.event.Q59Which statements are true, given the code new FileOutputStream("data", true) for creating an object of class FileOutputStream?1) FileOutputStream has no constructors matching the given arguments.2) An IOExeception will be thrown if a file named "data" already exists.3) An IOExeception will be thrown if a file named "data" does not already exist.4) If a file named "data" exists, its contents will be reset and overwritten.5) If a file named "data" exists, output will be appended to its current contents.Q60Given the following code, write a line of code that, when inserted at the indicated location, will make theoverriding method in Extension invoke the overridden method in class Base on the current object.class Base {public void print() {System.out.println("base");}}class Extention extends Base {public void print() {System.out.println("extension");// insert line of implementation here}}public class Q294d {public static void main(String args[]) {Extention ext = new Extention();ext.print();}}Fill in a single line of implementation.Q61Given 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?1) Vector filelist = ((Directory) file).getList();2) String[] filelist = file.directory();3) Enumeration filelist = file.contents();4) String[] filelist = file.list();5) Vector filelist = (new Directory(file)).files();Q62What will be written to the standard output when the following program is run?。
Sun-Java程序员认证考试题库(有精力的同学看看)

第一部分基础知识练习目标本章对应于《学生指南》各章的容分别提供了练习题集,包括:●第一章Java入门●第二章数据类型和运算符●第三章流程控制与数组●第四章封装●第五章继承●第六章抽象类与接口●第七章多态●第八章异常●第九章多线程机制●第十章输入输出流●第十一章使用泛型和集合框架●第十二章基于Swing的图形用户界面(GUI)设计●第十三章Java事件驱动编程第一章练习题(Java入门)1.下列哪项不是JDK所包含的容?(选一项)A.Java编程语言B.工具及工具的APIC.Java EE扩展APID.Java平台虚拟机2.下列关于JDK、JRE和JVM的描述。
哪项正确?A.JDK中包含了JRE,JVM中包含了JREB.JRE中包含了JDK,JDK中包含了JVMC.JRE中包含了JDK,JVM中包含了JRED.JDK中包含了JRE,JRE中包含了JVM3.下列哪个工具可以编译java源文件?A.javacB.jdbC.javadocD.junit4.JDK工具javadoc的作用是哪项?A.生成Java文档B.编译Java源文件C.执行Java类文件D.测试Java代码5.以下哪些包是Java标准库中常用的包?(选三项)A.java.langB.javax.servlet .httpC.j ava. ioD.java.sql6.使用JDK工具生成的Java文档的文件格式是?A.XML格式B.自定义格式c.二进制格式D.HTML格式7.以下关于JVM的叙述,哪项正确?(选两项)A.JVM运行于操作系统之上,它依赖于操作系统B.JVM运行于操作系统之上,它与操作系统无关C.JVM支持Java程序运行,它能够直接运行Java字节码文件D.JVM支持Java程序运行,它能够直接运行Java源代码文件8.以下关于支持Java运行平台的叙述,哪项错误?A.Java可在Solaris平台上运行B.Java可在Windows平台上运行C.Java语言与平台无关。
SCJP认证考试题库2

QUESTION 61GIVEN THE EXHIBIT:Which statement is true?A. All of the assert statements are used appropriately.B. Only the assert statement on line 31 is used appropriatelyC. The assert statements on lines 29 and 31 are used appropriatelyD. The assert statements on lines 26 and 29 are used appropriatelyE. The assert statements on lines 29 and 33 are used appropriatelyF. The assert statements on lines 29 ,31and 33 are used appropriatelyG. The assert statements on lines 26,29 and 31 are used appropriately断言应该用在“你认为”你的程序不可能产生错误的地方,而且有没有启用断言,都不会影响程序的正常运行。
断言使用限制:1.不要在public方法中,用断言来检查参数的正确性;2.不要让断言语句去处理一些程序必须的流程。
原因:1.public方法会被别人调用,你不能保证他一定启用断言;如果没有启用,那么用断言来做参数的检查也就没有意义了。
所以不要用断言来检查参数,公共方法的参数一定要用代码执行检查; 2.如果用断言来控制程序执行流程,如果没有启用断言,那么程序就不能正确执行下去。
另外,断言语句不可以有任何边界效应,不要使用断言语句去修改变量和改变方法的返回值,如果这样当启动断言和不启动断言执行的结果会截然不同。
断言的使用时机:1.检查流程的不变性:在if-else switch-case 的预期结果之外可以加上断言做额外的检查。
Sun认证Java程序员考试试题2023年

Sun认证Java程序员考试试题20231.以下哪项不是JDK所包含的内容?(选一项)A.Java编程语言B.工具及工具的APIC.Java EE扩展APID.Java平台虚拟机2.以下关于JDK、JRE和JVM的描述。
哪项正确?A.JDK中包含了JRE,JVM中包含了JREB.JRE中包含了JDK,JDK中包含了JVMC.JRE中包含了JDK,JVM中包含了JRED.JDK中包含了JRE,JRE中包含了JVM3.以下哪个工具可以编译java源文件?A.javacB.jdbC.javadocD.junit4.JDK工具javadoc的作用是哪项?A.生成Java文档B.编译Java源文件C.执行Java类文件D.测试Java代码5.以下哪些包是Java标准库中常用的包?(选三项)ngB.javax.servlet .httpC.j ava. ioD.java.sql6.使用JDK工具生成的Java文档的文件格式是?A.XML格式B.自定义格式c.二进制格式D.HTML格式7.以下关于JVM的表达,哪项正确?(选两项)A.JVM运行于操作系统之上,它依靠于操作系统B.JVM运行于操作系统之上,它与操作系统无关C.JVM支持Java程序运行,它能够直接运行Java字节码文件D.JVM支持Java程序运行,它能够直接运行Java源代码文件8.以下关于支持Java运行平台的表达,哪项错误?A.Java可在Solaris平台上运行B.Java可在Windows平台上运行C.Java语言与平台无关。
Java程序的运行结果依靠于操作系统D.Java语言与平台无关。
Java程序的运行结果与操作系统无关9.以下关于Applet和Java程序之间关系的表达,哪项错误?A. -个Applet就是一段Java程序B.Applet是一种特别的Java程序,它需要运行在Web效劳器上C.Applet是一种特别的Java程序,它需要运行在Web扫瞄器上D.Applet是一种Java SE平台的应用程序10.以下关于Java HotSpot的描述,哪两项错误?(选两项)A.JavaHotSpot是一种热编译技术,在编译Java源程序时会被使用B.Java HotSpot是一种热编译技术,在运行Java代码时会被使用C.Java HotSpot是一种热编译技术,它只对程序的局部字节码进展优化D.Java HotSpot是一种热编译技术,它会对程序的全部字节码进展优化11.环境变量PATH中含有多个路径时,路径和路径之间可以用哪项来隔开?A.:B. ,C.*D:|12.CLASSPATH中的“.”的含义是哪项?A.省略号B.当前名目C.全部名目D.上级名目13.JVM在执行一个Java类时,大致采纳以下过程?A.执行类中的代码一装载类一校验类B.校验类一装载类一执行类中的代码C.装载类一执行类中的代码一校验类D.装载类一校验类一执行类中的.代码14.当运行个Java程序时,传递参数的格式是哪项?A. java类名参数1,参数2B. javac类名参数1参数2C. java类名参数1参数2D. java类名参数1+参数215.以下关于Java文件名的表达,正确的有?(选两项)A.Java源文件的扩展名应为.javaB.Java源文件的文件名应与文件中的类名全都C. Java字节码文件的扩展名应为.javaD. 一个Java源文件中只能包含一个Java类 lC2D3A4ASACD6D7AC8C9B10 A D11 A12 B13 D14 C15 A B【Sun认证Java程序员考试试题2023】。
SUN认证Java2程序员考试(SCJP) 试题解析(2)

SUN认证Java2程序员考试(SCJP) 试题解析(2)SUN认证Java2程序员考试(SCJP) 试题解析(2)SUN认证Java2程序员考试(SCJP) 试题解析(2)whichofthefollowinglinesofcodewillcompilewithouterror?a.inti=0;if(i){system.out.println( hi );}b.booleanb=true;booleanb2=true;if(b==b2){system.out.println(whichtwodemonstratea"hasa"relationship?(choosetwo)a.publicinterfaceperson{}publicclassemployeeextendsperson{}b.publicinterfaceshape{}publicinterfacerectandleextendsshape{}c.publicinterfacecolorable{}publicclassshapeimplementscolorable{}d.publicclassspecies{}publicclassanimal{privatespeciesspecies;}e.interfacecomponent{}classcontainerimplementscomponent{privatecomponent[]children;}解答:d,e点评:在java中代码重用有两种可能的方式,即组合(hasa 关系)和继承(isa 关系)。
hasa 关系是通过定义类的属性的方式实现的;而isa 关系是通过类继承实现的。
本例中选项a、b、c体现了isa 关系;选项d、e体现了hasa 关系。
例题6:whichtwostatementsaretruefortheclassjava.util.treeset?(ch oosetwo)a.theelementsinthecollectionareordered.b.thecollectionisguaranteedtobeimmutable.c.theelementsinthecollectionareguaranteedtobeunique.d.theelementsinthecollectionareaccessedusingauniquekey.e.theelementsinthecollectionareguaranteedtobesynchroni zed解答:a,c点评:treeset类实现了set接口。
SCJP历年考题

Question No: 1Given:1. public class test (2. public static void main (String args[]) {3. int i = 0xFFFFFFF1;4. int j = ~i;5.6. }7. )What is the decimal value of j at line 5?A. 0B. 1C. 14D. –15E. An error at line 3 causes compilation to fail.F. An error at line 4 causes compilation to fail. Answer: DQuestion No: 2Given:Integer i = new Integer (42);Long 1 = new Long (42);Double d = new Double (42.0);Which two expressions evaluate to True? (Choose Two)A. (i ==1)B. (i == d)C. (d == 1)D. (i.equals (d))E. (d.equals (i))F. (i.equals (42))Answer: D, EQuestion No: 3Exhibit :1. public class test (2. private static int j = 0;3.4. private static boolean methodB(int k) (5. j += k;6. return true;6. )7.8. public static void methodA(int i) {9. boolean b:10. b = i < 10 | methodB (4);11. b = i < 10 || methodB (8); 12. )13.14. public static void main (String args[] } (15. methodA (0);16. system.out.printIn(j);17. )18. )What is the result?A. The program prints “0”B. The program prints “4”C. The program prints “8”D. The program prints “12”E. The code does not complete.Answer: BQuestion No: 4Given1. Public class test (2. Public static void main (String args[]) (3. System.out.printIn (6 ^ 3);4. )5. )What is the output?Answer: 5Question No: 5Given:1. public class Foo {2. public static void main (String [] args) {3. StringBuffer a = new StringBuffer (“A”);4. StringBuffer b = new StringBuffer (“B”);5. operate (a,b);6. system.out.printIn{a + “,”+b};7. )8. static void operate (StringBuffer x, StringBuffer y) {9. x.append {y};10. y = x;11. )12. }What is the result?A. The code compiles and prints “A,B”.B. The code compiles and prints “A,A”.C. The code compiles and prints “B,B”.D. The code compiles and prints “AB,B”.E. The code compiles and prints “AB,AB”.F. The code does not compile because “+”cannot beoverloaded for StringBuffer.Answer: DQuestion No: 6Exhibit:1. Public class test (2. Public static void stringReplace (String text) (3. Text = text.replace (‘j' , ‘i');4. )5.6. public static void bufferReplace (StringBuffer text) (7. text = text.append (“C”)8. )9.10. public static void main (String args[]} (11. String textString = new String (“java”);12. StringBuffer text BufferString = new StringBuffer (“java”);13.14. stringReplace (textString);15. BufferReplace (textBuffer);16.17. System.out.printIn (textString + textBuffer);18. }19. )What is the output?Answer: javajavaCQuestion No: 7Exhibit:1. public class test {2. public static void add3 (Integer i) }3. int val = i.intValue ( );4. val += 3;5. i = new Integer (val);6. }7.8. public static void main (String args [ ] ) {9. Integer i = new Integer (0);10. add3 (i);11. system.out.printIn (i.intValue ( ) );12. }13. )What is the result?A. Compilation will fail.B. The program prints “0”.C. The program prints “3”.D. Compilation will succeed but an exception will be thrown at line 3.Answer: BQuestion No: 8Given:1. public class ConstOver {2. public ConstOver (int x, int y, int z) {3. }4. }Which two overload the ConstOver constructor? (Choose Two)A. ConstOver ( ) { }B. Protected int ConstOver ( ) { }C. Private ConstOver (int z, int y, byte x) { }D. Public Object ConstOver (int x, int y, int z) { }E. Public void ConstOver (byte x, byte y, byte z) { } Answer: A, CQuestion No: 9Given:1. public class MethodOver {2. public void setVar (int a, int b, float c) {3. }4. }Which two overload the setVar method? (Choose Two)A. Private void setVar (int a, float c, int b) { }B. Protected void setVar (int a, int b, float c) { }C. Public int setVar (int a, float c, int b) (return a;)D. Public int setVar (int a, int b, float c) (return a;)E. Protected float setVar (int a, int b, float c) (return c;)Answer: A, CQuestion No: 10Given:1. class BaseClass {2. Private float x = 1.0f ;3. protected float getV ar ( ) ( return x;)4. }5. class Subclass extends BaseClass (6. private float x = 2.0f;7. //insert code here8. )Which two are valid examples of method overriding? (Choose Two)A. Float getVar ( ) { return x;}B. Public float getVar ( ) { return x;}C. Float double getVar ( ) { return x;}D. Public float getVar ( ) { return x;}E. Public float getVar (float f ) { return f;} Answer: B, DQuestion No: 11Which two demonstrate an “is a”relationship? (Choose Two)A. public interface Person { }public class Employee extends Person { }B. public interface Shape { }public class Employee extends Shape { }C. public interface Color { }public class Employee extends Color { }D. public class Species { }public class Animal (private Species species;)E. interface Component { }Class Container implements Component (Private Component[ ] children;)Answer: D, EQuestion No: 12Which statement is true?A. An anonymous inner class may be declared as final.B. An anonymous inner class can be declared as private.C. An anonymous inner class can implement multiple interfaces.D. An anonymous inner class can access final variables in any enclosing scope.E. Construction of an instance of a static inner class requires an instance of the enclosing outer class. Answer: DQuestion No 13Given:1. package foo;2.3. public class Outer (4. public static class Inner (5. )6. )Which statement is true?A. An instance of the Inner class can be constructed with “new Outer.Inner ()”B. An instance of the inner class cannot be constructed outside of package foo.C. An instance of the inner class can only be constructed from within the outer class.D. From within the package bar, an instance of the inner class can be constructed with “new inner()”Answer: AQuestion No 14Exhibit:1. public class enclosingone (2. public class insideone{}3. )4. public class inertest(5. public static void main (string[]args)(6. enclosingone eo= new enclosingone ();7. //insert code here8. )9. )Which statement at line 7 constructs an instance of the inner class?A. InsideOnew ei= eo.new InsideOn();B. Eo.InsideOne ei = eo.new InsideOne();C. InsideOne ei = EnclosingOne.new InsideOne();D. EnclosingOne.InsideOne ei = eo.new InsideOne(); Answer: DQuestion No 15Exhibit:1. interface foo {2. int k = 0;3. ]4.5. public class test implements Foo (6. public static void main(String args[]) (7. int i;8. Test test = new test ();9. i= test.k;10.i= Test.k;11.i= Foo.k;12.)13.)14.What is the result?A. Compilation succeeds.B. An error at line 2 causes compilation to fail.C. An error at line 9 causes compilation to fail.D. An error at line 10 causes compilation to fail.E. An error at line 11 causes compilation to fail. Answer: AQuestion No 16Given:1. //point X2. public class foo (3. public static void main (String[]args) throws Exception {4. printWriter out = new PrintWriter (new5. 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.PrintWriter;B. Include java.io.PrintWriter;C. Import java.io.OutputStreamWriter;D. Include java.io.OutputStreamWriter;E. No statement is needed.Answer: AQuestion No 17Which two statements are reserved words in Java? (Choose Two)A. RunB. ImportC. DefaultD. ImplementAnswer: B, CQuestion No 18Which three are valid declarations of a float? (Choose Three)A. Float foo = -1;B. Float foo = 1.0;C. Float foo = 42e1;D. Float foo = 2.02f;E. Float foo = 3.03d;F. Float foo = 0x0123;Answer: A, D, FQuestion No 19Given:8. int index = 1;9. boolean[] test = new Boolean[3]; 10. boolean foo= test [index];What is the result?A. Foo has the value of 0.B. Foo has the value of null.C. Foo has the value of true.D. Foo has the value of false.E. An exception is thrown.F. The code will not compile. Answer: DQuestion No 20Given:1. public class test(2. public static void main(string[]args){3. string foo = args [1];4. string foo = args [2];5. string foo = args [3];6. }7. }And command line invocation:Java Test red green blueWhat is the result?A. Baz has the value of “”B. Baz has the value of nullC. Baz has the value of “red”D. Baz has the value of “blue”E. Bax has the value of “green”F. The code does not compile.G. The program throws an exception. Answer: GQuestion No 21Given:8. int index = 1;9. int [] foo = new int [3];10.int bar = foo [index];11.int baz = bar + index;What is the result?A. Baz has the value of 0B. Baz has the value of 1C. Baz has the value of 2D. An exception is thrown.E. The code will not compile. Answer: BQuestion No 22Given:1. public class foo {2. public static void main (String[]args) {3. String s;4. system.out.printIn (“s=”+ s);5. }6. }What is the result?A. The code compiles and “s=”is printed.B. The code compiles and “s=null”is printed.C. The code does not compile because string s is not initialized.D. The code does not compile because string s cannot be referenced.E. The code compiles, but a NullPointerException is thrown when toString is called.Answer: CQuestion No 23Which will declare a method that forces a subclass to implement it?A. Public double methoda();B. Static void methoda (double d1) {}C. Public native double methoda();D. Abstract public void methoda();E. Protected void methoda (double d1){} Answer: DQuestion No 24You want subclasses in any package to have access to members of a superclass. Which is the most restrictive access modifier that will accomplish this objective?A. PublicB. PrivateC. ProtectedD. TransientE. No access modifier is qualifiedAnswer: CQuestion No 25Given:1. abstract class abstrctIt {2. abstract float getFloat ();3. )4. public class AbstractTest extends AbstractIt {5. private float f1= 1.0f;6. private float getFloat () {return f1;}7. }What is the result? A. Compilation is successful.B. An error on line 6 causes a runtime failure.C. An error at line 6 causes compilation to fail.D. An error at line 2 causes compilation to fail. Answer: CQuestion No 26Exhibit:1. public class test(2. public int aMethod()[3. static int i=0;4. i++;5. return I;6. )7. public static void main (String args[]){8. test test = new test();9. test.aMethod();10.int j = test.aMethod();11.System.out.printIn(j);12.]13.}What is the result?A. Compilation will fail.B. Compilation will succeed and the program will print “0”C. Compilation will succeed and the program will print “1”D. Compilation will succeed and the program will print “2”Answer: DQuestion No 27Given:1. class super {2. public float getNum() {return3.0f;}3. )4.5. public class Sub extends Super {6.7. )Which method, placed at line 6, will cause a compiler error?A. Public float getNum() {return 4.0f; }B. Public void getNum () { }C. Public void getNum (double d) { }D. Public double getNum (float d) {retrun 4.0f; } Answer: BQuestion No 28Which declaration prevents creating a subclass of an outer class?A. Static class FooBar{}B. Private class FooBar{}C. Abstract public class FooBar{}D. Final public class FooBar{}E. Final abstract class FooBar{}Answer: DQuestion No 29Given:1. byte [] arry1, array2[];2. byte array3 [][];3. byte[][] array4;If each array has been initialized, which statement will cause a compiler error?A. Array2 = array1;B. Array2 = array3;C. Array2 = array4;D. Both A and BE. Both A and CF. Both B and CAnswer: FQuestion No 30Exhibit:1. class super (2. public int I = 0;3.4. public super (string text) (5. I = 16. )7. )8.9. public class sub extends super (10. public sub (string text) (11. i= 212. )13.14. public static void main (straing args[]) (15. sub sub = new sub (“Hello”);16. system.out. PrintIn(sub.i);17. )18. )What is the result?A. Compilation will fail.B. Compilation will succeed and the program will print “0”C. Compilation will succeed and the program will print “1”D. Compilation will succeed and the program will print “2”Answer: AQuestion No 31Given:1. public class returnIt (2. returnType methodA(byte x, double y) (3. return (short) x/y * 2;4. )5. )What is the valid returnType for methodA in line 2?A. IntB. ByteC. LongD. ShortE. FloatF. DoubleAnswer: FQuestion No 32Given the ActionEvent, which method allows you to identify the affected component?A. GetClass.B. GetTarget.C. GetSource.D. GetComponent.E. GetTargetComponent.Answer: CQuestion No 33Which is a method of the MouseMotionListener interface?A. Public void mouseMoved(MouseEvent)B. Public boolean mouseMoved(MouseEvent)C. Public void mouseMoved(MouseMotionEvent)D. Public boolean MouseMoved(MouseMotionEvent)E. Public boolean mouseMoved(MouseMotionEvent) Answer: AQuestion No 34Exhibit: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 GridLayout (2,2));12.13. Panel p1 = new panel();14. Add(p1);15. Button b1= new Button (“One”);16. P1.add(b1);17.18. Panel p2 = new panel();19. Add(p2);20. Button b2= new Button (“Two”);21. P2.add(b2);22.23. Button b3= new Button (“Three”);24. add(b3);25.26. Button b4= new Button (“Four”);27. add(b4);28. )29. )Which two statements are true? (Choose Two)A. All the buttons change height if the frame height is resized.B. All the buttons change width if the Frame width is resized.C. The size of the button labeled “One”is constant even if the Frame is resized.D. Both width and height of the button labeled “Three”might change if the Frame is resized. Answer: C, DQuestion No 35You are assigned the task of building a panel containing a TextArea at the top, a label directly below it,and a button directly below the label. If the three components are added directly to the panel. Which layout manager can the panel use to ensure that the TextArea absorbs all of the free vertical space when the panel is resized?A. GridLayout.B. CardLayout.C. FlowLayout.D. BorderLayout.E. GridBagLayout.Answer: EQuestion No 36Which gets the name of the parent directory file “file.txt”?A. String name= File.getParentName(“file.txt”);B. String name= (new File(“file.txt”)).getParent();C. String name = (newFile(“file.txt”)).getParentName();D. String name= (newFile(“file.txt”)).getParentFile();E. Directory dir=(new File(“file.txt”)).getParentDir();String name= dir.getName();Answer: BQuestion No 37Which can be used to encode charS for output?A. Java.io.OutputStream.B. Java.io.OutputStreamWriter.C. Java.io.EncodeOutputStream.D. Java.io.EncodeWriter.E. Java.io.BufferedOutputStream.Answer: BQuestion No 38The file “file.txt”exists on the file system and contsins ASCII text.Given:38. try {39. File f = new File(“file.txt”);40. OutputStream out = new FileOutputStream(f, true);41. }42. catch (IOException) {}What is the result?A. The code does not compile.B. The code runs and no change is made to the file.C. The code runs and sets the length of the file to 0.D. An exception is thrown because the file is not closed.E. The code runs and deletes the file from the file system.Answer: AQuestion No 39Which constructs a DataOutputStream?A. New dataOutputStream(“out.txt”);B. New dataOutputStream(new file(“out.txt”));C. New dataOutputStream(new writer(“out.txt”));D. New dataOutputStream(newFileWriter(“out.txt”));E. New dataOutputStream(newOutputStream(“out.txt”));F. New dataOutputStream(new FileOutputStream(“out.txt”));Answer: FQuestion No 40What writes the text “”to the end of the file “file.txt”?A. OutputStream out= new FileOutputStream (“file.txt”);Out.writeBytes (“/n”);B. OutputStream os= new FileOutputStream (“file.txt”, true);DataOutputStream out = new DataOutputStream(os); out.writeBytes (“/n”);C. OutputStream os= new FileOutputStream (“file.txt”);DataOutputStream out = new DataOutputStream(os); out.writeBytes (“/n”);D. OutputStream os= new OutputStream (“file.txt”, true);DataOutputStream out = new DataOutputStream(os); out.writeBytes (“/n”);Answer: BQuestion No 41Given: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. return oa[0];8. }9. }When is the float object created in line 3, eligible for garbage collection? A. Just after line 5B. Just after line 6C. Just after line 7 (that is, as the method returns)D. Never in this method.Answer: DQuestion No 42Given:3. string foo = “ABCDE”;4. foo.substring(3);5. foo.concat(“XYZ”);6.Type the value of foo at line 6.Answer: ABCDEQuestion No 43Which method is an appropriate way to determine the cosine of 42 degrees?A. Double d = Math.cos(42);B. Double d = Math.cosine(42);C. Double d = Math.cos(Math.toRadians(42));D. Double d = Math.cos(Math.toDegrees(42));E. Double d = Math.cosine(Math.toRadians(42)); Answer: CQuestion No 44You need to store elements in a collection that guarantees that no duplicates are stored and all elementscan be accessed in natural order. Which interface provides that capability?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: DQuestion No 45Which statement is true for the classjava.util.HashSet?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: CQuestion No 46Given:1. public class IfTest (2. public static void main(string[]args) {3. int x = 3;4. int y = 1;5. if (x = y)6. system.out.printIn(“Not equal”);7. else8. system.out.printIn(“Equal”);9. }10. )What is the result?A. The output is “Equal”B. The output in “Not Equal”C. An error at line 5 causes compilation to fall.D. The program executes but does not print a message.Answer: CQuestion No 47Exhibit:1. public class test (2. public static void main(string args[]) {3. int 1= 0;4. while (i) {5. if (i==4) {6. break;7. )8. ++i;9. )10.11. )12. )What is the value of i at line 10?A. 0B. 3C. 4D. 5E. The code will not compile.Answer: EQuestion No 48Given: 3. int i= 1, j= 10 ;4. do (5. if (i++> --j) continue;6. ) while (i<5);After execution, what are the values for I and j?A. i = 6 and j= 5B. i = 5 and j= 5C. i = 6 and j= 4D. i = 5 and j= 6E. i = 6 and j= 6Answer: DQuestion No 49Given:1. switch (i) {2. default:310-025Leading the way in IT testing and certification tools, - 27 -3. System.out.printIn(“Hello”);4. )What are the two acceptable types for the variable i? (Choose Two)A. CharB. ByteC. FloatD. DoubleE. ObjectAnswer: A, BQuestion No 50Given:1. public class foo {2. public static void main (string[]args)3. try {return;}4. finally {system.out.printIn(“Finally”);}5. }6. )What is the result?A. The program runs and prints nothing.B. The program runs and prints “Finally”C. The code compiles, but an exception is thrown at runtime.D. The code will not compile because the catch block is missing.Answer: BQuestion No 51Exhibit:1. import java.io.IOException;2. public class ExceptionTest(3. public static void main (String[]args)4. try (5. methodA();6. ) catch (IOException e) (7. system.out.printIn(“Caught IOException”);8. ) catch (Exception e) (9. system.out.printIn(“Caught Exception”);10. )11. )12. public void methodA () {13. throw new IOException ();14. )15. )What is the result?A. The code will not compile.B. The output is caught exception.C. The output is caught IOException.D. The program executes normally without printing a message.Answer: AQuestion No 52Exhibit:1. public class test {2. public static string output = “”3.4. public static void foo(int i) {5. try {6. if(i= =1) {7. throw new Exception ();8. }9. output += “1”;10. )11. catch(Exception e) {12. output += “2”;13. return;14. )15. finally (16. output += “3”;17. )18. output += “4”;19. )20. 21. public static void main (string args[]) (22. foo(0);23. foo(1);24.25. )26. )What is the value of the variable output at line 24? Answer: 13423Question No 53Given: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 2 causes the compilation to fail.E. “Running”is printed and the program exits. Answer: DQuestion No 54Which statement is true?A. If only one thread is blocked in the wait method of an object, and another thread executes themodify on that same object, then the first thread immediately resumes execution.B. If a thread is blocked in the wait method of an object, and another thread executes the notify method on the same object, it is still possible that the first thread might never resume execution.C. If a thread is blocked in the wait method of an object, and another thread executes the notify method on the same object, then the first thread definitely resumes execution as a direct and sole consequence of the notify call.D. If two threads are blocked in the wait method of one object, and another thread executes the notify method on the same object, then the first thread that executed the wait call first definitely resumes execution as a direct and sole consequence of thenotify call.Answer: BQuestion No 55Which two CANNOT directly cause a thread to stop executing? (Choose Two)A. Calling the yield method.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 start method on another Thread object. Answer: C, DQuestion No 56Which two can be used to create a new Thread? (Choose Two)A. Extend ng.Thread and override the run method.B. Extend ng.Runnable and override the start method.C. Implement ng.thread and implement the run method.D. Implement ng.Runnable and implement the run method.E. Implement ng.Thread and implement the start method.Answer: A, DQuestion No 54Which statement is true?A. If only one thread is blocked in the wait method of an object, and another thread executes themodify on that same object, then the first thread immediately resumes execution.B. If a thread is blocked in the wait method of an object, and another thread executes the notify method on the same object, it is still possible that the first thread might never resume execution.C. If a thread is blocked in the wait method of an object, and another thread executes the notify method on the same object, then the first thread definitely resumes execution as a direct and sole consequence of the notify call.D. If two threads are blocked in the wait method of one object, and another thread executes the notify method on the same object, then the first thread that executed the wait call first definitely resumes notify call.Answer: BQuestion No 55Which two CANNOT directly cause a thread to stop executing? (Choose Two)A. Calling the yield method.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 start method on another Thread object. Answer: C, DQuestion No 56Which two can be used to create a new Thread? (Choose Two)A. Extend ng.Thread and override the run method.B. Extend ng.Runnable and override the start method.C. Implement ng.thread and implement the run method.D. Implement ng.Runnable and implement the run method.E. Implement ng.Thread and implement the start method.Answer: A, DQuestion No 57Given:1. public class SyncTest (2. private int x;3. private int y;4. private synchronized void setX (int i) (x=1;)5. private synchronized void setY (int i) (y=1;)6. public void setXY(int 1)(set X(i); setY(i);)7. public synchronized Boolean check() (returnx !=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.to allow x and y to be set separately.Answer: BQuestion No 58Exhibit:1. class A implements runable (2. int i;3. public void run () (4. try (5. thread.sleep(5000);6. i= 10;7. ) catch(InterruptedException e) {}8. )9. )10.11. public class Test {12. public static void main (string args[]) (13. try (14. A a = new A ();15. Thread t = new Thread (a);16. t.start();17.18. int j= a.i;19.20. ) catch (Exception e) {}21. )22. )Which statement al line 17 will ensure that j=10 at line 19?A. a.wait();B. t.wait();C. t.join();D. t.yield();E. t.notify();F. a.notify();G. t.interrupt();Answer: CQuestion No 59Exhibit: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 synchronized void run( ) (12. for (;;) (13. x++;14. y++;15. System.out.printIn(“x = “+ x + “, y = “+ y);16. )17. )18. )What is the result?A. An error at line 11 causes compilation to fail.B. Errors at lines 7 and 8 cause compilation to fail.C. 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”)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 twice (for example, “x=1, y=1”followed by“x=1, y=1”)E. 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=2s, y=2”)Answer: EQUESTION NO: 60Which two CANNOT directly cause a thread to stop executing? (Choose Two)A. Existing from a synchronized block.B. Calling the wait method on an object.C. Calling notify method on an object.D. Calling read method on an InputStream object.E. Calling the SetPriority method on a Thread object. Answer: A, CQUESTION NO: 61Exhibit1. public class SyncTest{2. public static void main(String[] args) {3. final StringBuffer s1= new StringBuffer();4. final StringBuffer s2= new StringBuffer();5. new Thread () {6. public void run() {。
SCJP官方题库

QUESTION NO: 1Given:1. public class Threads2 implements Runnable {2.3. public void run() {4. 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.)A. ng.RuntimeException: ProblemB. runng.RuntimeException: ProblemC. End of method.ng.RuntimeException: ProblemD. End of method.run.ng.RuntimeException: ProblemE. runng.RuntimeException: ProblemEnd of method.Answer: D,EQUESTION NO: 2Which two statements are true? (Choose two.)A. 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 usedincorrectly.E. It is possible for a single-threaded application to deadlock if synchronized blocks are usedincorrectly.F. If a piece of code is capable of deadlocking, you cannot eliminate the possibility of deadlockingby inserting invocations of Thread.yield().Answer: A,FQUESTION NO: 3Given: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 completenormally.F. This code does NOT compile unless "obj.wait()" is replaced with "((Thread)obj).wait()".Answer: BQUESTION NO: 4Click the Exhibit button.What is the output if the main() method is run?A. 4B. 5C. 8D. 9E. Compilation fails.F. An exception is thrown at runtime.G. It is impossible to determine for certain. Answer: DQUESTION NO: 5Given: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 class 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 Answer: BQUESTION NO: 6Given: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?A. Compilation 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. Answer: BQUESTION NO: 7Given: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 */ } Answer: B,EQUESTION NO: 8Given:11. public class Barn {12. public static void main(String[] args) {13. new Barn().go("hi", 1);14. new Barn().go("hi", "world", 2);15. }16. public void go(String... y, int x) {17. System.out.print(y[y.length - 1] + " ");18. }19. }What is the result?A. hi hiB. hi worldC. world worldD. Compilation fails.E. An exception is thrown at runtime.Answer: DQUESTION NO: 9Given:10. class Nav{11. public enum Direction { NORTH, SOUTH, EAST, WEST }12. }13. public class Sprite{14. // insert code here15. }Which code, inserted at line 14, 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; Answer: DQUESTION NO: 10Click the Exhibit button.Which statement is true about the classes and interfaces in the exhibit?A. Compilation will succeed for all classes and interfaces.B. Compilation of class C will fail because of an error in line 2.C. Compilation of class C will fail because of an error in line 6.D. Compilation of class AImpl will fail because of an error in line 2.Answer: CQUESTION NO: 11Click the Exhibit button.What is the result?A. 4321B. 0000C. An exception is thrown at runtime.D. Compilation fails because of an error in.Answer: DQUESTION NO: 12Given:11. public class Rainbow {12. public enum MyColor {13. RED(0xff0000), GREEN(0x00ff00), BLUE(0x0000ff);14. private final int rgb;15. MyColor(int rgb) { this.rgb = rgb; }16. public int getRGB() { return rgb; }17. }; 18. public static void main(String[] args) {19. // insert code here20. }21. }Which code fragment, inserted at line 19, allows the Rainbow class to compile?A. MyColor skyColor = BLUE;B. MyColor treeColor = MyColor.GREEN;C. if(RED.getRGB() < BLUE.getRGB()) { }D. Compilation fails due to other error(s) in the code.E. MyColor purple = new MyColor(0xff00ff);F. MyColor purple = MyColor.BLUE + MyColor.RED; Answer: BQUESTION NO: 13Given:11. class Mud {12. // insert code here13. System.out.println("hi");14. }15. }And the following five fragments:public static void main(String...a) {public static void main(String.* a) {public static void main(String... a) {public static void main(String[]... a) {public static void main(String...[] a) {How many of the code fragments, inserted independently at line 12, compile?A. 0B. 1C. 2D. 3E. 4F. 5Answer: DQUESTION NO: 14Given:5. class Atom {6. Atom() { System.out.print("atom "); }7. }8. class Rock extends Atom {9. Rock(String type) { System.out.print(type); }10. }11. public class Mountain extends Rock {12. Mountain() {13. super("granite ");14. new Rock("granite ");15. }16. public static void main(String[] a) { new Mountain(); }17. }What is the result?A. Compilation fails.B. atom graniteC. granite graniteD. atom granite graniteE. An exception is thrown at runtime.F. atom granite atom graniteAnswer: FQUESTION NO: 15Given: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.D. Compilation fails because of an error in line 1.E. Compilation fails because of an error in line 4.F. Compilation fails because of an error in line 5. Answer: AQUESTION NO: 16Given:11. public static void parse(String str) {12. try {13. float f = Float.parseFloat(str);14. } catch (NumberFormatException nfe) {15. f = 0;16. } finally {17. System.out.println(f);18. }19. }20. public static void main(String[] args) {21. parse("invalid");22. }What is the result?A. 0.0B. Compilation fails.C. A ParseException is thrown by the parse method at runtime.D. A NumberFormatException is thrown by the parse method at runtime.Answer: BQUESTION NO: 17Given:1. public class Blip {2. protected int blipvert(int x) { return 0; }3. }4. class Vert extends Blip {5. // insert code here6. }Which five methods, inserted independently at line 5, will compile? (Choose five.)A. public int blipvert(int x) { return 0; }B. private int blipvert(int x) { return 0; }C. private int blipvert(long x) { return 0; }D. protected long blipvert(int x) { return 0; }E. protected int blipvert(long x) { return 0; }F. protected long blipvert(long x) { return 0; }G. protected long blipvert(int x, int y) { return 0; } Answer: A,C,E,F,GQUESTION NO: 18Given:1. class Super {2. private int a;3. protected Super(int a) { this.a = a; }4. }...11. class Sub extends Super {12. public Sub(int a) { super(a); }13. public Sub() { this.a = 5; }14. }Which two, independently, will allow Sub to compile? (Choose two.)A. Change line 2 to:public int a;B. Change line 2 to:protected int a;C. Change line 13 to:public Sub() { this(5); }D. Change line 13 to:public Sub() { super(5); }E. Change line 13 to:public Sub() { super(a); }Answer: C,DQUESTION NO: 19Which Man class properly represents the relationship "Man has a best friend who is a Dog"?A. class Man extends Dog { }B. class Man implements Dog { }C. class Man { private BestFriend dog; }D. class Man { private Dog bestFriend; }E. class Man { private Dog<bestFriend>; }F. class Man { private BestFriend<dog>; } Answer: DQUESTION NO: 20Given:1. package test;2.3. class Target {4. public String name = "hello";5. }What can directly access and change the value of the variable name?A. any classB. only the Target classC. any class in the test packageD. any class that extends TargetAnswer: CQUESTION NO: 21Given:11. abstract class Vehicle { public int speed() { return 0; }12. class Car extends Vehicle { public int speed() { return 60; }13. class RaceCar extends Car { public int speed() { return 150; }...21. RaceCar racer = new RaceCar();22. Car car = new RaceCar();23. Vehicle vehicle = new RaceCar();24. System.out.println(racer.speed() + ", " + car.speed()25. + ", " + vehicle.speed());What is the result?A. 0, 0, 0B. 150, 60, 0C. Compilation fails.D. 150, 150, 150E. An exception is thrown at runtime.Answer: DQUESTION NO: 22Given:5. class Building { }6. public class Barn extends Building {7. public static void main(String[] args) {8. Building build1 = new Building();9. Barn barn1 = new Barn();10. Barn barn2 = (Barn) build1;11. Object obj1 = (Object) build1;12. String str1 = (String) build1;13. Building build2 = (Building) barn1;14. }15. }Which is true?A. If line 10 is removed, the compilation succeeds.B. If line 11 is removed, the compilation succeeds.C. If line 12 is removed, the compilation succeeds.D. If line 13 is removed, the compilation succeeds.E. More than one line must be removed for compilation to succeed.Answer: CQUESTION NO: 23A team of programmers is reviewing a proposed API for a new utility class. After some discussion,they realize that they can reduce the number of methods in the API without losing anyfunctionality. If they implement the new design, which two OO principles will they be promoting?A. Looser couplingB. Tighter couplingC. Lower cohesionD. Higher cohesionE. Weaker encapsulationF. Stronger encapsulationAnswer: AQUESTION NO: 24 Given:21. class Money {22. private String country = "Canada";23. public String getC() { return country; }24. }25. class Yen extends Money {26. public String getC() { return super.country; }27. }28. public class Euro extends Money {29. public String getC(int x) { return super.getC(); }30. public static void main(String[] args) {31. System.out.print(new Yen().getC() + " " + newEuro().getC());32. }33. }What is the result?A. CanadaB. nullCanadaC. Canada nullD. Canada CanadaE. Compilation fails due to an error on line 26.F. Compilation fails due to an error on line 29. Answer: EQUESTION NO: 25Assuming that the serializeBanana() and the deserializeBanana() methods will correctly use Java serialization and given:13. import java.io.*;14. class Food implements Serializable {int good = 3;}15. class Fruit extends Food {int juice = 5;}16. public class Banana extends Fruit {17. int yellow = 4;18. public static void main(String [] args) {19. Banana b = new Banana(); Banana b2 = new Banana();20. b.serializeBanana(b); // assume correct serialization21. b2 = b.deserializeBanana(); // assume correct22. System.out.println("restore "+b2.yellow+b2.juice+b2.good);24. }25. // more Banana methods go here50. }What is the result?A. restore 400B. restore 403C. restore 453D. Compilation fails.E. An exception is thrown at runtime.Answer: CQUESTION NO: 26Given a valid DateFormat object named df, and16. Date d = new Date(0L);17. String ds = "December 15, 2004";18. // insert code hereWhat updates d's value with the date represented by ds?A. 18. d = df.parse(ds);B. 18. d = df.getDate(ds);C. 18. try {19. d = df.parse(ds);20. } catch(ParseException e) { };D. 18. try {19. d = df.getDate(ds);20. } catch(ParseException e) { };Answer: CQUESTION NO: 27Given:11. double input = 314159.26;12. NumberFormat nf =NumberFormat.getInstance(Locale.ITALIAN);13. String b;14. //insert code hereWhich code, inserted at line 14, sets the value of b to 314.159,26?A. b = nf.parse( input );B. b = nf.format( input );C. b = nf.equals( input );D. b = nf.parseObject( input );Answer: BQUESTION NO: 28Given:1. public class TestString1 {2. public static void main(String[] args) {3. String str = "420";4. str += 42;5. System.out.print(str);6. }7. }What is the output?A. 42B. 420C. 462D. 42042E. Compilation fails.F. An exception is thrown at runtime.Answer: DQUESTION NO: 29Which capability exists only in java.io.FileWriter?A. Closing an open stream.B. Flushing an open stream.C. Writing to an open stream.D. Writing a line separator to an open stream. Answer: DQUESTION NO: 30Given that the current directory is empty, and that the user has read and write permissions, andthe following:11. import java.io.*;12. public class DOS {13. public static void main(String[] args) {14. File dir = new File("dir");15. dir.mkdir(); 16. File f1 = new File(dir, "f1.txt");17. try {18. f1.createNewFile();19. } catch (IOException e) { ; }20. File newDir = new File("newDir");21. dir.renameTo(newDir);22. }23. }Which statement is true?A. Compilation fails.B. The file system has a new empty directory named dir.C. The file system has a new empty directory named newDir.D. The file system has a directory named dir, containing a file f1.txt.E. The file system has a directory named newDir, containing a file f1.txt.Answer: EQUESTION NO: 31Given:22. StringBuilder sb1 = new StringBuilder("123");23. String s1 = "123";24. // insert code here25. System.out.println(sb1 + " " + s1);Which code fragment, inserted at line 24, outputs "123abc 123abc"?A. sb1.append("abc"); s1.append("abc");B. sb1.append("abc"); s1.concat("abc");C. sb1.concat("abc"); s1.append("abc");D. sb1.concat("abc"); s1.concat("abc");E. sb1.append("abc"); s1 = s1.concat("abc");F. sb1.concat("abc"); s1 = s1.concat("abc");G. sb1.append("abc"); s1 = s1 + s1.concat("abc");H. sb1.concat("abc"); s1 = s1 + s1.concat("abc"); Answer: EQUESTION NO: 32Click the Exhibit button.Which code, inserted at line 14, will allow this class tocorrectly serialize and deserialize?A. s.defaultReadObject();B. this = s.defaultReadObject();C. y = s.readInt(); x = s.readInt();D. x = s.readInt(); y = s.readInt();Answer: DQUESTION NO: 33Given:1. public class LineUp {2. public static void main(String[] args) {3. double d = 12.345;4. // insert code here5. }6. }Which code fragment, inserted at line 4, produces the output | 12.345|?A. System.out.printf("|%7d| \n", d);B. System.out.printf("|%7f| \n", d);C. System.out.printf("|%3.7d| \n", d);D. System.out.printf("|%3.7f| \n", d);E. System.out.printf("|%7.3d| \n", d);F. System.out.printf("|%7.3f| \n", d);Answer: FQUESTION NO: 34Given:11. public class Test {12. public static void main(String [] args) {13. int x = 5;14. boolean b1 = true;15. boolean b2 = false;16.17. if ((x == 4) && !b2 )18. System.out.print("1 ");19. System.out.print("2 ");20. if ((b2 = true) && b1 )21. System.out.print("3 ");22. }23. }What is the result?A. 2B. 3C. 1 2D. 2 3E. 1 2 3F. Compilation fails.G. An exception is thrown at runtime. Answer: DQUESTION NO: 35Given:10. interface Foo {}11. class Alpha implements Foo {}12. class Beta extends Alpha {}13. class Delta extends Beta {14. public static void main( String[] args ) {15. Beta x = new Beta(); 16. // insert code here17. }18. }Which code, inserted at line 16, will cause ang.ClassCastException?A. Alpha a = x;B. Foo f = (Delta)x;C. Foo f = (Alpha)x;D. Beta b = (Beta)(Alpha)x;Answer: BQUESTION NO: 36Given:22. public void go() {23. String o = "";24. z:25. for(int x = 0; x < 3; x++) {26. for(int y = 0; y < 2; y++) {27. if(x==1) break;28. if(x==2 && y==1) break z;29. o = o + x + y;30. }31. }32. System.out.println(o);33. }What is the result when the go() method is invoked?A. 00B. 0001C. 000120D. 00012021E. Compilation fails.F. An exception is thrown at runtime.Answer: CQUESTION NO: 37Given:11. static void test() throws RuntimeException {12. try {13. System.out.print("test ");14. throw new RuntimeException();15. }16. catch (Exception ex) { System.out.print("exception "); }17. }18. public static void main(String[] args) {19. try { test(); }20. catch (RuntimeException ex){ System.out.print("runtime "); }21. System.out.print("end ");22. }What is the result?A. test endB. Compilation fails.C. test runtime endD. test exception endE. A Throwable is thrown by main at runtime. Answer: DQUESTION NO: 38Given:33. try {34. // some code here35. } catch (NullPointerException e1) {36. System.out.print("a");37. } catch (Exception e2) {38. System.out.print("b");39. } finally {40. System.out.print("c");41. }If some sort of exception is thrown at line 34, which output is possible?A. aB. bC. cD. acE. abcAnswer: DQUESTION NO: 39Given:31. // some code here32. try {33. // some code here34. } catch (SomeException se) {35. // some code here36. } finally {37. // some code here38. }Under which three circumstances will the code on line 37 be executed? (Choose three.)A. The instance gets garbage collected.B. The code on line 33 throws an exception.C. The code on line 35 throws an exception.D. The code on line 31 throws an exception.E. The code on line 33 executes successfully. Answer: B,C,EQUESTION NO: 40Given:10. int x = 0;11. int y = 10;12. do {13. y--;14. ++x;15. } while (x < 5);16. System.out.print(x + "," + y);What is the result?A. 5,6B. 5,5C. 6,5D. 6,6Answer: BQUESTION NO: 41Given:1. public class Donkey2 {2. public static void main(String[] args) {3. boolean assertsOn = true;4. assert (assertsOn) : assertsOn = true;5. if(assertsOn) {6. System.out.println("assert is on");7. }8. }9. }If class Donkey is invoked twice, the first time without assertions enabled, and the second timewith assertions enabled, what are the results?A. no outputB. no output assert is onC. assert is onD. no outputAn AssertionError is thrown.E. assert is onAn AssertionError is thrown.Answer: CQUESTION NO: 42Click the Exhibit button.Given:31. public void method() {32. A a = new A();33. a.method1();34. }Which statement is true if a TestException is thrown on line 3 of class B?A. Line 33 must be called within a try block.B. The exception thrown by method1 in class A is not required to be caught.C. The method declared on line 31 must be declared to throw a RuntimeException.D. On line 5 of class A, the call to method2 of class B does not need to be placed in atry/catch block.Answer: BQUESTION NO: 43Given:11. Float pi = new Float(3.14f);12. if (pi > 3) {13. System.out.print("pi is bigger than 3. ");14. }15. else {16. System.out.print("pi is not bigger than 3. ");17. }18. finally {19. System.out.println("Have a nice day.");20. }What is the result?A. Compilation fails.B. pi is bigger than 3.C. An exception occurs at runtime.D. pi is bigger than 3. Have a nice day.E. pi is not bigger than 3. Have a nice day. Answer: AQUESTION NO: 44Given:1. public class Boxer1{2. Integer i;3. int x;4. public Boxer1(int y) {5. x = i+y;6. System.out.println(x);7. }8. public static void main(String[] args) {9. new Boxer1(new Integer(4));10. }11. }What is the result?A. The value "4" is printed at the command line.B. Compilation fails because of an error in line 5.C. Compilation fails because of an error in line 9.D. A NullPointerException occurs at runtime.E. A NumberFormatException occurs at runtime.F. An IllegalStateException occurs at runtime. Answer: DQUESTION NO: 45Given:1. public class Person {2. private String name;3. public Person(String name) { = name; }4. public boolean equals(Person p) {5. return .equals();6. }7. }Which statement is true?A. The equals method does NOT properly override the Object.equals method.B. Compilation fails because the private attribute cannot be accessed in line 5.C. To work correctly with hash-based data structures, this class must also implement thehashCode method.D. When adding Person objects to a java.util.Set collection, the equals method in line 4 willprevent duplicates. Answer: AQUESTION NO: 46Which two statements are true about the hashCode method? (Choose two.)A. The hashCode method for a given class can be used to test for object equality and objectinequality for that class.B. The hashCode method is used by thejava.util.SortedSet collection class to order the elements within that set.C. The hashCode method for a given class can be used to test for object inequality, butNOT object equality, for that class.D. The only important characteristic of the values returned by a hashCode method is that thedistribution of values must follow a Gaussian distribution.E. The hashCode method is used by the java.util.HashSet collection class to group the elementswithin that set into hash buckets for swift retrieval.Answer: C,EQUESTION NO: 47Given:1. public class Score implements Comparable<Score> {2. private int wins, losses;3. public Score(int w, int l) { wins = w; losses = l; }4. public int getWins() { return wins; }5. public int getLosses() { return losses; }6. public String toString() {7. return "<" + wins + "," + losses + ">";8. }9. // insert code here10. }Which method will complete this class?A. public int compareTo(Object o){/*more code here*/}B. public int compareTo(Score other){/*more code here*/}C. public int compare(Score s1,Score s2){/*more code here*/}D. public int compare(Object o1,Object o2){/*more code here*/}Answer: BQUESTION NO: 48Given a pre-generics implementation of a method:11. public static int sum(List list) {12. int sum = 0;13. for ( Iterator iter = list.iterator(); iter.hasNext(); ) {14. int i = ((Integer)iter.next()).intValue();15. sum += i;16. }17. return sum;18. }What three changes allow the class to be used with generics and avoid an unchecked warning?(Choose three.)A. Remove line 14.B. Replace line 14 with "int i = iter.next();".C. Replace line 13 with "for (int i : intList) {".D. Replace line 13 with "for (Iterator iter : intList) {".E. Replace the method declaration with "sum(List<int> intList)".F. Replace the method declaration with"sum(List<Integer> intList)".Answer: A,C,FQUESTION NO: 49Given:23. Object [] myObjects = {24. new Integer(12),25. new String("foo"),26. new Integer(5),27. new Boolean(true)28. };29. Arrays.sort(myObjects);30. for(int i=0; i<myObjects.length; i++) {31. System.out.print(myObjects[i].toString());32. System.out.print(" ");33. }What is the result?A. Compilation fails due to an error in line 23.B. Compilation fails due to an error in line 29.C. A ClassCastException occurs in line 29.D. A ClassCastException occurs in line 31.E. The value of all four objects prints in natural order. Answer: CQUESTION NO: 50Given a class Repetition:1. package utils;2.3. public class Repetition {4. public static String twice(String s) { return s + s; }5. }and given another class Demo:1. // insert code here2.3. public class Demo {4. public static void main(String[] args) {5. System.out.println(twice("pizza"));6. }7. }Which code should be inserted at line 1 of Demo.java to compile and run Demo to print"pizzapizza"?A. import utils.*;B. static import utils.*;C. import utils.Repetition.*;D. static import utils.Repetition.*;E. import utils.Repetition.twice();F. import static utils.Repetition.twice;G. static import utils.Repetition.twice;Answer: FQUESTION NO: 51A UNIX user named Bob wants to replace his chess program with a new one, but he is not surewhere the old one is installed. Bob is currently able to run a Java chess program starting from hishome directory /home/bob using the command:java -classpath /test:/home/bob/downloads/*.jar games.ChessBob's CLASSPATH is set (at login time) to:/usr/lib:/home/bob/classes:/opt/java/lib:/opt/java/lib/*.jar What is a possible location for the Chess.class file?A. /test/Chess.classB. /home/bob/Chess.classC. /test/games/Chess.classD. /usr/lib/games/Chess.classE. /home/bob/games/Chess.classF. inside jarfile /opt/java/lib/Games.jar (with a correct manifest)G. inside jarfile /home/bob/downloads/Games.jar (with a correct manifest)Answer: CQUESTION NO: 52Given the following directory structure:bigProject|--source| |--Utils.java||--classes|--And the following command line invocation:javac -d classes source/Utils.javaAssume the current directory is bigProject, what is the result?A. If the compile is successful, Utils.class is added to the source directory.B. The compiler returns an invalid flag error.C. If the compile is successful, Utils.class is added to the classes directory.D. If the compile is successful, Utils.class is added to the bigProject directory.Answer: CQUESTION NO: 53Given:1. package pany.application;2.3. public class MainClass {4. public static void main(String[] args) {}5. }And MainClass exists in the/apps/com/company/application directory. Assume the CLASSPATH environment variable is set to "." (current directory).Which two java commandsentered at the command line will run MainClass? (Choose two.)A. java MainClass if run from the /apps directoryB. java pany.application.MainClass if run from the /apps directoryC. java -classpath /appspany.application.MainClass if run from any directoryD. java -classpath . MainClass if run from the/apps/com/company/application directory。
scjp考题1(详尽答案)

scjp考题1(详尽答案)本文Matrix永久镜像:说明:本文可能由Matrix原创,也可能由Matrix的会员整理,或者由Matrix的Crawler在全球知名Java或者其他技术相关站点抓取并永久保留镜像,Matrix会保留所有原来的出处URL,并在显著地方作出说明,如果你发觉出处URL有误,请联系Matrix改正.好资源共享,这份考题有详尽答案,部分题目还有本人心得。
这是试题1。
1. What will happen when you attempt to compile and run the following code?(Assume that the code is compiled and run with assertions enabled.)public class AssertTest{public void methodA(int i){assert i >= 0 : methodB();System.out.println(i);}public void methodB(){ //无返回值System.out.println("The value must not be negative");}public static void main(String args[]){AssertT est test = new AssertTest();test.methodA(-10);}}A.it will print -10B.it will result in AssertionError showing the message-“the value must not be negative”.C.the code will not compile.D.None of these.C is correct. An assert statement can take any one of these two forms -assert Expression1;assert Expression1 : Expression2;Note that, in the second form; the second part of the statement must be an expression- Expression2. In this code, the methodB() returns void, which is not an expression and hence it results in a compile time error. The code will compile if methodB() returns any value such as int, String etc.Also, in both forms of the assert statement, Expression1 must have type boolean or a compile-time error occurs.2. What will happen when you attempt to compile and run the following code?public class Static{static{int x = 5; //在static内有效}static int x,y; //初始化为0public static void main(String args[]){x--; //-1myMethod();System.out.println(x + y + ++x);}public static void myMethod(){y = x++ + ++x; //y=-1+1 x=1}}piletime errorB.prints: 1C.prints: 2D.prints: 3E.prints: 7F.prints: 8D is the correct choice. The above code will not give any compilation error. Note that "Static" is a valid class name. Thus choice A is incorrect.In the above code, on execution, first the static variables (x and y) will be initialized to 0. Then static block will be called and finally main() method will be called. The execution of static block will have no effect on the output as it declares a new variable (int x).The first statement inside main (x--) will result in x to be -1. After that myMethod() will be executed. The statement "y = x++ + ++x;" will be evaluated to y = -1 + 1 and x will become 1. In case the statement be "y =++x + ++x", it would be evaluated to y = 0 + 1 and x would become 1. Finally when System.out is executed "x + y + ++x" will be evaluated to "1 + 0 + 2" which result in 3 as the output. Thus choice D is correct.3. Given the following code, what will be the output?class Value{public int i = 15;}public class Test{public static void main(String argv[]){Test t = new Test();t.first();}public void first(){int i = 5;Value v = new Value();v.i = 25;second(v, i);System.out.println(v.i);}public void second(Value v, int i){i = 0;v.i = 20;Value val = new Value();v = val;System.out.println(v.i + " " + i);}}A.15 0 20B.15 0 15C.20 0 20D.0 15 20A is correct. When we pass references in Java what actually gets passed is the value of that reference (i.e. memory address of the object being referenced and not the actual object referenced by that reference) and it gets passed as value (i.e a copy of the reference is made). Now when we make changes to the object referenced by that reference it reflects on that object even outside of the method being called but any changes made to the reference itself is not reflected on that reference outside of the method which is called. In the example above when the referencev is passed from method first() to second() the value of v is passed. When we assign the value val to v it is valid only inside the method second() and thus inside the method second() what gets printed is 15 (initial value of i in the object referenced by val), then a blank space and then 0 (value of local variable i). After this when we return to the method first() v actually refers to the same object to which it was referring before the method second() was called, but one thing should be noted here that the value of i in that object (referred by v inside the method first()) was changed to 20 in the method second() and this change does reflect even outside the method second(), hence 20 gets printed in the method first(). Thus overall output of the code in consideration is15 0204. What will happen when you attempt to compile and run the following code?class MyParent {int x, y;MyParent(int x, int y){this.x = x;this.y = y;}public int addMe(int x, int y){return this.x + x + y + this.y;}public int addMe(MyParent myPar){return addMe(myPar.x, myPar.y);}}class MyChild extends MyParent{int z;MyChild (int x, int y, int z){super(x,y);this.z = z;}public int addMe(int x, int y, int z){return this.x + x + this.y + y + this.z + z; }public int addMe(MyChild myChi){ return addMe(myChi.x, myChi.y, myChi.z); }public int addMe(int x, int y){return this.x + x + this.y + y;}}public class MySomeOne{public static void main(String args[]){ MyChild myChi = new MyChild(10, 20, 30); MyParent myPar = new MyParent(10, 20); int x = myChi.addMe(10, 20, 30);int y = myChi.addMe(myChi);int z = myPar.addMe(myPar);System.out.println(x + y + z);}}A.300B.240C.120D.180pile errorF.none of the aboveA is the correct choice. In the above code, MyChild class overrides the addMe(int x, int y) method of the MyParent class. And in both the MyChild and MyParent class, addMe() method is overloaded. There is no compilation error anywhere in the above code.On execution, first, the object of MyChild class will be constructed. Please note that there is a super() call from the constructor of MyChild class, which will call the constructor of MyParent class. This will cause the value of z variable of MyChild class to be 30 and x, y variables of MyParent class will become 10 and 20 respectively. The next statement will again call the constructor of MyParent class with same x and y values. This is followed by execution of addMe() method of MyChild class with x as 10, y as 20 and z as 30. Also x and y are inherited by MyChild class from the MyParent class. Thus in the addMe() method of the MyChild class, the value of this.x will be 10, this.y will be 20 and this.z will be 30. The return value of this method will be "10 + 10 + 20 + 20 + 30 + 30", which is equal to 120. Thus x will become 120.This is followed by the invocation of the other addMe() method which takes object reference of the MyChild class. From this method, the method which was called earlier is invoked. This call is exactly the same as the earlier one. Thus the value of y will also be 120 like x.Now the addMe() method of MyParent class is invoked. This method invokes another addMe() method of the same class. Itsequivalent to the invocation of addMe(int x, int y) method with x as 10 and y as 20. Also the value of instance variables x and y of My Parent class is 10 and 20 respectively. The value of z will be evaluated to "10 + 10 + 20 + 20", which is equal to 60. Thus the value of x, y and z after all the invocations will be 120, 120 and 60 respectively. As a result of this finally, "120 + 120 + 60" which is equal to 300 will be printed. Thus A is the correct choice.5. The class AssertionError has "is -a" relationship with these classes (choose two)A.RuntimeExceptionB.ErrorC.VirtualMachineErrorD.IllegalAccessExceptionE.ThrowableB and E are correct. The class AssertionError is an Error, which denotes an “incorrect condition” as opposed to an“unusual condition” (Exception). Since, the class Error descends from Throwable, AssertionError also has “is-a” relationship with Throwable. Here is the hierarchy –ng.Object|+ng.Throwable|+ng.Error Exception| |+ng.AssertionError +RuntimeException IOExceptionWant to know more?You can find more information about this as an answer to the question - “Why is AssertionError a subclass of Error rather thanRuntimeException?” at - /j2se/1.4/docs/guide/lang/assert.html #design-faq-error6. What will be the result of executing the following code?1. boolean a = true;2. boolean b = false;3. boolean c = true;4. if (a == true)5. if (b == true)6. if (c == true) System.out.println("Some things are true in this world");7. else System.out.println("Nothing is true in this world!");8. else if (a && (b = c)) //这里是赋值,不是比较System.out.println("It‘s too confusing to tell what is true and what is false");9. else System.out.println("Hey this won‘t compile");A.The code won’t compile.B.“some things are true in this world” will be printedC.“hey this won’t compile” will be printedD.None of theseD is correct. This is a very good question to test the concepts of execution flow in case of if conditions. The rule for attaching else statements with if conditions is the same as attaching close brackets with open brackets. A close bracket attaches with the closest open bracket, which is not already closed. Similarly an else statement attaches with the closest if statement, which doesn‘t have an else statement already, attached to it. So the else statement at line 7 attaches to the if statement at line 6. The else statement at line 8 attaches to the if statement at line 5. The else statement at line 9 attaches to the if statement at line 8.Now let‘s look at the execution. At line 4 since a is equal to true the execution falls to line 5. At line 5 since b is not true the execution goes to the corresponding else statement at line 8. Now it evaluates the condition inside the if statement. Please note here that an assignment statement also has a value equal to the value being assigned, hence (b = c) evaluates to true and subsequently a && (b = c) ev aluates to true and "It‘s too confusing to tell what is true and what is false" will be printed. Hence the correct answer is choice D.7. What will happen when you attempt to compile and run the following code?interface MyInterface{}public class MyInstanceTest implements MyInterface{static String s;public static void main(String args[]){MyInstanceT est t = new MyInstanceTest();if(t instanceof MyInterface){System.out.println("I am true interface");}else {System.out.println("I am false interface");}if(s instanceof String){System.out.println("I am true String");}else {System.out.println("I am false String");}}}pile time errorB.runtime errorC.prints: “I am true interface” followed by “I am true String”D.prints: “I am false interface” followed by “I am false String”E.prints: “I am true interface” followed by “I am false String”F.prints: “I am false interface” followed by “I am true String”E is the correct choice. The "instanceof" operator tests the class of an object at runtime. It returns true if the class of the left-hand argument is the same as, or is some subclass of, the class specified by the right-hand operand. The right-hand operand may equally well be an interface. In such a case, the test determines if the object at left-hand argument implements the specified interface.In the above case there will not be any compiletime or runtime error. The result of "t instance of MyInterface" will be true as "t" is the object of MyInstanceTest class which implements the MyInstance interface. But the result of "s instanceof String" will be false as "s" refers to null. Thus the output of the above program will be : "I am true interface" followed by " I am false String". Thus choice E is correct and others are incorrect.8. What results from attempting to compile and run the following code?public class Ternary{public static void main(String args[]){int a = 5;System.out.println("Value is - " + ((a < 5) ? 9.0 : 9));}}A.print:Value is -9B.print:Value is -5pilation errorD.None of theseD is correct. The code compiles successfully. In this code the optional value for the ternary operator, 9.0(a double) and 9(an int) are of different types. The result of a ternary operator must be determined at the compile time, and here the type chosen using the rules of promotion for binary operands, is double. Since the result is a double, the output value is printed in a floating point format. The choice of which value to be printed is made on the basis of the result of the comparison "a < 5" which results in false, hence the variable "a" takes the second of the two possible values, which is 9, but because the result type is promoted to double, the output value is actually written as 9.0, rather than the more obvious 9, hence D is correct.9. In the following pieces of code, A and D will compile without any error. True/False?A: StringBuffer sb1 = "abcd";B: Boolean b = new Boolean("abcd");C: byte b = 255;D: int x = 0x1234;E: float fl = 1.2;TrueFalseThe code segments B and D will compile without any error.A is not a valid way to construct a StringBuffer, you need to creata StringBuffer object using "new". B is a valid construction of a Boolean (any string other than "true" or "false" to the Boolean constructor will result in a Boolean with a value of "false"). C will fail to compile because the valid range for a byte is -128 to +127 (ie, 8 bits,signed). D is correct, 0x1234 is the hexadecimal representation in java. E fails to compile because the compiler interprets 1.2 as a double being assigned to a float (down-casting), which is not valid. You either need an explicit cast (as in "(float)1.2") or "1.2f", to indicate a float.10. Considering the following code, Which variables may be referenced correctly at line 12?1.public class Outer2.{3.public int a = 1;4.private int b = 2;5.public void method(final int c)6.{7.int d = 3;8.class Inner9.{10.private void iMethod(int e)11. {12.13.}14.}15.}16.}a b c d eA, B, C and E are correct. Since Inner is not a static inner class,it has a reference to an enclosing object, and all the variables of that object are accessible. Therefore A and B are correct, even if b is private. Variables in the enclosing method are only accessible when they are marked as final hence c is accessible but not d. E is obviously correct as it is a parameter to the method containing line 12 itself.11. What will be the result of executing the following code?public static void main(String args[]){char digit = ‘a‘;for (int i = 0; i < 10; i++){switch (digit){case ‘x‘ :{int j = 0;System.out.println(j);}default :{int j = 100;System.out.println(j);}}}int i = j;System.out.println(i);}A.100 will be printed 11 times.B.100 will be printed 10 times and then there will be a runtime exceptionC.The code will not compile because the variable i cannot be declared twice within the mani() method.D.The code will not compile because the variable j cannot be declared twice within the switch statement.E.None of these.E is correct. The code will not compile. There is no problem with the declaration of another variable i as both the variables are in disjoint blocks (first one is inside the for loop and its scope ends with the for loop, whereas the second is outside the for loop) and, therefore, different scopes and hence valid. The problem is with the variable j. The two declarations of the variable j are perfectly valid as they are in disjoint blocks and, therefore, different scopes. The error is that both the declarations of j are not available outside the case or default statement, whereas we are trying to assign it to the variable i. Therefore the compiler objects and reports variable j not found.12. Which of the following collection classes from java.util package are Thread safe?A.VectorB.ArrayList //与Vector类似,只是不同步C.HashMapD.HashtableA and D are correct. Vector and Hashtable are two collection classes that are inherently thread safe or synchronized; whereas, the classes ArrayList and HashMap are unsynchronized and must be "wrapped" via Collections.SynchronizedList or Collections.synchronizedMap if synchronization is desired.13. What will happen when you attempt to compile and run the following code?class MyThread extends Thread{public void run(){System.out.println("MyThread: run()");}public void start(){System.out.println("MyThread: start()");}}class MyRunnable implements Runnable{public void run(){System.out.println("MyRunnable: run()");}public void start(){System.out.println("MyRunnable: start()");}}public class MyTest {public static void main(String args[]){MyThread myThread = new MyThread();MyRunnable myRunnable = new MyRunnable();Thread thread = new Thread(myRunnable); myThread.start();thread.start();}}A.prints: MyThread: start() followed by MyRunnable: run()B.prints: MyThread: run() followed by MyRunnable: start()C.prints: MyThread: start() followed by MyRunnable: start()D.prints: MyThread: run() followed by MyRunnable: run()pile time errorF.None of the aboveA is the correct choice. In the above code there is not anycompilation error. Thus choice E is incorrect. Inside main() method, objects of MyThread and MyRunnable class are created followed by creation of Thread with object of MyRunnable class.Note that MyThread class extends Thread class and overrides the start() method of the Thread class. Thus on execution of "myThread.start()" statement, the start() method of the MyThread class will be executed and as a result "MyThread:start()" will be printed. Had the start() method not there in MyThread class, the start() method of the Thread class would be called which in turn would call the run() method of the MyThread class.On execution of "thread.start();", the start() method of the Thread class would be called which in turn will call the run() method of the class which is passed to Thread constructor (i.e. MyRunnable class). Thus "MyRunnable:run()" will be printed out. Thus choice A is correct.14. What will be the result of executing the following code?// Filename; SuperclassX.javapackage packageX;public class SuperclassX{protected void superclassMethodX(){}int superclassVarX;}// Filename SubclassY.java1.package packageX.packageY;2.3.public class SubclassY extends SuperclassX4.{5.SuperclassX objX = new SubclassY();6.SubclassY objY = new SubclassY();7.void subclassMethodY()8.{9.objY.superclassMethodX();10.int i;11.i = objY.superclassVarX;12.}13.}pile error at line 5.pile error at line 9.C.Runtime exception at line 11.D.None of theseD is correct. When no access modifier is specified for a member, it is only accessible by another class in the package where its class is defined. Even if its class is visible in another package, the member is not accessible there. In the question above the variable superclassVarX has no access modifier specified and hence it cannot be accessed in the packageY even though the class SuperclassX is visible and the protected method superclassMethodX() can be accessed. Thus the compiler will raise an error at line 11.15. Consider the class hierarchy shown below:FourWheeler(implements DrivingUtilities)/ / \ \/ / \ \/ / \ \/ / \ \/ / \ \Car Truck Bus CraneConsider the following code below:1.DrivingUtilities du;2.FourWheeler fw;3.Truck myTruck = new Truck();4.du = (DrivingUtilities)myTruck;5.fw = new Crane();6.fw = du;Which of the statements below are true?A.Line 4 will not compile because an interface cannot refer to an object.B.The code will compile and run.C.The code will not compile without an explicit cast at line 6, because going down the hierarchy without casting is not allowed.D.The code at line 4 will compile even without the explicit cast.E.The code will compile if we put an explicit cast at line 6 but will throw an exception at runtime.C andD are correct. A and B are obviously wrong because there is nothing wrong in an interface referring to an object. C is correct because an explicit cast is needed to go down the hierarchy. D is correct because no explicit cast is needed at line 4, because we are going up the hierarchy.E is incorrect because if we put an explicit cast at line 6, the code will compile and run perfectly fine, no exception will be thrown because the runtime class of du (that is Truck) can be converted to type FourWheeler without any problem.16. What results from the following code?1.class MyClass2.{3.void myMethod(int i) {System.out.println("int version");}4.void myMethod(String s) {System.out.println("String version");}5.public static void main(String args[])6.{7.MyClass obj = new MyClass();8.char ch = ‘c‘;9.obj.myMethod(ch);10.}11.}A.Line 4 will not compile as void method can’t e overridden.B.An exception at line 9.C.Line 9 will not compile as there is no version of myMethod which takes a char as argument.D.The code compiles and produces output: int versionE.The code compiles and produces output: String versionD is correct. A is incorrect as void methods can be overridden without any problem. B is incorrect as char ch declaration is valid.C is incorrect as char type in java is internally stored as integer and there is a method which takes int as an input.D is correct, on line 9 char ch is widened to an int and passed to int version of the myMethod().E is incorrect as int version of myMethod() is called.17. What is the result when you compile and run the following code?public class ThrowsDemo {static void throwMethod() {System.out.println("Inside throwMethod.");throw new IllegalAccessException("demo");}public static void main(String args[]) {try {throwMethod();} catch (IllegalAccessException e) {System.out.println("Caught " + e);}}}pile errorB.runtime errorpile successfully, nothing is printed.D.inside throwMethod followed by caught: ng.IllegalAccessException: demoA is correct. Exception :ng.IllegalAccessExcption must be caught or placed in the throws clause of the throwMethod(), i.e. the declaration of throwMethod() be changed to "static void throwMethod() throws IllegalAccessExcption". Thus compilation error will occur.18. What will be printed when you execute the following code?class X {Y b = new Y();X() {System.out.print("X");}}class Y {Y() {System.out.print("Y");}}public class Z extends X {Y y = new Y();Z() {System.out.print("Z");}public static void main(String[] args) {new Z();}}A.ZB.YZC.XYZD.YXYZD is correct. A difficult but a fundamental question, please observe carefully. Before any object is constructed the object of the parent class is constructed(as there is a default call to the parent‘s constructor from the constructor of the child class via the super() statement). Also note that when an object is constructed the variables are initialized first and then the constructor is executed. So when new Z() is executed , the object of class X will be constructed, which means Y b = new Y() will be executed and "Y" will be printed as a result. After that constructor of X will be called which implies "X" will be printed. Now the object of Z will be constructed and thus Y y = new Y() will beexecuted and Y will be printed and finally the constructor Z() will be called and thus "Z" will be printed. Thus YXYZ will be printed.19. What will happen when you attempt to compile and run the following code snippet?Boolean b = new Boolean("TRUE"); //不区分大小写if(b.booleanValue()){System.out.println("Yes : " + b);}else{System.out.println("No : " + b);}A.The code will not compile.B.It will print – Yes: trueC.It will print – Yes: TRUED.It will print – No: falseE.It will print – No: FALSEB is the correct choice. The wrapper class Boolean has the following constructor -public Boolean(String s) It allocates a Boolean object representing the value true if the string argument is not null and is equal, ignoring case, to the string "true". Otherwise, allocate a Boolean object representing the value false.E.g.new Boolean("TRUE") produces a Boolean object that represents true.new Boolean("anything") produces a Boolean object that represents false.The internal toString() representation of this object produces the boolean value string in lower case, hence it prints "Yes : true" instead of "Yes : TRUE".20. What is the result when you compile and run the following code?public class Test{public void method(){for(int i = 0; i < 3; i++) {System.out.print(i);}System.out.print(i);}}A. 0122B. 0123C. compile errorD. none of theseC is correct. The code on compilation will give compile time error because the scope of variable i is only within "for" loop.21. What will happen when you attempt to compile and run the following code?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);}pile errorpile and output of “we are equal 10”pile and output of “not equal!20”pile and output of “not equal!10”D is correct, according to short logic operator rule22. What will be the result of executing the following code?Given that Test1 is a class.1. Test1[] t1 = new Test1[10];2. Test1[][] t2 = new Test1[5][];3. if (t1[0] == null)4. {5.t2[0] = new Test1[10] ;6.t2[1] = new Test1[10];7.t2[2] = new Test1[10];8.t2[3] = new Test1[10];9.t2[4] = new Test1[10];10. }11. System.out.println(t1[0]);12. System.out.println(t2[1][0]);A. The code will not compile because the array t2 is not initialized in an unconditional statement before use.B. The code will compile but a runtime exception will be thrown at line 12.C. The code will compile but a runtime exception will be thrown at line 11.D. None of theseD is correct. Though we cannot use local variables without initializing them (compilation error), there is an exception to it. In case of arrays initialization is supposed to be complete when we specify the leftmost dimension of the array. The problem occurs at runtime if we try to access an element of the array which has not been initialized (specification of size). In the question above the array t2 is initialized before use, therefore there will be no。
SCJP认证考试题库1

●考试大纲●第一部分:Java语言基础●第二部分:流程控制●第三部分:面向对象封装,继承,多态●第四部分:异常处理●第五部分:多线程●第六部分:Java 垃圾回收机制●第七部分:Java I/O●第八部分:Java集合和泛型●第九部分:Java SE实用APIQUESTION 1Given the code in the exhibit.What is the result?A. Compilation failsB. An exception is thrown at runtime.C. An instance of Forest is serialized.D. An instance of Forest and an instance of Tree are both serialized.Answer: ( B )执行时期会抛出java.io.NotSerializableExcetpion异常。
Tree必须实现Serialized接口;因为Forest实现了序列化,并且引用了Tree,但是Tree没有实现序列化!!当一个实现序列化的类在类体里调用另外一个类的时候,那么另外一个类也要实现序列化!如果没有实现,则会报出运行时异常!! 如果要实现序列化,他的成员变量也必须实现序列化.本题中Tree没有实现序列化,所以会产生java.io.NotSerializableException的运行异常!参考大纲:IO操作—对象的序列化序列化的过程就是对象写入字节流和从字节流中读取对象。
见SCJP.u1. SerializableTestQUESTION 2Which code, inserted at line 14, will allow this class to correctly serialized anddesterilized?A. s.defaultReadObject ();B. this = s.defaultReadObject ();C. y = s.default (); x = s.readInt ();D. x = s.readInt(); y = s.readInt ();Answer: ( D )在反序列化方法中,从s对象中读取两个整数. 序列化是写对象,反序列化是读对象…参考大纲:IO操作—对象的序列化QUESTION 3Given the exhibit.What is the result?A. 0B. 1C. 4D. Compilation failsE. An exception is thrown at runtimeAnswer: ( D ) 产生illegal escape character 非法转意符的编译错误split()字符切割器本题是想用空格来分割字符串,只能用“ ”或者“\\ s”来分割,“\ s”没有这个转意字符!所以会报编译错误……tab可以用“\ t”;“\”可以用”\\”表示.String的split方法用来分割字符串,这个方法接受一个正则表达式,根据表达式来分割,“\\s”表示空格,“\s”没有这个转意字符,所以会产illegal escape character的编译错误。
SUN公司SCJP题库讲解学习

S U N公司S C J P题库yModule 1-JAVA 基础一、选择题:Question 1Given:35. String #name = "Jane Doe";36. int $age=24;37. Double _height = 123.5;38. double ~temp = 37.5;Which two are true? (Choose two.)A. Line 35 will not compile.B. Line 36 will not compile.C. Line 37 will not compile.D. Line 38 will not compile.Answer: AD 标识符以字母,下划线,或者$开始Question 2Given:11. public class Test {12. public static void main(String [] args) {13. int x =5;14. boolean b1 = true;15. boolean b2 = false;16.17.if((x==4) && !b2)18. System.out.print("l ");19. System.out.print("2 ");20. if ((b2 = true) && b1)21. System.out.print("3");22. }23. }What is the result?A. 2B. 3C. 1 2D. 2 3E. 1 2 3F. Compilation fails.G. An exceptional is thrown at runtime. Answer: D 注意20行,=为赋值,不要被骗Question 3Given:42. public class ClassA {43. public int getValue() {44. int value=0;45. boolean setting = true;46. String title="Hello";47. if (value || (setting && title == "Hello")) { return 1; }48. if (value == 1 & title.equals("Hello")) { return 2; }49. }50. }And:70. ClassA a = new ClassA();71. a.getValue();What is the result?A. 1B. 2C. Compilation fails.D. The code runs with no output.E. An exception is thrown at runtime.Answer: C 编译不通过,47行value为int类型不是boolean Question 4Given:11. public void testIfA() {12. if(testIfB("True")) {13. System.out.println("True");14. } else {15. System.out.println("Not true");16. }17. }18. public Boolean testIfB(String str) {19. return Boolean.valueOf(str);20. }What is the result when method testIfA is invoked?A. TrueB. Not trueC. An exception is thrown at runtime.D. Compilation fails because of an error at line 12.E. Compilation fails because of an error at line 19. Answer: A 19行,如果str为true则返回ture,否则返回false Question 5Given:11. public static void main(String[] args) {12. Integer i = new Integer(1) + new Integer(2);13. switch(i) {14. case 3: System.out.println("three"); break;15. default: System.out.println("other"); break;16. }17. }What is the result?A. threeB. otherC. An exception is thrown at runtime.D. Compilation fails because of an error on line 12.E. Compilation fails because of an error on line 13.F. Compilation fails because of an error on line 15. Answer: A 就是两个Integer类型相加Question 6Given:11. public static void main(String[] args) {12. String str = "null";13. if (str == null) {14. System.out.println("null");15. } else (str.length() == 0) {16. System.out.println("zero");17. } else {18. System.out.println("some");19. }20. }‘What is the result?A. nullB. zeroC. someD. Compilation fails.E. An exception is thrown at runtime.Answer: D 这题真恶心 15行少个ifQuestion 7Given:10.int x=0;11.int y=10;12. do {l3. y--;14. ++x;15. } while (x < 5);16. System.out.print(x + "," + y);What is the result?A. 5,6B. 5,5C. 6,5D. 6,6Answer: B (91,82,73,64,55)没啥争议Question 8Given:25.int x=12;26. while (x < 10) {27. x--;28. }29. System.out.print(x);What is the result?A. 0B. 10C. 12D. Line 29 will never be reached.Answer: C 12>10,所以直接跳出循环,输出x=12 Question 9Given:35. int x= 10;36. do {37. x--;38. } while(x< 10);How many times will line 37 be executed?A. ten timesB. zero timesC. one to me timesD. more than ten timesAnswer: D 死循环Question 10Given:11. public static void main(String[] args) {12. for (int i=0;i<= 10;i++){13. if( i>6) break;14. }15. System.out.println(i);16. }What is the result?A. 6B. 7C. 10D. 11E. Compilation fails.F. An exception is thrown at runtime. Answer: E 15行i超出了作用域Question 11Given:55. int []x= {1, 2,3,4, 5};56. int y[] =x;57. System.out.println(y[2]);Which is true?A. Line 57 will print the value 2.B. Line 57 will print the value 3.C. Compilation will fail because of an error in line 55.D. Compilation will fail because of an error in line 56. Answer: B 没争议,考察数组下标是从0开始Question 12Which two code fragments(片段) correctly(正确) create and initialize a static array of int elements? (Choose two.)A. static final int[] a = { 100,200 };B. static final int[] a;static { a=new int[2]; a[0]=100; a[1]=200; }C. static final int[] a = new int[2] { 100,200 };D. static final int[] a;static void init() { a = new int[3]; a[0]=100; a[1]=200; } Answer: AB c不能指定长度,d不能在init方法中赋值,要么在static 代码块中Question 13Given:11. public static void main(String[] args) {12. Object obj = new int[] { 1,2,3 };13. int[] someArray = (int[])obj;14. for (int i: someArray) System.out.print(i +" ")15. }‘What is the result?A. 1 2 3B. Compilation fails because of an error in line 12.C. Compilation fails because of an error in line 13.D. Compilation fails because of an error in line 14.E. A ClassCastException is thrown at runtime.Answer: A 没争议,foeach循环遍历数组Question 14Given:11. String[] elements = { "for", "tea", "too" };12. String first = (elements.length > 0)? elements[0] : null;What is the result?A. Compilation fails.B. An exception is thrown at runtime.C. The variable first is set to null.D. The variable first is set to elements[0].Answer: DQuestion 15Given:10. public class Bar {11.static void foo(int...x) {12. // insert code here13. }14. }Which two code fragments, inserted independently(独立的) at line 12, will allow the class to compile? (Choose two.)A. foreach(x) System.out.println(z);B. for(int z : x) System.out.println(z);C. while( x.hasNext()) System.out.println( x.next());D. for( int i=0; i< x.length; i++ )System.out.println(x[i]);Answer: BD x相当于一个数组,a明显错没有foreach,c中x没有hadNext方法Question 16A programmer(程序员) needs to create a logging method that can accept(接受) an arbitrary(随意任意) number of arguments. For example, it may be called in theseways:logIt("log message 1 ");logIt("log message2”,”log message3");logIt("log message4", "log message5", "log message6");Which declaration(说明) satisfies(符合) this requirement(需求)?A. public void logIt(String * msgs)B. public void logIt(String [] msgs)C. public void logIt(String... msgs)D. public void logIt(String msg1, String msg2, String msg3) Answer: C 可变长参数Question 171. public class A {2. public String doit(int x, int y) {3. return "a";4. }5.6. public String doit(int... vals) {7. return "b";8. }9. }Given:25. A a=new A();26. System.out.println(a.doit(4, 5));What is the result?A. Line 26 prints "a" to System.out.B. Line 26 prints "b" to System.out.C. An exception is thrown at line 26 at runtime.D. Compilation of class A will fail due to an error in line6.Answer: A 确定参数和可变长参数同时存在的时候,优先考虑确定参数的Question 18Given a file GrizzlyBear.java:1. package animals.mammals;2.3. public class GrizzlyBear extends Bear {4. void hunt() {5. Salmon s = findSalmon();6. s.consume();7. }8. }and another file, Salmon.java:1. package animals.fish;2.3. public class Salmon extends Fish {4. void consume() { /* do stuff */ }5. }Assume(假定) both classes are defined in the correct directories for theft packages, and that the Mammal class correctly defines the findSalmon() method. Which two changes allow this code to compile correctly? (Choose two.)A. add public to the start of line 4 in Salmon.javaB. add public to the start of line 4 in GrizzlyBear.javaC. add import animals.mammals.*; at line 2 in Salmon.javaD. add import animals.fish.*; at line 2 in GrizzlyBear.javaE. add import animals.fish.Salmon.*; at line 2 in GrizzlyBear.javaF. add import animals.mammals.GrizzlyBear.*;at line 2 in Salmon.javaAnswer: AD 调用不同包下的类,要先导入,方法权限要设置成public Question 19Given:10. package com.sun.scjp;11. public class Geodetics {12. public static final double DIAMETER = 12756.32; // kilometers13. }Which two correctly access(访问) the DIAMETER member of the Geodetics class? (Choose two.)A. import com.sun.scjp.Geodetics;public class TerraCarta {public double halfway(){ return Geodetics.DIAMETER/2.0; } }B. import static com.sun.scjp.Geodetics;public class TerraCarta {public double halfway() { return DIAMETER/2.0; } }C. import static com.sun.scjp.Geodetics. *;public class TerraCarta {public double halfway() { return DIAMETER/2.0; } }D. package com.sun.scjp;public class TerraCarta {public double halfway() { return DIAMETER/2.0; } }Answer: AC b中不能静态导入类,c中静态导入类属性,正确,d访问错误很明显Question 20Given classes defined in two different files:1. package util;2. public class BitUtils {3. private static void process(byte[] b) { }4. }1. package app;2. public class SomeApp {3. public static void main(String[] args) {4. byte[] bytes = new byte[256];5. // insert code here6. }7. }What is required(必需的) at line 5 in class SomeApp to use the process methodof BitUtils?A. process(bytes);B. BitUtils.process(bytes);C. app.BitUtils.process(bytes);D. util.BitUtils.process(bytes);E. import util.BitUtils. *; process(bytes);F. SomeApp cannot use the process method in BitUtils. Answer: F 私有的,不能被访问Question 21Given a class Repetition(重复):1. package utils;2.3. public class Repetition {4. public static String twice(String s) { return s + s; }5. }and given another class Demo:1. // insert code here2.3. public class Demo {4. public static void main(String[] args) {5. System.out.println(twice("pizza"));6. }7. }Which code should be inserted at line 1 of Demo.java to compile and run Demo to print “pizzapizza”?A. import utils.*;B. static import utils.*;C. import utils.Repetition.*;D. static import utils.Repetition. *;E. import utils.Repetition.twice();F. import static utils.Repetition.twice;G. static import utils.Repetition.twice;Answer: F 静态导入Question 22Given:1. package test;2.3. class Target(目标) {4. public String name = "hello";5. }What can directly(直接的) access and change the value ofthe variable(变量) name?A. any classB. only the Target classC. any class in the test packageD. any class that extends TargetAnswer: C default类型的类本包访问权限Question 23Given:11. rbo = new ReallyBigObject();12. // more code here13. rbo = null;14. /* insert code here */Which statement(语句) should be placed at line 14 tosuggest(促成) that the virtual machine(虚拟机) expend(消耗) effort(努力) toward recycling(回收) the memory used by the object rbo?A. System.gc();B. Runtime.gc();C. System.freeMemory();D. Runtime.getRuntime().growHeap();E. Runtime.getRuntime().freeMemory();Answer: A 题很简单。
2021年SUN认证JAVA2程序员考试(SCJP) 试题解析(1)

SUN认证Java2程序员考试(SCJP) 试题解析(1)SUN认证Java2程序员考试(SCJP) 试题解析(1)前言无论你是个新手,还是程序设计方面的专家,你都会惊异于sun公司java的无穷魅力。
java带给你的并不仅仅是面向对象、开放、平台无关、易用、安全和“write once, run anywhere”等软件开发方面的优势,更重要的一点是,它提供了一种新颖的表达思想的方式,一种全新的思维模式。
随着待解决问题的规模不断膨胀,java ___的面向对象思想的灵活性就会凸现出来。
毋庸置疑,java 是你开发大型软件时最得心应手的利器或是你转行it的入门首选。
scjp考试简介●考试方式全英文试题,以电脑作答,在授权的prometric考试中心参加考试考试编号:310-025先决条件:无考试题型:复选、填空和拖拽匹配题量:59及格标准:61%时限:120分钟费用:1250元●要求具备的能力●使用java编程语言创建java应用程序和applets。
●定义和描述垃圾搜集,安全性和java虚拟机(jvm)。
●描述和使用java语言面向对象的特点。
●开发图形用户界面(gui)。
利用java支持的多种布局管理。
●描述和使用java的事件处理模式。
●使用java语言的鼠标输入、文本、窗口和菜单窗口部件。
●使用java的例外处理来控制程序执行和定义用户自己的例外事件。
●使用java语言先进的面向对象特点, 包括方法重载、方法覆盖、抽象类、接口、final、static和访问控制。
●实现文件的输入/输出 (i/o)。
●使用java语言内在的线程模式来控制多线程。
●使用java 的sockets机制进行网络通信。
例题1:choose the three valid identifiers from those listed below.a. idolikethelongnameclassb. $bytec. constd. _oke. 3_case解答:a, b, d点评:java中的标示符必须是字母、美元符($)或下划线(_)开头。
[IT认证]sun公司认证scjp证书考题模拟试题2
![[IT认证]sun公司认证scjp证书考题模拟试题2](https://img.taocdn.com/s3/m/0d662885a45177232e60a23c.png)
QUESTION 1Exhibit:1.public class SimpleCalc {2.public: int value;3.public void calculate() ( value +- 7; }4 }And:1. public class HuitiCalc extends SiifcpleCalc(public void calculate() { value -* 3; ) public void 2 3 4-5678ealculate(int multiplier) { oail^ulat;supsr.calculate():value *±> multiplier:}publi3 static void iwain(String[ ] args)9. MultiCalc calculator newMultiualc();10.cailculatoi?. calculate( 2 );11.System.out printIn(°Value is: , + calculator value);12.}i*> \What is the result?A. Value is : 8B. Compilation fails.C. Value is : 12D. Value is ; -12E. The code runs with no outputF. An exception is thrown at runtime.Answer:( )QUESTION 2Given the exhibit:20 public clagg Certkiller Card (21.22private String card ID:23pnvale Iritcgi h口it,24public String ov^nerName^25.26 public void set Cardin form st i^n (String c ar dID,27. String o wne rName,28 Integer limit)(29 一this.cardLD= cardlB,30 this J wiietNdiHic —QWticiiTanie^31.thbs.limii =limit;32 }33. }Which statement is true?A. The class is fully encapsulatedB. The code demonstrates polymorphism.C. The ownerName variable breaks encapsulationD. The CardID and limit variables break polymorphismE. The setCardInformation method breaks encapsulationAnswer:( )QUESTION 3Given the exhibit:11 class Animal ( public String noise () ( return "peep"))12.chfs Dog extends Animal (13.public String noist () { return、角clT; }14}15Cat expends A DIHI^I(16.public String noise () { return "mo耻”;)17.} b ■ h h ri30Animal animal =new Dog ();31.Cat cal = (Cat) animal;32.System out.pnntln (Car Noise () )FWhat is the result?A. peepB. barkC. meowD. Compilation fails.E. An exception is thrown at runtimeAnswer:( )QUESTION 4Exhibit:1public class Car {2private int vheelCount;3private String vin (4pub 1 c Car (Str ing vm ) {5this vin = vin:6“this vheelCount - 4;7. )R public Stringextend() {3 return "zoom ^oom *.10- }11public St以ng getlnfo() (12return "WIN: " + vin + * vheels * + vheelCcunt13.)14.}And1public class MeGo ewtends Oar (2public MeGo(String vin)(3this vkeeiCount - 3;4- )5 }What two must the programmer do to oerrect the compilation errors?A. insert a call to this ( ) in the Car CONSTRUCTORB. insert a call to this ( ) in the MeGo constructorC. insert a call to super ( ) in the MeGo constructorD. insert a call to super (vin) in the MeGo constructorE. change the wheel Count variable in CAR TO PROTECTEDF. CHANGE LINE 3 IN THE MeGo class to super wheel Count =3;Answer:( )QUESTION 5Given the exhibit:10interface A { public int gtValue ();)11class B implements A {12.PUBLIC INT GETvALUE () return 1;)B )14.class C extends B (15.// insert code here16’)What three cade inserted mdh Lduallv at line 15. niake use ofWhat three code fragments inserted individually at line 15, make use of polymorphism? (choose three)A. public void add (C c) ( c.getValue ( ); }B. public void add (B b) ( b.getValue ( ); }C. public void add (A a) ( a.getValue ( ); }D. public void add (A a, B b) ( a.getValue ( ); }E. public void add (C c1 C c2) { c1.getV alue ( ); }Answer:( )QUESTION 6Given the exhibit:11 certkilter = new Rs ally Big Object ()t12.// more coce here13.cerftiller = null;14./x insert code here*/Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime ( ) growHeap ()E. Runtime.getRuntime ( ) free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )A. public void add (C c) { c.getValue ();}B. public void add (B b) { b.getValue ();}C. public void add (A a) { a.getValue ();}D. public void add (A a, B b) { a.getValue ();}E. public void add (C c1 C c2) { c1 .getV alue ();}Answer:( )QUESTION 6Given the exhibit:Which statement should be placed at line 14 to suggest that the virtual machine expend effort toward recycling the memory used by the object Certkiller ?A. System.gc ()B. Runtime. Gc ()C. System.freeMemory ()D. Runtime.getRuntime () growHeap ()E. Runtime.getRuntime () free Memory ()Answer:( )。
scjp认证试题及答案

scjp认证试题及答案1. 以下哪个选项是Java中声明接口的正确语法?A. interface MyInterface { }B. public interface MyInterface { }C. abstract class MyInterface { }D. class MyInterface { }答案:B2. 在Java中,以下哪个关键字用于定义一个方法?A. classB. interfaceC. methodD. function答案:B3. Java程序中的main方法的返回类型是什么?A. voidB. intC. StringD. boolean答案:B4. 以下哪个选项不是Java中的访问修饰符?A. publicB. protectedC. privateD. static答案:D5. 在Java中,以下哪个关键字用于捕获异常?A. tryB. catchC. throwD. finally答案:B6. Java中,以下哪个关键字用于定义一个类?A. classB. interfaceC. structD. type答案:A7. 在Java中,以下哪个关键字用于强制类型转换?A. castB. convertC. typeD. (Type)答案:D8. Java中,以下哪个关键字用于声明一个变量?A. varB. letC. defineD. declare答案:A9. 在Java中,以下哪个关键字用于实现接口?A. implementsB. extendsC. inheritD. override答案:A10. Java中,以下哪个关键字用于继承一个类?A. extendsB. implementsC. inheritD. override答案:A11. 在Java中,以下哪个关键字用于定义一个枚举?A. enumB. listC. setD. map答案:A12. Java中,以下哪个关键字用于定义一个方法的重载?A. overloadB. overloadsC. overloadingD. overload答案:D13. 在Java中,以下哪个关键字用于定义一个方法的重写?A. overrideB. extendsC. implementsD. overload答案:A14. Java中,以下哪个关键字用于声明一个静态方法?A. staticB. publicC. privateD. protected答案:A15. 在Java中,以下哪个关键字用于声明一个静态变量?A. staticB. finalC. constD. volatile答案:A。
SUN认证SCJP介绍

考试准备
• 题目并不难,但陷阱很多。答题时一定要 细心、冷静。 • 对Java基础的掌少90%的考 题出自题库。 • 死记答案是下策,应该要理解题目考的是 什么知识点、以及答案为什么是那样。 • 题库存在错误。有疑问请汇总、交流。
注意事项 – 乘车路线
• B1 – 八字桥 – B2/B2区间 – 浙江工商大学
注意事项 – 考试过程
• • • • • • • • • • 公共厕所在一楼,仅此一间 前台接待的阿姨很热情,但是需要你自己倒水 过来一个MM(也很亲切)让你登记(Testing ID、身份证号等) 运气好的话马上就可考试,也有可能得等待一会儿(最多只能安排六 人同时考试) 不能携带任何物品进入考场(有柜子存放物品),会提供“草稿纸” (一张A4大小的塑料卡片,绿色、有方格)、笔 MM会帮你启动软件,填写“Test Site Code”等信息……一路操作到 第一道题目出现(貌似连名字都是她给我填的,真的很周到哦,嘿嘿 ~不过这MM好像不太熟悉考试内容,把我第一题给直接跳过了) 全过程有语音及视频监控(MM会提醒你的,这是她的职责),考试 中务必保持安静,有问题随时举手 答完最后一题时可以选择交卷,也可返回检查 答完题后MM可能会请你填一份在线调查问卷 等待几分钟后就可以拿到考试成绩报告了
证书的意义
• • • • 用相同的时间,收获更多的技术。 提升英语水平,为进入外企铺路。 增加面试勇气,顺利通过技术考核。 一段考试经历,圆一个就业梦想。
你值得拥有!
注意事项 – 题目类型
• 选择
– 复选框(注意选择几项的提示) – 单选框 – Exhibit
• 拖拽
– Task
考试、证书寄达流程
• • • •
• • • •
SUN公司SCJP题库

yModule 1-JAVA 基础一、选择题:Question 1Given:35. String #name = "Jane Doe";36. int $age=24;37. Double _height = ;38. double ~temp = ;Which two are true? (Choose two.)A. Line 35 will not compile.B. Line 36 will not compile.C. Line 37 will not compile.D. Line 38 will not compile.Answer: AD 标识符以字母,下划线,或者$开始Question 2Given:11. public class Test {12. public static void main(String [] args) {13. int x =5;14. boolean b1 = true;15. boolean b2 = false;16.((x==4) && !b2)18. "l ");19. "2 ");20. if ((b2 = true) && b1)21. "3");22. }23. }What is the result?A. 2B. 3C. 1 2D. 2 3E. 1 2 3F. Compilation fails.G. An exceptional is thrown at runtime.Answer: D 注意20行,=为赋值,不要被骗Question 3Given:42. public class ClassA {43. public int getValue() {44. int value=0;45. boolean setting = true;46. String title="Hello";47. if (value || (setting && title == "Hello")) { return 1; }48. if (value == 1 & ("Hello")) { return 2; }49. }50. }And:70. ClassA a = new ClassA();71. ();What is the result?A. 1B. 2C. Compilation fails.D. The code runs with no output.E. An exception is thrown at runtime.Answer: C 编译不通过,47行value为int类型不是booleanQuestion 4Given:11. public void testIfA() {12. if(testIfB("True")) {13. "True");14. } else {15. "Not true");16. }17. }18. public Boolean testIfB(String str) {19. return (str);20. }What is the result when method testIfA is invoked?A. TrueB. Not trueC. An exception is thrown at runtime.D. Compilation fails because of an error at line 12.E. Compilation fails because of an error at line 19. Answer: A 19行,如果str为true则返回ture,否则返回falseQuestion 5Given:11. public static void main(String[] args) {12. Integer i = new Integer(1) + new Integer(2);13. switch(i) {14. case 3: "three"); break;15. default: "other"); break;16. }17. }What is the result?A. threeB. otherC. An exception is thrown at runtime.D. Compilation fails because of an error on line 12.E. Compilation fails because of an error on line 13.F. Compilation fails because of an error on line 15. Answer: A 就是两个Integer类型相加Question 6Given:11. public static void main(String[] args) {12. String str = "null";13. if (str == null) {14. "null");15. } else () == 0) {16. "zero");17. } else {18. "some");19. }20. }‘What is the result?A. nullB. zeroC. someD. Compilation fails.E. An exception is thrown at runtime.Answer: D 这题真恶心 15行少个ifQuestion 7Given:x=0;y=10;12. do {l3. y--;14. ++x;15. } while (x < 5);16. + "," + y);What is the result?A. 5,6B. 5,5C. 6,5D. 6,6Answer: B (91,82,73,64,55)没啥争议Question 8Given:x=12;26. while (x < 10) {27. x--;28. }29. is the result?A. 0B. 10C. 12D. Line 29 will never be reached.Answer: C 12>10,所以直接跳出循环,输出x=12Question 9Given:35. int x= 10;36. do {37. x--;38. } while(x< 10);How many times will line 37 be executed?A. ten timesB. zero timesC. one to me timesD. more than ten timesAnswer: D 死循环Question 10Given:11. public static void main(String[] args) {12. for (int i=0;i<= 10;i++){13. if( i>6) break;14. }15. }What is the result?A. 6B. 7C. 10D. 11E. Compilation fails.F. An exception is thrown at runtime.Answer: E 15行i超出了作用域Question 11Given:55. int []x= {1, 2,3,4, 5};56. int y[] =x;57. is true?A. Line 57 will print the value 2.B. Line 57 will print the value 3.C. Compilation will fail because of an error in line 55.D. Compilation will fail because of an error in line 56. Answer: B 没争议,考察数组下标是从0开始Question 12Which two code fragments(片段) correctly(正确) create and initialize a static array of int elements? (Choose two.)A. static final int[] a = { 100,200 };B. static final int[] a;static { a=new int[2]; a[0]=100; a[1]=200; }C. static final int[] a = new int[2] { 100,200 };D. static final int[] a;static void init() { a = new int[3]; a[0]=100; a[1]=200; }Answer: AB c不能指定长度,d不能在init方法中赋值,要么在static代码块中Question 13Given:11. public static void main(String[] args) {12. Object obj = new int[] { 1,2,3 };13. int[] someArray = (int[])obj;14. for (int i: someArray) +" ")15. }‘What is the res ult?A. 1 2 3B. Compilation fails because of an error in line 12.C. Compilation fails because of an error in line 13.D. Compilation fails because of an error in line 14.E. A ClassCastException is thrown at runtime.Answer: A 没争议,foeach循环遍历数组Question 14Given:11. String[] elements = { "for", "tea", "too" };12. String first = > 0)? elements[0] : null;What is the result?A. Compilation fails.B. An exception is thrown at runtime.C. The variable first is set to null.D. The variable first is set to elements[0].Answer: DQuestion 15Given:10. public class Bar {void foo(int...x) {12. }14. }Which two code fragments, inserted independently(独立的) at line 12, will allow the class to compile? (Choose two.)A. foreach(x) for(int z : x) while( ()) ());D. for( int i=0; i< ; i++ ) BD x相当于一个数组,a明显错没有foreach,c中x没有hadNext方法Question 16A programmer(程序员) needs to create a logging method that can accept(接受) an arbitrary(随意任意) number of arguments. For example, it may be called in these ways:logIt("log message 1 ");logIt("log message2”,”log message3");logIt("log message4", "log message5", "log message6");Which declaration(说明) satisfies(符合) this requirement(需求)?A. public void logIt(String * msgs)B. public void logIt(String [] msgs)C. public void logIt(String... msgs)D. public void logIt(String msg1, String msg2, String msg3)Answer: C 可变长参数Question 171. public class A {2. public String doit(int x, int y) {3. return "a";4. }5.6. public String doit(int... vals) {7. return "b";8. }9. }Given:25. A a=new A();26. 5));What is the result?A. Line 26 prints "a" to .B. Line 26 prints "b" to .C. An exception is thrown at line 26 at runtime.D. Compilation of class A will fail due to an error in line 6.Answer: A 确定参数和可变长参数同时存在的时候,优先考虑确定参数的Question 18Given a file :1. package ;2.3. public class GrizzlyBear extends Bear {4. void hunt() {5. Salmon s = findSalmon();6. ();7. }8. }and another file, :1. package ;2.3. public class Salmon extends Fish {4. void consume() { /* do stuff */ }5. }Assume(假定) both classes are defined in the correct directories for theft packages, and that the Mammal class correctly defines the findSalmon() method. Which two changes allow this code to compile correctly? (Choose two.)A. add public to the start of line 4 inB. add public to the start of line 4 inC. add import .*; at line 2 inD. add import .*; at line 2 inE. add import at line 2 inF. add import line 2 inAnswer: AD 调用不同包下的类,要先导入,方法权限要设置成publicQuestion 19Given:10. package public class Geodetics {12. public static final double DIAMETER = ; }Which two correctly access(访问) the DIAMETER member of the Geodetics class? (Choose two.)A. import class TerraCarta {public double halfway(){ return ; } }B. import static class TerraCarta {public double halfway() { return DIAMETER/; } }C. import static *;public class TerraCarta {public double halfway() { return DIAMETER/; } }D. package class TerraCarta {public double halfway() { return DIAMETER/; } }Answer: AC b中不能静态导入类,c中静态导入类属性,正确,d访问错误很明显Question 20Given classes defined in two different files:1. package util;2. public class BitUtils {3. private static void process(byte[] b) { }4. }1. package app;2. public class SomeApp {3. public static void main(String[] args) {4. byte[] bytes = new byte[256];5. }7. }What is required(必需的) at line 5 in class SomeApp to use the process methodof BitUtils?A. process(bytes);B. (bytes);C. import . *; process(bytes);F. SomeApp cannot use the process method in BitUtils.Answer: F 私有的,不能被访问Question 21Given a class Repetition(重复):1. package utils;2.3. public class Repetition {4. public static String twice(String s) { return s + s; }5. }and given another class Demo:1. 3. public class Demo {4. public static void main(String[] args) {5. "pizza"));6. }7. }Which code should be inserted at line 1 of to compile and run Demo to print “pizzapizza”?A. import utils.*;B. static import utils.*;C. import .*;D. static import . *;E. import import static static import F 静态导入Question 22Given:1. package test;2.3. class Target(目标) {4. public String name = "hello";5. }What can directly(直接的) access and change the value of the variable(变量) name?A. any classB. only the Target classC. any class in the test packageD. any class that extends TargetAnswer: C default类型的类本包访问权限Question 23Given:11. rbo = new ReallyBigObject();12. rbo = null;14. /* insert code here */Which statement(语句) should be placed at line 14 to suggest(促成) that the virtual machine(虚拟机) expend(消耗) effort(努力) toward recycling(回收) the memory used by the object rbo?A. ();B. ();C. ();D. ().growHeap();E. ().freeMemory();Answer: A 题很简单。
SCJP试题集及解析

SCJP试题集及解析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 valueis 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";翻译:下面的哪些程序片断可能导致错误。
sun公司国际认证试题及答案

sun公司国际认证试题及答案SUN认证是给网络设计界建立的一套认证标准,Sun公司推出了Java以及Solaris技术认证方案。
下面为帮助大家提高对SUN认证的认识,为大家最新的sun公司国际认证试题及答案,希望能帮助到大家!1.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";answer:(BD)这道题考察java字符串和连接符+的理解,B中s[3]是一个字符,而不能和一个字符串用连接符连起来。
而D那么是我们初学java时以为有+必定有-,所以导致错误。
java中的连接符只有一个就是+。
而且字符串和字符是两个不同的概念,我们要区分开来。
2. 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 Vectoranswer:(ADE)这题考察获得实例的内存变化。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
yModule 1-JAVA 基础一、选择题:Question 1Given:35. String #name = "Jane Doe";36. int $age=24;37. Double _height = ;38. double ~temp = ;Which two are true (Choose two.)A. Line 35 will not compile.B. Line 36 will not compile.C. Line 37 will not compile.D. Line 38 will not compile.Answer: AD 标识符以字母,下划线,或者$开始Question 2Given:11. public class Test {12. public static void main(String [] args) {13. int x =5;14. boolean b1 = true;15. boolean b2 = false;16.((x==4) && !b2)18. "l ");19. "2 ");20. if ((b2 = true) && b1)21. "3");22. }23. }What is the resultA. 2B. 3C. 1 2D. 2 3E. 1 2 3F. Compilation fails.G. An exceptional is thrown at runtime. Answer: D 注意20行,=为赋值,不要被骗Question 3Given:42. public class ClassA {43. public int getValue() {44. int value=0;45. boolean setting = true;46. String title="Hello";47. if (value || (setting && title == "Hello")) { return 1; }48. if (value == 1 & ("Hello")) { return 2; }49. }50. }And:70. ClassA a = new ClassA();71. ();What is the resultA. 1B. 2C. Compilation fails.D. The code runs with no output.E. An exception is thrown at runtime.Answer: C 编译不通过,47行value为int类型不是booleanQuestion 4Given:11. public void testIfA() {12. if(testIfB("True")) {13. "True");14. } else {15. "Not true");16. }17. }18. public Boolean testIfB(String str) {19. return (str);20. }What is the result when method testIfA is invokedA. TrueB. Not trueC. An exception is thrown at runtime.D. Compilation fails because of an error at line 12.E. Compilation fails because of an error at line 19.Answer: A 19行,如果str为true则返回ture,否则返回falseQuestion 5Given:11. public static void main(String[] args) {12. Integer i = new Integer(1) + new Integer(2);13. switch(i) {14. case 3: "three"); break;15. default: "other"); break;16. }17. }What is the resultA. threeB. otherC. An exception is thrown at runtime.D. Compilation fails because of an error on line 12.E. Compilation fails because of an error on line 13.F. Compilation fails because of an error on line 15. Answer: A 就是两个Integer类型相加Given:11. public static void main(String[] args) {12. String str = "null";13. if (str == null) {14. "null");15. } else () == 0) {16. "zero");17. } else {18. "some");19. }20. }‘What is the resultA. nullB. zeroC. someD. Compilation fails.E. An exception is thrown at runtime. Answer: D 这题真恶心 15行少个ifGiven:x=0;y=10;12. do {l3. y--;14. ++x;15. } while (x < 5);16. + "," + y);What is the resultA. 5,6B. 5,5C. 6,5D. 6,6Answer: B (91,82,73,64,55)没啥争议Question 8Given:x=12;26. while (x < 10) {27. x--;28. }29. is the resultA. 0B. 10C. 12D. Line 29 will never be reached.Answer: C 12>10,所以直接跳出循环,输出x=12Question 9Given:35. int x= 10;36. do {37. x--;38. } while(x< 10);How many times will line 37 be executedA. ten timesB. zero timesC. one to me timesD. more than ten timesAnswer: D 死循环Question 10Given:11. public static void main(String[] args) {12. for (int i=0;i<= 10;i++){13. if( i>6) break;14. }15. }What is the resultA. 6B. 7C. 10D. 11E. Compilation fails.F. An exception is thrown at runtime. Answer: E 15行i超出了作用域Question 11Given:55. int []x= {1, 2,3,4, 5};56. int y[] =x;57. is trueA. Line 57 will print the value 2.B. Line 57 will print the value 3.C. Compilation will fail because of an error in line 55.D. Compilation will fail because of an error in line 56. Answer: B 没争议,考察数组下标是从0开始Question 12Which two code fragments(片段) correctly(正确) create and initialize a static array of int elements (Choose two.)A. static final int[] a = { 100,200 };B. static final int[] a;static { a=new int[2]; a[0]=100; a[1]=200; }C. static final int[] a = new int[2] { 100,200 };D. static final int[] a;static void init() { a = new int[3]; a[0]=100; a[1]=200; }Answer: AB c不能指定长度,d不能在init方法中赋值,要么在static代码块中Question 13Given:11. public static void main(String[] args) {12. Object obj = new int[] { 1,2,3 };13. int[] someArray = (int[])obj;14. for (int i: someArray) +" ")15. }‘What is the resultA. 1 2 3B. Compilation fails because of an error in line 12.C. Compilation fails because of an error in line 13.D. Compilation fails because of an error in line 14.E. A ClassCastException is thrown at runtime. Answer: A 没争议,foeach循环遍历数组Question 14Given:11. String[] elements = { "for", "tea", "too" };12. String first = > 0) elements[0] : null;What is the resultA. Compilation fails.B. An exception is thrown at runtime.C. The variable first is set to null.D. The variable first is set to elements[0].Answer: DQuestion 15Given:10. public class Bar {void foo(int...x) {12. }14. }Which two code fragments, inserted independently(独立的) at line 12, will allow the class to compile (Choose two.)A. foreach(x) for(int z : x) while( ()) ());D. for( int i=0; i< ; i++ ) BD x相当于一个数组,a明显错没有foreach,c中x没有hadNext方法Question 16A programmer(程序员) needs to create a logging method that can accept(接受) an arbitrary(随意任意) number of arguments. For example, it may be called in theselogIt("log message 1 ");log It("log message2”,”log message3");logIt("log message4", "log message5", "log message6");Which declaration(说明) satisfies(符合) this requirement (需求)A. public void logIt(String * msgs)B. public void logIt(String [] msgs)C. public void logIt(String... msgs)D. public void logIt(String msg1, String msg2, String msg3)Answer: C 可变长参数Question 171. public class A {2. public String doit(int x, int y) {3. return "a";4. }5.6. public String doit(int... vals) {7. return "b";8. }Given:25. A a=new A();26. 5));What is the resultA. Line 26 prints "a" to .B. Line 26 prints "b" to .C. An exception is thrown at line 26 at runtime.D. Compilation of class A will fail due to an error in line 6.Answer: A 确定参数和可变长参数同时存在的时候,优先考虑确定参数的Question 18Given a file :1. package ;2.3. public class GrizzlyBear extends Bear {4. void hunt() {5. Salmon s = findSalmon();6. ();7. }and another file, :1. package ;2.3. public class Salmon extends Fish {4. void consume() { /* do stuff */ }5. }Assume(假定) both classes are defined in the correct directories for theft packages, and that the Mammal class correctly defines the findSalmon() method. Which two changes allow this code to compile correctly (Choose two.)A. add public to the start of line 4 inB. add public to the start of line 4 inC. add import .*; at line 2 inD. add import .*; at line 2 inE. add import at line 2 inF. add import line 2 inAnswer: AD 调用不同包下的类,要先导入,方法权限要设置成publicQuestion 19Given:10. package public class Geodetics {12. public static final double DIAMETER = ; }Which two correctly access(访问) the DIAMETER member of the Geodetics class (Choose two.)A. import class TerraCarta {public double halfway(){ return ; } }B. import static class TerraCarta {public double halfway() { return DIAMETER/; } }C. import static *;public class TerraCarta {public double halfway() { return DIAMETER/; } }D. package class TerraCarta {public double halfway() { return DIAMETER/; } }Answer: AC b中不能静态导入类,c中静态导入类属性,正确,d访问错误很明显Question 20Given classes defined in two different files:1. package util;2. public class BitUtils {3. private static void process(byte[] b) { }4. }1. package app;2. public class SomeApp {3. public static void main(String[] args) {4. byte[] bytes = new byte[256];5. }7. }What is required(必需的) at line 5 in class SomeApp to use the process methodof BitUtilsA. process(bytes);B. (bytes);C. import . *; process(bytes);F. SomeApp cannot use the process method in BitUtils.Answer: F 私有的,不能被访问Question 21Given a class Repetition(重复):1. package utils;2.3. public class Repetition {4. public static String twice(String s) { return s + s; }5. }and given another class Demo:1. 3. public class Demo {4. public static void main(String[] args) {5. "pizza"));6. }7. }Which code should be inserted at line 1 of to compile and run Demo to print “pizzapizza”A. import utils.*;B. static import utils.*;C. import .*;D. static import . *;E. import import static static import F 静态导入Question 22Given:1. package test;2.3. class Target(目标) {4. public String name = "hello";5. }What can directly(直接的) access and change the value of the variable(变量) nameA. any classB. only the Target classC. any class in the test packageD. any class that extends TargetAnswer: C default类型的类本包访问权限Question 23Given:11. rbo = new ReallyBigObject();12. rbo = null;14. /* insert code here */Which statement(语句) should be placed at line 14 to suggest (促成) that the virtual machine(虚拟机) expend(消耗) effort (努力) toward recycling(回收) the memory used by the object rboA. ();B. ();C. ();D. ().growHeap();E. ().freeMemory();Answer: A 题很简单。