JAVA试题英文版(答案)
经典java面试英文题
1.What is the result when you compile and run the following code?public class Test{public void method(){for(int i=0;i<3;i++){System.out.print(i);}System.out.print(i);}}result: compile error分析:i是局部变量。
for循环完成后,i的引用即消失。
2.What will be the result of executing the following code?Given that Test1 is a class.class Test1{public static void main(String[] args){Test1[] t1 = new Test1[10];Test1[][] t2 = new Test1[5][];if(t1[0]==null){t2[0] = new Test1[10];t2[1] = new Test1[10];t2[2] = new Test1[10];t2[3] = new Test1[10];t2[4] = new Test1[10];}System.out.println(t1[0]);System.out.println(t2[1][0]);}}result:null null分析:new数组后,数组有大小,但值为null3.What will happen when you attempt to compile and run the following code? class Base{int i = 99;public void amethod(){System.out.println("Base.method()");}Base(){amethod();}}public class Derived extends Base{int i = -1;public static void main(String args[]){Base b = new Derived();System.out.println(b.i);b.amethod();}public void amethod(){System.out.println("Derived.amethod()");}}result:Derived.amethod()99Derived.amethod()解释:Derived 重写了Base的amethod方法。
绝对经典Java英文笔试题、答案
Question 7) Which of the following are legal identifiers
1) 2variable 2) variable2 3) _whatavariable 4) _3_ 5) $anothervar 6) #myvar
Question 2)
What will happen if you try to compile and run the following code
public class MyClass { public static void main(String arguments[]) { amethod(arguments); } public void amethod(String[] arguments) { System.out.println(arguments); System.out.println(arguments[1]); }
1) a sequence of 5 0's will be printed 2) Error: ar is used before it is initialized 3) Error Mine must be declared abstract 4) IndexOutOfBoundes Error
System.out.println(argv[2]); } }
1) myprog 2) good 3) morning 4) Exception raised: "ng.ArrayIndexOutOfBoundsException: 2"
Question 6) Which of the following are keywords or reserved words in Java?
英文java面试题(含答案)
英文java面试题(含答案)1.Tell me a little about yourselfI am holding a master degress in software science and had 2-year work experience in software development. I have used J2EE technology for 2 years,including Jsp,servlet,javabean,XML,EJB,I also used C language for half year and IBM mainframe technology half year and IBM mainframe technology half year.And the projects I participated in follow the Waterfall model lifecycle starting from design,then coding ,testing,maintenance.2.Describe a situation where you had to work under pressure,and explain how you handle it.Once when we did a mainframe project,our customer wanted to see a demo from our team before they signed the contract with our company.It is urgent,because our customer didn t give us enough time to do it. So all my team menbers had to work overtime,but we finished it punctually and perfectly . Our customer was satisfied with it.Actually,It is common to meet some deadlines or work under pressure in IT field.I am ok with it.3.What would your last employer tell me about your work performanceI am sure my last employer will praise my work performance,because he was reluctant to let me go when I told him I want to quit and study abroad,and he said I am welcome to come back when I finish study.4.What is your major weaknessI always want everything to be perfect.Sometimes,I am over-sensitive. When a design pattern or technical solution comes up during a meeting discussion,I am always the first one to test the feasibility.Some leader don t like such person because sometimes it is embarrassing when I prove it doesn t work while the leader still believe it is a perfect solution,But I think I did nothing wrong about it,it is good for the company.5.Why did you leave your last jobAlthough I did well in the last company,I always feel the theoretical study and actual practice are equally important and depend on each other.So,I decide to further study and actual practice are equally important and dependent on each other.So,I decide to further study to extend my theory in computer science.6.What are your strengthsWhat I am superior to others I believe is strong interest in software development I have.Many friends of mine working in IT field are holding bachelor degree or master degree and have worked for several years,but they don t have much interest in it,they only treat what they do everything a job,a means to survive,they don t have career plan at all. I am different. I like writing programs.I have set up my career goal long time ago.I will do my best to make it possible in the future.And I have worked hard towards this goal for several years.7.What are your future career plansI would like to be a software engineer now.but my career goal is to be an excellent software architector in the future.I like writing programs. Software is a kind of art, although sometimes it drove me crazy,after I overcame the difficulties I feel I am useful,I will keep working in IT field.8.What are your salary expectationsI believe your company will set up reasonable salary for me according to my ability,so I don t worry about it at all.Between 7000 to 8000 monthly9. Why are you interested in this position?Your company specializes in providing technical solutionsto customers and the last company I worked in also specializes in this field. I have relevant skills and experiences meeting your requirement.I am sure I can do it well.10.Do you have any questions that you would like to ask meWhat is a typical workday like and what would I doWhat is your expectation for me in this job11.What J2EE design patterns have you used beforeCommand/Session Facade/Service Locator/Data Access Object/Business Delegate。
IBM java 英文面试题(附参考答案)
1.what is oracle.2.what is major differenece oracle8i and oracle9i.4.tell me some thing ur self.5.please tell me about oops.6.what is single inheritance.7.what is multiple inheritance.8.can java support multiple inheritance.9.what is interface.10.what is differenec between abstract class and interface.11.how to u prove that abstrace class cannot instantiate directly.12.what is differenece between string and stringbuffer.13.what is immutable14.how to write a program using sort program.15 how to write a program using unsort program.16.what is legacy.17.what is legacy api18.what is legacy interface.19.what is main difference hashmap and hastable20.what is main difference between arraylist and vector.21.what is struts framework.22.what are distributed techonologies.23.what is advantage and disadvantage of distributed techonologies.24.what is main difference between jsp and servlets.25.what is difference between procedure and functions.26.what is jdbc.27.what are type of drivers.28.what is type 4 driver.29.how to collect requuirements form u r client.30.which process use in ur project.31.what is deployment descriptor.32.what is heirarchy of files in struts.33.please draw struts frame wrok.34.please draw j2ee architecture.35.please draw mvc-2 architecture.36.please draw that how design op module.37.how to find a file on linux.38.how to configure weblogic8.1 on linux.39.why you use struts framework in ur project.40.what is platfrom independent41.what is awt and swing.42.what is heavy wieght components.43.what is feature of weblgoic8.1.44.why you choose application server on linux and database server on aix.45.please tell me about ur project.46.what is major concepts in oops.47.why u choose mvc-2 architecture.48.what is implicit object.49.how many implicit objects in jsp50.why choose weblogic8.1 other than any applicationserver.51.what is water fall model vs sdlc52.what is use of dataflowdiagrams53.wha t is ip in ur project.54.what about reception module—————————————————————————————————————————————————————————1. Oracle is an RDBMS product with DDL and DML from a company called Oracle Inc.2. Difference between 8i and 9i is given in the Oracle site3. Question not available4. Something5. oops is Object Oriented Programming6.what is single inheritance.ans:one class is inherited by only other one class7.what is multiple inheritance.ans:One class inheriting more than one class at atime8.can java support multiple inheritance.ans:No9.what is interface.ans:Interface has only method declarations but no defn10.what is differenec between abstract class and interface.ans:In abstract class some methods may contain definition,but in interface every method should be abstract11.how to u prove that abstrace class cannot instantiate directly.ans:As they dont have constructor they cant be instantiated 12.what is differenece between string and stringbuffer.ans:Strings are immutable where as string buffer can be modified 13.what is immutableans:Which cant be changed14.how to write a program using sort program.15 how to write a program using unsort program.ans: Both can be done using javascriptThis is for Sortfunction SelectTextSort(obj) { // sort by textvar N=obj.options.length;for (var i=0;i<N-1;i++) {for (var j=i+1;j<N;j++) {if ( obj.options[i].text > obj.options[j].text ) {var i1= (obj.options[i].selected == true ) ? true : falsevar j1= (obj.options[j].selected == true ) ? true : falsevar q1 = obj.options[j].text;var q2 = obj.options[j].value;obj.options[j].text = obj.options[i].text;obj.options[j].value = obj.options[i].value;obj.options[i].text = q1;obj.options[i].value = q2;obj.options[i].selected = (j1 && true ) ? true : falseobj.options[j].selected = (i1 && true ) ? true : false}}}return true}16.what is legacy.17.what is legacy api18.what is legacy interface.ans: legacy is something that is old in terms of technology/ system19.what is main difference hashmap and hastableans:Hash table is synchronised20.what is main difference between arraylist and vector.ans:Vector is synchronised21.what is struts framework.22.what are distributed techonologies.distributed technologies means any technology / s/w program that are having many components in multiple environments that interact with each other depending on the functional requirements and design.23.what is advantage and disadvantage of distributed techonologies.overdependance on single platform / single language is avoided. Application can be built flexible to meet requirements. Division of labour is possible. Best of all the technologies andplatforms can be optimally utilized. Complexity of requirements can be reduced.25.what is difference between procedure and functions.'ans:Fuctions can return value ,procedures cant return value26.what is jdbc.ans:Connecting to DB from java program requires JDBC27.what are type of drivers.type1,2,3,429.how to collect requuirements form u r client.is not a job of a technical person. It is better for a BA to do it.30.which process use in ur project.Generally u can say:Project related process: Analysis, Design, Sign-off Documents, Implementation, Integration, Testing, UATWork related process:Technical Design, Work Allocation, Code Review Checklist, Unit Test Form will be prepared by the Project Lead and given to the developer.Developer prepares the Unit Test CaseImplements Code, Performs TestSubmits Code through CVS / VSSSubmits documents along with Release Checklist to the tester / leader.31.what is deployment descriptor.ans:Which contains the infrnmation like which file to be used 40.what is platfrom independentans:A language is said to be platform independent if it can be run on any machine with out modifying code41.what is awt and swing.ans:AWT are heavy weight components and swings are light weight components46.what is major concepts in oops.ans:Abstraction,polymorphism,encapsulation,inheritance47.why u choose mvc-2 architecture.ans:In MVC-2 controller is servlet rather than JSP which makes it efficient48.what is implicit object.ans:Implicit objects are a set of Java objects that the JSP Container makes available to developers in each page49.how many implicit objects in jspans:out,page,session,request,response,application,page context,config。
Java笔试常见英语题(附答案)
Q1. How could Java classes direct program messages to the system console, but error messages, say to a file?.Java中如何将程序信息导航到系统的console,而把错误信息放入到一个file 中?The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:Stream st = new Stream(new FileOutputStream("output.txt"));System.setErr(st); System.setOut(st);系统有一个展现标准输出的out变量,以及一个负责标准错误设置的err变量,默认情况下这两个变量都指向系统的console,这就是标准输出如何能被改变方向(就是改变信息的输出位置)。
* Q2. What's the difference between an interface and an abstract class?抽象类和接口的区别:A. An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.抽象类中可能会含有带有方法体的一般方法,而这在接口中是不允许的。
JAVA 英文测试题
JAVA Test(30minutes)1.length () Does array has this method? What about string has this method?2.Expressions “switch (exp), write down all the types of exp.3.What's the difference between String and StringBuffer? List some common methods ofthe string and stringbuffer.4.What's the difference between Error and Exception?5.How many basic types does java have? What are the default values? How will a stringconvert to integer?6.What's the difference between INCLUDE in dynamic state and INCLUDE in static stateamong JSP? What's the difference of two jumping methods of JSP?7.What’s the operational principle of Spring?8.What’s work principle of Hibernate? What a dvantage does Hibernate have?9.Write down the complete code that jdbc connect mysql database.10.What’s the difference between Statement and PrepareStatement?11.Translation Test(15minutes)Please translate one of the following paragraphs into Chinese:请选择以下任一段翻译成中文:1.Many powerful Web sites today are built strictly on CGI, and you can in fact do nearlyanything with CGI. However, Web sites built on CGI programs can rapidly become overly complicated to maintain, and there is also the problem of response time. The response of a CGI program depends on how much data must be sent, as well as the load on both the server and the Internet. (On top of this, starting a CGI program tends to be slow.) The initial designers of the Web did not foresee how rapidly this bandwidth would be exhausted for the kinds of applications people developed.2.If Java is, in fact, yet another computer programming language, you may questionwhy it is so important and why it is being promoted as a revolutionary step in computer programming. The answer isn’t immediately obvious if you’re coming from a traditional programming perspective. Although Java is very useful for solving traditional standalone programming problems, it is also important because it will solve programming problems on the World Wide Web.12.Written Test(30 minutes)Please write two short essays at least 100words for each one in English.(每篇至少100字)1. What is the biggest IT challenge you have faced and how did you handle it?2. What are you looking for in your next job? What is important to you?。
IBM java 英文面试题(附参考答案)
1.what is oracle.2.what is major differenece oracle8i and oracle9i.4.tell me some thing ur self.5.please tell me about oops.6.what is single inheritance.7.what is multiple inheritance.8.can java support multiple inheritance.9.what is interface.10.what is differenec between abstract class and interface.11.how to u prove that abstrace class cannot instantiate directly.12.what is differenece between string and stringbuffer.13.what is immutable14.how to write a program using sort program.15 how to write a program using unsort program.16.what is legacy.17.what is legacy api18.what is legacy interface.19.what is main difference hashmap and hastable20.what is main difference between arraylist and vector.21.what is struts framework.22.what are distributed techonologies.23.what is advantage and disadvantage of distributed techonologies.24.what is main difference between jsp and servlets.25.what is difference between procedure and functions.26.what is jdbc.27.what are type of drivers.28.what is type 4 driver.29.how to collect requuirements form u r client.30.which process use in ur project.31.what is deployment descriptor.32.what is heirarchy of files in struts.33.please draw struts frame wrok.34.please draw j2ee architecture.35.please draw mvc-2 architecture.36.please draw that how design op module.37.how to find a file on linux.38.how to configure weblogic8.1 on linux.39.why you use struts framework in ur project.40.what is platfrom independent41.what is awt and swing.42.what is heavy wieght components.43.what is feature of weblgoic8.1.44.why you choose application server on linux and database server on aix.45.please tell me about ur project.46.what is major concepts in oops.47.why u choose mvc-2 architecture.48.what is implicit object.49.how many implicit objects in jsp50.why choose weblogic8.1 other than any applicationserver.51.what is water fall model vs sdlc52.what is use of dataflowdiagrams53.wha t is ip in ur project.54.what about reception module—————————————————————————————————————————————————————————1. Oracle is an RDBMS product with DDL and DML from a company called Oracle Inc.2. Difference between 8i and 9i is given in the Oracle site3. Question not available4. Something5. oops is Object Oriented Programming6.what is single inheritance.ans:one class is inherited by only other one class7.what is multiple inheritance.ans:One class inheriting more than one class at atime8.can java support multiple inheritance.ans:No9.what is interface.ans:Interface has only method declarations but no defn10.what is differenec between abstract class and interface.ans:In abstract class some methods may contain definition,but in interface every method should be abstract11.how to u prove that abstrace class cannot instantiate directly. ans:As they dont have constructor they cant be instantiated12.what is differenece between string and stringbuffer.ans:Strings are immutable where as string buffer can be modified 13.what is immutableans:Which cant be changed14.how to write a program using sort program.15 how to write a program using unsort program.ans: Both can be done using javascriptThis is for Sortfunction SelectTextSort(obj) { // sort by textvar N=obj.options.length;for (var i=0;i<N-1;i++) {for (var j=i+1;j<N;j++) {if ( obj.options[i].text > obj.options[j].text ) {var i1= (obj.options[i].selected == true ) ? true : false var j1= (obj.options[j].selected == true ) ? true : false var q1 = obj.options[j].text;var q2 = obj.options[j].value;obj.options[j].text = obj.options[i].text;obj.options[j].value = obj.options[i].value;obj.options[i].text = q1;obj.options[i].value = q2;obj.options[i].selected = (j1 && true ) ? true : falseobj.options[j].selected = (i1 && true ) ? true : false}}}return true}16.what is legacy.17.what is legacy api18.what is legacy interface.ans: legacy is something that is old in terms of technology/ system19.what is main difference hashmap and hastableans:Hash table is synchronised20.what is main difference between arraylist and vector.ans:Vector is synchronised21.what is struts framework.22.what are distributed techonologies.distributed technologies means any technology / s/w program that are having many components in multiple environments that interact with each other depending on the functional requirements and design.23.what is advantage and disadvantage of distributed techonologies.overdependance on single platform / single language isavoided. Application can be built flexible to meet requirements. Division of labour is possible. Best of all the technologies and platforms can be optimally utilized. Complexity of requirements can be reduced.25.what is difference between procedure and functions.'ans:Fuctions can return value ,procedures cant return value26.what is jdbc.ans:Connecting to DB from java program requires JDBC27.what are type of drivers.type1,2,3,429.how to collect requuirements form u r client.is not a job of a technical person. It is better for a BA to do it.30.which process use in ur project.Generally u can say:Project related process: Analysis, Design, Sign-off Documents, Implementation, Integration, Testing, UATWork related process:Technical Design, Work Allocation, Code Review Checklist, Unit Test Form will be prepared by the Project Lead and given to the developer.Developer prepares the Unit Test CaseImplements Code, Performs TestSubmits Code through CVS / VSSSubmits documents along with Release Checklist to the tester / leader.31.what is deployment descriptor.ans:Which contains the infrnmation like which file to be used40.what is platfrom independentans:A language is said to be platform independent if it can be run on any machine with out modifying code41.what is awt and swing.ans:AWT are heavy weight components and swings are light weight components 46.what is major concepts in oops.ans:Abstraction,polymorphism,encapsulation,inheritance47.why u choose mvc-2 architecture.ans:In MVC-2 controller is servlet rather than JSP which makes it efficient48.what is implicit object.ans:Implicit objects are a set of Java objects that the JSP Container makes available to developers in each page49.how many implicit objects in jspans:out,page,session,request,response,application,page context,config。
java考试选择题英文版
Read the questions carefullyI have tried to make the questions unambiguous (the meaning should be obvious), but make sure you have read what I have written not what you think I might have written. Thus if it says "Classes can be declared with the private modifier ", it means It is possible to declare a class with the private modifier and not that all classes in all situations can be declared as private. Each question may have one or more correct Answers.QuestionsQuestion 1)Which of the following lines will compile without warning or error.1) float f=1.3;2) char c="a";3) byte b=257;4) boolean b=null;5) int i=10;Question 2)What will happen if you try to compile and run the following codepublic class MyClass {public static void main(String arguments[]) {amethod(arguments);}public void amethod(String[] arguments) {System.out.println(arguments);System.out.println(arguments[1]);}}1) error Can't make static reference to void amethod.2) error method main not correct3) error array must include parameter4) amethod must be declared with StringBecause main is defined as static you need to create an instance of the class in order to call any non-static methods.--------------------------------------------------------------------------------Question 3)Which of the following will compile without error要先出现package1) import java.awt.*;package Mypackage;class Myclass {}2) package MyPackage;import java.awt.*;class MyClass{}3) /*This is a comment */package MyPackage;import java.awt.*;class MyClass{}--------------------------------------------------------------------------------Question 4)A byte can be of what size1) -128 to 1272) (-2 power 8 )-1 to 2 power 83) -255 to 2564)depends on the particular implementation of the Java Virtual machine--------------------------------------------------------------------------------Question 5)What will be printed out if this code is run with the following command line?Java myprog good morning;public class myprog{public static void main(String argv[]){System.out.println(argv[2]);}}1) myprog2) good3) morning4) Exception raised: "ng.ArrayIndexOutOfBoundsException: 2" --------------------------------------------------------------------------------Question 6)Which of the following are keywords or reserved (预定义)words in Java?1) if2) then3) goto4) while5) case--------------------------------------------------------------------------------Question 7)Which of the following are legal identifiers(标识符)1) 2variable2) variable23) _whatavariable4) _3_5) $anothervar6) #myvar--------------------------------------------------------------------------------Question 8)What will happen when you compile and run the following code?public class MyClass{static int i;public static void main(String argv[]){System.out.println(i);}}局部变量(在函数内部)必须先初始化,类级别的可以不初始化Class level variables are always initialised to default values. In the case of an int this will be 0. Method level variables are not given default values and if you attempt to use one before it has been initialised it will cause theError Variable i may not have been initialized1) Error Variable i may not have been initialized2) null3) 14) 0--------------------------------------------------------------------------------Question 9)What will happen if you try to compile and run the following code?public class Q {public static void main(String argv[]){int anar[]=new int[]{1,2,3};System.out.println(anar[1]);}}1) 12) Error anar is referenced before it is initialized3) 24) Error: size of array must be defined-------------------------------------------------------------------------------- Question 10)What will happen if you try to compile and run the following code?public class Q {public static void main(String argv[]){int anar[]=new int[5];System.out.println(anar[0]);}}1) Error: anar is referenced before it is initialized2) null3) 04) 5-------------------------------------------------------------------------------- Question 11)What will be the result of attempting to compile and run the following code?abstract class MineBase {abstract void amethod();static int i;}public class Mine extends MineBase {public static void main(String argv[]){int[] ar=new int[5];for(i=0;i < ar.length;i++)System.out.println(ar[i]);}}Any class derived from an abstract class must either define all of the abstract methods or be declared abstract itself.1) a sequence of 5 0's will be printed2) Error: ar is used before it is initialized3) Error Mine must be declared abstract4) IndexOutOfBoundes Error--------------------------------------------------------------------------------Question 12)What will be printed out if you attempt to compile and run the following code ?int i=1;switch (i) {case 0: System.out.println("zero");break;case 1: System.out.println("one");case 2: System.out.println("two");default: System.out.println("default");}1) one2) one, default3) one, two, default4) default--------------------------------------------------------------------------------Question 13)What will be printed out if you attempt to compile and run the following code?int i=9;switch (i) {default: System.out.println("default");case 0: System.out.println("zero");break;case 1: System.out.println("one");case 2: System.out.println("two");}1) default2) default, zero3) error default clause not defined4) no output displayed--------------------------------------------------------------------------------Question 14)Which of the following lines of code will compile without error1) int i=0;if(i) {System.out.println("Hello");}2) boolean b=true;boolean b2=true;if(b==b2) {System.out.println("So true");}3) int i=1;int j=2;if(i==1|| j==2) System.out.println("OK");4) int i=1;int j=2;if(i==1 &| j==2) System.out.println("OK");--------------------------------------------------------------------------------Question 15)What will be output if you try to compile and run the following code, but there is no file called Hello.txt in the current directory?.import java.io.*;public class Mine {public static void main(String argv[]){Mine m=new Mine();System.out.println(m.amethod());}public int amethod() {try {FileInputStream dis=new FileInputStream("Hello.txt");}catch (FileNotFoundException fne) {System.out.println("No such file found");return -1;}catch(IOException ioe) { }finally{System.out.println("Doing finally");}return 0;}}1) No such file found2 No such file found ,-13) No such file found, Doing finally, -14) 0--------------------------------------------------------------------------------Question 16)Which of the following statements are true?1) Methods cannot be overriden to be more private2) static methods cannot be overloadedStatic methods cannot be overriden but they can be overloaded3) private methods cannot be overloaded4) An overloaded method cannot throw exceptions not checked in the base class--------------------------------------------------------------------------------Question 17)What will happen if you attempt to compile and run the following code?class Base {}class Sub extends Base {}class Sub2 extends Base {}public class CEx{public static void main(String argv[]){Base b=new Base();Sub s=(Sub) b;}}1) Compile and run without error2) Compile time Exception3) Runtime Exception--------------------------------------------------------------------------------Question 18)Which of the following statements are true?1) System.out.println( -1 >>> 2);will output a result larger than 10 无符号右移2) System.out.println( -1 >> 2); will output a positive number 输出-13) System.out.println( 2 >> 1); will output the number 14) System.out.println( 1 <<< 2); will output the number 4--------------------------------------------------------------------------------Question 19)What will happen when you attempt to compile and run the following code?public class Tux extends Thread{static String sName = "vandeleur";public static void main(String argv[]){Tux t = new Tux();t.piggy(sName);System.out.println(sName);}public void piggy(String sName){sName = sName + " wiggy";start();}public void run(){for(int i=0;i < 4; i++){sName = sName + " " + i;}}}1) Compile time error2) Compilation and output of "vandeleur wiggy"3) Compilation and output of "vandeleur wiggy 0 1 2 3"4) Compilation and output of either "vandeleur", "vandeleur 0", "vandeleur 0 1" "vandaleur 0 1 2" or "vandaleur 0 1 2 3"--------------------------------------------------------------------------------Question 20)What will be displayed when you attempt to compile and run the following code//Code startimport java.awt.*;public class Butt extends Frame{public static void main(String argv[]){Butt MyBut=new Butt();}Butt(){Button HelloBut=new Button("Hello");Button ByeBut=new Button("Bye");add(HelloBut);add(ByeBut);setSize(300,300);setVisible(true); }}//Code end1) Two buttons side by side occupying all of the frame, Hello on the left and Bye on the right2) One button occupying the entire frame saying Hello3) One button occupying the entire frame saying Bye4) Two buttons at the top of the frame one saying Hello the other saying Bye--------------------------------------------------------------------------------Question 21)What will be output by the following code?public class MyFor{public static void main(String argv[]){int i;int j;outer: for (i=1;i <3;i++)inner: for(j=1; j<3; j++) {if (j==2) continue outer;System.out.println("Value for i=" + i + " Value for j=" +j);}}}1) Value for i=1 Value for j=12) Value for i=2 Value for j=13) Value for i=2 Value for j=24) Value for i=3 Value for j=1--------------------------------------------------------------------------------Question 22)Which statement is true of the following code?public class Agg{public static void main(String argv[]){Agg a = new Agg();a.go();}public void go(){DSRoss ds1 = new DSRoss("one");ds1.start();}}class DSRoss extends Thread{private String sTname="";DSRoss(String s){sTname = s;}public void run(){notwait();System.out.println("finished");}public void notwait(){while(true){try{System.out.println("waiting");wait();}catch(InterruptedException ie){}System.out.println(sTname);notifyAll();}} }1) It will cause a compile time error2) Compilation and output of "waiting"3) Compilation and output of "waiting" followed by "finished"4) Runtime error, an exception will be thrown--------------------------------------------------------------------------------Question 23)Which of the following methods can be legally inserted in place of the comment //Method Here ?class Base{public void amethod(int i) { }}public class Scope extends Base{public static void main(String argv[]){ }//Method Here}1) void amethod(int i) throws Exception {}2) void amethod(long i)throws Exception {}3) void amethod(long i){}4) public void amethod(int i) throws Exception {}--------------------------------------------------------------------------------Question 24)Which of the following will output -4.01) System.out.println(Math.floor(-4.7));2) System.out.println(Math.round(-4.7));3) System.out.println(Math.ceil(-4.7));4) System.out.println(Math.min(-4.7));Options 1 and 2 will produce -5 and option 4 will not compile because the min method requires 2 parameters.--------------------------------------------------------------------------------Question 25)What will happen if you attempt to compile and run the following code?Integer ten=new Integer(10);Long nine=new Long (9);System.out.println(ten + nine);int i=1;System.out.println(i + ten);1) 19 followed by 202) 19 followed by 113) Compile time error4) 10 followed by 1--------------------------------------------------------------------------------Question 26)If you run the code below, what gets printed out?String s=new String("Bicycle");int iBegin=1;char iEnd=3;System.out.println(s.substring(iBegin,iEnd));1) Bic2) ic3) icy4) error: no method matching substring(int,char)--------------------------------------------------------------------------------Question 27)If you wanted to find out where the position of the letter v (ie return 2) in the string s containing "Java", which of the following could you use?1) mid(2,s);2) charAt(2);3) s.indexOf('v');4) indexOf(s,'v');--------------------------------------------------------------------------------Question 28)Given the following declarationsString s1=new String("Hello");String s2=new String("there");String s3=new String();Which of the following are legal operations?1) s3=s1 + s2;2) s3=s1-s2;3) s3=s1 & s2;4) s3=s1 && s2--------------------------------------------------------------------------------Question 29)What is the result of the following operation?System.out.println(4 | 3); 1000111111) 62) 03) 14) 7--------------------------------------------------------------------------------Question 30)public class MyClass1 {public static void main(String argv[]){ }/*Modifier at XX */class MyInner {}}What modifiers would be legal at XX in the above code?1) public2) private3) static4) friend-------------------------------------------------------------------------------- Question 31)What will happen when you attempt to compile and run the following code?public class Holt extends Thread{private String sThreadName;public static void main(String argv[]){Holt h = new Holt();h.go();}Holt(){}Holt(String s){sThreadName = s;}public String getThreadName(){return sThreadName;}public void go(){Holt first = new Holt("first");first.start();Holt second = new Holt("second");second.start();}public void start(){for(int i = 0; i < 2; i ++){System.out.println(getThreadName()+i);try{Thread.sleep(100);}catch(InterruptedExceptione){System.out.println(e.getMessage());} } }}1) Compile time error2) Output of first0, second0, first0, second13) Output of first0, first1, second0, second14) Runtime error--------------------------------------------------------------------------------Question 32)An Applet has its Layout Manager set to the default of FlowLayout. What code would be correct to change to another Layout Manager.1) setLayoutManager(new GridLayout());2) setLayout(new GridLayout(2,2));3) setGridLayout(2,2);4) setBorderLayout();--------------------------------------------------------------------------------Question 33)What will happen when you attempt to compile and run the following code?.class Background implements Runnable{int i=0;public int r un(){while(true){i++;System.out.println("i="+i);} //End whilereturn 1;}//End run}//End class1) It will compile and the run method will print out the increasing value of i.2) It will compile and calling start will print out the increasing value of i.3) The code will cause an error at compile time.4) Compilation will cause an error because while cannot take a parameter of true.--------------------------------------------------------------------------------Question 34)Which of the following statements about this code are true?public class Morecombe{public static void main(String argv[]){Morecombe m = new Morecombe();m.go(new Turing(){});}public void go(Turing t){t.start();}}class Turing extends Thread{public void run(){for(int i =0; i < 2; i++){System.out.println(i); }}}1) Compilation error due to malformed parameter to go method2) Compilation error, class Turing has no start method3) Compilation and output of 0 followed by 14) Compilation but runtime error--------------------------------------------------------------------------------Question 35)What will be the result when you attempt to compile and run the following code?.public class Conv{public static void main(String argv[]){Conv c=new Conv();String s=new String("ello");c.amethod(s);}public void amethod(String s){char c='H';c+=s;System.out.println(c);}}1) Compilation and output the string "Hello"2) Compilation and output the string "ello"3) Compilation and output the string elloH4) Compile time error--------------------------------------------------------------------------------Question 36)Given the following code, what test would you need to put in place of the comment line? //place test hereto result in an output of the string Equalpublic class EqTest{public static void main(String argv[]){EqTest e=new EqTest();}EqTest(){String s="Java";String s2="java";//place test here {System.out.println("Equal");}else{System.out.println("Not equal");}}}1) if(s==s2)2) if(s.equals(s2)3) if(s.equalsIgnoreCase(s2))4)if(s.noCaseMatch(s2))--------------------------------------------------------------------------------Question 37)Given the following codeimport java.awt.*;public class SetF extends Frame{public static void main(String argv[]){SetF s=new SetF();s.setSize(300,200);s.setVisible(true);}}How could you set the frame surface color to pink1)s.setBackground(Color.pink);2)s.setColor(PINK);3)s.Background(pink);4)s.color=Color.pink--------------------------------------------------------------------------------Question 38)How can you change the current working directory using an instance of the File class called FileName?1) FileName.chdir("DirName")2) FileName.cd("DirName")3) FileName.cwd("DirName")4) The File class does not support directly changing the current directory.--------------------------------------------------------------------------------Question 39)If you create a TextField with a constructor to set it to occupy 5 columns, what difference will it make if you use it with a proportional font (ie Times Roman) or a fixed pitch typewriter style font (Courier).1)With a fixed font you will see 5 characters, with a proportional it will depend on the width of the characters2)With a fixed font you will see 5 characters,with a proportional it will cause the field to expand to fit the text3)The columns setting does not affect the number of characters displayed4)Both will show exactly 5 characters--------------------------------------------------------------------------------Question 40)Given the following code how could you invoke the Base constructor that will print out the string "base constructor";class Base{Base(int i){System.out.println("base constructor"); }Base(){ }}public class Sup extends Base{public static void main(String argv[]){Sup s= new Sup();//One }Sup() { //Two }public void derived() { //Three }}1) On the line After //One put Base(10);2) On the line After //One put super(10);3) On the line After //Two put super(10);4) On the line After //Three put super(10);--------------------------------------------------------------------------------Question 41)Given the following code what will be output?public class Pass{ static int j=20;public static void main(String argv[]){ int i=10; Pass p = new Pass(); p.amethod(i);System.out.println(i); System.out.println(j); }public void amethod(int x){ x=x*2; j=j*2; }}1) Error: amethod parameter does not match variable2) 20 and 403) 10 and 404) 10, and 20--------------------------------------------------------------------------------Question 42)What code placed after the comment //For loop would result in the population of every element of the array ia[] with a value from variable i.?public class Lin{ public static void main(String argv[]){ Lin l = new Lin(); l.amethod(); }public void amethod(){ int ia[] = new int[4]; //Start For loop{ ia[i]=i; System.out.println(ia[i]);}}}1) for(int i=0; i < ia.length() -1; i++)2) for (int i=0; i< ia.length(); i++)3) for(int i=1; i < 4; i++)4) for(int i=0; i< ia.length;i++)--------------------------------------------------------------------------------Question 43)What will be the result when you try to compile and run the following code?private class Base{Base(){int i = 100;System.out.println(i);}}public class Pri extends Base{static int i = 200;public static void main(String argv[]){Pri p = new Pri();System.out.println(i);}}1) Error at compile time2) 2003) 100 followed by 2004) 100--------------------------------------------------------------------------------Question 44)What will the following code print out?public class Oct{public static void main(String argv[]){ Oct o = new Oct(); o.amethod(); }public void amethod(){int oi= 012; System.out.println(oi);}}1)122)0123)10 8*1 + 8^0 * 2 = 104)10.0--------------------------------------------------------------------------------Question 45)You need to create a class that will store unique object elements. You do not need to sort these elements but they must be unique.What interface might be most suitable to meet this need?1)Set (集合)2)List3)Map4)Vector--------------------------------------------------------------------------------Question 46)Which of the following will successfully create an instance of the Vector class and add an element?1) Vector v=new Vector(99);v[1]=99;2) Vector v=new Vector();v.addElement(99);3) Vector v=new Vector();v.add(99);4 Vector v=new Vector(100);v.addElement("99");--------------------------------------------------------------------------------Question 47)You have created a simple Frame and overridden the paint method as followspublic void paint(Graphics g){g.drawString("Dolly",50,10);}What will be the result when you attempt to compile and run the program?1) The string "Dolly" will be displayed at the centre of the frame2) An error at compilation complaining at the signature of the paint method3) The lower part of the word Dolly will be seen at the top of the frame, with the top hidden.4) The string "Dolly" will be shown at the bottom of the frame.--------------------------------------------------------------------------------Question 48)Given the following codeimport java.io.*;public class Th{public static void main(String argv[]){Th t = new Th();t.amethod(); }public void amethod(){try{ioCall();}catch(IOException ioe){}}}What code would be most likely for the body of the ioCall method1) public void ioCall ()throws IOException{DataInputStream din = new DataInputStream(System.in);din.readChar(); }2) public void ioCall ()throw IOException{DataInputStream din = new DataInputStream(System.in);din.readChar();}3) public void ioCall (){DataInputStream din = new DataInputStream(System.in);din.readChar(); }4)public void ioCall throws IOException(){DataInputStream din = new DataInputStream(System.in);din.readChar(); }--------------------------------------------------------------------------------Question 49)Which of the following can you perform using the File class?1) Change the current directory2) Return the name of the parent directory3) Access a random file4) Find if a file contains text or binary information--------------------------------------------------------------------------------Question 50)You are using the GridBagLayout manager to place a series of buttons on a Frame. You want to make the size of one of the buttons bigger than the text it contains. Which of the following will allow you to do that?1) The GridBagLayout manager does not allow you to do this2) The setFill method of the GridBagLayout class3) The setFill method of the GridBagConstraints class4) The fill field of the GridBagConstraints class--------------------------------------------------------------------------------。
java英文面试题(含部分参考答案)-烽火通信
java英文面试题(含部分参考答案)-烽火通信1.what is oracle.2.what is major differenece oracle8i and oracle9i.4.tell me some thing ur self.5.please tell me about oops.6.what is single inheritance.7.what is multiple inheritance.8.can java support multiple inheritance.9.what is interface.10.what is differenec between abstract class and interface.11.how to u prove that abstrace class cannot instantiate directly.12.what is differenece between string and stringbuffer.13.what is immutable14.how to write a program using sort program.15 how to write a program using unsort program.16.what is legacy.17.what is legacy api18.what is legacy interface.19.what is main difference hashmap and hastable20.what is main difference between arraylist and vector.21.what is struts framework.22.what are distributed techonologies.23.what is advantage and disadvantage of distributed techonologies.24.what is main difference between jsp and servlets.25.what is difference between procedure and functions.26.what is jdbc.27.what are type of drivers.28.what is type 4 driver.29.how to collect requuirements form u r client.30.which process use in ur project.31.what is deployment descriptor.32.what is heirarchy of files in struts.33.please draw struts frame wrok.34.please draw j2ee architecture.35.please draw mvc-2 architecture.36.please draw that how design op module.37.how to find a file on linux.38.how to configure weblogic8.1 on linux.39.why you use struts framework in ur project.40.what is platfrom independent41.what is awt and swing.42.what is heavy wieght components.43.what is feature of weblgoic8.1.44.why you choose application server on linux and database server on aix.45.please tell me about ur project.46.what is major concepts in oops.47.why u choose mvc-2 architecture.48.what is implicit object.49.how many implicit objects in jsp—————————————————————————————————————————————————————————1. Oracle is an RDBMS product with DDL and DML from a company called Oracle Inc.2. Difference between 8i and 9i is given in the Oracle site3. Question not available4. Something5. oops is Object Oriented Programming6.what is single inheritance.ans:one class is inherited by only other one class7.what is multiple inheritance.ans:One class inheriting more than one class at atime8.can java support multiple inheritance.ans:No9.what is interface.ans:Interface has only method declarations but no defn10.what is differenec between abstract class and interface.ans:In abstract class some methods may contain definition,but in interface every method should be abstract11.how to u prove that abstrace class cannot instantiate directly.ans:As they dont have constructor they cant be instantiated12.what is differenece between string and stringbuffer.ans:Strings are immutable where as string buffer can be modified13.what is immutableans:Which cant be changed14.how to write a program using sort program.15 how to write a program using unsort program.ans: Both can be done using javascriptThis is for Sortfunction SelectTextSort(obj) { // sort by textvar N=obj.options.length;for (var i=0;ifor (var j=i+1;jif ( obj.options[i].text > obj.options[j].text ) {var i1= (obj.options[i].selected == true ) ? true : falsevar j1= (obj.options[j].selected == true ) ? true : falsevar q1 = obj.options[j].text;var q2 = obj.options[j].value;obj.options[j].text = obj.options[i].text;obj.options[j].value = obj.options[i].value;obj.options[i].text = q1;obj.options[i].value = q2;obj.options[i].selected = (j1 && true ) ? true : falseobj.options[j].selected = (i1 && true ) ? true : false}}}return true}16.what is legacy.17.what is legacy api18.what is legacy interface.ans: legacy is something that is old in terms of technology/ system19.what is main difference hashmap and hastableans:Hash table is synchronised20.what is main difference between arraylist and vector.ans:Vector is synchronised21.what is struts framework.22.what are distributed techonologies.distributed technologies means any technology / s/w program that are having many components in multiple environments that interact with each other depending on the functional requirements and design.23.what is advantage and disadvantage of distributed techonologies.overdependance on single platform / single language is avoided. Application can be built flexible to meet requirements. Division of labour is possible. Best of all the technologies and platforms can be optimally utilized. Complexity of requirements can be reduced.25.what is difference between procedure and functions.'ans:Fuctions can return value ,procedures cant return value26.what is jdbc.ans:Connecting to DB from java program requires JDBC27.what are type of drivers.type1,2,3,429.how to collect requuirements form u r client.is not a job of a technical person. It is better for a BA to do it.30.which process use in ur project.Generally u can say:Project related process: Analysis, Design, Sign-off Documents, Implementation, Integration, Testing, UAT Work related process:Technical Design, Work Allocation, Code Review Checklist, Unit Test Form will be prepared by the Project Lead and given tothe developer.Developer prepares the Unit Test CaseImplements Code, Performs TestSubmits Code through CVS / VSSSubmits documents along with Release Checklist to the tester / leader.31.what is deployment descriptor.ans:Which contains the infrnmation like which file to be used 不好意思,暂缺32到39的参考答案.40.what is platfrom independentans:A language is said to be platform independent if it can be run on any machine with out modifying code41.what is awt and swing.ans:AWT are heavy weight components and swings are light weight components46.what is major concepts in oops.ans:Abstraction,polymorphism,encapsulation,inheritance47.why u choose mvc-2 architecture.ans:In MVC-2 controller is servlet rather than JSP which makes it efficient48.what is implicit object.ans:Implicit objects are a set of Java objects that the JSP Container makes available to developers in each page49.how many implicit objects in jspans:out,page,session,request,response,application,page context,config转载请注明文章来源:笔试网/doc/2b1197711.html,—专业的笔试、面试资料搜索网站,原文网址:/doc/2b1197711.html,/shiti.aspx?id=536157。
java英语笔试试题及答案
java英语笔试试题及答案Java英语笔试试题及答案1. What is the difference between a class and an object in Java?A class is a blueprint or template that defines the properties and methods of an object. An object is an instance of a class, created at runtime.2. What is the purpose of the 'public static voidmain(String[] args)' method in Java?The 'public static void main(String[] args)' method is the entry point of a Java application. It is the first methodthat gets executed when the program starts.3. What is the difference between a method and a function in Java?In Java, a method is a block of code that is used to perform a specific task. A function is a term that is often used interchangeably with method, but technically, a function can return a value whereas a method does not necessarily do so.4. What is the 'this' keyword used for in Java?The 'this' keyword in Java is a reference to the current object. It can be used to access instance variables and methods of the current object.5. What is an interface in Java?An interface in Java is a completely abstract class that can contain only abstract methods and constants. It is used to achieve abstraction and to define a contract for classes to implement.6. What is the difference between a checked exception and an unchecked exception in Java?A checked exception is a type of exception that a method must either handle with a try-catch block or declare it with the 'throws' keyword. An unchecked exception is not required to be handled or declared, and includes RuntimeException and its subclasses.7. What is the 'final' keyword used for in Java?The 'final' keyword in Java can be used in three different contexts: to declare a class as final (cannot be subclassed), to declare a method as final (cannot be overridden), or to declare a variable as final (cannot be reassigned).8. What is a constructor in Java?A constructor in Java is a special method that is used to initialize objects. It has the same name as the class and is called when an object is created.9. What is the purpose of the 'super' keyword in Java?The 'super' keyword in Java is used to refer to the parent class's methods and variables. It is often used in constructors to call a superclass's constructor.10. What is the difference b etween '==’ and 'equals()' inJava?The '==' operator is used to compare primitive data types by value and object references by reference, whereas the'equals()' method is used to compare objects by content, and it can be overridden to provide custom comparison logic.Answers:1. A class is a blueprint, an object is an instance of a class.2. It is the entry point of a Java application.3. A method is a block of code in Java, a function is a more general term and can return a value.4. It refers to the current object.5. An interface is an abstract class with only abstract methods and constants.6. Checked exceptions must be handled or declared, unchecked do not.7. It is used to declare classes, methods, or variables as final.8. It initializes objects.9. It refers to the parent class's methods and variables.10. '==' compares by value or reference, 'equals()' compares by content.。
java英文试题及答案
java英文试题及答案1. What is the full form of Java?A. Just Another Virtual ApplicationB. Java Application Virtual ArchitectureC. Java Application Virtual ArchitectureD. Just Another Virtual AssistantAnswer: C2. Which of the following is not a feature of Java?A. Platform IndependenceB. RobustnessC. MultithreadingD. Memory ManagementAnswer: D3. What does JRE stand for?A. Java Runtime EnvironmentB. Java Runtime ExecutionC. Java Runtime EngineD. Java Runtime ExpressionAnswer: A4. What is the correct way to declare a variable in Java?A. int number = 10;B. int number = 10.0;C. int number = "ten";D. int number = 10.0f;Answer: A5. Which of the following is a valid Java identifier?A. 2variableB. variable2C. variable$2D. variable2!Answer: B6. What is the default access modifier in Java?A. publicB. privateC. protectedD. defaultAnswer: D7. What is the purpose of the 'this' keyword in Java?A. To call a constructor of the same classB. To call a method of the same classC. To refer to the current objectD. To refer to the parent classAnswer: C8. What is the correct syntax for a 'for' loop in Java?A. for (int i = 0; i < 10; i++)B. for (int i = 10; i > 0; i--)C. for (int i = 0; i <= 10; i++)D. All of the aboveAnswer: D9. What is the output of the following Java code snippet? ```javapublic class Test {public static void main(String[] args) {int x = 10;if (x > 5) {System.out.println("x is greater than 5");} else {System.out.println("x is not greater than 5"); }}}```A. x is greater than 5B. x is not greater than 5C. Compilation errorD. Runtime errorAnswer: A10. Which of the following is not a valid Java data type?A. intB. floatC. doubleD. realAnswer: D。
java英文版答案
public class Exercise1_2 {public static void main(String[] args) {System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");}}public class Exercise1_4 {public static void main(String[] args) {System.out.println("a a^2 a^3");System.out.println("1 1 1");System.out.println("2 4 8");System.out.println("3 9 27");System.out.println("4 16 64");}}public class Exercise1_6 {public static void main(String[] args) {System.out.println(1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9);}}public class Exercise1_8 {public static void main(String[] args) {// Display areaSystem.out.println(5.5 * 5.5 * 3.14159);// Display perimeterSystem.out.println(2 * 5.5 * 3.14159);}}import javax.swing.JOptionPane;public class Exercise2_1WithDialogBox {// Main methodpublic static void main(String[] args) {// Enter a temperatur in FahrenheitString celsiusString = JOptionPane.showInputDialog(null,"Enter a temperature in Celsius:","Exercise2_1 Input", JOptionPane.QUESTION_MESSAGE);// Convert string to doubledouble celsius = Double.parseDouble(celsiusString);// Convert it to Celsiusdouble fahrenheit = (9.0 / 5) * celsius + 32;// Display the resultJOptionPane.showMessageDialog(null, "The temperature is " +fahrenheit + " in Fahrenheit");}}import java.util.Scanner;public class Exercise2_2 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Enter radius of the cylinderSystem.out.print("Enter radius of the cylinder: ");double radius = input.nextDouble();// Enter length of the cylinderSystem.out.print("Enter length of the cylinder: ");double length = input.nextDouble();double volume = radius * radius * 3.14159 * length;System.out.println("The volume of the cylinder is " + volume);}}public class Exercise2_4 {public static void main(String[] args) {// Prompt the inputjava.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Enter a number in pounds: ");double pounds = input.nextDouble();double kilograms = pounds * 0.454;System.out.println(pounds + " pounds is " + kilograms + " kilograms"); }}// Exercise2_6.java: Summarize all digits in an integer < 1000public class Exercise2_6 {// Main methodpublic static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Read a numberSystem.out.print("Enter an integer between 0 and 1000: ");int number = input.nextInt();// Find all digits in numberint lastDigit = number % 10;int remainingNumber = number / 10;int secondLastDigit = remainingNumber % 10;remainingNumber = remainingNumber / 10;int thirdLastDigit = remainingNumber % 10;// Obtain the sum of all digitsint sum = lastDigit + secondLastDigit + thirdLastDigit;// Display resultsSystem.out.println("The sum of all digits in " + number+ " is " + sum);}}public class Exercise2_8 {public static void main(String args[]) {java.util.Scanner input = new java.util.Scanner(System.in);// Enter an ASCII codeSystem.out.print("Enter an ASCII code: ");int code = input.nextInt();// Display resultSystem.out.println("The character for ASCII code "+ code + " is " + (char)code);}}import java.util.Scanner;public class Exercise2_10 {/** Main method */public static void main(String[] args) {Scanner input = new Scanner(System.in);// Receive the amount entered from the keyboardSystem.out.print("Enter an amount in double, for example 11.56 ");double amount = input.nextDouble();int remainingAmount = (int)(amount * 100);// Find the number of one dollarsint numberOfOneDollars = remainingAmount / 100;remainingAmount = remainingAmount % 100;// Find the number of quarters in the remaining amountint numberOfQuarters = remainingAmount / 25;remainingAmount = remainingAmount % 25;// Find the number of dimes in the remaining amountint numberOfDimes = remainingAmount / 10;remainingAmount = remainingAmount % 10;// Find the number of nickels in the remaining amountint numberOfNickels = remainingAmount / 5;remainingAmount = remainingAmount % 5;// Find the number of pennies in the remaining amountint numberOfPennies = remainingAmount;// Display resultsString output = "Your amount " + amount + " consists of \n" +numberOfOneDollars + " dollars\n" +numberOfQuarters + " quarters\n" +numberOfDimes + " dimes\n" +numberOfNickels + " nickels\n" +numberOfPennies + " pennies";System.out.println(output);}}import javax.swing.JOptionPane;public class Exercise2_12a {public static void main(String args[]) {// Obtain inputString balanceString = JOptionPane.showInputDialog(null,"Enter balance:");double balance = Double.parseDouble(balanceString);String interestRateString = JOptionPane.showInputDialog(null,"Enter annual interest rate:");double annualInterestRate = Double.parseDouble(interestRateString);double monthlyInterestRate = annualInterestRate / 1200;double interest = balance * monthlyInterestRate;// Display outputJOptionPane.showMessageDialog(null, "The interest is " +(int)(100* interest) / 100.0);}}import java.util.Scanner;public class Exercise2_12b {public static void main(String args[]) {Scanner input = new Scanner(System.in);// Obtain inputSystem.out.print("Enter balance: ");double balance = input.nextDouble();System.out.print("Enter annual interest rate: ");double annualInterestRate = input.nextDouble();double monthlyInterestRate = annualInterestRate / 1200;double interest = balance * monthlyInterestRate;// Display outputSystem.out.println("The interest is " + (int)(100* interest) / 100.0);}}import java.util.Scanner;public class Exercise2_14 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter weight in poundsSystem.out.print("Enter weight in pounds: ");double weight = input.nextDouble();// Prompt the user to enter height in inchesSystem.out.print("Enter height in inches: ");double height = input.nextDouble();double bmi = weight * 0.45359237 / (height * 0.0254 * height * 0.0254);System.out.print("BMI is " + bmi);}}public class Exercise2_16 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Enter the amount of water in kilograms: ");double mass = input.nextDouble();System.out.print("Enter the initial temperature: ");double initialTemperature = input.nextDouble();System.out.print("Enter the final temperature: ");double finalTemperature = input.nextDouble();double energy =mass * (finalTemperature - initialTemperature) * 4184;System.out.print("The energy needed is " + energy);}}public class Exercise2_18 {// Main methodpublic static void main(String[] args) {System.out.println("a b pow(a, b)");System.out.println("1 2 " + (int)Math.pow(1, 2));System.out.println("2 3 " + (int)Math.pow(2, 3));System.out.println("3 4 " + (int)Math.pow(3, 4));System.out.println("4 5 " + (int)Math.pow(4, 5));System.out.println("5 6 " + (int)Math.pow(5, 6)); }}import java.util.Scanner;public class Exercise2_20 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Enter the first point with two double valuesSystem.out.print("Enter x1 and y1: ");double x1 = input.nextDouble();double y1 = input.nextDouble();// Enter the second point with two double valuesSystem.out.print("Enter x2 and y2: ");double x2 = input.nextDouble();double y2 = input.nextDouble();// Compute the distancedouble distance = Math.pow((x1 - x2) * (x1 - x2) +(y1 - y2) * (y1 - y2), 0.5);System.out.println("The distance of the two points is " + distance);}}import java.util.Scanner;public class Exercise2_22 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Enter the side of the hexagonSystem.out.print("Enter the side: ");double side = input.nextDouble();// Compute the areadouble area = 3 * 1.732 * side * side / 2;System.out.println("The area of the hexagon is " + area); }}import java.util.Scanner;public class Exercise2_24 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter speed v: ");double v = input.nextDouble();System.out.print("Enter acceleration a: ");double a = input.nextDouble();double length = v * v / (2 * a);System.out.println("The minimum runway length for this airplane is " + length + " meters");}}public class Exercise3_2 {/**Main method*/public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Prompt the user to enter an integerSystem.out.print("Enter an integer: ");int number = input.nextInt();// Display resultsSystem.out.println("Is " + number + " an even number? " +(number % 2 == 0));}}import javax.swing.*;public class Exercise3_4 {public static void main(String[] args) {int number1 = (int)(System.currentTimeMillis() % 100);int number2 = (int)(System.currentTimeMillis() * 7 % 100);String resultString = JOptionPane.showInputDialog("What is " + number1 + " + " + number2 + "?");int result = Integer.parseInt(resultString);JOptionPane.showMessageDialog(null,number1 + " + " + number2 + " = " + result + " is " +(number1 + number2 == result));}}import javax.swing.*;public class Exercise3_5WithJOptionPane {public static void main(String[] args) {int number1 = (int)(System.currentTimeMillis() % 10);int number2 = (int)(System.currentTimeMillis() * 7 % 10);int number3 = (int)(System.currentTimeMillis() * 3 % 10);String answerString = JOptionPane.showInputDialog("What is " + number1 + " + " + number2 + " + " +number3 + "?");int answer = Integer.parseInt(answerString);JOptionPane.showMessageDialog(null,number1 + " + " + number2 + " + " + number3 + " = " + answer + " is " + (number1 + number2 + number3 == answer));}}import java.util.Scanner;public class Exercise3_6 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter weight in poundsSystem.out.print("Enter weight in pounds: ");double weight = input.nextDouble();// Prompt the user to enter heightSystem.out.print("Enter feet: ");double feet = input.nextDouble();System.out.print("Enter inches: ");double inches = input.nextDouble();double height = feet * 12 + inches;// Compute BMIdouble bmi = weight * 0.45359237 /((height * 0.0254) * (height * 0.0254));// Display resultSystem.out.println("Your BMI is " + bmi);if (bmi < 16)System.out.println("You are seriously underweight");else if (bmi < 18)System.out.println("You are underweight");else if (bmi < 24)System.out.println("You are normal weight");else if (bmi < 29)System.out.println("You are over weight");else if (bmi < 35)System.out.println("You are seriously over weight");elseSystem.out.println("You are gravely over weight");}}public class Exercise3_8 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Enter three numbersSystem.out.print("Enter three integers: ");int num1 = input.nextInt();int num2 = input.nextInt();int num3 = input.nextInt();if (num1 > num2) {int temp = num1;num1 = num2;num2 = temp;}if (num2 > num3) {int temp = num2;num2 = num3;num3 = temp;}if (num1 > num2) {int temp = num1;num1 = num2;num2 = temp;}System.out.println("The sorted numbers are "+ num1 + " " + num2 + " " + num3);}}import javax.swing.JOptionPane;public class Exercise3_10 {public static void main(String[] args) {// 1. Generate two random single-digit integersint number1 = (int)(Math.random() * 10);int number2 = (int)(Math.random() * 10);// 2. Prompt the student to answer 搘hat is number1 + number2?? String answerString = JOptionPane.showInputDialog("What is " + number1 + " + " + number2 + "?");int answer = Integer.parseInt(answerString);// 4. Grade the annser and display the resultString replyString;if (number1 + number2 == answer)replyString = "You are correct!";elsereplyString = "Your answer is wrong.\n" + number1 + " + "+ number2 + " should be " + (number1 + number2);JOptionPane.showMessageDialog(null, replyString);}}import java.util.Scanner;public class Exercise3_12 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter an integerSystem.out.print("Enter an integer: ");int number = input.nextInt();if (number % 5 == 0 && number % 6 == 0)System.out.println(number + " is divisible by both 5 and 6");else if (number % 5 == 0 ^ number % 6 == 0)System.out.println(number + " is divisible by both 5 and 6, but not both");elseSystem.out.println(number + " is not divisible by either 5 or 6");}}public class Exercise3_14 {public static void main(String[] args) {// Obtain the random number 0 or 1int number = (int)(Math.random() * 2);// Prompt the user to enter a guessjava.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Guess head or tail? " +"Enter 0 for head and 1 for tail: ");int guess = input.nextInt();// Check the guessif (guess == number)System.out.println("Correct guess");else if (number == 0)System.out.println("Sorry, it is a head");elseSystem.out.println("Sorry, it is a tail");}}public class Exercise3_16 {public static void main(String[] args) {System.out.println((char)('A' + Math.random() * 27));}}import java.util.Scanner;public class Exercise3_18 {/** Main method */public static void main(String args[]) {Scanner input = new Scanner(System.in);// Prompt the user to enter a yearSystem.out.print("Enter a year: ");// Convert the string into an int valueint year = input.nextInt();// Check if the year is a leap yearboolean isLeapYear =((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);// Display the result in a message dialog boxSystem.out.println(year + " is a leap year? " + isLeapYear);}}public class Exercise3_20 {// Main methodpublic static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Enter the temperature in FahrenheitSystem.out.print("Enter the temperature in Fahrenheit: ");double fahrenheit = input.nextDouble();if (fahrenheit < -58 || fahrenheit > 41) {System.out.println("Temperature must be between -58癋and 41癋");System.exit(0);}// Enter the wind speed miles per hourSystem.out.print("Enter the wind speed miles per hour: ");double speed = input.nextDouble();if (speed < 2) {System.out.println("Speed must be greater than or equal to 2");System.exit(0);}// Compute wind chill indexdouble windChillIndex = 35.74 + 0.6215 * fahrenheit - 35.75 *Math.pow(speed, 0.16) + 0.4275 * fahrenheit *Math.pow(speed, 0.16);// Display the resultSystem.out.println("The wind chill index is " + windChillIndex);}}import java.util.Scanner;public class Exercise3_22 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Enter a point with two double valuesSystem.out.print("Enter a point with two coordinates: ");double x = input.nextDouble();double y = input.nextDouble();// Compute the distancedouble distance = Math.pow(x * x + y * y, 0.5);if (distance <= 10)System.out.println("Point (" + x + ", " + y +") is in the circle");elseSystem.out.println("Point (" + x + ", " + y +") is not in the circle");}}public class Exercise3_24 {public static void main(String[] args) {final int NUMBER_OF_CARDS = 52;// Pick a cardint number = (int)(Math.random() * NUMBER_OF_CARDS);System.out.print("The card you picked is ");if (number % 13 == 0)System.out.print("Ace of ");else if (number % 13 == 10)System.out.print("Jack of ");else if (number % 13 == 11)System.out.print("Queen of ");else if (number % 13 == 12)System.out.print("King of ");elseSystem.out.print((number % 13) + " of ");if (number / 13 == 0)System.out.println("Clubs");else if (number / 13 == 1)System.out.println("Diamonds");else if (number / 13 == 2)System.out.println("Hearts");else if (number / 13 == 3)System.out.println("Spades");}}public class Exercise3_26 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Enter an integerSystem.out.print("Enter an integer: ");int number = input.nextInt();System.out.println("Is " + number + " divisible by 5 and 6? " +((number % 5 == 0) && (number % 6 == 0)));System.out.println("Is " + number + " divisible by 5 or 6? " +((number % 5 == 0) || (number % 6 == 0)));System.out.println("Is " + number +" divisible by 5 or 6, but not both? " +((number % 5 == 0) ^ (number % 6 == 0)));}}import java.util.Scanner;public class Exercise3_28 {public static void main(String args[]) {Scanner input = new Scanner(System.in);System.out.print("Enter r1抯center x-, y-coordinates, width, and height: ");double x1 = input.nextDouble();double y1 = input.nextDouble();double w1 = input.nextDouble();double h1 = input.nextDouble();System.out.print("Enter r2抯center x-, y-coordinates, width, and height: ");double x2 = input.nextDouble();double y2 = input.nextDouble();double w2 = input.nextDouble();double h2 = input.nextDouble();double xDistance = x1 - x2 >= 0 ? x1 - x2 : x2 - x1;double yDistance = y1 - y2 >= 0 ? y1 - y2 : y2 - y1;if (xDistance <= (w1 - w2) / 2 && yDistance <= (h1 - h2) / 2)System.out.println("r2 is inside r1");else if (xDistance <= (w1 + w2) / 2 && yDistance <= (h1 + h2) / 2)System.out.println("r2 overlaps r1");elseSystem.out.println("r2 does not overlap r1");}}import java.util.Scanner;public class Exercise3_30 {public static void main(String[] args) {// Prompt the user to enter the time zone offset to GMTScanner input = new Scanner(System.in);System.out.print("Enter the time zone offset to GMT: ");long timeZoneOffset = input.nextInt();// Obtain the total milliseconds since the midnight, Jan 1, 1970long totalMilliseconds = System.currentTimeMillis();// Obtain the total seconds since the midnight, Jan 1, 1970long totalSeconds = totalMilliseconds / 1000;// Compute the current second in the minute in the hourlong currentSecond = totalSeconds % 60;// Obtain the total minuteslong totalMinutes = totalSeconds / 60;// Compute the current minute in the hourlong currentMinute = totalMinutes % 60;// Obtain the total hourslong totalHours = totalMinutes / 60;// Compute the current hourlong currentHour = (totalHours + timeZoneOffset) % 24;// Display resultsSystem.out.print("Current time is " + (currentHour % 12) + ":"+ currentMinute + ":" + currentSecond);if (currentHour < 12)System.out.println(" AM");elseSystem.out.println(" PM");}}public class Exercise4_2 {public static void main(String[] args) {int correctCount = 0; // Count the number of correct answersint count = 0; // Count the number of questionsjava.util.Scanner input = new java.util.Scanner(System.in);long startTime = System.currentTimeMillis();while (count < 10) {// 1. Generate two random single-digit integersint number1 = 1 + (int)(Math.random() * 15);int number2 = 1 + (int)(Math.random() * 15);// 2. Prompt the student to answer 搘hat is number1 ?number2?? System.out.print("What is " + number1 + " + " + number2 + "? ");int answer = input.nextInt();// 3. Grade the answer and display the resultString replyString;if (number1 + number2 == answer) {replyString = "You are correct!";correctCount++;}else {replyString = "Your answer is wrong.\n" + number1 + " + "+ number2 + " should be " + (number1 + number2);}System.out.println(replyString);// Increase the countcount++;}System.out.println("Correct count is " + correctCount);long endTime = System.currentTimeMillis();System.out.println("Time spent is " + (endTime - startTime) / 1000 + " seconds"); }}public class Exercise4_4 {public static void main(String[] args) {System.out.println("Miles\t\tKilometers");System.out.println("-------------------------------");// Use while loopint miles = 1;while (miles <= 10) {System.out.println(miles + "\t\t" + miles * 1.609);miles++;}/** Alternatively use for loopfor (int miles = 1; miles <= 10; miles++) {System.out.println(miles + "\t\t" + miles * 1.609);}*/}}public class Exercise4_6 {public static void main(String[] args) {System.out.printf("%10s%10s | %10s%10s\n", "Miles", "Kilometers", "Kilometers", "Miles");System.out.println("---------------------------------------------");// Use while loopint miles = 1; int kilometers = 20; int count = 1;while (count <= 10) {System.out.printf("%10d%10.3f | %10d%10.3f\n", miles, miles * 1.609, kilometers, kilometers / 1.609);miles++; kilometers += 5; count++;}/* Use for loopint miles = 1; int kilometers = 20;for (int count = 1; count <= 10; miles++, kilometers += 5, count++) {System.out.printf("%10d%10.3f | %10d%10.3f\n", miles, miles * 1.609, kilometers, kilometers / 1.609);}*/}}import java.util.*;public class Exercise4_8 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter the number of studentsSystem.out.print("Enter the number of students: ");int numOfStudents = input.nextInt();System.out.print("Enter a student name: ");String student1 = input.next();System.out.print("Enter a student score: ");double score1 = input.nextDouble();for (int i = 0; i < numOfStudents - 1; i++) {System.out.print("Enter a student name: ");String student = input.next();System.out.print("Enter a student score: ");double score = input.nextDouble();if (score > score1) {student1 = student;score1 = score;}}System.out.println("Top student " +student1 + "'s score is " + score1);}}public class Exercise4_10 {public static void main(String[] args) {int count = 1;for (int i = 100; i <= 1000; i++)if (i % 5 == 0 && i % 6 == 0)System.out.print((count++ % 10 != 0) ? i + " ": i + "\n"); }}/** Find the smallest number such that n*n < 12000 */public class Exercise4_12 {// Main methodpublic static void main(String[] args) {int i = 1;while (i * i <= 12000 ) {i++;}System.out.println("This number is " + i);}}public class Exercise4_14 {public static void main(String[] args) {int count = 1;for (int i = '!'; i < '~'; i++) {System.out.print((count++ % 10 != 0) ? (char)i + " " :(char)i + "\n");}}public class Exercise4_16 {// Main methodpublic static void main(String args[]) {java.util.Scanner input = new java.util.Scanner(System.in);// Prompt the user to enter a positive integerSystem.out.print("Enter a positive integer: ");int number = input.nextInt();// Find all the smallest factors of the integerSystem.out.println("The factors for " + number + " is");int factor = 2;while (factor <= number) {if (number % factor == 0) {number = number / factor;System.out.println(factor);}else {factor++;}}}}public class Exercise4_20 {// Main methodpublic static void main(String[] args) {int count = 1; // Count the number of prime numbersint number = 2; // A number to be tested for primenessboolean isPrime = true; // If the current number is prime?System.out.println("The prime numbers from 2 to 1000 are \n");// Repeatedly test if a new number is primewhile (number <= 1000) {// Assume the number is primeisPrime = true;// Set isPrime to false, if the number is primefor (int divisor = 2; divisor <= number / 2; divisor++) {if (number % divisor == 0) { // If true, the number is primeisPrime = false;break; // Exit the for loop}}// Print the prime number and increase the countif (isPrime) {if (count%8 == 0) {// Print the number and advance to the new lineSystem.out.println(number);}elseSystem.out.print(number + " ");count++; // Increase the count}// Check if the next number is primenumber++;}}}import javax.swing.JOptionPane;public class Exercise4_22 {public static void main(String[] args) {int numOfYears;double loanAmount;java.util.Scanner input = new java.util.Scanner(System.in);// Enter loan amountSystem.out.print("Enter loan amount, for example 120000.95: ");loanAmount = input.nextDouble();// Enter number of yearsSystem.out.print("Enter number of years as an integer, \nfor example 5: ");numOfYears = input.nextInt();// Enter yearly interest rateSystem.out.print("Enter yearly interest rate, for example 8.25: ");。
JAVA全英试卷
1.Which of the following statements compiles OK?A. String #name = "Jane Doe";B. int $age = 24;C. Double _height = "123.5";D. double ~temp = 37.5;2.What are the extension names of Java source file and executable file?A. .java and .exeB. .jar and .classC. .java and .classD. .jar and .exe3.Given:10. class CertKiller {11. static void alpha() { /*more code here*/ }12. void beta() { /*more code here*/ }13. }Which statement is wrong?A. CertKiller.beta() is a valid invocation of beta()B. CertKiller.alpha() is a valid invocation of alpha()C. Method beta() can directly call method alpha()D. The method beta() can only be called via references to objects of CertKiller 4.Which method name does not follow the JavaBeans standard on Accessor/Mutator?A. getSizeB. setCustC. notAvailableD. isReadable5.Read the following class ClassA, which statement is correct after executing “new ClassA().getValue();”public class ClassA {public int getValue() {int value = 0;boolean setting = true;String title = "Hello";if (value || (setting && title == "Hello")) { return 1; }if (value == 1 & title.equals("Hello")) { return 2; }}}A. There is compilation error for ClassAB. It outputs 2C. It outputs 1D. Executes OK, but no output6.Given:public void testIfA() {if (testIfB("true")) {System.out.println("True");} else {System.out.println("Not true");}}public Boolean testIfB(String str) {return Boolean.valueOf(str);}What is the result when method testIfA is invoked?A. TrueB. Not trueC. An exception is thrown at runtimeD. Compilation fails7.Given:public class Pass {public static void main(String[] args) {int x = 5;Pass p = new Pass();p.doStuff(x);System.out.print(" main x = " + x);}void doStuff(int x) {System.out.print("doStuff x = " + x++);}}What is the result?A. doStuff x = 6 main x = 6B. doStuff x = 5 main x = 5C. doStuff x = 5 main x = 6D. doStuff x = 6 main x = 5 8.Given:String a = "str";String b = new String("str");String c = "str";System.out.print(a == b);System.out.print(a == c);What is the result?A. truefalseB. truetrueC. falsetrueD. falsefalse9.Given:33. try {34. // smoe code here35. } catch (NullPointerException el) {36. System.out.print("a");37. } catch (RuntimeException el) {38. System.out.print("b");39. } finally {40. System.out.print("c");41. }What is the result if NullPointerException occurs on line 34?A. acB. abcC. cD. No output10.Which of the following statements is correct about Java package?A. If there is no package statement used, the current class will not be in any package.B. Package is a way to manage source code, each package contains several “.java” files.C. Using one “import” statement can include the classes from one or more packages.D. A package can contain sub-packages.11.Given:1. public class Target {2. private int i = 0;3. public int addOne() {4. return ++i;5. }6. }And:1. public class Client {2. public static void main(String[] args) {3. System.out.println(new Target().addOne());4. }5. }Which change can you make to Target without affecting Client?A. Line 4 of class Target can be changed to return i++;B. Line 2 of class Target can be changed to private int i = 1;C. Line 3 of class Target can be changed to private int addOne() {D. Line 2 of class Target can be changed to private Integer i = 0;12.Given:public abstract class Shape {int x;int y;public abstract void draw();public void setAnchor(int x, int y){this.x = x;this.y = y;}}And a class Circle that extends and fully implements the Shape class. Which is correct?A. Shape s = new Shape();s.setAnchor(10, 10);s.draw();B. Circle c = new Shape();c.setAncohor(10, 10);c.draw();C. Shape s = new Circle();s.setAnchor(10, 10);s.draw();D. Shape s = new Circle();s.Shape.setAnchor(10, 10);s.shape.draw();13.In Java event handling model, which object responses to and handles events?A. event source objectB. listener objectC. event objectD. GUI component object14.Given:public static void main(String[] args) {System.out.print(method2(1, method2(2, 3, 4)));}public int method2(int x1, int x2) {return x1 + x2;}public float method2(int x1, int x2, int x3) {return x1 + x2 + x3;}What is the result?A. Compilation failsB. 0C. 10D. 915.Given:public class Test {public Test() {System.out.print("test ");}public Test(String val) {this();System.out.print("test with " + val);}public static void main(String[] args) {Test test = new Test("wow");}}What is the result?A. testB. test test with wowC. test with wowD. Compilation fails16.Given:public class ItemTest {private final int id;public ItemTest(int id) { this.id = id; }public void updateId(int newId) { id = newId; }public static void main(String[] args) {ItemTest fa = new ItemTest(42);fa.updateId(69);System.out.println(fa.id);}}What is the result?A. Compilation failsB. An exception is thrown at runtimeC. A new Item object is created with the preferred value in the id attributeD. The attribute id in the Item object remains unchanged17.Method m() is defined as below in a parent class, which method in the sub-classes overrides the method m()?protected double m() { return 1.23; }A. protect int m() { return 1; }B. public double m() { return 1.23; }C. protected double m(double d) { return 1.23; }D. private double m() { return 1.23; }18.Given:1. public class abc {2. int abc = 1;3. void abc(int abc) {4. System.out.print(abc);5. }6. public static void main(String[] args) {7. new abc().abc(new abc().abc);8. }9. }Which option is correct?A. Compilation fails only at line 2, 3B. Compilation fails only at line 7C. Compilation fails at line 1, 2, 3, 4D. The program runs and outputs 1 19.Which declaration is correct?A. abstract final class Hl { }B. abstract private move() { }C. protected private number;D. public abstract class Car { }20.Given:public class Hello {String title;int value;public Hello() {title += "World";}public Hello(int value) {this.value = value;title = "Hello";Hello();}}And:Hello c = new Hello(5);System.out.println(c.title);What is the result?A. HelloB. An exception is thrown at runtimeC. Hello WorldD. Compilation fails21.Given:public abstract interface Frobnicate {public void twiddle(String s);}Which is a correct class?A. public abstract class Frob implements Frobnicate {public abstract void twiddle(String s) { }}B. public abstract class Frob implements Frobnicate { }C. public class Frob extends Frobnicate {public void twiddle(Integer i) { }}D. public class Frob implements Frobnicate {public void twiddle(Integer i) { }}22.Which statement is true about has-a and is-a relationships?A. Inheritance represents an is-a relationship.B. Inheritance represents a has-a relationship.C. Interfaces must be use when creating a has-a relationship.D. Instance variables must be used when creating an is-a relationship.23.Which option has syntax error?class Animal { … }class Dog extends Animal { … }class Cat extends Animal { … }A. Animal animal = new Dog();B. Cat cat = (Cat) new Animal();C. Dog dog = (Dog) new Cat();D. Cat cat = new Cat();24.Assume that class A is a sub-class of class B, which of the following figures illustrates their relationship?A.B.C.D.25.Given:public class Plant {private String name;public Plant(String name) { = name }public String getName() { return name; }}public class Tree extends Plant {public void growFruit() {}public void dropLeaves() {}}Which statement is true?A. The code will compile without changes.B. The code will compile if the following code is added to the Plant class:public Plant() { this("fern"); }C. The code will compile if the following code is added to the Plant classpublic Plant(){Plant("fern");}D. The code will compile if the following code is added to the Tree class:public Tree() { Plant(); }26.Which of the following statement is correct about exception handling?A. Exception is an error occurred in runtime, so it should be avoided by debugging.B. Exception is described by the form of objects, their classes are organized by a single-root inheritance hierarchy (级联结构).C. There is no exception any more after executing a try-catch-finally structure.D. In Java, all exceptions should be caught and handled in runtime.27.What are the two major parts of an object?A. property and behaviorB. identity and contentC. inheritance and polymorphismD. message and encapsulation28.Which is the correct output according to the program given bellow?public static void main(String[] args) {Scanner scanner = new Scanner("this is one that is two");eDelimiter(" is"); // there is a space before "is"while (scanner.hasNext()) {System.out.print(scanner.next());}}A. this one that twoB. th one that twoC. thone that twoD. this is one that is two 29.Which fragment can not correctly create and initialize an int array?A. int[] a = {1, 2};B. int[] a; a = new int[2]; a[0] = 1; a[1] = 2;C. int[] a = new int[2]{1, 2};D. int[] a = new int[]{1, 2};30.What is the output of the following program?String s1 = "Java";String s2 = new String("Java");System.out.println((s1 == s2) + "," + (s1.equals(s2)));A. true,trueB. true,falseC. false,trueD. false,false1.(6 points)public class Bootchy {int bootch;String snootch;public Bootchy() {this("snootchy");System.out.print("first ");}public Bootchy(String snootch) {this(420, "snootchy");System.out.print("second ");}public Bootchy(int bootch, String snootch) {this.bootch = bootch;this.snootch = snootch;System.out.print("third ");}public static void main(String[] args) {Bootchy b = new Bootchy();System.out.print(b.snootch + " " + b.bootch);}}third second first snootchy4202.(6 points)public class TestJava {class A {public A(int v1, int v2) {this.v1 = v1; this.v2 = v2;}int v1; int v2;}void m1(A a1, A a2) {A t; t = a1; a1 = a2; a2=t;}void m2(A a1, A a2) {A t = new A(a1.v1, a1.v2);a1 = new A(a2.v1, a2.v2);a2 = new A(t.v1, t.v2);}void m3(A a1, A a2) {A t = a1;a1.v1 = a2.v1; a1.v2 = a2.v2;a2.v1 = t.v1; a2.v2 = t.v2;}public static void main(String[] args) {TestJava tj = new TestJava();A a1 = tj.new A(0, 2);A a2 = tj.new A(1, 3);tj.m1(a1, a2);System.out.println(a1.v1+ " " + a2.v2 + " ");tj.m2(a1, a2);System.out.println(a1.v1+ " " + a2.v2 + " ");tj.m3(a1, a2);System.out.println(a1.v1+ " " + a2.v2 + " ");} 0 3} 0 31 3Given:interface Repeater {/*** Repeat the char `c' n times to construct a String.* @param c the character to be repeated* @param n the times of repeat* @return a string containing all the `c'*/String repeat(char c, int n);}public static void main(String[] args) {Repeater arrayRepeater = new ArrayRepeater(); //(1)Repeater stringRepeater = new StringRepeater(); //(2)Repeater stringBufferRepeater = //(3)Repeater r = //(4)long startTime = System.nanoTime();for (int i = 0; i < 1000; i++) {r.repeat('s', 10000);}long endTime = System.nanoTime();long duration = endTime - startTime;System.out.println(duration);}1. Complete the definition of class ArrayRepeater which appears at //(1) to implement the Repeater by constructing the string using new String(char[]).2. Complete the definition of class StringRepeater which appears at //(2) to implement the Repeater using string concatenation (use + to join strings).3. Complete the definition of strigBufferRepeater at //(3) by defining an anonymous class implementing Repeater (i.e. new Repeater(){ ... }), using StringBuffer to construct the required string.4. The code below //(4) is designed to test the performance of Repeater r. By assigning different implementation of Repeater to r, the code can output the consumed time (duration). Answer the question: arrayRepeater, stringRepeater, stringBufferRepeater, which consumes the longest time?---------------------------------------------------------------------------(1)class ArrayRepeater implements Repeater{public String repeat(char c ,int n){char[] arr = new char[n];for(int i=0;i<n;i++){arr[i]='c';}String s = new String(arr);return s;}}(2)class StringRepeater implements Repeater {public String repeat(char c,int n){String s ="";for(int i=0;i<n;i++){s=s+'c';}return s;}}(3)new Repeater(){public String repeat(char c,int n){StringBuffer bf = new StringBuffer();for(int i=0;i<n;i++){bf.append('c');}return bf.toString();}};(4) arrayRepeaterusing the knowledge of interface and polymorphism. (12 points)public class Test {public static void main(String[] args) {Object[] shapes = { new Circle(5.0), //(3)new Rectangle(5.0, 4.5), //(4)new Circle(3.5) }; //(5)System.out.println("Total Area: " + sumArea(shapes));}public static double sumArea(Object[] shapes) {double sum = 0;for(int i = 0; i < shapes.length; i++) {if (shapes[i] instanceof CalcArea) { //(1)sum += ((CalcArea) shapes[i]).getArea(); //(2)}}return sum;} }The interface CalcArea in comment //(1) and //(2) is undefined; the class Circle and Rectangle in comment //(3), //(4) and //(5) are undefined either. Please define: 1.interface CalcArea2.class Circle3.class Rectangleinterface CalcArea{double getArea();}class Circle implements CalcArea{private double radius;public Circle(double radius){this.radius = radius;}public double getArea(){return Math.PI*radius*radius;}}class Rectangle implements CalcArea{private double width,height;public Rectangle(double width,double heigth){this.width = width;this.height = height;}public double getArea(){return width*height;}}。
java英文笔试题
1.Which of the following lines will compile without warning or error.答案(5)1) float f=1.3;2) char c="a";3) byte b=257;4) boolean b=null;5) int i=10;2. What will happen if you try to compile and run the following codepublic class MyClass {public static void main(String arguments[]) {amethod(arguments);}public void amethod(String[] arguments) {System.out.println(arguments);System.out.println(arguments[1]);}}答案(1)1) error Can't make static reference to void amethod.2) error method main not correct3) error array must include parameter4) amethod must be declared with String3. Which of the following will compile without error答案(23)1) import java.awt.*;package Mypackage;class Myclass {}2) package MyPackage;import java.awt.*;class MyClass{}3) /*This is a comment */package MyPackage;import java.awt.*;class MyClass{}4. What will be printed out if this code is run with the following command line? java myprog good morningpublic class myprog{public static void main(String argv[]){System.out.println(argv[2]);}}答案(4)1) myprog2) good3) morning4) Exception raised:"ng.ArrayIndexOutOfBoundsException: 2"5. What will happen when you compile and run the following code? public class MyClass{static int i;public static void main(String argv[]){System.out.println(i);}}答案(4)1) Error Variable i may not have been initialized2) null3) 14) 06. What will happen if you try to compile and run the following code? public class Q {public static void main(String argv[]){int anar[]=new int[]{1,2,3};System.out.println(anar[1]);}}答案(3)1) 12) Error anar is referenced before it is initialized3) 24) Error: size of array must be defined7. What will happen if you try to compile and run the following code? public class Q {public static void main(String argv[]){int anar[]=new int[5];System.out.println(anar[0]);}}答案(3)1) Error: anar is referenced before it is initialized2) null3) 04) 58. What will be the result of attempting to compile and run the following code?答案(3)abstract class MineBase {abstract void amethod();static int i;}public class Mine extends MineBase {public static void main(String argv[]){int[] ar=new int[5];for(i=0;i < ar.length;i++)System.out.println(ar[i]);}}1) a sequence of 5 0's will be printed2) Error: ar is used before it is initialized3) Error Mine must be declared abstract4) IndexOutOfBoundes Error9. What will be printed out if you attempt to compile and run the following code ? int i=1;switch (i) {case 0:System.out.println("zero");break;case 1:System.out.println("one");case 2:System.out.println("two");default:System.out.println("default");}答案(3)1) one2) one, default3) one, two, default4) default10. Which of the following lines of code will compile without error答案(23)1) int i=0;if(i) {System.out.println("Hello");}2) boolean b=true;boolean b2=true;if(b==b2) {System.out.println("So true");}3) int i=1;int j=2;if(i==1|| j==2)System.out.println("OK");4) int i=1;int j=2;if(i==1 &| j==2)System.out.println("OK");11. What will be output if you try to compile and run the following code, but there is no file called Hello.txt in the current directory?.import java.io.*;public class Mine{public static void main(String argv[]){Mine m=new Mine();System.out.println(m.amethod());}public int amethod(){try{FileInputStream dis=new FileInputStream("Hello.txt");}catch (FileNotFoundException fne){System.out.println("No such file found");return -1;}catch(IOException ioe){}finally{System.out.println("Doing finally");}return 0;}}答案(3)1) No such file found2 No such file found ,-13) No such file found, Doing finally, -14) 012.Which of the following statements are true?答案(1)1) Methods cannot be overriden to be more private2) static methods cannot be overloaded3) private methods cannot be overloaded4) An overloaded method cannot throw exceptions not checked in the base class13.What will happen if you attempt to compile and run the following code?答案(3)class Base {}class Sub extends Base {}class Sub2 extends Base {}public class CEx{public static void main(String argv[]){Base b=new Base();Sub s=(Sub) b;}}1) Compile and run without error2) Compile time Exception3) Runtime Exception14.Which of the following statements are true?答案(123)1) System.out.println( -1 >>> 2);will output a result larger than 102) System.out.println( -1 >>> 2); will output a positive number3) System.out.println( 2 >> 1); will output the number 14) System.out.println( 1 <<< 2); will output the number 415.What will happen when you attempt to compile and run the following code? public class Tux extends Thread{static String sName = "vandeleur";public static void main(String argv[]){Tux t = new Tux();t.piggy(sName);System.out.println(sName);}public void piggy(String sName){sName = sName + " wiggy";start();}public void run(){for(int i=0;i < 4; i++){sName = sName + " " + i;}}}答案(4)1) Compile time error2) Compilation and output of "vandeleur wiggy"3) Compilation and output of "vandeleur wiggy 0 1 2 3"4) Compilation and output of either "vandeleur", "vandeleur 0", "vandeleur 0 1" "vandaleur 0 1 2" or "vandaleur 0 1 2 3"16.What will be displayed when you attempt to compile and run the following code//Code startimport java.awt.*;public class Butt extends Frame{public static void main(String argv[]){Butt MyBut=new Butt();}Butt(){Button HelloBut=new Button("Hello");Button ByeBut=new Button("Bye");add(HelloBut);add(ByeBut);setSize(300,300);setVisible(true);}}//Code end答案(3)1) Two buttons side by side occupying all of the frame, Hello on the left and Bye on the right2) One button occupying the entire frame saying Hello3) One button occupying the entire frame saying Bye4) Two buttons at the top of the frame one saying Hello the other saying Bye17.What will be output by the following code?public class MyFor{public static void main(String argv[]){int i;int j;outer:for (i=1;i <3;i++)inner:for(j=1; j<3; j++) {if (j==2)continue outer;System.out.println("Value for i=" + i + " Value for j=" +j); }}}答案(12)1) Value for i=1 Value for j=12) Value for i=2 Value for j=13) Value for i=2 Value for j=24) Value for i=3 Value for j=118.Which statement is true of the following code?public class Agg{public static void main(String argv[]){Agg a = new Agg();a.go();}public void go(){DSRoss ds1 = new DSRoss("one");ds1.start();}}class DSRoss extends Thread{private String sTname="";DSRoss(String s){sTname = s;}public void run(){notwait();System.out.println("finished");}public void notwait(){while(true){try{System.out.println("waiting");}catch(InterruptedException ie){}System.out.println(sTname);notifyAll();}}}答案(4)1) It will cause a compile time error2) Compilation and output of "waiting"3) Compilation and output of "waiting" followed by "finished"4) Runtime error, an exception will be thrown19.Which of the following methods can be legally inserted in place of the comment //Method Here ?class Base{public void amethod(int i) { }}public class Scope extends Base{public static void main(String argv[]){}//Method Here}答案(23)1) void amethod(int i) throws Exception {}2) void amethod(long i)throws Exception {}3) void amethod(long i){}4) public void amethod(int i) throws Exception {}20.You have created a simple Frame and overridden the paint method as followspublic void paint(Graphics g){g.drawString("Dolly",50,10);}What will be the result when you attempt to compile and run the program?答案(3)1) The string "Dolly" will be displayed at the centre of the frame2) An error at compilation complaining at the signature of the paint method3) The lower part of the word Dolly will be seen at the top of the frame, with the top hidden.4) The string "Dolly" will be shown at the bottom of the frame.21.What will be the result when you attempt to compile this program?public class Rand{public static void main(String argv[]){iRand = Math.random();System.out.println(iRand);}}答案(1)1) Compile time error referring to a cast problem2) A random number between 1 and 103) A random number between 0 and 14) A compile time error about random being an unrecognised method22.Given the following codeimport java.io.*;public class Th{public static void main(String argv[]){Th t = new Th();t.amethod();}public void amethod(){try{ioCall();}catch(IOException ioe){}}}What code would be most likely for the body of the ioCall method答案(1)1) public void ioCall ()throws IOException{DataInputStream din = new DataInputStream(System.in);din.readChar();}2) public void ioCall ()throw IOException{DataInputStream din = new DataInputStream(System.in);din.readChar();}3) public void ioCall (){DataInputStream din = new DataInputStream(System.in);din.readChar();}4) public void ioCall throws IOException(){DataInputStream din = new DataInputStream(System.in);din.readChar();}23.What will happen when you compile and run the following code?public class Scope{private int i;public static void main(String argv[]){Scope s = new Scope();s.amethod();}//End of mainpublic static void amethod(){System.out.println(i);}//end of amethod}//End of class答案(3)1) A value of 0 will be printed out2) Nothing will be printed out3) A compile time error4) A compile time error complaining of the scope of the variable i24.You want to lay out a set of buttons horizontally but with more space between the first button and the rest. You are going to use the GridBagLayout manager to control the way the buttons are set out. How will you modify the way the GridBagLayout acts in order to change the spacing around the first button?答案(2)1) Create an instance of the GridBagConstraints class, call the weightx() method and then pass the GridBagConstraints instance with the component to the setConstraints method of the GridBagLayout class.2) Create an instance of the GridBagConstraints class, set the weightx field and then pass the GridBagConstraints instance with the component to the setConstraints method of the GridBagLayout class.3) Create an instance of the GridBagLayout class, set the weightx field and then call the setConstraints method of the GridBagLayoutClass with the component as a parameter.4) Create an instance of the GridBagLayout class, call the setWeightx() method and then pass the GridBagConstraints instance with the component to the setConstraints method of the GridBagLayout class.25.Which of the following can you perform using the File class?答案(23)1) Change the current directory2) Return the name of the parent directory3) Delete a file4) Find if a file contains text or binary information26.Which statement is true of the following code?public class Rpcraven{public static void main(String argv[]){Pmcraven pm1 = new Pmcraven("One");pm1.run();Pmcraven pm2 = new Pmcraven("Two");pm2.run();}}class Pmcraven extends Thread{private String sTname="";Pmcraven(String s){sTname = s;}public void run(){for(int i =0; i < 2 ; i++){try{sleep(1000);}catch(InterruptedException e){}yield();System.out.println(sTname);}}}答案(2)1) Compile time error, class Rpcraven does not import ng.Thread2) Output of One One Two Two3) Output of One Two One Two4) Compilation but no output at runtime27.You are concerned that your program may attempt to use more memory than is available. To avoid this situation you want to ensure that the Java Virtual Machine will run its garbage collection just before you start a complex routine. What can you do to be certain that garbage collection will run when you want .答案(1)1) You cannot be certain when garbage collection will run2) Use the Runtime.gc() method to force garbage collection3) Ensure that all the variables you require to be garbage collected are set to null4) Use the System.gc() method to force garbage collection28、Which statements about the garbage collection are true?答案(2)1. The program developer must create a thread to be responsible for free the memory.2. The garbage collection will check for and free memory no longer needed.3. The garbage collection allow the program developer to explicity and immediately free the memory.4. The garbage collection can free the memory used java object at expect time.29.You have these files in the same directory. What will happen when you attempt to compile and run Class1.java if you have not already compiled Base.java//Base.javapackage Base;class Base{protected void amethod(){System.out.println("amethod");}//End of amethod}//End of class basepackage Class1;//Class1.javapublic class Class1 extends Base{public static void main(String argv[]){Base b = new Base();b.amethod();}//End of main}//End of Class1答案(4)1) Compile Error: Methods in Base not found2) Compile Error: Unable to access protected method in base class3) Compilation followed by the output "amethod"4)Compile error: Superclass Class1.Base of class Class1.Class1 not found30.What will happen when you attempt to compile and run the following codeclass Base{private void amethod(int iBase){System.out.println("Base.amethod");}}class Over extends Base{public static void main(String argv[]){Over o = new Over();int iBase=0;o.amethod(iBase);}public void amethod(int iOver){System.out.println("Over.amethod");}}答案(4)1) Compile time error complaining that Base.amethod is private2) Runtime error complaining that Base.amethod is private3) Output of "Base.amethod"4) Output of "Over.amethod"一个袋子中有100个黑球,100个白球,每次从中取出两个球,然后放回一个球,如果取出两个球颜色相同,则放入一个黑球,如果取出一百一黑,则放入一个白球,请问到最后袋中剩下的球的颜色:1)黑球2)白球3)不一定。
Java英文题
Java英文题Multiple-Choice1.The name of a Java source file(a)has no restrictions(b)must be the same as the class it defines, ignoring case(c)must use the extension .class(d)must be the same as the class it defines, respecting case2.Which of the following statements is (are) true about the use of an asterisk (*) in a Javaimport statement?Ⅰ.It does not incur run-time overhead.Ⅱ.It can be used to import multiple packages with a sing le statement.Ⅲ.It can be used to import multiple classes with a single statement(a)I, II, and III(b)I and III only(c)I only(d)III only3.What is the name of the wrapper class for the type int?(a) INT (b) integer (c) Integer (d) Int4. A difference between the methods print and println of the classjava.io.PrintWriter is that(a) println inserts a new line at the beginning of its output, but print does not(b) print inserts a new line at the beginning of its output, but println does not(c) print appends a new line to the end of its output, butprintln does not(d) println appends a new line to the end of its output, but print does not5. Consider the following Java program segment.int x = 5;int y = 2;System.out.println(x + "1" + y);Which of the following statements is true about the program segment?(a)The output caused by the code will be 512.(b)The output caused by the code will be 5 1 2.(c)The output caused by the code will be 8.(d)The code will cause a compilation error.6. All Java exception classes are derived from the class(a) ng.RuntimeException(b) ng.Throwable(c) ng.Error(d) java.io.IOException7. What is the right way to handle abnormalities in input on Java?(a) By writing while loops to guard against bad input(b) By handling these problems by providing exception handlers(c) By using the class FileFilter which gracefully filters out bad input data(d) By always specifying the throws clause in every method header where file I/O isperformed8. Which of the following patterns of characters opens a Javadoc comment block?(a) /* (b) **/ (c) /** (d) //9. According to the Java code conventions, files that contain Java source code have the suffix_____, and compiled bytecode files have the suffix _____.(a) .class, .java (b) .class, .javac(c) .java, .class (d) .javac, .class10. As an aid in debugging a program in Java, print statements may be used to display whichof the following types of information?I.The names of methods being calledII.The values of the parameters of a methodⅢ. The values of the instance variables of a class(a) I and II only (b) I and III only(c) II and III only (d) I, II, and III1.In a UML class diagram's representation of a class, the top, middle, and lower rectangularcompartments respectively describe the _____ of the class.(a) name, attributes, and methods (b) name, methods, and constants(c) attributes, methods, and name (d) attributes, methods, and constants2. UML class diagrams can describe which of the following?I.The internal structure of classesⅡ. Relationships between classes(a) I and II (b) II only (c) None (d) I only3. Consider the following UML class diagram.According to the diagram, instances of the class named _____ have references to instances of the class named _____.(a) B, A (b) A, C (c) B, C (d) A, B4. Which of the following is true about association and aggregation in UML class diagrams?(a) Association is the opposite of aggregation.(b) Aggregation is a special form of association.(c) Association is a special form of aggregation.(d) Association and aggregation have no meaningful relationship.5. A binary association is said to exist between two classes when(a) one class belongs to the same package as the other class(b) an object of one class requires an object of the other class(c) an object of one class is instantiated in the same method as an object of the other class(d) one class is a subtype of the other class6. Consider the following UML class diagram.According to the diagram, which of the following statements is (are) true?I.ClassB is a specialization of ClassA.II.ClassA is a generalization of ClassC.Ⅲ. ClassC is involved in a self-containment loop.(a) II and III only (b) I and II only(c) I, II, and III (d) I and III only7. A collection typically models a _____ relationship.(a) one-to-one (b) many-to-many(c) zero-to-one (d) one-to-many8. Consider the following UML class diagram.Which of the following is (are) true about the system described by the diagram?I.An instance of Picture can contain a collection of instances of the class Shape. Ⅱ. An instance of Shape can contain a collection of instances of the class Picture.(a) II only (b) None (c) I only (d) I and II9. When using noun-phrase analysis to model a software system, which of the followingshould typically be eliminated from the list of potential classes?I.References to the software system itselfII.Nouns that imply roles between objectsⅢ. Synonyms to other nouns in the list(a) II and III only (b) I and III only(c) III only (d) I, II, and III10. The static model of a software system typically includes which of the following?I.Attributes of classesII.Actions that occur between classesⅢ. Structural relationships between classes(a) I and III only (b) II and III only(c) I, II, and III (d) I and II only1.The term class variable is a synonym for(a) a private data field(b) a static data field(c) a read-only variable(d) an instance variable2. Consider the following Java program segment.import java.io.*;public class Test {public Test( ) {System.out.println("default");}public Test( int i ) {System.out.println("non-default");}public static void main(String[] args) {Test t = new Test(2);}}Which of the following will be output during execution of the program segment?(a)The line of text "default"(b)The line of text "default" followed by the line of text "non-default"(c)The line of text "non-default"(d)The line of text "non-default" followed by the line of text "default"3. Which of the following categorizations can be applied to both the data fields and themethods in a Java class?(a) native and non-native(b) default and non-default(c) static and non-static(d) abstract and non-abstract4. Which of the following statements about class variables in Java is not true?(a) Class variables require the modifier static in the declarations.(b) All objects have their own copy of the class variable defined in the instantiated class.(c) Non-static methods in a class can access the class variable defined in the same class.(d) Class variables do not need the reference to the object of the instantiated class toaccess them.5. If a class contains a constructor, that constructor will be invoked(a) each time an object of that class goes out of scope(b) each time an object of that class is instantiated(c) once the first time an object of that class is instantiated(d) once at the beginning of any program that uses that class6. Which of the following statements about constructors in Java is true?(a) A class can define more than one constructor.(b) A constructor must be defined as public.(c) A constructor must be defined as static.(d) A class must define at least one constructor.7. If the method int sum(int a, int b) is defined in a Java class C, which of the following methods cannot coexist as a different method in class C?(a) int sum(int x, float y)(b) int sum(float a, int b)(c) int sum(int x, int y)(d) float sum(int x, float y)8. Consider the following Java class definitions.public class Object1 {protected String d(){return "Hi";}}public class Object2 extends Object1 {protected String d(){return super.d();}}Which of the following statements is (are) true regarding the definitions?I.Class Object2 inherits from class Object1.II.Class Object2 overrides method d.Ⅲ. Method d returns equivalent results when executed from either class.(a) I, II, and III (b) I and III only(c) III only (d) I and II only9. When a subclass defines an instance method with the same return type and signature asa method in its parent, the parent's method is said to be(a) private (b) hidden (c) overloaded (d) overridden10. Which is a Java access modifier used to designate that a particular data field will not beinherited by a subclass?(a) final (b) protected (c) private(d) default1. Consider the following Java program segment.String[] str = {"Three","Two","One"};for (int i = 0; i < str.length; ++i) {System.out.println(str[i]+"/");}What will be output upon execution of the program segment?(a) Three/Two/One/ (b) Three,Two,One(c) One,Two,Three (d) One/Two/Three/2. Consider the following Java program segment.int[] arr;arr = new int[3];arr[2]=19;arr[1]=17;arr[0]=15;Which of the following Java statements is syntactically correct and semantically identical to the program segment?(a)int[] arr= {15, 17, 19};(b)int[3] arr = {15, 17, 19};(c)int arr = {15, 17, 19};(d)int arr[3]= {15, 17, 19};3. Regarding the following declaration, what is the index of the element containing 45?int[] numbers = {-1, 45, 6, 132};(a) 0 (b) 1(c) 45 (d) 24.Legal Java statements to initialize an array reference include which of the following? I.int[] aobj = {0, 1, 2};II.int[4] aobj = {0, 1, 2};Ⅲ. int[] aobj = new int[3];(a) I and II only (b) I only(c) III only (d) I and III only5. If the length of a particular array is the value of LIMIT, whatis the index of the last itemin that array?(a) LIMIT (b) LIMIT – 1 (c) LIMIT / 2 (d) 06. Consider the Java program below.public class Arr{public static void main(String[] args) {int[] a = {1, 2, 3};System.out.println(a[1]);System.out.println(a[3]);}}Which of the following is true about the result of executing the program?(a)The number 1 is printed and there is no abnormal termination.(b)The number 3 is printed and a run-time exception terminates execution.(c)The number 2 is printed and there is no abnormal termination.(d)The number 2 is printed and a run-time exception terminates execution.7. In which of the following ways can items be added to a collection implemented byjava.util.ArrayList?I.Items can be inserted at the beginning of the collection.II.Items can be inserted between two existing items in the collection.Ⅲ. Items can be appended to the end of the collection.(a) I only (b) I, II, and III (c) I and III only (d) III only8. An object that contains methods that traverse a collectionlinearly from start to finish isknown as a(n)(a) int (b) iterator(c) loop (d) Exception9. Consider the following method call, where c is an instance of the classjava.util.ArrayList.c.size();This method call returns the number of(a)times that the method c.add has been called(b)bytes used by c(c)ArrayList objects that have been instantiated(d)elements in the ArrayList represented by c10. The class java.util.ArrayList implements a collection that(a) can grow to accommodate new items(b) can only store primitive variables such as int or Boolean(c) can only store instances of the class ng.String(d) cannot be accessed using an integer index1. The subclass of an abstract class must(a) be abstract(b) be abstract and implement all of the parent's abstract methods(c) be abstract or implement all of the parent's abstract methods(d) implement all of the parent's abstract methods2. Which of the following statements is (are) true about any abstract method in Java?I.It contains no definition.Ⅱ. It cannot be declared public.(a) I and II (b) I only (c) None (d) II only3. Consider the following Java program fragment.public void drive(Vehicle v) {...}...drive(obj);The method call drive(obj) is valid if obj is which of the following?I. A descendent of class VehicleII.An ancestor of class VehicleⅢ. An object of class Vehicle(a) I and III only (b) I, II, and III(c) III only (d) II and III only4. Which of the following statements is (are) true in Java?I.An abstract class may contain data fields.Ⅱ. Interfaces may contain data fields.(a)I and II (b) I only (c) None (d) II only5. Which of the following statements is (are) true about interfaces in Java?I.Interfaces can extend other interfaces.Ⅱ. Interfaces can contain data fields.(a) I only (b) None (c) II only (d) I and II6. Which of the following statements is (are) true in Java?I.All of the methods in an abstract class must be abstract.Ⅱ. All of the methods in an interface must be abstract.(a) None (b) I only (c) II only (d) I and II7. Which of the following statements is (are) true about all data fields in an interface in Java?I.They are implicitly public.II.They are implicitly final.Ⅲ. The y are implicitly static.(a) I and II only (b) I, II, and III(c) II and III only (d) II only8. A design pattern is typically used to(a) reduce the number of classes in the design of a program(b) ensure that code executes at optimal speed during runtime(c) allow the use of object-orientated concepts in a language that is not object-oriented(d) describe a practical solution to a common design problem9. The constructor of a class that adheres to the Singleton design pattern must have _____visibility.(a) public (b) protected (c) package (d) private10. The Strategy design pattern is likely to be useful when implementing which of thefollowing?I.An application that offers several alternate sorting algorithmsⅡ. A simple class to store the address of an organization of which only one instance can be instantiated(a) II only (b) I only (c) None (d) I and II1.Consider the following Java program segment.PrintWriter fileOut = new PrintWriter(new FileWriter("output.txt"));If the file output.txt already exists, which of the following events will occur when the program segment is executed?(a)The existing contents of output.txt will be erased.(b) A FileAlreadyExists exception will be raised.(c)The existing contents of output.txt will be preserved.(d)A run-time error will be generated.2.The model part of the Model-View-Controller (MVC) paradigm embodies the(a)automatic mechanism by which the user interface is displayed and by which eventsare communicated between the view and the controller(b)way in which the abstract domain knowledge of an application is presented to theuser(c)abstract domain knowledge of an application(d)list of abstract classes in an application3.Which of the following is true regarding the controller part in the Model-View-Controller(MVC) paradigm?(a)The controller is the list of abstract classes in an application.(b)The controller is the way in which the abstract domain knowledge of an applicationis presented to the user.(c)The controller is the abstract domain knowledge of an application.(d)The controller is the automatic mechanism by which the user interface is displayedand by which events are communicated between the model and the view.4.In Java, the default layout manager for a JFrame component is(a) GridLayout (b) GridBagLayout(c) BorderLayout (d) FlowLayout5. The view part of the Model-View-Controller (MVC)paradigm is the(a) list of abstract classes in an application(b) automatic mechanism by which the user interface is displayed and by which eventsare communicated between the model and the controller(c) way in which the abstract domain knowledge of an application is presented to theuser(d) abstract domain knowledge of an application6. Which of the following is (are) true regarding event handling in Java?I.When a GUI component is created, the component automatically has the abilityto generate events during user interaction.Ⅱ. Each Listener object must be registered with the specific component object or objects for which the Listener object is to respond.(a) None (b) II only (c) I and II (d) I only7. Which of the following is a Java event that is generated when a JButton component ispressed? b(a) ActionEvent (b) ButtonEvent(c) ClickEvent (d) WindowEvent8. What is the signature of the method specified in the Java ListSelectionListenerinterface?(a) void valueChanged (ListSelectionEvent lse)(b) void ListSelectionListener (ListSelectionEvent lse)(c) void valueChanged (ListSelectionListener lsl)(d) void actionPerformed (ListSelectionEvent lse)9. The ActionEvent class and ActionListener interface are available in the ____package of Java.(a) java.event (b) javax.event(c) javax.swing.event (d) java.awt.event10. Which of the following is a Java event that is generated when the close button on aFrame component is pressed?(a) WindowEvent (b) ExitEvent(c) CloseEvent (d) DisposeEvent。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
一.Which 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 Sha pe { }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;二.which statement is true?A. An anonymous inner class may be declared as finalB. An anonymous inner class can be declared as privateC. An anonymous inner class can implement mutiple interfacesD. 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 encloing outer class构造一个静态的内部类对象需要构造包含它的外部类的对象三. Given: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他们都是public的,只要在外部import就行C. An instance of the inner class can only be constructed from within the outerclassD. From within the package bar, an instance of the inner class can be constructed with “new inner()”四.Exhibit(展览、陈列):1 public class enclosinggone{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 }}Which statement at line 7 constructs an instance of the inner class?A. InsideOne ei = eo.new InsideOne(); 写程序试出来B. Eo.InsideOne ei = eo.new InsideOne();C InsideOne ei = EnclosingOne.new InsideOne();D.EnclosingOne InsideOne ei = eo.new InsideOne();五.1)interface Foo{2)int k=0;3)}4) public class Test implements Foo{5)public static void main(String args[]){6)int i;7) Test test =new Test();8)i=test.k;9)i=Test.k;10)i=Foo.k;11)}12) }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.六.//point Xpublic class Foo{public static void main(String[] args){PrintWriter out=new PrintWriter(newjava.io.OutputStreamWriter(System.out),true);out.println("Hello");}}which statement at point X on line 1 allows this code to compile and run?在point X这个位置要填入什么代码才能使程序运行A.import java.io.PrintWriterB.include java.io.PrintWriterC.import java.io.OutputStreamWriterD.include java.io.OutputStreamWriterE.No statement is needed本来两个都要import,但是后者OutputStreamWriter指定了包结构java.io.OutputStreamWriter七.what is reserved words in java? 保留字而非关键字A. runB.defaultC. implementD. import八. which three are valid declaraction of a float?(float作为整数是可以的,其余几个都是double)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;九.Given:8.int index = 1;9.boolean[] test = new boolean[3]; (数组作为对象缺省初始化为false)10. boolean foo= test [index];What is the result?A. foo has the value of 0B. foo has the value of nullC. foo has the value of trueD. foo has the value of falseE. an exception is thrownF. the code will not compile十. Given: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 the command line invocation:Java TestWhat 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 compileG. the program throws an exception(此题题目出错了,重复定义了变量foo,如果没有重复的话,应选G,因为只传递了0-2三个数组元素,而题目中需要访问args [3],所以会抛出数组越界异常)十一.int index=1;int foo[]=new int[3];int bar=foo[index]; //bar=0int baz=bar+index; //baz=1what is the result?A. baz has a value of 0B. baz has value of 1C. baz has value of 2D. an exception is thrownE. the code will not compile十二.1)public class Foo{2)public static void main(String args[]){3)String s;4)System.out.println("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.十三. Which 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){}十四.You 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 qualified十五. Given: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.(子类覆盖父类方法的时候,不能比父类方法具有更严格的访问权限)十六. Click the exhibit button: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”.十七.1)class Super{2)public float getNum(){return 3.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){return 4.0d;}十八. Which declaration prevents creating a subclass of an outer class?A.static class FooBar{}B.pivate class Foobar{}C.abstract class FooBar{}D.final public class FooBar{}E.final abstract class FooBar{} 抽象类不能声明为final十九. byte[] array1,array2[]byte array3[][]byte[][] array4if each has been initialized, which statement will cause a compile error?A. array2 = array1;B. array2 = array3;C. array2 = array4;D. both A and BE. both A and CF. both B and C(一维数组和二维数组的区别)二十.class Super{public int i=0;public Super(String text){i=1;}}public class Sub extends Super{public Sub(String text){i=2;}public static void main(String args[]){Sub sub=new Sub("Hello");System.out.println(sub.i);}}what is the result?A. compile will failB. compile success and print "0"C. compile success and print "1"D. compile success and print "2"子类总要去调用父类的构造函数,有两种调用方式,自动调用(无参构造函数),主动调用带参构造函数。