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英文版答案

public class Exercise1_2 {public static void main(String[] args) {System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");System.out.println("Welcome to Java");}}public class Exercise1_4 {public static void main(String[] args) {System.out.println("a a^2 a^3");System.out.println("1 1 1");System.out.println("2 4 8");System.out.println("3 9 27");System.out.println("4 16 64");}}public class Exercise1_6 {public static void main(String[] args) {System.out.println(1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9);}}public class Exercise1_8 {public static void main(String[] args) {// Display areaSystem.out.println(5.5 * 5.5 * 3.14159);// Display perimeterSystem.out.println(2 * 5.5 * 3.14159);}}import javax.swing.JOptionPane;public class Exercise2_1WithDialogBox {// Main methodpublic static void main(String[] args) {// Enter a temperatur in FahrenheitString celsiusString = JOptionPane.showInputDialog(null,"Enter a temperature in Celsius:","Exercise2_1 Input", JOptionPane.QUESTION_MESSAGE);// Convert string to doubledouble celsius = Double.parseDouble(celsiusString);// Convert it to Celsiusdouble fahrenheit = (9.0 / 5) * celsius + 32;// Display the resultJOptionPane.showMessageDialog(null, "The temperature is " +fahrenheit + " in Fahrenheit");}}import java.util.Scanner;public class Exercise2_2 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Enter radius of the cylinderSystem.out.print("Enter radius of the cylinder: ");double radius = input.nextDouble();// Enter length of the cylinderSystem.out.print("Enter length of the cylinder: ");double length = input.nextDouble();double volume = radius * radius * 3.14159 * length;System.out.println("The volume of the cylinder is " + volume);}}public class Exercise2_4 {public static void main(String[] args) {// Prompt the inputjava.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Enter a number in pounds: ");double pounds = input.nextDouble();double kilograms = pounds * 0.454;System.out.println(pounds + " pounds is " + kilograms + " kilograms"); }}// Exercise2_6.java: Summarize all digits in an integer < 1000public class Exercise2_6 {// Main methodpublic static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Read a numberSystem.out.print("Enter an integer between 0 and 1000: ");int number = input.nextInt();// Find all digits in numberint lastDigit = number % 10;int remainingNumber = number / 10;int secondLastDigit = remainingNumber % 10;remainingNumber = remainingNumber / 10;int thirdLastDigit = remainingNumber % 10;// Obtain the sum of all digitsint sum = lastDigit + secondLastDigit + thirdLastDigit;// Display resultsSystem.out.println("The sum of all digits in " + number+ " is " + sum);}}public class Exercise2_8 {public static void main(String args[]) {java.util.Scanner input = new java.util.Scanner(System.in);// Enter an ASCII codeSystem.out.print("Enter an ASCII code: ");int code = input.nextInt();// Display resultSystem.out.println("The character for ASCII code "+ code + " is " + (char)code);}}import java.util.Scanner;public class Exercise2_10 {/** Main method */public static void main(String[] args) {Scanner input = new Scanner(System.in);// Receive the amount entered from the keyboardSystem.out.print("Enter an amount in double, for example 11.56 ");double amount = input.nextDouble();int remainingAmount = (int)(amount * 100);// Find the number of one dollarsint numberOfOneDollars = remainingAmount / 100;remainingAmount = remainingAmount % 100;// Find the number of quarters in the remaining amountint numberOfQuarters = remainingAmount / 25;remainingAmount = remainingAmount % 25;// Find the number of dimes in the remaining amountint numberOfDimes = remainingAmount / 10;remainingAmount = remainingAmount % 10;// Find the number of nickels in the remaining amountint numberOfNickels = remainingAmount / 5;remainingAmount = remainingAmount % 5;// Find the number of pennies in the remaining amountint numberOfPennies = remainingAmount;// Display resultsString output = "Your amount " + amount + " consists of \n" +numberOfOneDollars + " dollars\n" +numberOfQuarters + " quarters\n" +numberOfDimes + " dimes\n" +numberOfNickels + " nickels\n" +numberOfPennies + " pennies";System.out.println(output);}}import javax.swing.JOptionPane;public class Exercise2_12a {public static void main(String args[]) {// Obtain inputString balanceString = JOptionPane.showInputDialog(null,"Enter balance:");double balance = Double.parseDouble(balanceString);String interestRateString = JOptionPane.showInputDialog(null,"Enter annual interest rate:");double annualInterestRate = Double.parseDouble(interestRateString);double monthlyInterestRate = annualInterestRate / 1200;double interest = balance * monthlyInterestRate;// Display outputJOptionPane.showMessageDialog(null, "The interest is " +(int)(100* interest) / 100.0);}}import java.util.Scanner;public class Exercise2_12b {public static void main(String args[]) {Scanner input = new Scanner(System.in);// Obtain inputSystem.out.print("Enter balance: ");double balance = input.nextDouble();System.out.print("Enter annual interest rate: ");double annualInterestRate = input.nextDouble();double monthlyInterestRate = annualInterestRate / 1200;double interest = balance * monthlyInterestRate;// Display outputSystem.out.println("The interest is " + (int)(100* interest) / 100.0);}}import java.util.Scanner;public class Exercise2_14 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter weight in poundsSystem.out.print("Enter weight in pounds: ");double weight = input.nextDouble();// Prompt the user to enter height in inchesSystem.out.print("Enter height in inches: ");double height = input.nextDouble();double bmi = weight * 0.45359237 / (height * 0.0254 * height * 0.0254);System.out.print("BMI is " + bmi);}}public class Exercise2_16 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Enter the amount of water in kilograms: ");double mass = input.nextDouble();System.out.print("Enter the initial temperature: ");double initialTemperature = input.nextDouble();System.out.print("Enter the final temperature: ");double finalTemperature = input.nextDouble();double energy =mass * (finalTemperature - initialTemperature) * 4184;System.out.print("The energy needed is " + energy);}}public class Exercise2_18 {// Main methodpublic static void main(String[] args) {System.out.println("a b pow(a, b)");System.out.println("1 2 " + (int)Math.pow(1, 2));System.out.println("2 3 " + (int)Math.pow(2, 3));System.out.println("3 4 " + (int)Math.pow(3, 4));System.out.println("4 5 " + (int)Math.pow(4, 5));System.out.println("5 6 " + (int)Math.pow(5, 6)); }}import java.util.Scanner;public class Exercise2_20 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Enter the first point with two double valuesSystem.out.print("Enter x1 and y1: ");double x1 = input.nextDouble();double y1 = input.nextDouble();// Enter the second point with two double valuesSystem.out.print("Enter x2 and y2: ");double x2 = input.nextDouble();double y2 = input.nextDouble();// Compute the distancedouble distance = Math.pow((x1 - x2) * (x1 - x2) +(y1 - y2) * (y1 - y2), 0.5);System.out.println("The distance of the two points is " + distance);}}import java.util.Scanner;public class Exercise2_22 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Enter the side of the hexagonSystem.out.print("Enter the side: ");double side = input.nextDouble();// Compute the areadouble area = 3 * 1.732 * side * side / 2;System.out.println("The area of the hexagon is " + area); }}import java.util.Scanner;public class Exercise2_24 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter speed v: ");double v = input.nextDouble();System.out.print("Enter acceleration a: ");double a = input.nextDouble();double length = v * v / (2 * a);System.out.println("The minimum runway length for this airplane is " + length + " meters");}}public class Exercise3_2 {/**Main method*/public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Prompt the user to enter an integerSystem.out.print("Enter an integer: ");int number = input.nextInt();// Display resultsSystem.out.println("Is " + number + " an even number? " +(number % 2 == 0));}}import javax.swing.*;public class Exercise3_4 {public static void main(String[] args) {int number1 = (int)(System.currentTimeMillis() % 100);int number2 = (int)(System.currentTimeMillis() * 7 % 100);String resultString = JOptionPane.showInputDialog("What is " + number1 + " + " + number2 + "?");int result = Integer.parseInt(resultString);JOptionPane.showMessageDialog(null,number1 + " + " + number2 + " = " + result + " is " +(number1 + number2 == result));}}import javax.swing.*;public class Exercise3_5WithJOptionPane {public static void main(String[] args) {int number1 = (int)(System.currentTimeMillis() % 10);int number2 = (int)(System.currentTimeMillis() * 7 % 10);int number3 = (int)(System.currentTimeMillis() * 3 % 10);String answerString = JOptionPane.showInputDialog("What is " + number1 + " + " + number2 + " + " +number3 + "?");int answer = Integer.parseInt(answerString);JOptionPane.showMessageDialog(null,number1 + " + " + number2 + " + " + number3 + " = " + answer + " is " + (number1 + number2 + number3 == answer));}}import java.util.Scanner;public class Exercise3_6 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter weight in poundsSystem.out.print("Enter weight in pounds: ");double weight = input.nextDouble();// Prompt the user to enter heightSystem.out.print("Enter feet: ");double feet = input.nextDouble();System.out.print("Enter inches: ");double inches = input.nextDouble();double height = feet * 12 + inches;// Compute BMIdouble bmi = weight * 0.45359237 /((height * 0.0254) * (height * 0.0254));// Display resultSystem.out.println("Your BMI is " + bmi);if (bmi < 16)System.out.println("You are seriously underweight");else if (bmi < 18)System.out.println("You are underweight");else if (bmi < 24)System.out.println("You are normal weight");else if (bmi < 29)System.out.println("You are over weight");else if (bmi < 35)System.out.println("You are seriously over weight");elseSystem.out.println("You are gravely over weight");}}public class Exercise3_8 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Enter three numbersSystem.out.print("Enter three integers: ");int num1 = input.nextInt();int num2 = input.nextInt();int num3 = input.nextInt();if (num1 > num2) {int temp = num1;num1 = num2;num2 = temp;}if (num2 > num3) {int temp = num2;num2 = num3;num3 = temp;}if (num1 > num2) {int temp = num1;num1 = num2;num2 = temp;}System.out.println("The sorted numbers are "+ num1 + " " + num2 + " " + num3);}}import javax.swing.JOptionPane;public class Exercise3_10 {public static void main(String[] args) {// 1. Generate two random single-digit integersint number1 = (int)(Math.random() * 10);int number2 = (int)(Math.random() * 10);// 2. Prompt the student to answer 搘hat is number1 + number2?? String answerString = JOptionPane.showInputDialog("What is " + number1 + " + " + number2 + "?");int answer = Integer.parseInt(answerString);// 4. Grade the annser and display the resultString replyString;if (number1 + number2 == answer)replyString = "You are correct!";elsereplyString = "Your answer is wrong.\n" + number1 + " + "+ number2 + " should be " + (number1 + number2);JOptionPane.showMessageDialog(null, replyString);}}import java.util.Scanner;public class Exercise3_12 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter an integerSystem.out.print("Enter an integer: ");int number = input.nextInt();if (number % 5 == 0 && number % 6 == 0)System.out.println(number + " is divisible by both 5 and 6");else if (number % 5 == 0 ^ number % 6 == 0)System.out.println(number + " is divisible by both 5 and 6, but not both");elseSystem.out.println(number + " is not divisible by either 5 or 6");}}public class Exercise3_14 {public static void main(String[] args) {// Obtain the random number 0 or 1int number = (int)(Math.random() * 2);// Prompt the user to enter a guessjava.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Guess head or tail? " +"Enter 0 for head and 1 for tail: ");int guess = input.nextInt();// Check the guessif (guess == number)System.out.println("Correct guess");else if (number == 0)System.out.println("Sorry, it is a head");elseSystem.out.println("Sorry, it is a tail");}}public class Exercise3_16 {public static void main(String[] args) {System.out.println((char)('A' + Math.random() * 27));}}import java.util.Scanner;public class Exercise3_18 {/** Main method */public static void main(String args[]) {Scanner input = new Scanner(System.in);// Prompt the user to enter a yearSystem.out.print("Enter a year: ");// Convert the string into an int valueint year = input.nextInt();// Check if the year is a leap yearboolean isLeapYear =((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);// Display the result in a message dialog boxSystem.out.println(year + " is a leap year? " + isLeapYear);}}public class Exercise3_20 {// Main methodpublic static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Enter the temperature in FahrenheitSystem.out.print("Enter the temperature in Fahrenheit: ");double fahrenheit = input.nextDouble();if (fahrenheit < -58 || fahrenheit > 41) {System.out.println("Temperature must be between -58癋and 41癋");System.exit(0);}// Enter the wind speed miles per hourSystem.out.print("Enter the wind speed miles per hour: ");double speed = input.nextDouble();if (speed < 2) {System.out.println("Speed must be greater than or equal to 2");System.exit(0);}// Compute wind chill indexdouble windChillIndex = 35.74 + 0.6215 * fahrenheit - 35.75 *Math.pow(speed, 0.16) + 0.4275 * fahrenheit *Math.pow(speed, 0.16);// Display the resultSystem.out.println("The wind chill index is " + windChillIndex);}}import java.util.Scanner;public class Exercise3_22 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Enter a point with two double valuesSystem.out.print("Enter a point with two coordinates: ");double x = input.nextDouble();double y = input.nextDouble();// Compute the distancedouble distance = Math.pow(x * x + y * y, 0.5);if (distance <= 10)System.out.println("Point (" + x + ", " + y +") is in the circle");elseSystem.out.println("Point (" + x + ", " + y +") is not in the circle");}}public class Exercise3_24 {public static void main(String[] args) {final int NUMBER_OF_CARDS = 52;// Pick a cardint number = (int)(Math.random() * NUMBER_OF_CARDS);System.out.print("The card you picked is ");if (number % 13 == 0)System.out.print("Ace of ");else if (number % 13 == 10)System.out.print("Jack of ");else if (number % 13 == 11)System.out.print("Queen of ");else if (number % 13 == 12)System.out.print("King of ");elseSystem.out.print((number % 13) + " of ");if (number / 13 == 0)System.out.println("Clubs");else if (number / 13 == 1)System.out.println("Diamonds");else if (number / 13 == 2)System.out.println("Hearts");else if (number / 13 == 3)System.out.println("Spades");}}public class Exercise3_26 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Enter an integerSystem.out.print("Enter an integer: ");int number = input.nextInt();System.out.println("Is " + number + " divisible by 5 and 6? " +((number % 5 == 0) && (number % 6 == 0)));System.out.println("Is " + number + " divisible by 5 or 6? " +((number % 5 == 0) || (number % 6 == 0)));System.out.println("Is " + number +" divisible by 5 or 6, but not both? " +((number % 5 == 0) ^ (number % 6 == 0)));}}import java.util.Scanner;public class Exercise3_28 {public static void main(String args[]) {Scanner input = new Scanner(System.in);System.out.print("Enter r1抯center x-, y-coordinates, width, and height: ");double x1 = input.nextDouble();double y1 = input.nextDouble();double w1 = input.nextDouble();double h1 = input.nextDouble();System.out.print("Enter r2抯center x-, y-coordinates, width, and height: ");double x2 = input.nextDouble();double y2 = input.nextDouble();double w2 = input.nextDouble();double h2 = input.nextDouble();double xDistance = x1 - x2 >= 0 ? x1 - x2 : x2 - x1;double yDistance = y1 - y2 >= 0 ? y1 - y2 : y2 - y1;if (xDistance <= (w1 - w2) / 2 && yDistance <= (h1 - h2) / 2)System.out.println("r2 is inside r1");else if (xDistance <= (w1 + w2) / 2 && yDistance <= (h1 + h2) / 2)System.out.println("r2 overlaps r1");elseSystem.out.println("r2 does not overlap r1");}}import java.util.Scanner;public class Exercise3_30 {public static void main(String[] args) {// Prompt the user to enter the time zone offset to GMTScanner input = new Scanner(System.in);System.out.print("Enter the time zone offset to GMT: ");long timeZoneOffset = input.nextInt();// Obtain the total milliseconds since the midnight, Jan 1, 1970long totalMilliseconds = System.currentTimeMillis();// Obtain the total seconds since the midnight, Jan 1, 1970long totalSeconds = totalMilliseconds / 1000;// Compute the current second in the minute in the hourlong currentSecond = totalSeconds % 60;// Obtain the total minuteslong totalMinutes = totalSeconds / 60;// Compute the current minute in the hourlong currentMinute = totalMinutes % 60;// Obtain the total hourslong totalHours = totalMinutes / 60;// Compute the current hourlong currentHour = (totalHours + timeZoneOffset) % 24;// Display resultsSystem.out.print("Current time is " + (currentHour % 12) + ":"+ currentMinute + ":" + currentSecond);if (currentHour < 12)System.out.println(" AM");elseSystem.out.println(" PM");}}public class Exercise4_2 {public static void main(String[] args) {int correctCount = 0; // Count the number of correct answersint count = 0; // Count the number of questionsjava.util.Scanner input = new java.util.Scanner(System.in);long startTime = System.currentTimeMillis();while (count < 10) {// 1. Generate two random single-digit integersint number1 = 1 + (int)(Math.random() * 15);int number2 = 1 + (int)(Math.random() * 15);// 2. Prompt the student to answer 搘hat is number1 ?number2?? System.out.print("What is " + number1 + " + " + number2 + "? ");int answer = input.nextInt();// 3. Grade the answer and display the resultString replyString;if (number1 + number2 == answer) {replyString = "You are correct!";correctCount++;}else {replyString = "Your answer is wrong.\n" + number1 + " + "+ number2 + " should be " + (number1 + number2);}System.out.println(replyString);// Increase the countcount++;}System.out.println("Correct count is " + correctCount);long endTime = System.currentTimeMillis();System.out.println("Time spent is " + (endTime - startTime) / 1000 + " seconds"); }}public class Exercise4_4 {public static void main(String[] args) {System.out.println("Miles\t\tKilometers");System.out.println("-------------------------------");// Use while loopint miles = 1;while (miles <= 10) {System.out.println(miles + "\t\t" + miles * 1.609);miles++;}/** Alternatively use for loopfor (int miles = 1; miles <= 10; miles++) {System.out.println(miles + "\t\t" + miles * 1.609);}*/}}public class Exercise4_6 {public static void main(String[] args) {System.out.printf("%10s%10s | %10s%10s\n", "Miles", "Kilometers", "Kilometers", "Miles");System.out.println("---------------------------------------------");// Use while loopint miles = 1; int kilometers = 20; int count = 1;while (count <= 10) {System.out.printf("%10d%10.3f | %10d%10.3f\n", miles, miles * 1.609, kilometers, kilometers / 1.609);miles++; kilometers += 5; count++;}/* Use for loopint miles = 1; int kilometers = 20;for (int count = 1; count <= 10; miles++, kilometers += 5, count++) {System.out.printf("%10d%10.3f | %10d%10.3f\n", miles, miles * 1.609, kilometers, kilometers / 1.609);}*/}}import java.util.*;public class Exercise4_8 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter the number of studentsSystem.out.print("Enter the number of students: ");int numOfStudents = input.nextInt();System.out.print("Enter a student name: ");String student1 = input.next();System.out.print("Enter a student score: ");double score1 = input.nextDouble();for (int i = 0; i < numOfStudents - 1; i++) {System.out.print("Enter a student name: ");String student = input.next();System.out.print("Enter a student score: ");double score = input.nextDouble();if (score > score1) {student1 = student;score1 = score;}}System.out.println("Top student " +student1 + "'s score is " + score1);}}public class Exercise4_10 {public static void main(String[] args) {int count = 1;for (int i = 100; i <= 1000; i++)if (i % 5 == 0 && i % 6 == 0)System.out.print((count++ % 10 != 0) ? i + " ": i + "\n"); }}/** Find the smallest number such that n*n < 12000 */public class Exercise4_12 {// Main methodpublic static void main(String[] args) {int i = 1;while (i * i <= 12000 ) {i++;}System.out.println("This number is " + i);}}public class Exercise4_14 {public static void main(String[] args) {int count = 1;for (int i = '!'; i < '~'; i++) {System.out.print((count++ % 10 != 0) ? (char)i + " " :(char)i + "\n");}}public class Exercise4_16 {// Main methodpublic static void main(String args[]) {java.util.Scanner input = new java.util.Scanner(System.in);// Prompt the user to enter a positive integerSystem.out.print("Enter a positive integer: ");int number = input.nextInt();// Find all the smallest factors of the integerSystem.out.println("The factors for " + number + " is");int factor = 2;while (factor <= number) {if (number % factor == 0) {number = number / factor;System.out.println(factor);}else {factor++;}}}}public class Exercise4_20 {// Main methodpublic static void main(String[] args) {int count = 1; // Count the number of prime numbersint number = 2; // A number to be tested for primenessboolean isPrime = true; // If the current number is prime?System.out.println("The prime numbers from 2 to 1000 are \n");// Repeatedly test if a new number is primewhile (number <= 1000) {// Assume the number is primeisPrime = true;// Set isPrime to false, if the number is primefor (int divisor = 2; divisor <= number / 2; divisor++) {if (number % divisor == 0) { // If true, the number is primeisPrime = false;break; // Exit the for loop}}// Print the prime number and increase the countif (isPrime) {if (count%8 == 0) {// Print the number and advance to the new lineSystem.out.println(number);}elseSystem.out.print(number + " ");count++; // Increase the count}// Check if the next number is primenumber++;}}}import javax.swing.JOptionPane;public class Exercise4_22 {public static void main(String[] args) {int numOfYears;double loanAmount;java.util.Scanner input = new java.util.Scanner(System.in);// Enter loan amountSystem.out.print("Enter loan amount, for example 120000.95: ");loanAmount = input.nextDouble();// Enter number of yearsSystem.out.print("Enter number of years as an integer, \nfor example 5: ");numOfYears = input.nextInt();// Enter yearly interest rateSystem.out.print("Enter yearly interest rate, for example 8.25: ");。
java英文笔试题

1.Which of the following lines will compile without warning or error.答案(5)1) float f=1.3;2) char c="a";3) byte b=257;4) boolean b=null;5) int i=10;2. What will happen if you try to compile and run the following codepublic class MyClass {public static void main(String arguments[]) {amethod(arguments);}public void amethod(String[] arguments) {System.out.println(arguments);System.out.println(arguments[1]);}}答案(1)1) error Can't make static reference to void amethod.2) error method main not correct3) error array must include parameter4) amethod must be declared with String3. Which of the following will compile without error答案(23)1) import java.awt.*;package Mypackage;class Myclass {}2) package MyPackage;import java.awt.*;class MyClass{}3) /*This is a comment */package MyPackage;import java.awt.*;class MyClass{}4. What will be printed out if this code is run with the following command line? java myprog good morningpublic class myprog{public static void main(String argv[]){System.out.println(argv[2]);}}答案(4)1) myprog2) good3) morning4) Exception raised:"ng.ArrayIndexOutOfBoundsException: 2"5. What will happen when you compile and run the following code? public class MyClass{static int i;public static void main(String argv[]){System.out.println(i);}}答案(4)1) Error Variable i may not have been initialized2) null3) 14) 06. What will happen if you try to compile and run the following code? public class Q {public static void main(String argv[]){int anar[]=new int[]{1,2,3};System.out.println(anar[1]);}}答案(3)1) 12) Error anar is referenced before it is initialized3) 24) Error: size of array must be defined7. What will happen if you try to compile and run the following code? public class Q {public static void main(String argv[]){int anar[]=new int[5];System.out.println(anar[0]);}}答案(3)1) Error: anar is referenced before it is initialized2) null3) 04) 58. What will be the result of attempting to compile and run the following code?答案(3)abstract class MineBase {abstract void amethod();static int i;}public class Mine extends MineBase {public static void main(String argv[]){int[] ar=new int[5];for(i=0;i < ar.length;i++)System.out.println(ar[i]);}}1) a sequence of 5 0's will be printed2) Error: ar is used before it is initialized3) Error Mine must be declared abstract4) IndexOutOfBoundes Error9. What will be printed out if you attempt to compile and run the following code ? int i=1;switch (i) {case 0:System.out.println("zero");break;case 1:System.out.println("one");case 2:System.out.println("two");default:System.out.println("default");}答案(3)1) one2) one, default3) one, two, default4) default10. Which of the following lines of code will compile without error答案(23)1) int i=0;if(i) {System.out.println("Hello");}2) boolean b=true;boolean b2=true;if(b==b2) {System.out.println("So true");}3) int i=1;int j=2;if(i==1|| j==2)System.out.println("OK");4) int i=1;int j=2;if(i==1 &| j==2)System.out.println("OK");11. What will be output if you try to compile and run the following code, but there is no file called Hello.txt in the current directory?.import java.io.*;public class Mine{public static void main(String argv[]){Mine m=new Mine();System.out.println(m.amethod());}public int amethod(){try{FileInputStream dis=new FileInputStream("Hello.txt");}catch (FileNotFoundException fne){System.out.println("No such file found");return -1;}catch(IOException ioe){}finally{System.out.println("Doing finally");}return 0;}}答案(3)1) No such file found2 No such file found ,-13) No such file found, Doing finally, -14) 012.Which of the following statements are true?答案(1)1) Methods cannot be overriden to be more private2) static methods cannot be overloaded3) private methods cannot be overloaded4) An overloaded method cannot throw exceptions not checked in the base class13.What will happen if you attempt to compile and run the following code?答案(3)class Base {}class Sub extends Base {}class Sub2 extends Base {}public class CEx{public static void main(String argv[]){Base b=new Base();Sub s=(Sub) b;}}1) Compile and run without error2) Compile time Exception3) Runtime Exception14.Which of the following statements are true?答案(123)1) System.out.println( -1 >>> 2);will output a result larger than 102) System.out.println( -1 >>> 2); will output a positive number3) System.out.println( 2 >> 1); will output the number 14) System.out.println( 1 <<< 2); will output the number 415.What will happen when you attempt to compile and run the following code? public class Tux extends Thread{static String sName = "vandeleur";public static void main(String argv[]){Tux t = new Tux();t.piggy(sName);System.out.println(sName);}public void piggy(String sName){sName = sName + " wiggy";start();}public void run(){for(int i=0;i < 4; i++){sName = sName + " " + i;}}}答案(4)1) Compile time error2) Compilation and output of "vandeleur wiggy"3) Compilation and output of "vandeleur wiggy 0 1 2 3"4) Compilation and output of either "vandeleur", "vandeleur 0", "vandeleur 0 1" "vandaleur 0 1 2" or "vandaleur 0 1 2 3"16.What will be displayed when you attempt to compile and run the following code//Code startimport java.awt.*;public class Butt extends Frame{public static void main(String argv[]){Butt MyBut=new Butt();}Butt(){Button HelloBut=new Button("Hello");Button ByeBut=new Button("Bye");add(HelloBut);add(ByeBut);setSize(300,300);setVisible(true);}}//Code end答案(3)1) Two buttons side by side occupying all of the frame, Hello on the left and Bye on the right2) One button occupying the entire frame saying Hello3) One button occupying the entire frame saying Bye4) Two buttons at the top of the frame one saying Hello the other saying Bye17.What will be output by the following code?public class MyFor{public static void main(String argv[]){int i;int j;outer:for (i=1;i <3;i++)inner:for(j=1; j<3; j++) {if (j==2)continue outer;System.out.println("Value for i=" + i + " Value for j=" +j); }}}答案(12)1) Value for i=1 Value for j=12) Value for i=2 Value for j=13) Value for i=2 Value for j=24) Value for i=3 Value for j=118.Which statement is true of the following code?public class Agg{public static void main(String argv[]){Agg a = new Agg();a.go();}public void go(){DSRoss ds1 = new DSRoss("one");ds1.start();}}class DSRoss extends Thread{private String sTname="";DSRoss(String s){sTname = s;}public void run(){notwait();System.out.println("finished");}public void notwait(){while(true){try{System.out.println("waiting");}catch(InterruptedException ie){}System.out.println(sTname);notifyAll();}}}答案(4)1) It will cause a compile time error2) Compilation and output of "waiting"3) Compilation and output of "waiting" followed by "finished"4) Runtime error, an exception will be thrown19.Which of the following methods can be legally inserted in place of the comment //Method Here ?class Base{public void amethod(int i) { }}public class Scope extends Base{public static void main(String argv[]){}//Method Here}答案(23)1) void amethod(int i) throws Exception {}2) void amethod(long i)throws Exception {}3) void amethod(long i){}4) public void amethod(int i) throws Exception {}20.You have created a simple Frame and overridden the paint method as followspublic void paint(Graphics g){g.drawString("Dolly",50,10);}What will be the result when you attempt to compile and run the program?答案(3)1) The string "Dolly" will be displayed at the centre of the frame2) An error at compilation complaining at the signature of the paint method3) The lower part of the word Dolly will be seen at the top of the frame, with the top hidden.4) The string "Dolly" will be shown at the bottom of the frame.21.What will be the result when you attempt to compile this program?public class Rand{public static void main(String argv[]){iRand = Math.random();System.out.println(iRand);}}答案(1)1) Compile time error referring to a cast problem2) A random number between 1 and 103) A random number between 0 and 14) A compile time error about random being an unrecognised method22.Given the following codeimport java.io.*;public class Th{public static void main(String argv[]){Th t = new Th();t.amethod();}public void amethod(){try{ioCall();}catch(IOException ioe){}}}What code would be most likely for the body of the ioCall method答案(1)1) public void ioCall ()throws IOException{DataInputStream din = new DataInputStream(System.in);din.readChar();}2) public void ioCall ()throw IOException{DataInputStream din = new DataInputStream(System.in);din.readChar();}3) public void ioCall (){DataInputStream din = new DataInputStream(System.in);din.readChar();}4) public void ioCall throws IOException(){DataInputStream din = new DataInputStream(System.in);din.readChar();}23.What will happen when you compile and run the following code?public class Scope{private int i;public static void main(String argv[]){Scope s = new Scope();s.amethod();}//End of mainpublic static void amethod(){System.out.println(i);}//end of amethod}//End of class答案(3)1) A value of 0 will be printed out2) Nothing will be printed out3) A compile time error4) A compile time error complaining of the scope of the variable i24.You want to lay out a set of buttons horizontally but with more space between the first button and the rest. You are going to use the GridBagLayout manager to control the way the buttons are set out. How will you modify the way the GridBagLayout acts in order to change the spacing around the first button?答案(2)1) Create an instance of the GridBagConstraints class, call the weightx() method and then pass the GridBagConstraints instance with the component to the setConstraints method of the GridBagLayout class.2) Create an instance of the GridBagConstraints class, set the weightx field and then pass the GridBagConstraints instance with the component to the setConstraints method of the GridBagLayout class.3) Create an instance of the GridBagLayout class, set the weightx field and then call the setConstraints method of the GridBagLayoutClass with the component as a parameter.4) Create an instance of the GridBagLayout class, call the setWeightx() method and then pass the GridBagConstraints instance with the component to the setConstraints method of the GridBagLayout class.25.Which of the following can you perform using the File class?答案(23)1) Change the current directory2) Return the name of the parent directory3) Delete a file4) Find if a file contains text or binary information26.Which statement is true of the following code?public class Rpcraven{public static void main(String argv[]){Pmcraven pm1 = new Pmcraven("One");pm1.run();Pmcraven pm2 = new Pmcraven("Two");pm2.run();}}class Pmcraven extends Thread{private String sTname="";Pmcraven(String s){sTname = s;}public void run(){for(int i =0; i < 2 ; i++){try{sleep(1000);}catch(InterruptedException e){}yield();System.out.println(sTname);}}}答案(2)1) Compile time error, class Rpcraven does not import ng.Thread2) Output of One One Two Two3) Output of One Two One Two4) Compilation but no output at runtime27.You are concerned that your program may attempt to use more memory than is available. To avoid this situation you want to ensure that the Java Virtual Machine will run its garbage collection just before you start a complex routine. What can you do to be certain that garbage collection will run when you want .答案(1)1) You cannot be certain when garbage collection will run2) Use the Runtime.gc() method to force garbage collection3) Ensure that all the variables you require to be garbage collected are set to null4) Use the System.gc() method to force garbage collection28、Which statements about the garbage collection are true?答案(2)1. The program developer must create a thread to be responsible for free the memory.2. The garbage collection will check for and free memory no longer needed.3. The garbage collection allow the program developer to explicity and immediately free the memory.4. The garbage collection can free the memory used java object at expect time.29.You have these files in the same directory. What will happen when you attempt to compile and run Class1.java if you have not already compiled Base.java//Base.javapackage Base;class Base{protected void amethod(){System.out.println("amethod");}//End of amethod}//End of class basepackage Class1;//Class1.javapublic class Class1 extends Base{public static void main(String argv[]){Base b = new Base();b.amethod();}//End of main}//End of Class1答案(4)1) Compile Error: Methods in Base not found2) Compile Error: Unable to access protected method in base class3) Compilation followed by the output "amethod"4)Compile error: Superclass Class1.Base of class Class1.Class1 not found30.What will happen when you attempt to compile and run the following codeclass Base{private void amethod(int iBase){System.out.println("Base.amethod");}}class Over extends Base{public static void main(String argv[]){Over o = new Over();int iBase=0;o.amethod(iBase);}public void amethod(int iOver){System.out.println("Over.amethod");}}答案(4)1) Compile time error complaining that Base.amethod is private2) Runtime error complaining that Base.amethod is private3) Output of "Base.amethod"4) Output of "Over.amethod"一个袋子中有100个黑球,100个白球,每次从中取出两个球,然后放回一个球,如果取出两个球颜色相同,则放入一个黑球,如果取出一百一黑,则放入一个白球,请问到最后袋中剩下的球的颜色:1)黑球2)白球3)不一定。
经典java面试英文题

1.What is the result when you compile and run the following code?public class Test{public void method(){for(int i=0;i<3;i++){System.out.print(i);}System.out.print(i);}}result: compile error分析:i是局部变量。
for循环完成后,i的引用即消失。
2.What will be the result of executing the following code?Given that Test1 is a class.class Test1{public static void main(String[] args){Test1[] t1 = new Test1[10];Test1[][] t2 = new Test1[5][];if(t1[0]==null){t2[0] = new Test1[10];t2[1] = new Test1[10];t2[2] = new Test1[10];t2[3] = new Test1[10];t2[4] = new Test1[10];}System.out.println(t1[0]);System.out.println(t2[1][0]);}}result:null null分析:new数组后,数组有大小,但值为null3.What will happen when you attempt to compile and run the following code? class Base{int i = 99;public void amethod(){System.out.println("Base.method()");}Base(){amethod();}}public class Derived extends Base{int i = -1;public static void main(String args[]){Base b = new Derived();System.out.println(b.i);b.amethod();}public void amethod(){System.out.println("Derived.amethod()");}}result:Derived.amethod()99Derived.amethod()解释:Derived 重写了Base的amethod方法。
绝对经典Java英文笔试题、答案

Question 7) Which of the following are legal identifiers
1) 2variable 2) variable2 3) _whatavariable 4) _3_ 5) $anothervar 6) #myvar
Question 2)
What will happen if you try to compile and run the following code
public class MyClass { public static void main(String arguments[]) { amethod(arguments); } public void amethod(String[] arguments) { System.out.println(arguments); System.out.println(arguments[1]); }
1) a sequence of 5 0's will be printed 2) Error: ar is used before it is initialized 3) Error Mine must be declared abstract 4) IndexOutOfBoundes Error
System.out.println(argv[2]); } }
1) myprog 2) good 3) morning 4) Exception raised: "ng.ArrayIndexOutOfBoundsException: 2"
Question 6) Which of the following are keywords or reserved words in Java?
英文java面试题(含答案)

英文java面试题(含答案)1.Tell me a little about yourselfI am holding a master degress in software science and had 2-year work experience in software development. I have used J2EE technology for 2 years,including Jsp,servlet,javabean,XML,EJB,I also used C language for half year and IBM mainframe technology half year and IBM mainframe technology half year.And the projects I participated in follow the Waterfall model lifecycle starting from design,then coding ,testing,maintenance.2.Describe a situation where you had to work under pressure,and explain how you handle it.Once when we did a mainframe project,our customer wanted to see a demo from our team before they signed the contract with our company.It is urgent,because our customer didn t give us enough time to do it. So all my team menbers had to work overtime,but we finished it punctually and perfectly . Our customer was satisfied with it.Actually,It is common to meet some deadlines or work under pressure in IT field.I am ok with it.3.What would your last employer tell me about your work performanceI am sure my last employer will praise my work performance,because he was reluctant to let me go when I told him I want to quit and study abroad,and he said I am welcome to come back when I finish study.4.What is your major weaknessI always want everything to be perfect.Sometimes,I am over-sensitive. When a design pattern or technical solution comes up during a meeting discussion,I am always the first one to test the feasibility.Some leader don t like such person because sometimes it is embarrassing when I prove it doesn t work while the leader still believe it is a perfect solution,But I think I did nothing wrong about it,it is good for the company.5.Why did you leave your last jobAlthough I did well in the last company,I always feel the theoretical study and actual practice are equally important and depend on each other.So,I decide to further study and actual practice are equally important and dependent on each other.So,I decide to further study to extend my theory in computer science.6.What are your strengthsWhat I am superior to others I believe is strong interest in software development I have.Many friends of mine working in IT field are holding bachelor degree or master degree and have worked for several years,but they don t have much interest in it,they only treat what they do everything a job,a means to survive,they don t have career plan at all. I am different. I like writing programs.I have set up my career goal long time ago.I will do my best to make it possible in the future.And I have worked hard towards this goal for several years.7.What are your future career plansI would like to be a software engineer now.but my career goal is to be an excellent software architector in the future.I like writing programs. Software is a kind of art, although sometimes it drove me crazy,after I overcame the difficulties I feel I am useful,I will keep working in IT field.8.What are your salary expectationsI believe your company will set up reasonable salary for me according to my ability,so I don t worry about it at all.Between 7000 to 8000 monthly9. Why are you interested in this position?Your company specializes in providing technical solutionsto customers and the last company I worked in also specializes in this field. I have relevant skills and experiences meeting your requirement.I am sure I can do it well.10.Do you have any questions that you would like to ask meWhat is a typical workday like and what would I doWhat is your expectation for me in this job11.What J2EE design patterns have you used beforeCommand/Session Facade/Service Locator/Data Access Object/Business Delegate。
Java笔试常见英语题(附答案)

Q1. How could Java classes direct program messages to the system console, but error messages, say to a file?.Java中如何将程序信息导航到系统的console,而把错误信息放入到一个file 中?The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:Stream st = new Stream(new FileOutputStream("output.txt"));System.setErr(st); System.setOut(st);系统有一个展现标准输出的out变量,以及一个负责标准错误设置的err变量,默认情况下这两个变量都指向系统的console,这就是标准输出如何能被改变方向(就是改变信息的输出位置)。
* Q2. What's the difference between an interface and an abstract class?抽象类和接口的区别:A. An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.抽象类中可能会含有带有方法体的一般方法,而这在接口中是不允许的。
JAVA全英试卷

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;}}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
1.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;Answer :de2. 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 fooC. 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()”Answer:c3.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. B. Eo.InsideOne ei = eo.new InsideOne();C InsideOne ei = EnclosingOne.new InsideOne();D.EnclosingOne InsideOne ei = eo.new InsideOne();Answer:aC. 4.D. 1) class Super{E. 2) public float getNum(){return 3.0f;}F. 3) }G. 4)H. 5) public class Sub extends Super{I. 6)J. 7) }K. which method, placed at line 6, will cause a compiler error?L. A. public float getNum(){return 4.0f;}M. B. public void getNum(){}N. C. public void getNum(double d){}O. D. public double getNum(float d){return 4.0d;}Answer :B5.1)public class Foo{2) public static void main(String args[]){3) try{return;}4) finally{ System.out.println("Finally");}5) }6) }what is the result?A. The program runs and prints nothing.B. The program runs and prints “Finally”.C. The code compiles, but an exception is thrown at runtime.D. The code will not compile because the catch block is missing.Answer:b6.//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? A.import java.io.PrintWriter B.include java.io.PrintWriterC.import java.io.OutputStreamWriterD.include java.io.OutputStreamWriterE.No statement is neededAnswer:a7. which three are valid declaraction of a float?A. float foo=-1;B. float foo=1.0;C. float foo=42e1;D. float foo=2.02f;E. float foo=3.03d;F. float foo=0x0123;Answer:adf8.int index=1;int foo[]=new int[3];int bar=foo[index];int baz=bar+index;what 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 compileAnswer:b9.1)int i=1,j=10;2)do{3)if(i++>--j) continue; 192837464)}while(i<5);After Execution, what are the value for i and j?A. i=6 j=5B. i=5 j=5C. i=6 j=4D. i=5 j=6E. i=6 j=6Answer: d10.1)public class X{2) public Object m(){3) Object o=new Float(3.14F);4) Object[] oa=new Object[1];5) oa[0]=o;6) o=null;7) oa[0]=null;8)System.out.println(oa[0]);9) }10) }which line is the earliest point the object a refered is definitely elibile to be garbage collectioned?A.After line 4B. After line 5C.After line 6D.After line 7E.After line 9Answer: d11.1. public class X {2. public static void main(String [] args) {3. Object o1= new Object();4. Object o2= o1;5. if(o1 .equals(o2)) {6. System.out.println("Equal");7. }8. }9. }What is the result?A. The program runs and prints nothing.B. The program runs and prints "Equal".C. An error at line 5 causes compilation to fail.D. The program runs but aborts with an exception.Answer :B12.1)public class Test{2)public static void add3(Integer i){3)int val=i.intValue();4)val+=3;5)i=new Integer(val);6)}7)public static void main(String args[]){8)Integer i=new Integer(0);9)add3(i);10)System.out.println(i.intValue()); 11)}12)}what is the result?A. compile failB.print out "0"C.print out "3"pile succeded but exception at line 3 Answer: b13.Given:1. public class Foo {2. public void main (String [] args) {3. system.out.printIn(“Hello World.”);4. }5. }What is the result?A.An exception is thrown.B.The code does not compile.C.“Hello World.” is printed to the terminal.D.The program exits without printing anything. Answer A14.Given:13. public class Foo {14. public static void main (String [] args) {15. StringBuffer a = new StringBuffer (“A”);16. StringBuffer b = new StringBuffer (“B”);17. operate (a,b);18. system.out.printIn{a + “,” +b};19. )20. static void operate (StringBuffer x, StringBuffer y) {21. y.append (x);22. y = x;23. )24. }What is the result?A.The code compiles and prints “A,B”.B.The code compiles and prints “A, BA”.C.The code compiles and prints “AB, B”.D.The code compiles and prints “AB, AB”.E.The code compiles and prints “BA, BA”.F.The code does not compile because “+” cannot be overloaded for stringBuffer.Answer B15.Given:1. public class SyncTest {2. private int x;3. private int y;4. public synchronized void setX (int i) (x=1;)5. public synchronized void setY (int i) (y=1;)6. public synchronized void setXY(int 1)(set X(i); setY(i);)7. public synchronized Boolean check() (return x !=y;)8. )Under which conditions will check () return true when called from a different class?A. Check() can never return true.B. Check() can return true when setXY is called by multiple threads.C. Check() can return true when multiple threads call setX and setY separately.D. Check() can only return true if SyncTest is changed to allow x and y to be set separately.Answer: A16.1)public class Test{2)public static void main(String[] args){3)String foo=args[1];4)Sring bar=args[2];5)String baz=args[3];6)}7)}java Test Red Green Bluewhat is the value of baz?A. baz has value of ""B. baz has value of nullC. baz has value of "Red"D. baz has value of "Blue"E. baz has value of "Green"F. the code does not compileG. the program throw an exceptionAnswer: G17.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. Answer:a18.class BaseClass{private float x=1.0f;private float getVar(){return x;}}class SubClass extends BaseClass{private float x=2.0f;//insert code}what are true to override getVar()?A.float getVar(){B.public float getVar(){C.public double getVar(){D.protected float getVar(){E.public float getVar(float f){Answer: a,b,d19.Given:int i=1,j=10;do{if(i>j)continue;j--;}while(++i<6);what are the vale of i and j?A.i=6,j=5B.i=5,j=5C.i=6,j=4D.i=5,j=6E.i=6,j=6Answer: A20.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 CAnswer: a21.which four types of objects can be thrown use "throws"?A.ErrorB.EventC.ObjectD.ExcptionE.ThrowableF.RuntimeExceptionAnswer: A,D,E,F22.1)public class Test{2) public static void main(String[] args){3) unsigned byte b=0;4) b--;5)6) }7) }what is the value of b at line 5?A.-1B.255C.127pile failpile succeeded but run errorAnswer: d23.public class ExceptionTest{class TestException extends Exception{}public void runTest() throws TestException{}public void test() /* point x */ {runTest();}}At point x, which code can be add on to make the code compile?A.throws ExceptionB.catch (Exception e)C.throws RuntimeExceptionD.catch (TestException e)E.no code is necessaryAnswer: A24.String foo="blue";boolean[] bar=new boolean[1];if(bar[0]){foo="green";}what is the value of foo?A.""B.nullC.blueD.greenAnswer: C25.which two are equivalent?A. 3/2B. 3<2C. 3*4D. 3<<2E. 3*2^2F. 3<<<2Answer: c,d26.int index=1;String[] test=new String[3];String foo=test[index];what is the result of foo?A. foo has the value “”B. foo has the value nullC. an exception is thrownD. the code will not compileAnswer: b27.which two are true?A. static inner class requires a static initializerB. A static inner class requires an instance of the enclosing classC. A static inner class has no reference to an instance of the enclosing classD. A static inner class has accesss to the non-static member of the other classE. static members of a static inner class can be referenced using the class name of the static inner classAnswer: c,e28.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 qualifiedAnswer:c29. 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.Answer:c30.public class Test{static void leftshift(int i, int j){i<<=j;}public static void main(String args[]){int i=4, j=2;leftshift(i,j);System.out.println(i);}}what is the result?A.2B.4C.8D.16E.The code will not compileAnswer: B31.You want a class to have access to members of another class in the same package which is the most restrictive access modifier that will accomplish this objective?A. publicB. privateC. protectedD. transientE. No acess modifier is requiredAnswer: e32.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.Answer: c33.public class SwitchTest{public static void main(String[] args){3) System.out.println("value="+switchIt(4));}public static int switchIt(int x){int j=1;switch(x){case 1: j++;case 2: j++;case 3: j++;case 4: j++; 2case 5: j++; 3default: j++;}return j+x; 3+4=7}}what is the output from line 3?A. value=3B. value=4C. value=5D. value=6E. value=7F. value=8 Answer: F34. 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){}Answer:d35.class A implements Runnable{public int i=1;public void run(){this.i=10;}}public class Test{public static void main(String[] args){A a=new A();11) new Thread(a).start();int j=a.i;13)}}what is the value of j at line 13?A. 1B. 10C. the value of j cannot be determinedD. An error at line 11 cause compilation to fail Answer: c36.1) public class SuperClass{2) class SubClassA extends SuperClass{}3) class SubClassB extends SuperClass{}4) public void test(SubClassA foo){5) SuperClass bar=foo; //子类对象可以赋值给超类对象6) }7) }which statement is true about the assignment in line 5?A. The assignment in line 5 is illegalB. The assignment in line 5 is legalC. legal and will always executes without throw an ExceptionD.throw a ClassCastExceptionAnswer: c37.which two declaretions prevent the overriding of a method?A. final void methoda(){}B. void final methoda(){} final voidC. static void methoda(){}D. static final void methoda(){}E. final abstract void methoda(){}Answer: ad38. 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{}Answer:d39. 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 CAnswer:f40.Click the exhibit button:1. class A {2. public int getNumber(int a) {3. return a + 1;4. }5. }6.7. class B extends A {8. public int getNumber (int a) {9. return a + 210. }11.12. public static void main (String args[]) {13. A a = new B();14. System.out.printIn(a.getNumber(0));15. }16. }What is the result?A. Compilation succeeds and 1 is printed.B. Compilation succeeds and 2 is printed.C. An error at line 8 causes compilation to fail.D. An error at line 13 causes compilation to fail.E. An error at line 14 causes compilation to fail.Answer:b41.which two interfaces provide the capability to store objects using akey-value pair?A. java.util.MapB. java.util.SetC. java.util.ListD. java.util.SortedSetE. java.util.SortedMapF. java.util.CollectionAnswer: a,e42.1. public class Test {2. private static int j=0;3.4. public static boolean methodB(int k) {5. j+=k6. return true;7. }8.9. public static void methodA(int I) {10. boolean b;11. b=i>10&methodB(1);12. b=i>10&&methodB(2);13. }14.15. public static void main(String args[]) {16. methodA(0);17.18. }19.}What is the value of j at line 17?A. 0B. 1C. 2D. 3E. The code will not compile. Answer : B43.public class Test{public static void main(String[] args){ String foo="blue";4)String bar=foo;5)foo="green";6)System.out.println(bar);}}what is the result?A.An exception is thrown.B.The code will not compile.C.The program prints “null”.D.The program prints “blue”.E.The program prints “green”. Answer: D44.class A{public int getNumber(int a){return a+1;}}class B extends A{public int getNumber(int a, char c){ return a+2;}public static void main(String[] args){B b=new B();14) System.out.println(b.getNumber(0));}}what is the result?A. compilation succeeds and 1 is printedB. compilation succeeds and 2 is printedC. An error at line 8 cause compilation to failD. An error at line 14 cause compilation to failAnswer: a45.You are assigned the task of building a Panel containing a TextArea at the top, a Labbel directly bellow it, and a Button directly bellow the Label. If the three components added directly to the Panel. which layout manager can the Panel use to ensure that the TextArea absorbs all of the free vertical space when the Panel is resized?A.GridLayoutB.CardLayoutC.FlowLayoutD.BorderLayoutE.GridbagLayoutAnswer: e46.which two are true to describe an entire encapsulation class?A. member data have no access modifiersB. member data can be modified directlyC. the access modifier for methods is protectedD. the access modifier to member data is privateE. methods provide for access and modification of dataAnswer: d,e47.public class X implements Runnable{public static void main(String[] args){3) //insert code}public void run(){int x=0,y=0;for(;;){x++;Y++;System.out.println("x="+x+",y="+y);}}}You want to cause execution of the run method in a new thread of execution. Which line(s) should be added to the main method at line 3?A. X x=new X();x.run();B. X x=new X();new Thread(x).run();C. X x=new X();new Thread(x).start();D. Thread t=new Thread(x).run();E. Thread t=new Thread(x).start();Answer: a,c48.which gets the name of the parent directory of file "file.txt"?A. String name=File.getParentName("file.txt");B. String name=(new File("file.txt")).getParent();C. String name=(new File("file.txt")).getParentName();D. String name=(new File("file.txt")).getParentFile();E. Diretory dir=(new File("file.txt")).getParentDir();String name=dir.getName();Answer: b49.The file "file.txt" exists on the file system and contains ASCII text.try{File f=new File("file.txt");OutputStream out=new FileOutputStream(f);}catch (IOException e){}A. the code does not compileB. the code runs and no change is made to the fileC. the code runs and sets the length of the file to 0D. An exception is thrown because the file is not closedE. the code runs and deletes the file from the file system Answer: c50.The file “file.txt”exists on the file system and contains ASCII text. Given:38. try {39. File f = new File(“file.txt”);40. OutputStream out = new FileOutputStream(f, true);41. }42. catch (IOException) {}What is the result?A. The code does not compile.B. The code runs and no change is made to the file.C. The code runs and sets the length of the file to 0.D. An exception is thrown because the file is not closed.E. The code runs and deletes the file from the file system.Answer :A51.import java.io.IOException;public class ExceptionTest{public static void main(String args[]){try{methodA();}catch(IOException e){System.out.println("Caught Exception");}}public void methodA(){throw new IOException();}}what is the result?A.The code will not compileB.The output is Caught ExceptionC.The output is Caught IOExceptionD.The program executes normally without printing a message Answer: a52.Which two can directly cause a thread to stop executing? (Choose Two)A. Exiting from a synchronized block.B. Calling the wait method on an object.C. Calling the notify method on an object.D. Calling the notifyAll method on an object.E. Calling the setPriority method on a thread object.Answer: B, E53.You need to store elements in a collection that guarantees that no duplicates are stored and all elements can be access in nature order, which interace provides that capability?A. java.uil.MapB.java.util.SetC.java.util.ListD.java.util.SortedSetE.java.util.SortedMapF.java.util.CollectionAnswer: B54.which two cannot directly cause a thread to stop executing?A.calling the yield methodB.calling the wait method on an objectC.calling the notify method on an objectD.calling the notifyAll method on an objectE.calling the start method on another thread objectAnswer: C,D55.Which two CANNOT directly cause a thread to stop executing? (Choose Two)A.Existing from a synchronized blockB.Calling the wait method on an objectC.Calling notify method on an objectD.Calling read method on an InputStream objectE.Calling the SetPriority method on a Thread objectANSWER:A,C56.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 scopeE. Construction of an instance of a static inner class requires an instance of the encloing outer classAnswer: d57.1. public class X {2. public object m () {3. object o = new float (3.14F);4. object [] oa = new object [1];5. oa[0]= o;6. o = null;7. oa[0] = null;8.return o;9. }10. }when is the float Object, created in line 3 ,collected as garbage?A.just after line 5B.just after line 6C.just after line 7D.never in this methodAnswer: C58.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" Answer: a59.1. public class Foo implements Runnable (2. public void run (Thread t) {3. system.out.printIn(“Running.”);4. }5. public static void main (String[] args) {6. new thread (new Foo()).start();7. )8. )what is the result?A.An Exception is thrownB.The program exits without printing anythingC.An error at line 1 causes complication to failD.An error at line 2 causes complication to failE."Running" is pinted and the program exits Answer: C60.which prevent create a subclass of outer class?A.static class FooBar{}B.pivate class Foobar{}C.abstract class FooBar{}D.final public class FooBar{}E.final abstract class FooBar{}Answer: d。