scjp模拟题 (13)

合集下载

SCJP 6.0认证教战手册考题201-244.pdf

SCJP 6.0认证教战手册考题201-244.pdf

SCJP 6.0 認證教戰手冊黃彬華著碁峰出版書名:SCJP 6.0 認證教戰手冊作者:黃彬華完全擬真試題 201-244(共 244 題)第201題Given:1.import java.util.*;2.class A{}3.class B extends A{}4.public class Test{5.public static void main(Strang[] args){6.List<A> listA = new LinkedList<A>();7.List<B> listB = new LinkedList<B>();8.List<Obect> listO = new LinkedList<Obect>();9.//insert code here10.}11.public static void m1(List<? extends A> list){}12.public static void m2(List<A> list){}Place a result onto each method call to indicate what would happen if the method call were inserted at line 9. Note: Results can be used more than once.Method Calls Resultm1(listA); m2(listA); Does not compile.m1(listB); m2(listB); Compiles and runs without error.m1(listO); m2(listO); An exception is thrown atruntime.答案:m1(listA);Compiles and runs without error.m1(listB);Compiles and runs without error.m1(listO);Does not compile.m2(listA);Compiles and runs without error.m2(listB);Does not compile.m2(listO);Does not compile.參考:12-3 泛型第202題Given:NumberNames nn = new NumberNames();nn.put("one", 1);System.out.println(nn.getNames());Place the code into position to create a class that maps from Strings to integer values. The result of execution must be [one]. Some options may be used more than once.public class NumberNames{private HashMap< Place here , Place here > map =SCJP 6.0 認證教戰手冊黃彬華著碁峰出版public void put(String name, int value){map.put( Place here , Place here );}public Place here getNames(){return map.keySet();}}CodeSet<int> Set<Integer> HashSetSet<Integer, String> Set<int, String> Set<String, Integer>Set<String, int> Set<String> NumberNamesString Integer int >>() namevalue map答案:public class NumberNames{private HashMap< String , Integer > map =new HashMap< String , Integer>() ;public void put(String name, intvalue){ map.put( name , value );}public Set<String>getNames(){ returnmap.keySet();}}參考:12-5-1 HashMap第203題 Given:5.import java.util.*;6.public class SortOf{7.public static void main(String[] args){8.ArrayList<Integer> a = new ArrayList<Integer>();9. a.add(1); a.add(5); a.add(3);10.Collections.sort(a);11. a.add(2);12.Collections.reverse(a);13.System.out.println(a);14.}15.}What is the result?A.[1, 2, 3, 5]2D.[5, 3, 2, 1]E.[1, 3, 5, 2]pilation fails.G.An exception is thrown at runtime.答案:C參考:12-2-2 Collections 類別、12-4-5 List 集合第204題Given:11.public class Person{12.private name;13.public Person(String name){ = name;15.}16.public int hashCode(){17.return 420;18.}19.}Which statement is true?A.The time to find the value from HashMap with a Person key depends on the size of the map.B.Deleting a Person key from a HashMap will delete all map entries for all keys of type Person.C.Inserting a second Person object into a HashSet will cause the first Person object to be removed asa duplicate.D.The time to determine whether a Person object is contained in a HashSet is constant and does NOTdepend on the size of the map.答案:A參考:12-4-2 equals()、hashCode()方法的改寫第205題Given:12.import java.util.*;13.public class Explorer2{14.public static void main(String[] args){15.TreeSet<Integer> s = new TreeSet<Integer>();16.TreeSet<Integer> subs = new TreeSet<Integer>();17.for(int i=606; i<613; i++)18.if(i%2 == 0) s.add(i);19.subs = (TreeSet)s.subSet(608, true, 611, true);20.s.add(629);21.System.out.println(s + " " + subs);22.}23.}What is the result?pilation fails.B.An exception is thrown at runtime.C.[608, 610, 612, 629] [608, 610]D.[608, 610, 612, 629] [608, 610, 629]E.[606, 608, 610, 612, 629] [608, 610]F.[606, 608, 610, 612, 629] [608, 610, 629]答案:E參考:12-4-4 子集檢視第206題Given:1.public class Drink implements Comparable{2.public String name;3.public int compareTo(Object o){4.return 0;5.}6.}and:20.Drink one = new Drink();21.Drink two = new Drink(); = "Coffee"; = "Tea";24.TreeSet set = new TreeSet();25.set.add(one);26.set.add(two);A programmer iterates over the TreeSet and prints the name of each Drink object.What is the result?A.TeaB.CoffeeC.Coffee Teapilation fails.E.The code runs with no output.F.An exception is thrown at runtime.答案:B參考:12-4-3 SortedSet 集合第207題A programmer must create a generic class MinMax and the type parameter of MinMax must implement Comparable. Which implementation of MinMax will compile?A.class MinMax<E extendsComparable<E>>{ E min = null;E max = null;public MinMax(){}public void put(E value){/* store min or max */}B.class MinMax<E implementsComparable<E>>{ E min = null;E max = null;public MinMax(){}public void put(E value){/* store min or max */}C.class MinMax<E extendsComparable<E>>{ <E> E min = null;<E> E max = null;public MinMax(){}public <E> void put(E value){/* store min or max */}D.class MinMax<E implementsComparable<E>>{ <E> E min = null;<E> E max = null;public MinMax(){}public <E> void put(E value){/* store min or max */}答案:A參考:12-3 泛型第208題Given:1.import java.util.*;2.public class Example{3.public static void main(String[] args){4.//insert code here5.set.add(new Integer(2));6.set.add(new Integer(1)),7.System.out.println(set);8.}9.}Which code, inserted at line 4, guarantees that this program will output [1, 2]?A.Set set = new TreeSet();B.Set set = new HashSet();C.Set set = new SortedSet();D.List set = new SortedList();E.Set set = new LinkedHashSet();答案:A參考:12-4-3 SortedSet 集合第209題Given:1.import java.util.*;2.public class TestSet{3.enum Example{ONE, TWO, THREE}4.public static void main(String[] args){5.Collection coll = new ArrayList();6.coll.add(Example.THREE);7.coll.add(Example.THREE);8.coll.add(Example.THREE);9.coll.add(Example.TWO);10.coll.add(Example.TWO);11.coll.add(Example.ONE)12.Set set = new HashSet(coll);13.}14.}Which statement is true about the set variable on line 12?A.The set variable contains all six elements from the coll collection, and the order is guaranteed tobe preserved.B.The set variable contains only three elements from the coll collection, and the order is guaranteed tobe preserved.C.The set variable contains all six elements from the coll collection, but the order is NOT guaranteed tobe preserved.D.The set variable contains only three elements from the coll collection, but the order is NOTguaranteed to be preserved.答案:D參考:12-4-1 Set 集合、12-4-5 List 集合第210題Given:11.public class Person{12.private String name, comment;13.private int age;14.public Person(String n, int a, String c){ = n; age = a; comment = c;16.}17.public boolean equals(Object o){18.if (!(0 instanceof Person)) return false;19.Person p = (Person)o;20.return age == p.age && name.equals();21.}22.}What is the appropriate definition of the hashCode method in class Person?A.return super.hashCode();B.return name.hashcode() + age * 7;C.return name.hashCode() + comment.hashCode() / 2;D.return name.hashCode() + comment.hashCode() / 2- age * 3;答案:D參考:12-4-2 equals()、hashCode()方法的改寫第211題Given:11.public class Key{12.private long id1,13.private long id2;14.15.//class Key methods16.}A programmer is developing a class Key, that will be used as a key in a standard java.util.HashMap. Which two methods should be overridden to assure that Key works correctly as a key? (Choose two.)A.public int hashCode()B.public void hashCode()C.public int compareTo(Object o)D.public boolean equals(Object o)E.public boolean compareTo(Key k)答案:AD參考:12-4-2 equals()、hashCode()方法的改寫第212題Given:3.import java.util.*;4.public class Hancock{5.//insert code here6.list.add("foo");7.}8.}Which two code fragments, inserted independently at line 5, will compile without warnings? (Choose two.)A.public void addStrings(List list){B.public void addStrings(List<String> list){C.public void addStrings(List<? super String> list){D.public void addStrings(List<? extends String> list){答案:BC參考:12-4-2 equals()、hashCode()方法的改寫第213題Given a class whose instances, when found in a collection of objects, are sorted by using the compareTo() method, which two statements are true? (choose two.)A.The class implements parable.B.The class implements parator.C.The interface used to implement sorting allows this class to define only one sort sequence.D.The interface used to implement sorting allows this class to define many different sort sequences. 答案:AC參考:12-4-3 SortedSet 集合第214題Given:12.import java.util.*;13.public class Explorer3{14.public static void main(String[] args){15.TreeSet<Integer> s = new TreeSet<Integer>();16.TreeSet<Integer> subs = new TreeSet<Integer>();17.for(int i=606; i<613; i++)18.if(i%2 == 0) s.add(i);19.subs = (TreeSet)s.subSet(608, true, 611, true);20.subs.add(629);21.System.out.println(s + " " + subs);22.}23.}What is the result?pilation fails.B.An exception is thrown at runtime.C.[608, 610, 612, 629] [608, 610]D.[608, 610, 612, 629] [608, 610, 629]E.[606, 608, 610, 612, 629] [608, 610]F.[606, 608, 610, 612, 629] [608, 610, 629]答案:B參考:12-4-4 子集檢視第215題Given:1.import java.util.*;2.3.public class LetterASort{4.public static void main(String[] args){5.ArrayList<String> strings = new ArrayList<String>();6.strings.add("aAaA");7.strings.add("AaA");8.strings.add("aAa");9.strings.add("AAaa");10.Collections.sort(strings);11.for(String s : strings){System.out.print(s + " ");}12.}13.}What is the result?pilation fails.B.aAaA aAa AAaa AaAC.AAaa AaA aAa aAaAD.AaA AAaa aAaA aAaE.aAa AaA aAaA AAaaF.An exception is thrown at runtime.答案:C參考:12-2-2 Collections 類別、12-4-5 List 集合第216題Given:1.import java.util.*,2.public class TestGenericConversion{3.public static void main(String[] args){4.List list = new LinkedList();5.list.add("one");6.list.add("two");7.System.out.print(((String)list.get(O)).length());8.}9.}Refactor this class to use generics without changing the code's behavior.1. import java.util.*,2. public class TestGenericConversion{3. public static void main(String[] args){4. Place here5. list.add("one");6. list.add("two");7. Place here8. }9. }CodeList list = new LinkedList();System.out.print(list.get(0).length());List<String> list = new LinkedList<String>();System.out.print(list.get<String>(0).length()); List<String> list = new LinkedList(); System.out.print(<String>list.get(0).length());List list = new LinkedList<String>(); System.out.print((List<String>)list.get(0).length());1.import java.util.*,2.public class TestGenericConversion{3.public static void main(String[] args){4.List<String> list = new LinkedList<String>();5.list.add("one");6.list.add("two");7.System.out.print(list.get(0).length());8.}9.}參考:12-3 泛型SCJP 6.0 認證教戰手冊黃彬華著碁峰出版第217題Place the code into the GenericB class definition to make the class compile successfully.答案:參考:12-3 泛型10SCJP 6.0 認證教戰手冊黃彬華著碁峰出版第218題Place the code elements in position so that the Flags2 class will compile and make appropriate use of the wait/notify mechanism. Note You may reuse code elements.class Flags2{private boolean isReady = false;public Place here void produce(){isReady = true;Place here ;}public Place here voidconsume(){ while(!isReady){try{Placehere ; }catch(Exceptionex){}}isReady = Place here ;}}Code Elementssynchronizedtruefalsewait()volatilesynchronized()notifyAll()synchronize答案:class Flags2{private boolean isReady = false;public synchronized void produce(){isReady = true;notifyAll() ;}public synchronized voidconsume(){ while(!isReady){try{wait() ; }catch(Exception ex){}}isReady = false ;}}參考:13-5 執行緒的互動處理第219題 Given:1.public class Threads2 implements Runnable{114.System.out.println("run.");5.throw new RuntimeException("Problem");6.}7.public static void main(String[] args){8.Thread t = new Thread(new Threads2());9.t.start();10.System.out.println("End of method.");11.}12.}Which two can be results? (Choose two.)ng.RuntimeException: ProblemB.run.ng.RuntimeException: ProblemC.End of method.ng.RuntimeException: ProblemD.End of method.run.ng.RuntimeException: ProblemE.run.ng.RuntimeException: ProblemEnd of method.答案:DE參考:13-2 Java 執行緒與 Thread 類別第220題Which factor or factorsA.It is possible for more than two threads to deadlock at once.B.The JVM implementation guarantees that multiple threads cannot enter into a deadlocked state.C.Deadlocked threads release once their sleep() method's sleep duration has expired.D.Deadlocking can occur only when the wait(), notify() and notifyAll() methods are used incorrectly.E.It is possible for a single-threaded application to deadlock if synchronized blocks are used incorrectly.F.If a piece of code is capable of deadlocking, you cannot eliminate the possibility of deadlocking byinserting invocations of Thread.yield().答案:AF參考:13-5 執行緒的互動處理第221題Given:7.void waitForSignal(){8.Object obj = new Object();9.synchronized(Thread.currentThread()){10.obj.wait();11.obj.notify();12.}13.}Which statement is true?A.This code can throw an InterruptedException.B.This code can throw an IllegalMonitorStateException.C.This code can throw a TimeoutException after ten minutes.D.Reversing the order of obj.wait() and obj.notify() might cause this method to complete normally.E. A call to notify() or notifyAll() from another thread might cause this method to complete normally.F.This code does NOT compile unless "obj.wait()" is replaced with "((Thread) obj).wait()".答案:B參考:13-5 執行緒的互動處理第222題Given:10.public class Starter extends Thread{11.private int x = 2;12.public static void main(String[] args) throws Exception{13.new Starter().makeItSo();14.}15.public Starter(){16.x = 5;17.start();18.}19.public void makeItSo() throws Exception{20.join();21.x = x - 1;22.System.out.println(x);23.}24.public void run(){x *= 2;}25.}What is the output if the main() method is run?A. 4B. 5C.8D.9pilation fails.F.An exception is thrown at runhime.G.It is impossible to determine for certain.答案:D參考:13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第223題Given:11.class PingPong2{12.synchronized void hit(long n){13.for(int i=1; i<3; i++)14.System.out.print(n + "-" + i + " ");15.}16.}17.public dass Tester implements Runnable{18.static PingPong2 pp2 = new PingPong2();19.public static void main(String[] args){20.new Thread(new Tester()).start();21.new Thread(new Tester()).start();22.}23.public void run(){pp2.hit(Thread.currentThread.getId());}24.}Which statement is true?A.The output could be 5-1 6-1 6-2 5-2B.The output could be 6-1 6-2 5-1 5-2C.The output could be 6-1 5-2 6-2 5-1D.The output could be 6-1 6-2 5-1 7-1答案:B參考:13-4 執行緒的同步性與安全性第224題Given:1.public class Threads4{2.public static void main(String[] args){3.new Threads4.go();4.}5.public void go(){6.Runnable r = new Runnable(){7.public void run(){8.System.out.print("foo");9.}10.};11.Thread t = new Thread(r);12.t.start();13.t.start();14.}15.}What is the result?pilation fails.B.An exception is thrown at runtime.C.The code executes normally and prints "foo";D.The code executes normally, but nothing is printed.答案:B參考:13-4 執行緒的同步性與安全性第225題Given:10.Runnable r = new Runnable(){11.public void run(){12.try{13.Thread.sleep(1000);14.}catch(InterruptedException e){15.System.out.println("interrupted");16.}17.System.out.println("ran");18.}19.};20.Thread t = new Thread(r);21.t.start();22.System.out.println("started");23.t.sleep(2000):24.System.out.println("interrupting");25.t.interrupt();26.System.out.println("ended");Assume that sleep(n) executes in exactly n milliseconds. and all other code executes in an insignificant amount of time.Place the fragments in the output area to show the result of running this code.答案:第226題Which two statements are true? (Choose two.)A. It is possible to synchronize static methods.15SCJP 6.0 認證教戰手冊黃彬華著碁峰出版B.When a thread has yielded as a result of yield(), it releases its locks.C.When a thread is sleeping as a result of sleep(), it releases its locks.D.The Object.wait() method can be invoked only from a synchronized context.E.The Thread.sleep() method can be invoked only from a synchronized context.F.When the thread scheduler receives a notify() request, and notifies a thread, that thread immediatelyreleases its lock.答案:AD參考:13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面、13-5 執行緒的互動處理第227題Given:1.public class TestOne implements Runnable{2.public static void main (String[] args)throws Exception{3.Thread t = new Thread(new TestOne());4.t.start();5.System.out.pririt("Started");6.t.join();7.System.out.print("Complete");8.}9.public void run(){10.for(int i=0; i<4; i++){11.System.out.print(i);12.}13.}14.}What can be a result?pilation fails.B.An exception is thrown at runtime.C.The code executes and prints "StartedComplete".D.The code executes and prints "StartedComplete0123".E.The code executes and prints "Started0123Complete".答案:E參考:13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第228題Which three will compile and run without exception? (Choose three.)A.private synchronized Object o;B.void go(){synchronized(){/* code here */}C.public synchronized void go(){/* code here */}D.private synchronized(this) void go(){/* code here */}E.void go(){synchronized(Object.class){/* code here */}F.void go(){Object o = new Object();synchronized(o){/* code here */}答案:CEF參考:13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面、13-5 執行緒的互動處理第229題Given:1.public class TestFive{2.private int x;3.public void foo(){4.int current = x;5.x = current + 1;6.}7.public void go(){8.for(int i=0; i<5; i++){9.new Thread(){10.public void run(){11. foo();12. System.out.print(x + ", ");13.}}.start();14.}}Which two changes, taken together, would guarantee the output: 1, 2, 3, 4, 5, ? (Choose two.)A.move the line 12 print statement into the foo() methodB.change line 7 to public synchronized void go(){C.change the variable declaration on line 2 to private volatile int x;D.wrap the code inside the foo() method with a synchronized(this) blockE.wrap the for loop code inside the go() method with a synchronized block synchronized(this){//for loopcode here}答案:AD參考:8-5-4 匿名內部類別、13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第230題Given that t1 is a reference to a live thread, which is true?A.The Thread.sleep() method can take t1 as an argument.B.The Object.notify() method can take t1 as an argument.C.The Thread.yield() method can take t1 as an argument.D.The Thread.setPriority() method can take t1 as an argument.E.The Object.notify() method arbitrarily chooses which thread to notify.答案:E參考:13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面、13-5 執行緒的互動處理第231題Given:11.Runnable r = new Runnable(){12.public void run(){13.System.out.print("Cat");14.}15.};16.Thread t = new Thread(r){17.public void run(){18.System.outprint("Dog");19.}20.};21.t.start();What is the result?A.CatB.Dogpilation fails.D.The code runs with no output.E.An exception is thrown at runtime.答案:B參考:8-5-4 匿名內部類別、13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第232題Given:1.public class Threads5{2.public static void main(String[] args){3.new Thread(new Runnable(){4.public void run(){5.System.out.print("bar");6.}}).start();7.}8.}What is the result?pilation fails.B.An exception is thrown at runtime.C.The code executes normally and prints "bar".D.The code executes normally, but nothing prints.答案:C參考:8-5-4 匿名內部類別、13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第233題Given:1.public class Threads1{2.int x = 0;3.public class Runner implements Runnable{4.public void run(){S.int current = 0;6.for(int i=0; i<4; i++){7.current = x;8.System.out.print(current + ", ");9.x = current + 2;10.}11.}12.}13.14.public static void main(String[] args){15.new Threads1().go();16.}17.18.public void go(){19.Runnable rl = new Runner();20.new Thread(r1).start();21.new Thread(r1).start();22.}23.}Which two are possible results? (Choose two.)A.0, 2, 4, 4, 6, 8, 10, 6,B.0, 2, 4, 6, 8, 10, 2, 4,C.0, 2, 4, 6, 8, 10, 12, 14,D.0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14,E.0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14,答案:AC參考:8-5-4 匿名內部類別、13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第234題Given:foo and bar are public references available to many other threads, foo refers to a Thread and bar is an Object. The thread foo is currently executing bar.wait().From another thread, what provides the most reliable way to ensure that foo will stop executing wait()?A.foo.notify();B.bar.notify();C.foo.notifyAll();D.Thread.notify();E.bar.notifyAll();F.Object.notify();答案:E參考:13-5 執行緒的互動處理第235題Given:11.public class PingPong implements Runnable{12.synchronized void hit(long n){13.for(int i=1; i<3; i++)14.System.out.print(n + "-" + i + " ");15.}16.public static void main(String[] args){17.new Thread(new PingPong()).start();18.new Thread(new PingPong()).start();19.}20.public void run(){21.hit(Thread.currentThread().getId);22.}23.}Which two statements are true? (Choose two.)A.The output could be 8-1 7-2 8-2 7-1B.The output could be 7-1 7-2 8-1 6-1C.The output could be 8-1 7-1 7-2 8-2D.The output could be 8-1 8-2 7-1 7-2答案:CD參考:13-4 執行緒的同步性與安全性第236題Given:1.class Computation extends Thread{2.3.private int num;4.private boolean isComplete;5.private int result;6.7.public Computation(int num){this.num = num;}8.9.public synchronized void run(){10.result = num * 2;11.isComplete = true;12.notify();13.}14.15.public synchronized int getResult(){16.while(!isComplete){17.try{18.wait();19.}catch(InterruptedException e){}20.}21.return result;22.}23.24.public static void main(String[] args){putation[] computations = new Computation[4];26.for(int i=0; i<computations.length; i++){putations[i] = new Computation(i);putations[i].start();29.}30.for(Computation c : computations)31.System.out.print(c.getResult() + " ");32.}33.}What is the result?A.The code will deadlock.B.The code may run with no output.C.An exception is thrown at runtime.D.The code may run with output "0 6".E.The code may run with output "2 0 6 4".F.The code may run with output "0 2 4 6".答案:F參考:13-4 執行緒的同步性與安全性第237題Place the code elements into the class so that the code compiles and prints "Run. Run. doIt. " in exactly that order. Note that there may be more than one correct solution.class TesTwo extends Thread{public static void main(String[] a) throwsException{ TesTwo t = new TesTwo();t.start();Place herePlace herePlace here}public voidrun(){ System.out.print("Run. ");}public voiddoIt(){ System.out.print("doIt. ");}}Code Elementst.start();t.join();t.pause(10);run();t.run();t.doIt(); doIt();答案:class TesTwo extends Thread{public static void main(String[] a) throws21SCJP 6.0 認證教戰手冊黃彬華著碁峰出版t.run();t.join();t.doIt();}public voidrun(){ System.out.print("Run. ");}public voiddoIt(){ System.out.print("doIt. ");}}參考:13-2 Java 執行緒與 Thread 類別第238題Which two code fragments will execute the method doStuff() in a separate thread? (Choose two.)A.new Thread(){public voidrun(){doStuff();} };B.new Thread(){public voidstart(){doStuff();} };C new Thread(){public voidstart(){doStuff();} }.run();D.new Thread(){public voidrun(){doStuff();} }.start();E.new Thread(newRunnable(){ public voidrun(){doStuff();} }).run();F.new Thread(newRunnable(){ public voidrun(){doStuff();}}).start();答案:DF參考:8-5-4 匿名內部類別、13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第239題 Given:22SCJP 6.0 認證教戰手冊黃彬華著碁峰出版4.System.out.println("sleep");5.}6.}What is the result?pilation fails.B.An exception is thrown at runtime.C.The code executes normally and prints "sleep".D.The code executes normally, but nothing is printed.答案:C參考:13-2 Java 執行緒與 Thread 類別第240題Place a Class on each method that is declared in the class.參考:13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面、13-5 執行緒的互動處理第241題Given:1.public class Threads3 implements Runnable{2.public void run(){3.System.out.print("running");4.}5.public static void main(String[] args){6.Thread t = new Thread(new Threads3());7.t.run();11.}23What is the result?pilation fails.B.An exception is thrown at runtime.C.The code executes and prints "running".D.The code executes and prints "runningrunning".E.The code executes and prints "runningrunningrunning".答案:E參考:13-3 Runnable 介面第242題Given:public classNamedCounter{ privatefinal String name; privateint count;public NamedCounter(String name){ = name;}public String getName(){return name;}public void increment(){count++;}public int getCount(){return count;}public void reset(){count = 0;}Which three changes should be made to adapt this class to be used safely by multiple threads? (Choose three.)A.declare reset() using the synchronized keywordB.declare getName() using the synchronized keywordC.declare getCount() using the synchronized keywordD.declare the constructor using the synchronized keywordE.declare increment() using the synchronized keyword答案:ACE參考:13-3 Runnable 介面第243題Given that Triangle implements Runnable, and:31.void go() throws Exception{32.Thread t = new Thread(new Triangle());33.t.start();34.for(int x=1; x<100000; x++){35.//insert code here36.if(x%100 == 0) System.out.print("g");37.}}38.public void run(){39.try{40.for(int x=1; x<100000; x++){41.//insert the same code here42.if(x%100 == 0) System.out.print("t");43.}24。

2023年四川省南充市全国计算机等级考试C++语言程序设计模拟考试(含答案)

2023年四川省南充市全国计算机等级考试C++语言程序设计模拟考试(含答案)

2023年四川省南充市全国计算机等级考试C++语言程序设计模拟考试(含答案)学校:________ 班级:________ 姓名:________ 考号:________一、1.选择题(10题)1.在C++语言中函数返回值的类型是由()决定的。

A.调用该函数时系统临时B.return 语句中的表达式类型C.定义该函数时所指定的函数类型D.调用该函数时的主调函数类型2. 下列程序的运行结果为#include<iostream.h>class Location {protected:int X,Y;publiC:void SeX(int myx){X=myx;}void SetY(int myy){Y=myy;} void showxy( ) {cout<<"X=" <<X<<" " <<"Y"=<<Y<<endl;} };Class Rectangle :public Location{A.X=3 Y=5 X=3 Y=5 H=4 W=6B.X=3 Y=5X=3 Y=5 H=3 W=6C.X=3 Y=5X=3 Y=4 H=4 W=6D.X=3 Y=5X=3 Y=3 H=4 W=63. 若有以下程序:#include <iostream>using namespace std; class Base { public: Base ( ) { x=0; } int x; }; class Derivedl : virtual public Base { public: Derivedl () { x=10; } }; class Derived2 : virtual public Base { public: Derived2 () { x=20; } }; class Derived : public Derivedl,protected Derived2{ }; int main ( ) { Derived obj; cout<<obj .x<<end1; return 0; }该程序运行后的输出结果是( )。

SCJP认证试题及答案

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?。

英文SCJP模拟题200道附答案

英文SCJP模拟题200道附答案

英文SCJP模拟题200道附答案,因为目录分隔符不正确。

3)执行此代码时,不会在硬盘上创建文件。

4)如果文件已经存在,运行时将引发异常。

5)代码无法编译,因为这不是文件类的有效构造函数。

问题7:关于随机访问文件类,下列哪项陈述是正确的?1)如果使用\模式创建时指定的文件不存在,则会引发IOException。

2)这个类有一个允许从硬盘上删除文件的方法。

3)可以将这个类与DataInputStream类结合使用。

4)当与\模式一起使用时,如果指定的文件不存在,它将在磁盘驱动器上创建。

5)有读和写主词的方法(例如,readInt(),writeInt(),等等)。

考虑下面这段代码,并从下面选择正确的语句。

1.字符串s =新字符串(\ 2 . s . replace(“d”、“q”);3.系统输出打印输入。

1)代码编译失败,在第2行报告了一个错误。

字符串是不可变的,因此replace()方法毫无意义。

2)代码编译正确,并显示文本\ 3)代码编译正确,并显示文本\4)代码编译,但是在执行第2行时会引发异常。

5)代码编译,但是在第3行抛出异常。

Q9下列哪个关键字可以应用到界面的变量或方法中。

1)静态2)私有3)同步4)受保护5)公共Q10真或假。

只有框架可以包含菜单栏或下拉菜单。

1)真2)假。

Q11考虑以下代码,选择正确的语句:1.甲级2.受保护的int方法(){ 3。

} 4。

} 5。

6.B类扩展了A{ 7。

int方法(){ 8。

} 9。

}1)代码无法编译,因为您不能重写一个比其父方法更私有的方法。

2)代码无法编译,因为方法()被声明为受保护的,因此对任何子类都不可用。

3)代码编译正确,但是在运行时抛出一个空指针异常。

4)代码无法编译。

但是,可以通过在第7行前加上访问限定符\来正确编译5)代码无法编译。

但是,可以通过在第7行前加上访问限定符\ Q12真或假来进行正确编译。

可抛出类是Java语言中所有异常的超类。

一些SCJP考试题含答案

一些SCJP考试题含答案

一些SCJP考试题含答案Leading the way in IT testing and certification tools,QUESTION NO: 92 Given:1. String foo = “blue”;2. Boolean[]bar = new Boolean [1];3. if (bar[0]) {4. foo = “green”;5. }What is the result?A. Foo has the value of “”B. Foo has the value of null.C. Foo has the value of “blue”D. Foo has the value of “green”E. An exception is thrown.F. The code will not compile.Answer: FQUESTION NO: 93Exhibit:1. public class X {2. public static void main (String[]args) {3. String s1 = new String (“true”);4. Boolean b1 = new Boolean (true);5. if (s2.equals(b1)) {6. System.out.printIn(“Equal”);7. }8. }9. }What is the result?A. The program runs and prints nothing.B. The program runs and prints “Equal”C. An error at line 5 causes compilation to fail.D. The program runs but aborts with an exception.Answer: AQUESTION NO: 94Given:1. public class Foo {2. public static void main (String []args) {3. int i = 1;4. int j = i++;5. if ((i&gt;++j) &amp;&amp; (i++ ==j)) {6. i +=j;7. }9. }What is the final value of i?A. 1B. 2C. 3D. 4E. 5Answer: BQUESTION NO: 95Exhibit:1. public class X {2. public static void main (String[]args) {3. string s = new string (“Hello”);4. modify(s);5. System.out.printIn(s);6. }7.8. public static void modify (String s) {9. s += “world!”;10. }11. }What is the result?E. The program runs and prints “Hello”F. An error causes compilation to fail.G. The program runs and prints “Hello world!”H. The program runs but aborts with an exception. Answer: AQUESTION NO: 96Which two are equivalent? (Choose Two)A. 16&gt;4B. 16/2C. 16*4D. 16&gt;&gt;2E. 16/2^2F. 16&gt;&gt;&gt;2Answer: D, EQUESTION NO: 97Exhibit:1. public class X {2. public static void main (String[]args) {3. int [] a = new int [1]4. modify(a);5. System.out.printIn(a[0]);7.8. public static void modify (int[] a) {9. a[0] ++;10. }11. }What is the result?A. The program runs and prints “0”B. The program runs and prints “1”C. The program runs but aborts with an exception.D. An error “possible undefined variable” at line 4 causes compilation to fail.E. An error “possible undefined variable” at line 9 causes compilation to fail. Answer: BQUESTION NO: 98Given:13. public class Foo {14. public static void main (String [] args) {15. StringBuffer a = new StringBuffer (“A”);16. StringBuffer b = new StringBuffer (“B”);17. operate (a,b);18. system.out.printIn,a + “,” +b-;19. )20. static void operate (StringBuffer x, StringBuffer y) {21. y.append {x};22. y = x;23. )24. }What is the result?A. The code compiles and prints “A,B”.B. The code compiles and prints “A, BA”.C. The code compiles and prints “AB, B”.D. The code compiles and prints “AB, AB”.E. The code compiles and prints “BA, BA”.F. The code does not compile because “+” cannot be overloaded for stringBuffer. Answer: BQUESTION NO: 99Given:1. public class X {2. public static void main (String[] args) {3. byte b = 127;4. byte c = 126;5. byte d = b + c;6. }7. }Which statement is true?A. Compilation succeeds and d takes the value 253.B. Line 5 contains an error that prevents compilation.C. Line 5 throws an exception indicating “Out of range”D. Line 3 and 4 contain error that prevent compilation.E. The compilation succeeds and d takes the value of 1.Answer: BQUESTION NO: 100Given:1. public class WhileFoo {2. public static void main (String []args) {3. int x= 1, y = 6;4. while (y--) {x--;}5. system.out.printIn(“x=” + x “y =” + y);6. }7. }What is the result?A. The output is x = 6 y = 0B. The output is x = 7 y = 0C. The output is x = 6 y = -1D. The output is x = 7 y = -1E. Compilation will fail.Answer: EQUESTION NO: 101Which statement is true?A. The Error class is a untimeException.B. No exceptions are subclasses of Error.C. Any statement that may throw an Error must be enclosed in a try block.D. Any statement that may throw an Exception must be enclosed in a try block.E. Any statement that may thro a runtimeException must be enclosed in a try block. Answer: DQUESTION NO: 102Exhibit:1. int I=1, j=02.3. switch(i) {4. case 2:5. j+=6;6.7. case 4:8. j+=1;9.10. default:11. j +=2;12.13. case 0:14. j +=4;15. }16.What is the value of j at line 16?A. 0B. 1C. 2D. 4E. 6Answer: AEQUESTION NO: 103Given:1. switch (i) {2. default:3. System.out.printIn(“Hello”);4. )What is the acceptable type for the variable i?A. ByteB. LongC. FloatD. DoubleE. ObjectF. A and BG. C and DAnswer: AQUESTION NO: 104You need to store elements in a collection that guarantees that no duplicates are stored. Which twointerfaces provide that capability? (Choose Two)A. Java.util.MapB. Java.util.SetC. Java.util.ListD. Java.util.StoredSetE. Java.util.StoredMapF. Java.util.CollectionAnswer: B, DQUESTION NO: 105Which statement is true for the class java.util.ArrayList?A. The elements in the collection are ordered.B. The collection is guaranteed to be immutable.C. The elements in the collection are guaranteed to be unique.D. The elements in the collection are accessed using a unique key.E. The elements in the collections are guaranteed to be synchronized.Answer: AQUESTION NO: 106Exhibit:1. public class X implements Runnable(2. private int x;3. private int y;4.5. public static void main(String[]args)6. X that = new X();7. (new Thread(that)).start();8. (new Thread(that)).start();9. )10.11. public void run() (12. for (;;) (13. x++;14. y++;15. System.out.printIn(“x=” + x + “, y = ” + y);16. )17. )18. )What is the result?A. Errors at lines 7 and 8 cause compilation to fail.B. The program prints pairs of values for x and y that might not always be the same on the same line(for example, “x=2, y=1”).C. The program prints pairs of values for x and y that are always the same on the same line (for example, “x=1, y=1”.In addition, each value appears twice (for example, “x=1, y=1” followed by “x=1, y=1”).D. The program prints pairs of values for x and y that are always the same on the same line (for example, “x=1, y=1”. In addition, each value appears only for once (for example, “x=1, y=1”followed by “x=2, y=2”).Answer: DQUESTION NO: 107Given:1. public class SyncTest {2. private int x;3. private int y;4. public synchronized void setX (int i) (x=1;)5. public synchronized void setY (int i) (y=1;)6. public synchronized void setXY(int 1)(set X(i); setY(i);)7. public synchronized Boolean check() (return x !=y;)8. )Under which conditions will check () return true when called from a different class?A. Check() can never return true.B. Check() can return true when setXY is called by multiple threads.C. Check() can return true when multiple threads call setX and setY separately.D. Check() can only return true if SyncTest is changed to allow x and y to be set separately. Answer: AQUESTION NO: 108Which is a method of the MouseMotionListener interface?A. Public void mouseDragged(MouseEvent)B. Public boolean mouseDragged(MouseEvent)C. Public void mouseDragged(MouseMotionEvent)D. Public boolean MouseDragged(MouseMotionEvent)E. Public boolean mouseDragged(MouseMotionEvent)Answer: AQUESTION NO: 109Given:1. String foo = “base”;2. foo.substring(0,3);3. foo.concat(“ket”);4. foo += “ball”;5.Type the value of foo at line 8.Answer: BASEBALLQUESTION NO 110Given:1. public class Test {2. public static void leftshift(int i, int j) {3. i&lt;&lt;=j;4. }5. public static void main(String args[]) {6. int i = 4, j = 2;7. leftshift(i, j);8. System.out.printIn(i);9. }10. }What is the result?A. 2B. 4C. 8D. 16E. The code will not compile.Answer: BQUESTION NO 111Given:1. public class Foo {2. private int val;3. public foo(int v) (val = v;) }4. public static void main (String [] args) {5. Foo a = new Foo (10);6. Foo b = new Foo (10);7. Foo c = a;8. int d = 10;9. double e = 10.0;10. }11. }Which three logical expression evaluate to true? (Choose Three)A. (a ==c)B. (d ==e)C. (b ==d)D. (a ==b)E. (b ==c)F. (d ==10.0)Answer: A, B, FQUESTION NO 112Exhibit:1. public class X {2. private static int a;3.5. public static void main (String[] args) {6. modify (a);7. }8.9. public static void modify (int a) {10. a++;11. }12. }What is the result?A. The program runs and prints “0”B. The program runs and prints “1”C. The program runs but aborts with an exception.D. En error “possible undefined variable” at line 5 causes compilation to fail.F. En error “possible undefined variable” at line 10 causes compilation to fail. Answer: AQUESTION NO 113Exhibit:1. public class Test {2. public static void replaceJ(string text) {3. text.replace (‘j’, ‘l’);4. }5.6. public static void main(String args[]) {7. string text = new String (“java”)8. replaceJ(text);9. system.out.printIn(text);10. }11. }What is the result?A. The program prints “lava”B. The program prints “java”C. An error at line 7 causes compilation to fail.D. Compilation succeeds but the program throws an exception. Answer: BQUESTION NO 114Which two are equivalent? (Choose Two)A. 3/2B. 3&lt;2C. 3*4D. 3&lt;&lt;2E. 3*2^2F. 3&lt;&lt;&lt;2Answer: C, DQUESTION NO 115What is the numerical range of a char?A. 0 . . . 32767B. 0 . . . 65535C. ?256 . . . 255D. ?32768 . . . 32767E. Range is platform dependent.Answer: BQUESTION NO 116Given:1. public class Test {2. public static void main (String []args) {3. unsigned byte b = 0;4. b--;5.6. }7. }What is the value of b at line 5?A. -1B. 255C. 127D. Compilation will fail.E. Compilation will succeed but the program will throw an exception at line 4.Answer: DQUESTION NO 117Given:1. public class Foo {2. public void main (String [] args) {3. system.out.printIn(“Hello World.”);4. }5. }What is the result?A. An exception is thrown.B. The code does no compile.C. “Hello World.” Is printed to the terminal.D. The program exits without printing anything.Answer: AQUESTION NO 118Given:1. //point X2. public class foo (3. public static void main (String[]args) throws Exception {4. java.io.printWriter out = new java.io.PrintWriter (5. new java.io.outputStreamWriter (System.out), true;6. out.printIn(“Hello”);7. }8. }Which statement at PointX on line 1 allows this code to compile and run?A. Import java.io.*;B. Include java.io.*;C. Import java.io.PrintWriter;D. Include java.io.PrintWriter;E. No statement is needed.Answer: EQUESTION NO 119Which will declare a method that is available to all members of the same package and can be referencedwithout an instance of the class?A. Abstract public void methoda();B. Public abstract double methoda();C. Static void methoda(double d1){}D. Public native double methoda() {}E. Protected void methoda(double d1) {}Answer: CQUESTION NO 120Which type of event indicates a key pressed on a ponent?A. KeyEventB. KeyDownEventC. KeyPressEventD. KeyTypedEventE. KeyPressedEventAnswer: AQUESTION NO 121Exhibit:1. import java.awt.*;2.3. public class X extends Frame {4. public static void main (String [] args) {5. X x = new X();6. x.pack();7. x.setVisible(true);8. }9.10. public X() {11. setLayout (new BordrLayout());12. Panel p = new Panel ();13. add(p, BorderLayout.NORTH);14. Button b = new Button (“North”);15. p.add(b):16. Button b = new Button (“South”);17. add(b1, BorderLayout.SOUTH):18. }19. }Which two statements are true? (Choose Two)A. The buttons labeled “North” and “South” will have the s ame width.B. The buttons labeled “North” and “South” will have the same height.C. The height of the button labeled “North” can very if the Frame is resized.D. The height of the button labeled “South” can very if the Frame is resized.E. The width of the button labeled “North” is constant even if the Frame is resized.F. The width of the button labeled “South” is constant even if the Frame is resized. Answer: B, EQUESTION NO 122How can you create a listener class that receives events when the mouse is moved?A. By extending MouseListener.B. By implementing MouseListener.C. By extending MouseMotionListener.D. By implementing MouseMotionListener.E. Either by extending MouseMotionListener or extending MouseListener.F. Either by implementing MouseMotion Listener or implementing MouseListener.Answer: DQUESTION NO 123Which statement is true?A. A grid bag layout can position components such that they span multiple rows and/or columns.B. The “North” region of a border layout is the proper place to locat e a menuBar component in a Frame.C. Components in a grid bag layout may either resize with their cell, or remain centered in that cell attheir preferred size.D. A border layout can be used to position a component that should maintain a constant size evenwhen the container is resized.Answer: AQUESTION NO 124You want a class to have access to members of another class in the same package. Which is the mostrestrictive access modifier that will accomplish that will accomplish this objective?A. PublicB. PrivateC. ProtectedD. TransientE. No access modifier is required.Answer: EQUESTION NO 125Which two statements are true regarding the creation of a default constructor? (Choose Two)A. The default constructor initializes method variables.B. The default constructor invokes the no-parameter constructor of the superclass.C. The default constructor initializes the instance variables declared in the class.D. If a class lacks a no-parameter constructor,, but has other constructors, the compiler creates a default constructor.E. The compiler creates a default constructor only when there are no other constructors for the class.Answer: C, EQUESTION NO 126Given:1. public class OuterClass {2. private double d1 1.0;3. //insert code here4. }You need to insert an inner class declaration at line2. Which two inner class declarations are valid?(Choose Two)A. static class InnerOne {public double methoda() {return d1;}}B. static class InnerOne {static double methoda() {return d1;}}C. private class InnerOne {public double methoda() {return d1;}}D. protected class InnerOne {static double methoda() {return d1;}}E. public abstract class InnerOne {public abstract double methoda();}Answer: C, EQUESTION NO 127Which two declarations prevent the overriding of a method? (Choose Two)A. Final void methoda() {}B. Void final methoda() {}C. Static void methoda() {}D. Static final void methoda() {}E. Final abstract void methoda() {}Answer: A, DQUESTION NO 128Given:1. public class Test {2. public static void main (String args[]) {3. class Foo {4. public int i = 3;5. }6. Object o = (Object) new Foo();7. Foo foo = (Foo)o;8. System.out.printIn(foo. i);9. }10. }What is the result?A. Compilation will fail.B. Compilation will succeed and the progr am will print “3”C. Compilation will succeed but the program will throw a ClassCastException at line 6.D. Compilation will succeed but the program will throw a ClassCastException at line 7. Answer: BQUESTION NO 129Which two create an instance of an array? (Choose Two)A. int[] ia = new int [15];B. float fa = new float [20];C. char*+ ca = “Some String”;D. Object oa = new float[20];E. Int ia [][] = (4, 5, 6) (1, 2, 3)Answer: A, DQUESTION NO 130Given:1. public class ExceptionTest {2. class TestException extends Exception {}3. public void runTest () throws TestException {}4. public void test () /* Point X*/ {5. runTest ();6. }7. }At point X on line 4, which code can be added to make the code compile?A. Throws Exception.B. Catch (Exception e).C. Throws RuntimeException.D. Catch (TestException e).E. No code is necessary.Answer: BQUESTION NO 131Exhibit:1. public class SwitchTest {2. public static void main (String []args) {3. System.out.PrintIn(“value =” +switchIt(4));4. }5. public static int switchIt(int x) {6. int j = 1;7. switch (x) {8. case 1: j++;9. case 2: j++;10. case 3: j++;11. case 4: j++;12. case 5: j++;13. default:j++;14. }15. return j + x;16. }17. }What is the output from line 3?A. Value = 3B. Value = 4C. Value = 5D. Value = 6E. Value = 7F. Value = 8Answer: FQUESTION NO 132Which four types of objects can be thrown using the throw statement? (Choose Four)A. ErrorB. EventC. ObjectD. ExceptionE. ThrowableF. RuntimeExceptionAnswer: A, D, E, FQUESTION NO 133Given:1. public class ForBar {2. public static void main(String []args) {3. int i = 0, j = 5;4. tp: for (;;) {5. i ++;6. for(;;)7. if(i &gt; --j) break tp;8. }9. system.out.printIn(“i = ” + i + “, j = “+ j);10. }11. }What is the result?A. The program runs and prints “i=1, j=0”B. The program runs and prints “i=1, j=4”C. The program runs and prints “i=3, j=4”D. The program runs and prints “i=3, j=0”E. An error at line 4 causes compilation to fail.F. An error at line 7 causes compilation to fail.Answer: AQUESTION NO 134Which two can directly cause a thread to stop executing? (Choose Two)A. Exiting from a synchronized block.B. Calling the wait method on an object.C. Calling the notify method on an object.D. Calling the notifyAll method on an object.E. Calling the setPriority method on a thread object.Answer: B, EQUESTION NO 135Given:1. public class Foo implements Runnable (2. public void run (Thread t) {3. system.out.printIn(“Running.”);4. }5. public static void main (String[] args) {6. new thread (new Foo()).start();7. )8. )What is the result?A. An exception is thrown.B. The program exists without printing anything.C. An error at line 1 causes compilation to fail.D. An error at line 6 causes the compilation to fail.E. “Running” is printed and the program exits. Answer: CQUESTION NO 136Which constructs a DataOutputStream?A. New dataInputStream(“in.txt”);B. New dataInputStream(new file(“in.txt”));C. New dataInputStream(new writer(“in.txt”));D. New dataInputSt ream(new FileWriter(“in.txt”));E. New dataInputStream(new InputStream(“in.txt”));F. New dataInputStream(new FileInputStream(“in.txt”)); Answer: FQUESTION NO 137Which can be used to decode charS for output?A. Java.io.InputStream.B. Java.io.EncodedReader.C. Java.io.InputStreamReader.D. Java.io.InputStreamWriter.E. Java.io.BufferedInputStream.Answer: CQUESTION NO 138Given:1. public class Test {2. public static void main (String [] args) {3. string foo = “blue”;4. string bar = foo;5. foo = “green”;6. System.out.printIn(bar);7. }8. }What is the result?A. An exception is thrown.B. The code will not compile.C. The program prints “null”D. The program prints “blue”E. The program prints “green”Answer: DQUESTION NO 139Which code determines the int value foo closest to a double value bar?A. Int foo = (int) Math.max(bar);B. Int foo = (int) Math.min(bar);C. Int foo = (int) Math.abs(bar);D. Int foo = (int) Math.ceil(bar);E. Int foo = (int) Math.floor(bar);F. Int foo = (int) Math.round(bar);Answer: FQUESTION NO 140Which two demonstrate encapsulation of data? (Choose Two)A. Member data have no access modifiers.B. Member data can be modified directly.C. The access modifier for methods is protected.D. The access modifier to member data is private.E. Methods provide for access and modification of data.Answer: D, EQUESTION NO 141Exhibit:1. class A {2. public String toString () {3. return “4”;4. }5. }6. class B extends A {7. 8. public String toString () {8. return super.toString() + “3”;9. }10. }11. public class Test {12. public static void main(String[]args) {13. System.out.printIn(new B());14. }15. }What is the result?A. Compilation succeeds and 4 is printed.B. Compilation succeeds and 43 is printed.C. An error on line 9 causes compilation to fail.D. An error on line 14 causes compilation to fail.E. Compilation succeeds but an exception is thrown at line 9.Answer: BQUESTION NO 142Which two statements are true? (Choose Two)A. An anonymous inner class can be declared inside of a methodB. An anonymous inner class constructor can take arguments in some situation.C. An anonymous inner class that is a direct subclass that is a direct subclass of Object can implementmultiple interfaces.D. Even if a class Super does not implement any interfaces, it is still possible to define an anonymousinner class that is an immediate subclass of Super that implements a single interface.E. Event if a class Super does not implement any interfaces, it is still possible to define an anonymousinner class that is an immediate subclass of Super that implements multiple interfaces. Answer: A, BQUESTION NO 143Given:1. public class MethodOver {2. private int x, y;3. private float z;4. public void setVar(int a, int b, float c){5. x = a;6. y = b;7. z = c;8. }9. }Which two overload the setVar method? (Choose Two)A. void setVar (int a, int b, float c){x = a;y = b;z = c;}B. public void setVar(int a, float c, int b) {setVar(a, b, c);}C. public void setVar(int a, float c, int b) {this(a, b, c);}D. public void setVar(int a, float b){x = a;z = b;}E. public void setVar(int ax, int by, float cz) {x = ax;y = by;z = cz;}Answer: B, DQUESTION NO 144Which statements about static inner classes are true? (Choose Two)A. A static inner class requires a static initializer.B. A static inner class requires an instance of the enclosing class.C. A static inner class has no reference to an instance of the enclosing class.D. A static inner class has access to the non-static members of the outer class.E. Static members of a static inner class can be referenced using the class name of the static inner class.Answer: C, EQUESTION NO 145Given:1. public class X {2. public object m () {3. object o = new float (3.14F);4. object [] oa = new object [1];5. oa[0]= o;6. o = null;7. oa[0] = null;9. return o;9. }10. }When is the float object created in line 3, eligible for garbage collection?A. Just after line 5.B. Just after line 6.C. Just after line 7.D. Just after line 8(that is, as the method returns).Answer: CQUESTION NO 146Which two interfaces provide the capability to store objects using a key-value pair? (Choose Two)A. Java.util.Map.B. Java.util.Set.C. Java.util.List.D. Java.util.StoredSet.E. Java.util.StoredMap.F. Java.util.Collection.Answer: A, EQUESTION NO 147Which interface does java.util.Hashable implement?A. Java.util.Map.B. Java.util.List.C. Java.util.Hashable.D. Java.util.Collection. Answer: A。

SCJP历年考题

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官方题库

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题库之欧阳理创编

SCJP题库之欧阳理创编

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类型不是booleanQuestion 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,否则返回falseQuestion 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 resul t?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 line 6.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 调用不同包下的类,要先导入,方法权限要设置成publicQuestion 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 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. // more code here13. 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. System.gc();B. Runtime.gc();C. System.freeMemory();D. Runtime.getRuntime().growHeap();E. Runtime.getRuntime().freeMemory();Answer: A 题很简单。

SUN公司SCJP题库讲解学习

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 题很简单。

SCJP考试真题和解析-Read

SCJP考试真题和解析-Read

SCJP考试真题和解析Choose the three valid identifiers from those listed below.A. IDoLikeTheLongNameClassB. $byteC. constD. _okE. 3_case解答:A, B, D点评:Java中的标示符必须是字母、美元符($)或下划线(_)开头。

关键字与保留字不能作为标示符。

选项C中的const是Java的保留字,所以不能作标示符。

选项E中的3_case以数字开头,违反了Java的规则。

例题2:How can you force garbage collection of an object?A. Garbage collection cannot be forcedB. Call System.gc().C. Call System.gc(), passing in a reference to the object to be garbage collected.D. Call Runtime.gc().E. Set all references to the object to new values(null, for example).解答:A点评:在Java中垃圾收集是不能被强迫立即执行的。

调用System.gc()或Runtime.gc()静态方法不能保证垃圾收集器的立即执行,因为,也许存在着更高优先级的线程。

所以选项B、D不正确。

选项C的错误在于,System.gc()方法是不接受参数的。

选项E中的方法可以使对象在下次垃圾收集器运行时被收集。

例题3:Consider the following class:1. class Test(int i) {2. void test(int i) {3. System.out.println(“I am an int.”);4. }5. void test(String s) {6. System.out.println(“I am a string.”);7. }8.9. public static void main(String args[]) {10. Test t=new Test();11. char ch=“y”;12. t.test(ch);13. }14. }Which of the statements below is true?(Choose one.)A. Line 5 will not compile, because void methods cannot be overridden.B. Line 12 will not compile, because there is no version of test() that rakes a char argument.C. The code will compile but will throw an exception at line 12.D. The code will compile and produce the following output: I am an int.E. The code will compile and produce the following output: I am a String.解答:D点评:在第12行,16位长的char型变量ch在编译时会自动转化为一个32位长的int型,并在运行时传给void test(int i)方法。

OCJP(前SCJP)考试认证题目示例

OCJP(前SCJP)考试认证题目示例

TThe safer , easier way to help you pass any IT exams.Exam : 1Z0-851Title :Version : DemoJava Standard Edition 6 Programmer CertifiedProfessional Exam1.Given a pre-generics implementation of a method:public static int sum(List list) {int sum = 0;for ( Iterator iter = list.iterator(); iter.hasNext(); ) {int i = ((Integer)iter.next()).intValue();sum += i;}return sum;}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,F2.A programmer has an algorithm that requires a java.util.List that provides an efficient implementation of add(0, object), but does NOT need to support quick random access.What supports these requirements.?A. java.util.QueueB. java.util.ArrayListC. java.util.LinearListD. java.util.LinkedListAnswer: D3.Given:// insert code hereprivate N min, max;public N getMin() { return min; }public N getMax() { return max; }public void add(N added) {if (min == null || added.doubleValue() < min.doubleValue())min = added;if (max == null || added.doubleValue() > max.doubleValue())max = added;}}Which two, inserted at line 11, will allow the code to compile? (Choose two.)A. public class MinMax<?> {B. public class MinMax<? extends Number> {C. public class MinMax<N extends Object> {D. public class MinMax<N extends Number> {E. public class MinMax<? extends Object> {F. public class MinMax<N extends Integer> {Answer: D,F4.Given:import java.util.*;public class Explorer2 {public static void main(String[] args) {TreeSet<Integer> s = new TreeSet<Integer>();TreeSet<Integer> subs = new TreeSet<Integer>();for(int i = 606; i < 613; i++)if(i%2 == 0) s.add(i);subs = (TreeSet)s.subSet(608, true, 611, true);s.add(629);System.out.println(s + " " + subs);}}What is the result?A. Compilation fails.B. An exception is thrown at runtime.C. [608, 610, 612, 629] [608, 610]D. [608, 610, 612, 629] [608, 610, 629]E. [606, 608, 610, 612, 629] [608, 610]F. [606, 608, 610, 612, 629] [608, 610, 629]Answer: E5.Given:public class Score implements Comparable<Score> { private int wins, losses;public Score(int w, int l) { wins = w; losses = l; }public int getWins() { return wins; }public int getLosses() { return losses; }public String toString() {return "<" + wins + "," + losses + ">";}// insert code here}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: B6.Given:public class Person {private name;public Person(String name) { = name;}public int hashCode() {return 420;}}Which statement is true?A. The time to find the value from HashMap with a Person key depends on the size of the map.B. Deleting a Person key from a HashMap will delete all map entries for all keys of type Person.C. Inserting a second Person object into a HashSet will cause the first Person object to be removed as a duplicate.D. The time to determine whether a Person object is contained in a HashSet is constant and does NOT depend on the size of the map.Answer: A7.Given:import java.util.*;public class SortOf {public static void main(String[] args) {ArrayList<Integer> a = new ArrayList<Integer>();a.add(1); a.add(5); a.add(3);Collections.sort(a);a.add(2);Collections.reverse(a);System.out.println(a);}}What is the result?A. [1, 2, 3, 5]B. [2, 1, 3, 5]C. [2, 5, 3, 1]D. [5, 3, 2, 1]E. [1, 3, 5, 2]F. Compilation fails.G. An exception is thrown at runtime.Answer: C8.Givenpublic interface Status {/* insert code here */ int MY_VALUE = 10;} Which three are valid on line12?(Choose three.)A. finalB. staticC. nativeD. publicE. privateF. abstractG. protectedAnswer: A,B,D9.Given:class Atom {Atom() { System.out.print("atom "); }}class Rock extends Atom {Rock(String type) { System.out.print(type); }}public class Mountain extends Rock {Mountain() {super("granite ");new Rock("granite ");}public static void main(String[] a) { new Mountain(); } }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: F10.Click the Exhibit button.Which three statements are true? (Choose three.)A. Compilation fails.B. The code compiles and the output is 2.C. If lines 16, 17 and 18 were removed, compilation would fail.D. If lines 24, 25 and 26 were removed, compilation would fail.E. If lines 16, 17 and 18 were removed, the code would compile and the output would be 2.F. If lines 24, 25 and 26 were removed, the code would compile and the output would be 1. Answer: B,E,F11.Given:class Line {public class Point { public int x,y;}public Point getPoint() { return new Point(); }}class Triangle {public Triangle() {// insert code here}}Which code, inserted at line 16, 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();Answer: D12.Given:class Alpha {public void foo() { System.out.print("Afoo "); } }public class Beta extends Alpha {public void foo() { System.out.print("Bfoo "); } public static void main(String[] args) {Alpha a = new Beta();Beta b = (Beta)a;a.foo();b.foo();}}What is the result?A. Afoo AfooB. Afoo BfooC. Bfoo AfooD. Bfoo BfooE. Compilation fails.F. An exception is thrown at runtime. Answer: D13.Click 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: C14.Which 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: A,B15.Given:interface Foo { int bar(); }public class Sprite {public int fubar( Foo foo ) { return foo.bar(); }public void testFoo() {fubar(// insert code here);}}Which code, inserted at line 15, allows the class Sprite to compile?A. Foo { public int bar() { return 1; }B. new Foo { public int bar() { return 1; }C. new Foo() { public int bar() { return 1; }D. new class Foo { public int bar() { return 1; }Answer: C16.Given:class Alligator {public static void main(String[] args) {int []x[] = {{1,2}, {3,4,5}, {6,7,8,9}};int [][]y = x;System.out.println(y[2][1]);}}What is the result?A. 2B. 3C. 4D. 6E. 7F. Compilation fails.Answer: E17.Given:StringBuilder sb1 = new StringBuilder("123");String s1 = "123";// insert code hereSystem.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: E18.Given that the current directory is empty, and that the user has read and write permissions, and the following:import java.io.*;public class DOS {public static void main(String[] args) {File dir = new File("dir");dir.mkdir();File f1 = new File(dir, "f1.txt");try {f1.createNewFile();} catch (IOException e) { ; }File newDir = new File("newDir");dir.renameTo(newDir);}}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: EThe safer , easier way to help you pass any IT exams.19.Given:class Converter {public static void main(String[] args) {Integer i = args[0];int j = 12;System.out.println("It is " + (j==i) + " that j==i.");}}What is the result when the programmer attempts to compile the code and run it with the command java Converter 12?A. It is true that j==i.B. It is false that j==i.C. An exception is thrown at runtime.D. Compilation fails because of an error in line 13.Answer: D20.Given:String test = "Test A. Test B. Test C.";// insert code hereString[] result = test.split(regex);Which regular expression, inserted at line 12, correctly splits test into "Test A", "Test B", and "Test C"?A. String regex = "";B. String regex = " ";C. String regex = ".*";D. String regex = "\\s";E. String regex = "\\.\\s*";F. String regex = "\\w[ \.] +";Answer: E10 / 10。

SCJP试题集及解析

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 value is correct?A. long number = 345L;B. long number = 0345;C. long number = 0345L;D. long number = 0x345L翻译:哪些是将一个十六进制值赋值给一个long型变量。

答案D解析:十六进制数以0x开头,long型数以L(大小写均可,一般使用大写,因为小写的l和数字1不易区分)。

4. Which of the following fragments might cause errors?A. String s = "Gone with the wind";String t = " good ";String k = s + t;B. String s = "Gone with the wind";String t;t = s[3] + "one";C. String s = "Gone with the wind";String standard = s.toUpperCase();D. String s = "home directory";String t = s - "directory";翻译:下面的哪些程序片断可能导致错误。

Cshap试题

Cshap试题
7、程序员定义的异常类应该能够扩展类SystemException
正确
不正确
8、构造函数没有返回值
正确
不正确
9、任何事物都是对象
正确
不正确
10、可以同时定义多个同类型的变量,变量之间用逗号分隔
正确
不正确
enum WorkDays{Sumday=65,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Invalid=-1} ;
WorkDay myday=WorkDays.Sunday; Console.Write((char)myday);
A、Sunday
一、单项选择题(每题2分,共30题)
1、有关抽象类和抽象方法,下面哪种说法是错误的?( )
A、抽象类不能实例化
B、抽象类必须包含抽象方法
C、只允许在抽象类中使用抽象方法声明
D、抽象方法实现由overriding方法提供
2、下面哪种类型不是值类型()。
A、整数类型
B、浮点光标置于" ( )"窗口的某一项时,它将立即显示与之相关的文章。
D、虚拟方法可以作为抽象方法的重载实现
14、下列哪个不是可行的c#对象名。
A、score4
B、four_score
C、oursource
D、4score
15、下面哪种类型不是引用类型( )。
A、接口类型
B、委托类型
C、结构类型
D、数组类型
16、创建对象和调用构造函数时,通常使用( )关键字。
A、typeof
C、App.ico文件
D、AssemblyInfo.cs文件
6、C#中的所有数据类型都派生自( )类。

scjp认证试题及答案

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。

j经典笔试题

j经典笔试题

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 value is correct?A. long number = 345L;B. long number = 0345;C. long number = 0345L;D. long number = 0x345L翻译:哪些是将一个十六进制值赋值给一个long型变量。

答案D解析:十六进制数以0x开头,long型数以L(大小写均可,一般使用大写,因为小写的l和数字1不易区分)。

4. Which of the following fragments might cause errors?A. String s = "Gone with the wind";String t = " good ";String k = s + t;B. String s = "Gone with the wind";String t;t = s[3] + "one";C. String s = "Gone with the wind";String standard = s.toUpperCase();D. String s = "home directory";String t = s - "directory";翻译:下面的哪些程序片断可能导致错误。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Given:1. public class OuterClass {2. private double d1 = 1.0;3. // insert code here4. }Which two are valid if inserted at line 3? (Choose two)A. static class InnerOne {public double methoda() { return d1; }}B. static class InnerOne {static double methoda() { return d1; }}C. private class InnerOne {public double methoda() { return d1; }}D. protected class InnerOne {static double methoda() { return d1; }}E. public abstract class InnerOne {public abstract double methoda();}QUESTION NO: 2Given:1. public class Outer{2. public void someOuterMethod() {3. // Line 34. }5. public class Inner{}6. public static void main( String[]argv ) {7. Outer o = new Outer();8. // Line 89. }10. }Which instantiates an instance of Inner?A. new Inner(); // At line 3B. new Inner(); // At line 8C. new o.Inner(); // At line 8D. new Outer.Inner(); // At line 8Given:1. package foo;2. public class Outer {3. public static class Inner {4. }5. }Which statement is true?A. Compilation fails.B. An instance of the Inner class can be constructed with “new Outer.Inner()”.C. An instance of the Inner class cannot be constructed outside of package foo.D. An instance of the Inner class can be constructed only from within the Outer class.E. From within the package foo, and instance of the Inner class can be constructed with “new Inner()”.QUESTION NO: 4Given:1. class BaseClass{2. private float x= 1.0f;3. protected void setVar (float f) {x = f;}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. Void setVar(float f) {x = f;}B. Public void setVar(int f) {x = f;}C. Public void setVar(float f) {x = f;}D. Public double setVar(float f) {x = f;}E. Public final void setVar(float f) {x = f;}F. Protected float setVar() {x=3.0f; return 3.0f; }QUESTION NO: 5public class MyOuter {public static class MyInner { public static void foot) { } }}Which, if placed in a class other than MyOuter or MyInner, instantiates an instanceof the nested class?A.MyOuter.MyInner m = new MyOuter.Mylnner();B.MyOuter.MyInner mi = new MyInner();C.MyOuter m = new Myouter();MyOuter.MyInner mi = m.new Myouter.MyInner();D.MyInner mi = new MyOuter.MyInner();QUESTION NO: 6Which are true about a static nested class? (Choose all that apply.)A.You must have a reference to an instance of the enclosing class in orderto instantiate it.B.It does not have access to non-static members of the enclosing class.C.Its variables and methods must be static.D.If the outer class is named MyOuter, and the nested class is namedMyInner, it can be instantiated using new MyOuter.MyInner();.E.It must extend the enclosing classQUESTION NO:7Given:public interface Runnable { void run(); }Which construct an anonymous inner class instance? (Choose all that apply.)A.Runnable r = new Runnable() { };B.Runnable r = new Runnable(public void run() { });C.Runnable r = new Runnable { public void run(){}};D.Runnable r = new Runnable() {public void run{}};E.System.out.println(new Runnable() (public void run() { }});F.System.out.println(new Runnable(public void run() {}));QUESTION NO:8Given:class Boo {Boo(String s) { }Boo() { }}class Bar extends Boo {Bar() { }Bar(String s) (super(s);}void zoo() {// insert code here}}Which create an anonymous inner class from within class Bar? (Choose all that apply.)A.Boo f = new Boo(24) { };B.Boo f = new Bar() { };C.Boo f = new Boo() (String s; };D.Bar f = new Boo(String s) { };E.Boo f = new Boo.Bar(String s) { } ;QUESTION NO:91. class Foo {2. class Bar{ }3. }4. class Test {5. public static void main(String[] args) {6. Foo f = new Foo();7. // Insert code here8. }9. }Which, inserted at line 7, creates an instance of Bar? (Choose all that apply.)A.Foo.Bar b = new Foo.Bar();B.Foo.Bar b = f.new Bar () ;C.Bar b = new f.Bar();D.Bar b = f.new Bar();E.Foo.Bar b = new f.Bar();QUESTION NO:10Which are true about a method-local inner class? (Choose all that apply.)A.It must be marked final.B.It can be marked abstract.C.It can be marked public.D.It can be marked static.E.It can access private members of the enclosing classQUESTION NO:11Which are true about an anonymous inner class? (Choose all that apply.)A.It can extend exactly one class and implement exactly one interface.B.It can extend exactly one class and can implement multiple interfaces.C.It can extend exactly one class or implement exactly one interface.D.It can implement multiple interfaces regardless of whether it also extends aclass.E.It can implement multiple interfaces if it does not extend a class QUESTION NO:12Given:public class Foo {Foo() {System.out.print("foo");}class Bar{Bar() {System.out.print("bar");}public void go() {System.out.print("hi");}}public static void main(String[] args) {Foo f = new Foo ();f.makeBar();}void makeBar() {(new Bar() {}).go();}}What is the result?pilation fails.B.An error occurs at runtime.C.foobarhiD.barhiE.hiF.foohiQUESTION NO:13Given:1. public class TestObj {2. public static void main(String[] args) {3. Object o = new Object() {4. public boolean equals(Object obj) {5. return true;6. }7. }8. System.out.println(o.equals("Fred"));9. }10. }What is the result?A.An exception occurs at runtime.B.trueC.Fredpilation fails because of an error on line 3.pilation fails because of an error on line 4.pilation fails because of an error on line 8.pilation fails because of an error on a line other than 3, 4, or 8.QUESTION NO:14Given:1. public class HorseTest {2. public static void main(String [] args) {3. class Horse {4. public String name;5. public Horse(String s) {6. name = s;7. }8. }9. Object obj = new Horse("Zippo");10. Horse h = (Horse) obj;11. System.out.println();12. }13. }What is the result?A.An exception occurs at runtime at line 10.B.Zippopilation fails because of an error on line 3.pilation fails because of an error on line 9.pilation fails because of an error on line 10.pilation fails because of an error on line 11.QUESTION NO:15Given:1. public class HorseTest {2. public static void main(String[] args) {3. class Horse {4. public String name;5. public Horse(String s) {6. name = s;7. }8. }9. Object obj = new Horse("Zippo");10. System.out.println();11. }12. }What is the result?A.An exception occurs at runtime at line 10.B.Zippopilation fails because of an error on line 3.pilation fails because of an error on line 9.pilation fails because of an error on line 10.QUESTION NO:16Given:public abstract class AbstractTest {public int getNum() {return 45;}public abstract class Bar {public int getNum() {return 38;}}public static void main(String[] args) {AbstractTest t = new AbstractTest() {public int getNum() {return 22;}};AbstractTest.Bar f = t.new Bar() {public int getNum() {return 57;}};System.out.println(f.getNum() + " " + t.getNum());}}What is the result?A.57 22B.45 38C.45 57D.An exception occurs at runtime.pilation fails.。

相关文档
最新文档