JAVA试题英文版.doc

合集下载

JAVA试题英文版(答案)

JAVA试题英文版(答案)

一.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"子类总要去调用父类的构造函数,有两种调用方式,自动调用(无参构造函数),主动调用带参构造函数。

JAVA双语教学考试试B卷及答案.docx

JAVA双语教学考试试B卷及答案.docx

注意事项:请将各题答案按编号顺序填写到答题卷上,答在试卷上无效。

一、单选题(本题共40小题,每小题1分,共40分〉1. What is the return-type of the methods that implement the MouseListener interface?A. booleanB. BooleanC. voidD. Point 2. Select valid identifier of Java:A. %passwdB. 3d_gameC. SchargeD. this3・ Which declares an abstract method in an abstract Java class? IA. public abstract method();B. public abstract void method();C. public void abstract Method(};D. public abstract void method() {}4・ Which statement about listener is true?A ・ Most component unallow multiple listeners to be added ・B. If multiple listener be add to a single component, the event only affected one listener.C. Component don't allow multiple listeners to be add ・D ・ The listener mechanism allows you to call an addXxxxListener method as many times as is needed, specifying as many different listeners as your design require ・Which method you define as the starting point of new thread in a class from which new the thread can be excution? A. public void start() B ・ public void run()C. public void int()D. public static void main(String argsf]) 6. Which statement is correctly declare a variable a which is suitable for refering to an array of 50 string empty object?A. String [] aB. String aC. char a[][]D. String a[50]7. Which cannot be added to a Container?8. Which is the main() methocPs return of a application?0|PA. a MenuB. a ComponentC. a ContainerD. an AppletA. StringB. byteC. charD. voidWhich is corrected argument of main() method of application?A. String args B・ String ar[]C. Char args[][]D. StringBuffer arg fl Float s=new Float(0.9F);Float t=new Float(0.9F);Double u=new Double(0.9);Which expression s result is true?A. s==tB. s.equals(t)C. s==uD. t.equals(u)11. Which are not Java keyword?A. It must be anonymousB. It can not implement an interfaceC. It is only accessible in the enclosing classD ・ It can access any final variables in any enclosing scope ・17. What is written to the standard output given the following statement: System.out.println(4|7);Select the right answer: A.4B.5C.6D.718. A class design requires that a particular member variable must be accessible for direct access by any subclasses ofthis class ・ but otherwise not by classes which are not members of the same package ・ What should be done to achieve this?A ・ The variable should be marked publicB ・ The variable should be marked private C. The variable should be marked protectedD. The variable should have no special access modifier 19. main 方法是JavaApplication 稈•序执行的入口点,关于main 方法的方法头以下哪项是合法的()?A) public static void main ()B) public static void main ( String argsf]) C) public static int main (String [] arg ) D) public void main (String arg[]) 20.卜•面哪种注释方法能够支持javadoc 命令:A) /**...**/ B) /*...*/C) //D) /**...*/21. Java Application 源程序的主类是指包含有()方法的类。

英文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。

JAVA全英试卷

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;}}。

30道英文Java面试题附英文答案(1-15)

30道英文Java面试题附英文答案(1-15)

* Q1. How could Java classes direct program messages to the system console, but error messages, say to a 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);* 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.* Q3. Why would you use a synchronized block vs. synchronized method?A. Synchronized blocks place locks for shorter periods than synchronized methods.* Q4. Explain the usage of the keyword transient?A. This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).* Q5. How can you force garbage collection?A. You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.* Q6. How do you know if an explicit object casting is needed?A. If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:Object a; Customer b; b = (Customer) a;When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.* Q7. What's the difference between the methods sleep() and wait()A. The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.* Q8. Can you write a Java class that could be used both as an applet as well as an application?A. Yes. Add a main() method to the applet.* Q9. What's the difference between constructors and other methods?A. Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.* Q10. Can you call one constructor from another if a class has multiple constructorsA. Yes. Use this() syntax.* Q11. Explain the usage of Java packages.A. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.* Q12. If a class is located in a package, what do you need to change in the OS environment to be able to use it?A. You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:c:\>java com.xyz.hr.Employee* Q13. What's the difference between J2SDK 1.5 and J2SDK 5.0?A.There's no difference, Sun Microsystems just re-branded this version.* Q14. What would you use to compare two String variables - the operator == or the method equals()?A. I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.* Q15. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?A. Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.。

java面试题 英文

java面试题 英文

java面试题英文Java Interview QuestionsIntroduction:In recent years, Java has become one of the most popular programming languages worldwide. Its versatility and wide range of applications have made it a sought-after skill in the IT industry. As a result, job interviews often include a section dedicated to Java. In this article, we will explore some commonly asked Java interview questions and provide detailed explanations and solutions. Whether you are a seasoned developer or preparing for your first Java interview, this article will help you enhance your knowledge and boost your confidence.1. What is Java?Java is a high-level, object-oriented programming language developed by Sun Microsystems. It was designed to be platform-independent, which means Java programs can run on any operating system that has a Java Virtual Machine (JVM). Java consists of a compiler, runtime environment, and a vast library, making it a powerful tool for building a wide range of applications.2. Explain the difference between JDK, JRE, and JVM.JDK (Java Development Kit) is a software package that includes the necessary tools for developing, compiling, and running Java applications. It consists of the Java compiler, debugger, and other development tools.JRE (Java Runtime Environment) is a software package that contains the necessary components to run Java applications. It includes the JVM and a set of libraries required to execute Java programs.JVM (Java Virtual Machine) is a virtual machine that provides an execution environment for Java programs. It interprets the Java bytecode and translates it into machine code that can be executed by the underlying operating system.3. What is the difference between a class and an object?In object-oriented programming, a class is a blueprint or template for creating objects. It defines the properties and behaviors that an object will possess. An object, on the other hand, is an instance of a class. It represents a specific entity or concept and can interact with other objects.4. What are the features of Java?Java is known for its robustness, portability, and security. Some key features of Java include:- Object-oriented: Java follows the object-oriented programming paradigm, allowing developers to build modular and reusable code.- Platform-independent: Java programs can run on any platform that has a JVM, including Windows, Mac, and Linux.- Memory management: Java has automatic memory management through garbage collection, which helps in deallocating memory occupied by unused objects.- Exception handling: Java provides built-in mechanisms for handling exceptions, ensuring the smooth execution of programs.- Multi-threading: Java supports concurrent programming through multi-threading, allowing programs to perform multiple tasks simultaneously.5. Explain the concept of inheritance in Java.Inheritance is a fundamental concept in object-oriented programming, where a class inherits properties and behaviors from another class, known as the superclass or base class. The class that inherits these properties is called the subclass or derived class. In Java, inheritance allows code reuse, promotes modularity, and enables hierarchical classification of objects.There are several types of inheritance in Java, including single inheritance (where a class inherits from only one superclass) and multiple inheritance (where a class inherits from multiple superclasses using interfaces).6. What is the difference between method overloading and method overriding?Method overloading refers to the ability to have multiple methods with the same name but different parameters within a class. The methods can have different return types or different numbers and types of arguments. The compiler determines which method to call based on the arguments provided during the method call.Method overriding, on the other hand, occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The signature of the overridden method (name, return type, and parameters)must match exactly with that of the superclass. The overridden method in the subclass is called instead of the superclass's method when invoked.Conclusion:In this article, we have explored some common Java interview questions and provided detailed explanations and solutions. Understanding these concepts will not only help you ace your Java interview but also enhance your overall programming skills. Remember to practice coding and explore real-world scenarios to strengthen your understanding of Java. Good luck with your Java interviews!。

JAVA双语教学考试试A卷及答案.docx

JAVA双语教学考试试A卷及答案.docx

注意事项:请将各题答案按编号顺序填写到答题卷上,答在试卷上无效。

-、单项选择题(1~20每小题1分,21*30每小题2分,共40分)Which statement of assigning a long type variable to a hexadecimal value is correct? A. long number = 345L; B. long number = 0345; C. long number = 0345L; D. long number = 0x345L; Which layout manager is used when the frame is resized the buttons's position in the Frame might be changed? A. BorderLayout B. FlowLayout C. CardLayout D. GridLayout Which are not Java primitive types?A. shortB. BooleanC. byteD. float Given the following code:if (x>0) { System.out.println("first n); }else if (x>-3) { System.out.println(M second H); } else { System.out.println(Mthird H); }Which range of x value would print the string usecond 11?A. x > 0B. x > -3C. x <= -3D. x <= 0 & x > -37. Given the following code: public class Person{ int arr| | = new int| 10]; public static voidmain(String a| ]) {System.out.println(arr| 11);Which statement is correct?I2. Which are keywords in Java? A. Null B ・TRUEConsider the following code: Integer s = new Integer(9); Integer t = new Integer(9); Long u = new Long(9);Which test would return true? A. (s.equals(new Integer(9))C. sizeofB. (s.equals(9)) D. (s==t)D. implements0|Pg' 曲4. un I5.A. When compilation some error will occur.B・ It is correct when compilation but will cause error when running.C.The output is zero.D.The output is null.8.Short answer:The decimal value of i is 13, the octal i value is:A. 14B. 015C. 0x14D. 0129.A public member vairable called MAX_LENGTH which is int type, the value of thevariable remains constant value 100. Use a short statement to define the variable.A. public int MAX_LENGTH=100;B. final int MAX_LENGTH=100;C.final public int MAX_LENGTH=100;D. public final int MAX_LENGTH=100.10.Which correctly create an array of five empty Strings?A. String a [] = f "};B. String a [5];C. String [5] a;D.String [] a = new String[5]; for (int i = 0; i < 5; a[i++] = null);11 .Given the following method body:{if (sometest()) {unsafe();}else {safe();}}The method "unsafe” might throw an IOException (which is not a subclass ofRunTimeException). Which correctly completes the method of declaration when added at line one?A. public void methodName() throws ExceptionB・ public void methodname()C.public void methodName() throw IOExceptionD.public IOException methodName()12.What would be the result of attempting to compile and run the following piece of code?public class Test { static int x;public static void main(String args[J){System.out.println(H Value is 11 + x);A.The output n Value is 0H is printed.B.An object of type NullPointerException is thrown.C.A "possible reference before assignment11 compiler error occurs.D.An object of type ArraylndexOutOfBoundsException is thrown.13.What is the return-type of the methods that implement the MouseListener interface?C.The displayed line will show exactly thirty characters.D.The maximum number of characters in a line will be thirty.16.Which declares an abstract method in an abstract Java class?A. public abstract method();B. public abstract void method();C. public void abstract Method(}; D・ public abstract void method() {}17.What happens when this method is called with an input of n Java rules11?1.public String addOK(String S) {2.S + 二” OK!”;3.return S;4.}Select one correct answerA. The method will return u Java rules OK!H.be thrown.C. The method will return "OK!”;n Java rules11.18.Which of the following are Java keywords? B. A runtime exception will D. The method will returnA. arrayB. booleanC. IntegerD. Long19.Assume that val has been defined as an int for the code below.if(val >4){System.out.println(H Test A n);}else if(val > 9){System.out.println(u Test B n);else System.out.println(H Test C H);Which values of val will result in ”Test C” being printed:A.val < 4B. val between 4 and 9C. val = 10D. val > 920.Which of the following are valid definitions of an application's main () method?A. public static void main();B. public static void main( String args );C. public static void main( String args [] );D. public static voidmain( Graphics g );21.After the declaration:char[] c = new char[100];what is the value of c[50]?A. 50B. ””C. ‘\u0032’D. ,\u0000,22.Whic h of the following statements assigns "Hello Java” to the String variable s ?A. String s = "Hello Java";B. String s [] = "Hello Java";C. new String s = "Hello Java”;D. String s[] = new String ("HelloJava");23.If arr[] contains only positive integer values, what does this function do?public int guessWhat(int arr[]){int x = 0;for(int i = 0; i < arr.length; i++)x = x < arr[i] ? arr[i] : x;return x;}A. Returns the index of the highest element in the arrayB・ Returns true/false if there are any elements that repeat in the arrayC.Returns how many even numbers are in the arrayD.Returns the highest element in the array24. Which of the following are legal declarations of a two-dimensional array of integers?A. int[5][5] a = new int[][];B. int a = new int[5,5];C. int a[J[] = new int [5][5];D. int[][]a = new [5]int[5];25.If val = 1 in the code below:switch (val){case 1: System.out.print(n P M);case 2:case 3: System.out.print (n Q H);break;case 4: System.out.print(n R n);default: System.out.print (n S u);}A. PB. PQC. QSD. PQRS26.Given the following code:Which line would cause one error during compilation?A. line 3B. line 5C. line 6D. line 1027.For the code:m = 0;while( ++m < 2 )System.out.println(m);Which of the following are printed to standard output?A. 0B. 1C. 2D. 328.Consider the following code: What will happen when you try to compile it?public class InnerClass{public static void main(String[Jargs){}public class Mylnnerf }}A. It will compile fine.B・ It will not compile, because you cannot have a public inner class.C.It will compile fine, but you cannot add any methods, because then it will fail tocompile.D.It will compile fail.29.What is the result of executing the following code:public class Test{public static void main(String args[]) {String word 二 M restructure M;System.out.println(word.substring(2, 5)); } }A. restB. esC. strD. st30. What will be written to the standard output when the following program is run? public classTest {public static void main(String argsfl) {System.out.println(9 A2);3L When call fact(3), What is the result?int fact(int n){if(n<=l) return 1; elsereturn n^fact(n-l);} A. 2 B. 6 C. 332. What is the result of executing the following code: String s=newString(H abcdefg H);for(int i=0;i<s.length();i+=2){System.out.print(s.char At(i));}A. acegB. bdfC. abcdefg 33- What is the result of executing the following code: public class Test {public static void changeStr(String str){ str=n welcome H;public static void main(String[] args) { String st —” 12345”; changeStr(str); System.out.println(str);Please write the output result : A. welcome B. 12345 C. welcomel2345D. 12345welcome 34. What is the result of executing the following code:1. public class Test {A. 11B. 7C. 18D. 0D. 0D. abed2.static boolean foo(char c) {3.System.out.print(c);4.return true;5.}6.public static void main( String[] argv ) {7.int i=0;& for ( foo(A); foo('B')&&(i<2); foo(C)){9.i++ ;10.foo(D);12.}13.}14.}What is the result?A. ABDCBDCBB. ABCDABCDC. Compilation fails.D. An exception is thrown at runtime.35.What will happen when you attempt to compile and run the following code?public final class Test4{class Inner{void test(){if (Test4.this.flag);elsesample();}}private boolean flag=false;public void sample(){System.out.println(H Sample H);}public Test4(){(new Inner()).test();public static void main(String args[]){ new Test4();What is the result:A. Print out "Sample^B・ Program produces no output but termiantes correctly.C.Program does not terminate.D.The program will not compile36.What is the result of executing the following fragment of code: class Base {Base(){amethod();}int i= 100;public void amethod(){System.o u 匚println(n Base.amethod()H);}}public class Derived extends Base{int i = -1;public static void main(String argv[]) { Base b = new Derived();System.out.println(b.i); b.amethod();public void amethod()System.out.println(H Derived.amethod()n);A. Derived.amethod()Derived.amethod()C. 100Derived.amethod()B.Derived.amethod()100Derived.amethod()D. Compile time errorpublic class Test {String sl=n menu n;public static void main(String args[]) { int z=2;Test t=new Test();System.out.println(t.sl+z);38. What is the result of executing the following code: public class Testimplements A {int x=5;public static void main(String args[]) {Test cl = new Test();System.out.println(c l.x+A.k);} }interface A {intk= 10; } A. 5B. 10C. 1539- What is the result of executing the following code: import java.util.Arrays;public class Test {public static void main(String[] unused) {String[] str = {"xxx”,”zzz",”yyy”,”aaa"};Arrays.sort(str);int index=Arrays.binarySearch(str,H zzz n); if(index==-l)System.out.println(H no H); elseSystem.out.println(H yes H); } } A. noB. xxxC. 0D. yesA. menu2B. 2C. 2menu D ・ menuD. 105int b[][]={{2,3,4},{5,6},{7,8}};int sum=O;for(int i=O;ivb」ength;i++) { for(int j=O;j<b[i]」ength;j++) { sum+=b[i]U];}}System.out.println(',sum=,,4-sum);A. 9B. 11C. 1541.What is the result of executing the following code: public class Test{static void leftshift(int i, int j){i«=j;}public static void main(String args[]){int i=4, j=2;leftshift(ij);System.out.println(i);}}A. 2B.4C. 842.What is the result of executing the following code: public class Test {int x=2;int y;public static void main(String args[]) {int z=3;Test t=new Test();System, out. println(t.x+t.y+z);}}A. 5B. 23C. 243.What is the result of executing the following fragment of code:boolean flag = false;if (flag 二true) {System.out.println(n true H);D. 35D. 16D. 3} else {System.o u 匸println(H false n);}A. trueB. falseC. An exception is raisedD. Nothing happens44.In the following applet, how many buttons will be displayed?import java.applet.*;import java.awt.*;public class Q16 extends Applet {Button okButton = new Button("Ok n);public void init() {add(okButton);add(okButton);add(okButton);add(new Button("Cancel H));add(new Button("Cancel H));add(new Button("Cancel H));add(new Button("Cancel H));setSize(300,300);}}A.1 Button with label "Ok" and 1 Button with label "Cancel”.B.1 Button with label "Ok" and 4 Buttons with label "Cancel'1.C.3 Buttons with label "Ok” and 1 Button with label "CanceF'.D.4 Buttons with label "Ok" and 4 Buttons with label "Ca ncel”.45• What is the result of executing the following code:1.class StaticStuff {2.static int x = 10;3.static { x += 5; }4.public static void main(String args[]){5.System.out.println(H x = n + x);6・}7. static { x /= 5; }8. }A. x = 10B. x = 15C. x = 3D. x=546.What will appear in the standard output when you run the Tester class?class Tester {int var;Tester(double var) {this.var = (int)var;}Tester(int var) {this(n hello");}Tester(String s) {this();System.out.println(s);}Tester() {System.out.println(n good-bye n);}public static void main(String args[]) {Tester t = new Tester(5);}}A. “hello”B. H good-bye nC."hello" followed by "good-bye" D "good-bye" followed by "hello"47.What letters are written to the standard output with the following code? class Unchecked {public static void main(String args[]){method();} catch(Exception e) { }}static void method() {try {wrench();System.out.println(H a n);} catch(ArithmeticException e) {System.out.println(n b n);} finally {System.out.println(n c H);System.out.println(n d n);}static void wrench() {throw new NullPointerException(); } }Select all valid answers. A. H a n B. n b H C. ”c” D. ”d”48. Given this code snippet :try {tryThis(); return;} catch(IOException xl) {System.out.println(n exception l n); return;} catch(Exception x2) {System.out.println(n exception 2n); return; } finally {System.out.println(n finally H);}what will appear in the standard output if tryThis() throws a IOException? A. "exception 1" followed by "finally" B. "exception 2" followed by "finally" C. "exception 1” D. "exception 2"二、填空题(每空1分,共10分) Java 中的字符变量在内存中占【2】位(bit)。

java考试选择题英文版

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考试选择题英文版

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 JavaVirtual 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: "/doc/8d6822986.html,ng.ArrayIndexOutOfBou ndsException: 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 thefollowing 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 takea 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 EqT est();}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 typewriterstyle 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?。

恩士迅java面试英文题

恩士迅java面试英文题

恩士迅java面试英文题Enson Java Interview English Questions1. What is Java?Java is a high-level, object-oriented programming language developed by Sun Microsystems (now owned by Oracle) in 1995. It is known for its platform independence, which means that Java programs can run on any device or operating system that has a Java Virtual Machine (JVM). Java is widely used for creating web applications, mobile applications, desktop software, and enterprise solutions.2. What are the main features of Java?Java has several key features that make it popular among developers:- Object-oriented: Java follows the principles ofobject-oriented programming (OOP), allowing developers to create reusable and modular code.- Platform independence: Java's 'write once, run anywhere' approach allows programs to be run on any device with a JVM, making it highly portable.- Memory management: Java uses automatic garbage collection, freeing developers from managing memory manually. - Multi-threading: Java supports concurrent programmingwith its built-in support for threads, allowing multiple tasks to run simultaneously.- Security: Java provides a secure environment with its built-in security features, such as sandboxing and permission-based access control.3. What is the difference between JDK and JVM?JDK (Java Development Kit) and JVM (Java Virtual Machine) are both essential components of the Java platform, but they serve different purposes.- JDK: JDK is a software development kit that provides tools and libraries necessary for Java development. It includes the Java compiler, debugger, and other utilities required to write, compile, and run Java programs.- JVM: JVM is a runtime environment that executes Java bytecode. It interprets the compiled Java code and converts it into machine code that can be understood by the underlying operating system. JVM also handles memory management and provides various runtime services.4. What is the difference between an abstract class and an interface?- Abstract class: An abstract class is a class that cannot be instantiated and is typically used as a base class for otherclasses. It can contain both abstract and non-abstract methods. Subclasses of an abstract class must implement its abstract methods. An abstract class can also have fields and constructors.- Interface: An interface is a collection of abstract methods and constants. It cannot be instantiated and is used to define a contract for implementing classes. A class can implement multiple interfaces, but it can only extend a single class. Interfaces are used to achieve multiple inheritance in Java.5. What are the different types of exceptions in Java? Java has two types of exceptions: checked exceptions and unchecked exceptions.- Checked exceptions: These are exceptions that are checked at compile-time. The developer must either handle these exceptions using try-catch blocks or declare them in the method signature using the 'throws' keyword. Examples of checked exceptions include IOException and SQLException.- Unchecked exceptions: These are exceptions that are not checked at compile-time. They are subclasses of RuntimeException and Error classes. Unchecked exceptions do not need to be declared or caught explicitly. Examples ofunchecked exceptions include NullPointerException and ArrayIndexOutOfBoundsException.These are just a few sample questions that can be asked during a Java interview. It is important to remember that the depth and complexity of questions may vary depending on the level of the position being applied for. It is advisable to thoroughly prepare and revise various topics related to Java programming to increase the chances of success in a Java interview.。

java 英文面试题

java 英文面试题

java 英文面试题Java面试题1. What is Java?Java is a high-level programming language developed by Sun Microsystems (now owned by Oracle) in 1995. It is widely used for developing various applications, including web and mobile applications.2. What are the key features of Java?- Platform independence: Java programs can run on any system that has a Java Virtual Machine (JVM) installed.- Object-oriented: Java follows the object-oriented programming paradigm and supports concepts like encapsulation, inheritance, and polymorphism.- Robust: Java includes features like automatic memory management (garbage collection) and exception handling, which make it less prone to errors and crashes.- Secure: Java includes built-in security features that protect against viruses, tampering, and unauthorized access.- Multithreading: Java supports multithreading, allowing programs to execute multiple tasks concurrently.- Portable: Java programs can be easily moved from one system to another without any modification.3. What is the difference between JDK, JRE, and JVM?- JDK (Java Development Kit): It includes the tools necessary for developing and running Java applications. It includes the Java compiler, debugger, and other development utilities.- JRE (Java Runtime Environment): It provides the necessary runtime environment for executing Java applications. It includes the JVM and Java libraries.- JVM (Java Virtual Machine): It is responsible for executing the Java bytecode. It provides a platform-independent execution environment for Java programs.4. What are the various access specifiers in Java?Java provides four access specifiers to control the visibility and accessibility of classes, methods, and variables:- public: Accessible from anywhere.- private: Accessible only within the same class.- protected: Accessible within the same class, package, and subclasses.- default (no specifier): Accessible within the same package.5. What are the primitive data types in Java?Java has eight primitive data types:- byte: 8-bit signed integer.- short: 16-bit signed integer.- int: 32-bit signed integer.- long: 64-bit signed integer.- float: 32-bit floating-point number.- double: 64-bit floating-point number.- boolean: true or false.- char: 16-bit Unicode character.6. What is the difference between an interface and an abstract class?- An interface is a completely abstract class that defines a contract for its implementing classes. It cannot have method implementations. In contrast, an abstract class can have both abstract and non-abstract methods.- A class can implement multiple interfaces, but it can only extend a single abstract class.- Interfaces are used to achieve multiple inheritance in Java, while abstract classes provide a way to partially implement a class.7. What is the purpose of the "final" keyword in Java?The "final" keyword in Java is used to restrict certain behaviors:- A final class cannot be inherited.- A final method cannot be overridden by subclasses.- A final variable cannot be reassigned once initialized.8. What are the differences between checked and unchecked exceptions in Java?- Checked exceptions are checked at compile-time, and the compiler forces the developers to handle them using try-catch blocks or by declaring them in the method signature. Examples include IOException and SQLException.- Unchecked exceptions do not require mandatory handling and are checked at runtime. Examples include NullPointerException and ArrayIndexOutOfBoundsException.9. What are the benefits of using Java generics?- Type safety: Generics allow you to enforce compile-time type checking, preventing type-related errors at runtime.- Code reusability: With generics, you can write a single generic method or class that can work with various types, reducing code duplication.- Performance: Generics can improve performance by eliminating the need for type casting, which can be expensive in terms of memory and processing time.10. What is the difference between method overloading and method overriding?- Method overloading occurs when a class has multiple methods with the same name but different parameters. The methods are differentiated basedon the number, order, and types of parameters.- Method overriding occurs when a subclass provides a different implementation of a method already defined in its superclass. The methodsignature (name and parameters) must be the same in both the superclass and subclass.In conclusion, these are some common Java interview questions that cover various aspects of the Java programming language. It is important to understand these concepts thoroughly to succeed in a Java interview.。

java英语笔试试题及答案

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基础试题及答案英文

java基础试题及答案英文1. What is Java?Java is a high-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It is a general-purpose programming language intended to let application developers write once, run anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.2. What are the main features of Java?The main features of Java include platform independence, object-oriented, simple syntax, robust, secure, architecture-neutral, portable, multi-threaded, high performance, and interpreted.3. What is the difference between JDK and JRE?JDK (Java Development Kit) is a development environment used for developing Java applications, which includes the JRE (Java Runtime Environment) and tools required to compile Java code. JRE is the runtime environment for executing Java applications, which includes the Java Virtual Machine (JVM), Java core classes, and supporting libraries.4. What is an exception in Java?An exception in Java is an event that disrupts the normal flow of the program's instructions. It is an error in the program that occurs at runtime. Exceptions in Java arehandled using try, catch, and finally blocks.5. What is the difference between checked and unchecked exceptions in Java?Checked exceptions are exceptions that are checked at compile time and must be either caught or declared in the method signature. Unchecked exceptions are not checked at compiletime and are usually caused by programming errors, such as NullPointerException or ArrayIndexOutOfBoundsException.6. What is the purpose of the main method in Java?The main method is the entry point for any Java application.It is the method that is called when the application starts, and it must be defined with the following signature: public static void main(String[] args).7. What is an interface in Java?An interface in Java is a reference type that is used to specify the behavior of a class. It can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces are used to achieve abstraction and to define a contract that can be implemented by multiple classes.8. What is the difference between abstract class andinterface in Java?An abstract class is a class that cannot be instantiated and may contain both abstract and non-abstract methods. An interface is a completely abstract class that can onlycontain abstract methods, default methods, static methods,and constants. A class can implement multiple interfaces butcan only extend one abstract class.9. What is garbage collection in Java?Garbage collection in Java is the process of automatically identifying and deallocating memory that is no longer in use by the program. The Java Virtual Machine (JVM) has a garbage collector that periodically frees up memory by identifying objects that are no longer reachable.10. What is the purpose of the 'this' keyword in Java?The 'this' keyword in Java is used to refer to the current object. It can be used to access instance variables, methods, and constructors of the current class. It is also used to pass the current object as an argument to another method.11. What is the purpose of the 'super' keyword in Java?The 'super' keyword in Java is used to refer to the parent class or superclass. It can be used to access the variables, methods, and constructors of the parent class. It is also used to call the constructor of the parent class from within a subclass constructor.12. What is the difference between '==’ and 'equals()' method in Java?The '==' operator is used to compare the references of two objects, whereas the 'equals()' method is used to compare the content of two objects. The 'equals()' method can be overridden in a class to provide a custom comparison logic.13. What is encapsulation in Java?Encapsulation in Java is the principle of wrapping the data(variables) and the code acting on the data (methods)together as a single unit. It is one of the fundamental concepts of object-oriented programming and is used torestrict direct access to some of an object's components, which can prevent the accidental modification of data.14. What is the purpose of the 'final' keyword in Java?The 'final' keyword in Java can be used in different contexts: - A final variable cannot be changed once it is assigned.- A final method cannot be overridden by subclasses.- A final class cannot be subclassed.15. What is the purpose of the 'static' keyword in Java?The 'static' keyword in Java is used to create classvariables and methods that are not associated with any object of the class. Static variables and methods belong to theclass itself rather than any particular object. They can be accessed without creating an instance of the class.16. What is a package in Java?A package in Java is a namespace that organizes a set of related classes and interfaces. It is used to group related classes and to avoid naming conflicts. Java packages also provide a level of access control.17. What is。

JAVA英文笔试题.doc

JAVA英文笔试题.doc

JAVA英文笔试题isoracle.ismajordiffereneceoracle8iandoracle9i. mesomethingurself.telImeaboutoops.issingleinheritance.ismultipleinheritance.javasupportmultipleinheritance.isinterface.isdifferenecbetweenabst ractclassa n dinterfac e.toupr ovet hatabs trace class cannot inst antiate dir ectly.i sdifferene cebetweenst ringandstri ngbuffer.is immutabl etowrit eapro gramu singso rtpr ogram.1 5howtowri t eaprogramu singunsortp rogram.isle gacy.isl ega cyapii slega cyint erface .ismaindi ff erencehas h mapandhast ableismai ndifferenc e betweenar ra ylistand vec tor.1.Ora cleis anRDBM Spro ductwit hDD LandDMLf romacompany c alledOracl eInc.2.Di fferencebe t ween8iand 9i isgiveni nth eOracle site3.Q uestio nnot availab le4.Somethi n g5.oopsi sObjectOrie ntedProgra m ming issi ngleinheri tanc e.a ns: one clas sisinhe rit edbyonly ot heronecla s sismulti pleinherita nee.ans : 0 neclassi nhe ritingm oret hanone class atati meja vas upportmu It ipleinher i tance.ans:Noisinterf a ce.ans : In terface haso nlymet hodde clara tionsb utno defni sd ifferenec b etweenabst ractclassan dinterface.ans: Ina bs tractcla sss omemeth odsm aycont ainde finit ion, bu tini nterfac eev erymetho ds houldbeab s tracttou provethatab straceclas s cannotins ta ntiatedi rec tly.ans:A sthey dontha veco nstruct ort heycantb ei nstantiat e disdiffe renecebetwe enstringan d stringbuf fe r.ans : Str ingsar eimmu table wherea sstr ingbuff ere anbemodi fi ed isimmut ableans :W hichcantbe c hangedtow riteapr ogra musing sortp rogra m.15 how towritea pr ogramusin g unsortprog ram.ans:B othcanbedo n eusingjav as criptTh isis forSor tfu ncti onSelec tTe xtSort (o bj ) (//sortb y textvarN=;for(vari=0 ; ifor (var j=i +1; jif([i ]. tex t>[j]. text ) {var il = ([i]. sei e cted==true ) ?true: fals evarjl= ([j]. select ed ==true)?tru e:false varq 1= [j]. text;var q2= [ j]. v al ue;[j]. te xt= [i]. text ;[j]. value =[i]. value ;[i]. text =ql;[i]. v alue=q 2;[i]. sei ec ted= (jltr u e)?true:fa Ise[j] . se lected=(il t rue)?true :f alse retu rntrue }isle gacy .islega cy apiislega cyinterface .ans:leg a cyissomet hi ngthatis old interms ofte chnolo gy/sy stemismai ndi fference ha shmapandh a stablean s:Hashtable issynchron i sedism ain differe nceb etween array lista ndvect or.ans:Ve ct orissynch r onised。

java英文试题及答案

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双语试卷

java双语试卷

Java Program Design Final Examination(Paper B)(notification:Examination time is 120 minutes,all result should bewrote in answer sheet)Class:________ Number:_________ Name:___________1、Discriminate the following sentences, if finding errors, please give your reasons(16 points)1、Java can implement multi-thread operation only in terms of implementingRunnable interface.2、There is no difference between error and exception in Java program.3、The purpose of importing LayoutManager in Java is to enhance the beauty ofinterface.4、In Java program, threads work in terms of cooperative multi-task fashion,they may share data and code.2、Answer the following questions briefly.(24 points)1、Please briefly explain the execution principle of java applet.2、Which types of objects is the processing model of AWT event composed of?What are their functions?3、When using socket to write Client / Server communication program supportingmulti clients, what do we need key technologies? What are their workingprinciples?4、Describe interactive method of Servlet and form.3、Complement program(20 points)1、The following program implement the multiplication of matrix A and matrix B, then the result is saved in matrix C.public class MatrixMultiply{public static void main(String args[]){int m,n,k;int a[][]=new int [2][3];int b[][]={{1,5,2,8},{5,9,10,-3},{2,7,-5,-18}};int c[][]=new int[2][4];for (m=0;m<2;m++)for (n=0; n<3 ;n++)a // Initialize the matrix A, every array// element‟s value equals the multiplication of its two subscript values.for (m=0;m<2;m++){for (n=0;n<4;n++){c[m][n]=0;for(k=0;k<3;k++)b // Multiplication calculation of matrix.}}}2、The following class sequentially read a readable file, the operation will stop when meeting “Bye” string or arriving to EOF.import java.io.*;public class ReadFile{public static void main(String args[]){String s;FileInputStream is;InputStreamReader ir;BufferedReader in;try{is=new FileInputStream("bbs.txt");a ;in=new BufferedReader(ir);b ;System.out.println("Read: "+s);}catch(FileNotFoundException e) {System.out.println("File not found!");System.exit(-2);}catch(IOException e) {System.out.println("Error:"+e);System.exit(-3);}}}3、Complement source code in …a‟ point, let this program output the values of coordinate X and Y in screen.import java.awt.*;import java.awt.event.*;public class MyApplet extends java.applet.Applet {public void init( ) {Button b = new Button("Button1");b.addMouseListener(new ClickHandler());add(b);}class ClickHandler extends MouseAdapter {public void mouseClicked(MouseEvent evt) {a}}}4、The following method is incomplete, unsafe() will throw an IOException, please complement corresponding statement in a point to integrate the method.a{if(unsafe()){// do something }else if(safe()){// do something }}4、Program Analysis(24 points)1、Can the following program be compiled? Please give your reason.class Ellipse{public int draw(){return 1;};}class Circle extends Ellipse{public void draw(){};}public class OOTest1{public static void main(String[] args){Circle c = new Circle();}}2、1、Using the parameters a=4, b=0 to invocate the following method, what can you get? Please give your reason.public void divide(int a, int b) {try {int c = a / b;System.out.print("The result is" + c);}catch (Exception e) {System.out.print("The operation is exceptional ! ");}finally {System.out.println("The operation is over.");}}3、What is the following program‟s running result? Please give your reason.public void CompareBoolean( ) {Boolean b1 = new Boolean(true);Boolean b2 = new Boolean(true);if (b1 == b2)if (b1.equals(b2))System.out.println("a");elseSystem.out.println("b");elseif (b1.equals(b2))System.out.println("c");elseSystem.out.println("d");}4、What is the following program‟s running result? Please give your reason.void Calculate() {int i = 3;int j = 0;float k = 3.8F;long m = -3;if (Math.ceil(i) < Math.round(k))if (Math.abs(m) == i)System.out.println(i);elseSystem.out.println(j);elseSystem.out.println(Math.abs(m) + 1);}}5、May the following program normally compile and run? Please give your reason.class First {private int a = 1;int b = 2;}class Second extends First {public void method() {System.out.println(a + b);}}6、May the following program normally run? Please give your reason.class Ellipse{public void draw(){System.out.println("Ellipse");};}class Circle extends Ellipse{public void draw(){System.out.println("Circle");};}public class OOTest2{public static void main(String[] args){Circle c = new Ellipse ();c.draw();}}5、Programming(16 points)(1) Programme and calculate the summation of non-even and non-prime number between 100 and 1000.(2) Given the following conditions: the data driver is “A”, the data source name is “B”, the username is “C”, the password is “D”, the data table is “T”. Please use JDBC to retrieve all data from table “T”.The reference Answer of Java Program Design FinalExaminationA Paper (2001 Grade)1、Discriminate the following sentences, if finding errors, please give your reasons(16 points)1、Answer: error. Java has two methods to implement multi-thread operation:implementing Runnable interface and inheriting “Thread” class.2、Answer: error. The error denotes that system brings severe problems which arevery difficult to recover, e.g., memory overflow. There is no hope for program to handle the situation. The exception denotes a kind of problem of design andimplementation, i.e., the situation will not occur when the program normally runs, even if it occurs, the program can take corresponding measure to handle it.3、Answer: error. In order to implement the character of cross platform and acquiredynamic layout effect, Java imports LayoutManager. Java sends the task ofarranging all components in container to Layoutmanager, e.g., size and location of component. When windows are shifted or adjusted, the function of adjustingcomponents is authorized to Layoutmanager.4、Answer: error. The threads in Java work according to imperative multi-taskfashion, all these threads may share date and code, Java can try its best to avoid severe memory management problems, e.g., deadlock2、Answer the following questions briefly.(24 points)1、Answer: Java applet program is also a kind of class, its compiling fashion is thesame to common java application program. Java applet can produce a .class file after compiling. The execution fashion of Java applet is completely different from java application. Java applet program must be embedded into html file and then be executed. So, encoding html file is necessary.2、Answer: It refers to three kinds of objects in course of java event processing: (1)Event, it is java language description of user interface operation. (2) Enent Source, it is the taking-place site of event, it commonly is in fashion of component, e.g., Button. (3) Event Handler, it is handler of event, its task is to receiving eventobject and then handle it.3、Answer: Firstly, Socket uses getInputStream() and getOutStream() to implementthe read/write operation of input/output stream, the two methods returnInputStream and OutputSteam class object respectively. Secondly, multi-threadtechnology is needed, server always monitors if there is client request in special port. If there is a client request, server will start a special service thread toresponse this request. After starting the thread, the server will wait next clientrequest immediately.4、Answer: Servlet interacts with form using the methods in HttpServlet class. Thereare several methods that are not completely implemented in HttpServlet class,you may define the content of these methods freely, but, you must use rightmethod name so that HTTP Server can correctly map client request tocorresponding function. The service method of HttpServlet can invocatedoOptions method automatically when receiving an OPTIONS request, and it can invocate doTrace method when receiving an TRACE request3、Complement program(20 points)1、a:a[m][n]=m*n;b: c[m][n]+=a[m][k]*b[k][n];2、a:ir=new InputStreamReader(is);b:while((s=in.readLine())!=null )3、a:System.out.println("Current mouse position: "+evt.getX() +” , ” + evt.getY );4、a:public void methodName() throws Exception 或public void methodName() throws IOException 4、Program Analysis(24 points)1、It can‟t pass compi ling because overlay functions return different kinds of data types.2、The operation is exceptional !, The operation is over.Because computing 4/0 will throw operation exception, thus, the program will firstly run the statements in catch{ } block, then runthe statements in finally{} block.3、cBecause there is not converting association between Integer and Boolean, we can‟t use “=” operation, but we can use equals() function to finish compare operation4、3Because we may compare the values of Integer and Long Integer (update Integer into Long Integer before compare operation)5、It can‟t run. Because variable “a” is private type in “First” class, thus, it can‟t be accessed in other classes.6、It may be compiled and run. Because “Circle” class and “Ellipse” have different parameters, this situation belongs to method reload rather than method overlay.5、Programming(16 points)1、public class TotalPrime {int i,j,k,primeCount=0;boolean isSuShu;for(i=100;i<=1000;i++){isSuShu=true;k=i/2;for(j=2;j<=k;j++)if(i%j==0){isSuShu=false;break;}if(isSuShu)primeCount++;}System.out.println(“The summation of non-even and non- prime number between 100 and 1000 is” + primeCount);}2、public class RetrieveTable {String URL=”jdbc:odbc: B”;String query;Connection conn;Statement statement;Resultset rs=null;Try {Class.forName(“A”);conn = DriverManager.getConnection(URL, ”C”, ”D”);statement = conn.createStatement( );query = select * from T;rs = statement.executeQuery(query);rs.close( );statement.close( );conn.close( );}catch(Exception e) {System.out.print(e.getMessage());}}。

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

一. Which two demonstrate an“is a” relationship? (Choose Two)A. public interface Person { }public interface Shape { }public interface Color { } 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 () ”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 outer classD. 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}4public class inertest{5public static void main (String[] args){6enclosingone eo = new enclosingone();7 InsideOne ei = InsideOne();写程序试出来B. ei = InsideOne();C InsideOne ei = InsideOne();InsideOne ei = 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=;9) i=;10) i=;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.六.B.defaultC.implementD.import八. which three are valid declaraction of a float?( float作为整数是可以的,其余几个都是double )A. float foo=-1;B. float foo=;C. float foo=42e1;D. float foo=;E. float foo=;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];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]; 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) "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= ;6.private float getFloat () {return f1;}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. ();10. int j = ();11.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)}5)public class Sub extends Super{6)7)}which method, placed at line 6, will cause a compiler error?A. public float getNum(){return ;}B. public void getNum(){} 返回值类型不同不足以构成方法的重载C.public void getNum(double d){}D. public double getNum(float d){return ;}十八 . Which declaration prevents creating a subclass of an outer class?class FooBar{}class Foobar{}class FooBar{}public class FooBar{}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");}}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"子类总要去调用父类的构造函数,有两种调用方式,自动调用(无参构造函数),主动调用带参构造函数。

相关文档
最新文档