Java试题及答案英文版

合集下载

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

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英文笔试题

java英文笔试题

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

经典java面试英文题

经典java面试英文题

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英文笔试题、答案

绝对经典Java英文笔试题、答案
1) if 2) then 3) goto 4) while 5) case
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面试题(含答案)

英文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笔试常见英语题(附答案)

Q1. How could Java classes direct program messages to the system console, but error messages, say to a file?.Java中如何将程序信息导航到系统的console,而把错误信息放入到一个file 中?The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:Stream st = new Stream(new FileOutputStream("output.txt"));System.setErr(st); System.setOut(st);系统有一个展现标准输出的out变量,以及一个负责标准错误设置的err变量,默认情况下这两个变量都指向系统的console,这就是标准输出如何能被改变方向(就是改变信息的输出位置)。

* Q2. What's the difference between an interface and an abstract class?抽象类和接口的区别:A. An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.抽象类中可能会含有带有方法体的一般方法,而这在接口中是不允许的。

JAVA全英试卷

JAVA全英试卷

1.Which of the following statements compiles OK?A. String #name = "Jane Doe";B. int $age = 24;C. Double _height = "123.5";D. double ~temp = 37.5;2.What are the extension names of Java source file and executable file?A. .java and .exeB. .jar and .classC. .java and .classD. .jar and .exe3.Given:10. class CertKiller {11. static void alpha() { /*more code here*/ }12. void beta() { /*more code here*/ }13. }Which statement is wrong?A. CertKiller.beta() is a valid invocation of beta()B. CertKiller.alpha() is a valid invocation of alpha()C. Method beta() can directly call method alpha()D. The method beta() can only be called via references to objects of CertKiller 4.Which method name does not follow the JavaBeans standard on Accessor/Mutator?A. getSizeB. setCustC. notAvailableD. isReadable5.Read the following class ClassA, which statement is correct after executing “new ClassA().getValue();”public class ClassA {public int getValue() {int value = 0;boolean setting = true;String title = "Hello";if (value || (setting && title == "Hello")) { return 1; }if (value == 1 & title.equals("Hello")) { return 2; }}}A. There is compilation error for ClassAB. It outputs 2C. It outputs 1D. Executes OK, but no output6.Given:public void testIfA() {if (testIfB("true")) {System.out.println("True");} else {System.out.println("Not true");}}public Boolean testIfB(String str) {return Boolean.valueOf(str);}What is the result when method testIfA is invoked?A. TrueB. Not trueC. An exception is thrown at runtimeD. Compilation fails7.Given:public class Pass {public static void main(String[] args) {int x = 5;Pass p = new Pass();p.doStuff(x);System.out.print(" main x = " + x);}void doStuff(int x) {System.out.print("doStuff x = " + x++);}}What is the result?A. doStuff x = 6 main x = 6B. doStuff x = 5 main x = 5C. doStuff x = 5 main x = 6D. doStuff x = 6 main x = 5 8.Given:String a = "str";String b = new String("str");String c = "str";System.out.print(a == b);System.out.print(a == c);What is the result?A. truefalseB. truetrueC. falsetrueD. falsefalse9.Given:33. try {34. // smoe code here35. } catch (NullPointerException el) {36. System.out.print("a");37. } catch (RuntimeException el) {38. System.out.print("b");39. } finally {40. System.out.print("c");41. }What is the result if NullPointerException occurs on line 34?A. acB. abcC. cD. No output10.Which of the following statements is correct about Java package?A. If there is no package statement used, the current class will not be in any package.B. Package is a way to manage source code, each package contains several “.java” files.C. Using one “import” statement can include the classes from one or more packages.D. A package can contain sub-packages.11.Given:1. public class Target {2. private int i = 0;3. public int addOne() {4. return ++i;5. }6. }And:1. public class Client {2. public static void main(String[] args) {3. System.out.println(new Target().addOne());4. }5. }Which change can you make to Target without affecting Client?A. Line 4 of class Target can be changed to return i++;B. Line 2 of class Target can be changed to private int i = 1;C. Line 3 of class Target can be changed to private int addOne() {D. Line 2 of class Target can be changed to private Integer i = 0;12.Given:public abstract class Shape {int x;int y;public abstract void draw();public void setAnchor(int x, int y){this.x = x;this.y = y;}}And a class Circle that extends and fully implements the Shape class. Which is correct?A. Shape s = new Shape();s.setAnchor(10, 10);s.draw();B. Circle c = new Shape();c.setAncohor(10, 10);c.draw();C. Shape s = new Circle();s.setAnchor(10, 10);s.draw();D. Shape s = new Circle();s.Shape.setAnchor(10, 10);s.shape.draw();13.In Java event handling model, which object responses to and handles events?A. event source objectB. listener objectC. event objectD. GUI component object14.Given:public static void main(String[] args) {System.out.print(method2(1, method2(2, 3, 4)));}public int method2(int x1, int x2) {return x1 + x2;}public float method2(int x1, int x2, int x3) {return x1 + x2 + x3;}What is the result?A. Compilation failsB. 0C. 10D. 915.Given:public class Test {public Test() {System.out.print("test ");}public Test(String val) {this();System.out.print("test with " + val);}public static void main(String[] args) {Test test = new Test("wow");}}What is the result?A. testB. test test with wowC. test with wowD. Compilation fails16.Given:public class ItemTest {private final int id;public ItemTest(int id) { this.id = id; }public void updateId(int newId) { id = newId; }public static void main(String[] args) {ItemTest fa = new ItemTest(42);fa.updateId(69);System.out.println(fa.id);}}What is the result?A. Compilation failsB. An exception is thrown at runtimeC. A new Item object is created with the preferred value in the id attributeD. The attribute id in the Item object remains unchanged17.Method m() is defined as below in a parent class, which method in the sub-classes overrides the method m()?protected double m() { return 1.23; }A. protect int m() { return 1; }B. public double m() { return 1.23; }C. protected double m(double d) { return 1.23; }D. private double m() { return 1.23; }18.Given:1. public class abc {2. int abc = 1;3. void abc(int abc) {4. System.out.print(abc);5. }6. public static void main(String[] args) {7. new abc().abc(new abc().abc);8. }9. }Which option is correct?A. Compilation fails only at line 2, 3B. Compilation fails only at line 7C. Compilation fails at line 1, 2, 3, 4D. The program runs and outputs 1 19.Which declaration is correct?A. abstract final class Hl { }B. abstract private move() { }C. protected private number;D. public abstract class Car { }20.Given:public class Hello {String title;int value;public Hello() {title += "World";}public Hello(int value) {this.value = value;title = "Hello";Hello();}}And:Hello c = new Hello(5);System.out.println(c.title);What is the result?A. HelloB. An exception is thrown at runtimeC. Hello WorldD. Compilation fails21.Given:public abstract interface Frobnicate {public void twiddle(String s);}Which is a correct class?A. public abstract class Frob implements Frobnicate {public abstract void twiddle(String s) { }}B. public abstract class Frob implements Frobnicate { }C. public class Frob extends Frobnicate {public void twiddle(Integer i) { }}D. public class Frob implements Frobnicate {public void twiddle(Integer i) { }}22.Which statement is true about has-a and is-a relationships?A. Inheritance represents an is-a relationship.B. Inheritance represents a has-a relationship.C. Interfaces must be use when creating a has-a relationship.D. Instance variables must be used when creating an is-a relationship.23.Which option has syntax error?class Animal { … }class Dog extends Animal { … }class Cat extends Animal { … }A. Animal animal = new Dog();B. Cat cat = (Cat) new Animal();C. Dog dog = (Dog) new Cat();D. Cat cat = new Cat();24.Assume that class A is a sub-class of class B, which of the following figures illustrates their relationship?A.B.C.D.25.Given:public class Plant {private String name;public Plant(String name) { = name }public String getName() { return name; }}public class Tree extends Plant {public void growFruit() {}public void dropLeaves() {}}Which statement is true?A. The code will compile without changes.B. The code will compile if the following code is added to the Plant class:public Plant() { this("fern"); }C. The code will compile if the following code is added to the Plant classpublic Plant(){Plant("fern");}D. The code will compile if the following code is added to the Tree class:public Tree() { Plant(); }26.Which of the following statement is correct about exception handling?A. Exception is an error occurred in runtime, so it should be avoided by debugging.B. Exception is described by the form of objects, their classes are organized by a single-root inheritance hierarchy (级联结构).C. There is no exception any more after executing a try-catch-finally structure.D. In Java, all exceptions should be caught and handled in runtime.27.What are the two major parts of an object?A. property and behaviorB. identity and contentC. inheritance and polymorphismD. message and encapsulation28.Which is the correct output according to the program given bellow?public static void main(String[] args) {Scanner scanner = new Scanner("this is one that is two");eDelimiter(" is"); // there is a space before "is"while (scanner.hasNext()) {System.out.print(scanner.next());}}A. this one that twoB. th one that twoC. thone that twoD. this is one that is two 29.Which fragment can not correctly create and initialize an int array?A. int[] a = {1, 2};B. int[] a; a = new int[2]; a[0] = 1; a[1] = 2;C. int[] a = new int[2]{1, 2};D. int[] a = new int[]{1, 2};30.What is the output of the following program?String s1 = "Java";String s2 = new String("Java");System.out.println((s1 == s2) + "," + (s1.equals(s2)));A. true,trueB. true,falseC. false,trueD. false,false1.(6 points)public class Bootchy {int bootch;String snootch;public Bootchy() {this("snootchy");System.out.print("first ");}public Bootchy(String snootch) {this(420, "snootchy");System.out.print("second ");}public Bootchy(int bootch, String snootch) {this.bootch = bootch;this.snootch = snootch;System.out.print("third ");}public static void main(String[] args) {Bootchy b = new Bootchy();System.out.print(b.snootch + " " + b.bootch);}}third second first snootchy4202.(6 points)public class TestJava {class A {public A(int v1, int v2) {this.v1 = v1; this.v2 = v2;}int v1; int v2;}void m1(A a1, A a2) {A t; t = a1; a1 = a2; a2=t;}void m2(A a1, A a2) {A t = new A(a1.v1, a1.v2);a1 = new A(a2.v1, a2.v2);a2 = new A(t.v1, t.v2);}void m3(A a1, A a2) {A t = a1;a1.v1 = a2.v1; a1.v2 = a2.v2;a2.v1 = t.v1; a2.v2 = t.v2;}public static void main(String[] args) {TestJava tj = new TestJava();A a1 = tj.new A(0, 2);A a2 = tj.new A(1, 3);tj.m1(a1, a2);System.out.println(a1.v1+ " " + a2.v2 + " ");tj.m2(a1, a2);System.out.println(a1.v1+ " " + a2.v2 + " ");tj.m3(a1, a2);System.out.println(a1.v1+ " " + a2.v2 + " ");} 0 3} 0 31 3Given:interface Repeater {/*** Repeat the char `c' n times to construct a String.* @param c the character to be repeated* @param n the times of repeat* @return a string containing all the `c'*/String repeat(char c, int n);}public static void main(String[] args) {Repeater arrayRepeater = new ArrayRepeater(); //(1)Repeater stringRepeater = new StringRepeater(); //(2)Repeater stringBufferRepeater = //(3)Repeater r = //(4)long startTime = System.nanoTime();for (int i = 0; i < 1000; i++) {r.repeat('s', 10000);}long endTime = System.nanoTime();long duration = endTime - startTime;System.out.println(duration);}1. Complete the definition of class ArrayRepeater which appears at //(1) to implement the Repeater by constructing the string using new String(char[]).2. Complete the definition of class StringRepeater which appears at //(2) to implement the Repeater using string concatenation (use + to join strings).3. Complete the definition of strigBufferRepeater at //(3) by defining an anonymous class implementing Repeater (i.e. new Repeater(){ ... }), using StringBuffer to construct the required string.4. The code below //(4) is designed to test the performance of Repeater r. By assigning different implementation of Repeater to r, the code can output the consumed time (duration). Answer the question: arrayRepeater, stringRepeater, stringBufferRepeater, which consumes the longest time?---------------------------------------------------------------------------(1)class ArrayRepeater implements Repeater{public String repeat(char c ,int n){char[] arr = new char[n];for(int i=0;i<n;i++){arr[i]='c';}String s = new String(arr);return s;}}(2)class StringRepeater implements Repeater {public String repeat(char c,int n){String s ="";for(int i=0;i<n;i++){s=s+'c';}return s;}}(3)new Repeater(){public String repeat(char c,int n){StringBuffer bf = new StringBuffer();for(int i=0;i<n;i++){bf.append('c');}return bf.toString();}};(4) arrayRepeaterusing the knowledge of interface and polymorphism. (12 points)public class Test {public static void main(String[] args) {Object[] shapes = { new Circle(5.0), //(3)new Rectangle(5.0, 4.5), //(4)new Circle(3.5) }; //(5)System.out.println("Total Area: " + sumArea(shapes));}public static double sumArea(Object[] shapes) {double sum = 0;for(int i = 0; i < shapes.length; i++) {if (shapes[i] instanceof CalcArea) { //(1)sum += ((CalcArea) shapes[i]).getArea(); //(2)}}return sum;} }The interface CalcArea in comment //(1) and //(2) is undefined; the class Circle and Rectangle in comment //(3), //(4) and //(5) are undefined either. Please define: 1.interface CalcArea2.class Circle3.class Rectangleinterface CalcArea{double getArea();}class Circle implements CalcArea{private double radius;public Circle(double radius){this.radius = radius;}public double getArea(){return Math.PI*radius*radius;}}class Rectangle implements CalcArea{private double width,height;public Rectangle(double width,double heigth){this.width = width;this.height = height;}public double getArea(){return width*height;}}。

Java英文面试题

Java英文面试题

英文Java tm试题Question: What is transient variable?Answer: Transient variable 臼n't be serialize. For example if a variable is declared as transient in a Serializable c1ass and the c1ass is written to an ObjectStream,the value of the variable can't be wn忧en to the stream instead when the c1ass is retrieved from the ObjectStream the value of the variable becomes nullQuestion: Name the containers which uses Border Layout as their default layout?Answer: Containers which uses Border Layout as their default are: window,Frame and Dialogc1asses.Question: What do you understand by Synchronization?Answer: Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application,it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronizationprevents such type of data corruptionE.g. Synchronizing a function:public synchronized void Methodl 0 {j j Appropriate method-related code.E.g. Synchronizing a block of code inside a function:public myFunction O{synchronized (this) {j j Synchronized code here.Question: What is Collection API?Answer: The Collection API is a set of c1asses and interfaces that support operation on collectionsof objects. These classes and interfaces are more flexi.ble,more powerfu,lthe vectors,arrays,and hashtables if e仔'ectively replaces.and more regular thanExample of c1asses: HashSet,HashMap,Array List,LinkedList,TreeSet and TreeMap. Example of interfaces: Collection,5时,List and Map.Question: Is Iterator a Class or Interface? What is its use?Answer: Iterator is an interface which is used to step through the elements of a Collection.Question: What is similaritiesjdifference between an Abstract c1ass and Interface? Answer: Differences are as follows:Interfaces provide a form of multiple inheritance. A class can extend only one other classInterfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation,protected parts,static methods,etc.A Class may implement several interfaces. But in case of abstract class ,a class may extend only one abstract class.Interfaces are slow as it requires extra indirection to find corresponding method in the actual class. Abstract classes are fast.Similarities:Neither Abstract classes or Interface can be instantiated. Question: How to define an Abstract class?Answer: A class containing abstract method is called Abstract class. An Abstract class can't be instantiated.Example of Abstract class:abstract c lass testAbstractClass { protected String myString; public String getMγStringO {return myString;public abstract string anyAbstractFunctionO;Question: How to define an Interface?Answer: In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.Emaple of Interface:public interface samplelnterface {public void functionOneO;public long CONSTANT_ONE = 1000;Question: Explain the user defined Exceptions?Answer: User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.Example:class myCustomException extends Exception {// The class simply has to exist to be an exceptionQuestion: Explain the new Features of JDBC 2.0 Core API?Answer: The JDBC 2.0 API includes the complete JDBC API ,which includes both core and OptionalPackage API,and provides inductrial-strength database computing capabilitiesNew Features in JDBC 2.0 Core API:Scrollable result sets- using new methods in the ResultSet interface allows programmatically move the to particular row or to a position relative to its current position JDBC 2.0 Core API provides the Batch Updates functionality to the java applicationsJava applications can now use the ResultSet.updateXXX methods. New data types - interfaces mapping the SQL3 data typesCustom mapping of user-defined types (UTDs)Miscellaneous features,including performance hints,the use of character streams,full precision for java.math.BigDecimal values ,additional security,and support for time zones in date,time,and timestamp values.Question: Explain garbage collection?Answer: Garbage collection is one of the most important feature of Java. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program cann't directly free the object from memory,instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method fromng.Object,the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java ,it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(),JVM tries to recycle the unused objects,but there is no guarantee when all the objects will garbage collected.Question: How you can force the garbage collection?Answer: Garbage collection automatic process and can't be forced.Question: What is OOPS?Answer: OOP is the common abbreviation for Object-Oriented Programming.Question: Describe the principles of OOPSAnswer: There are three main principals of oops which are called Polymorphism,Inheritance andQuestion: Explain the Encapsulation principle.Answer: Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.Question: Explain the Inheritance principle.Answer: Inheritance is the process by which one object acquires the properties of another object.Question: Explain the Polymorphism principle.Answer: The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can beexplained as "one interface,multiple methods".Question: Explain the different forms of Polymorphism.Answer: From a practical programming viewpoint,polymorphism exists in three distinct forms inJava:Method overloadingMethod overriding through inheritanceMethod overriding through the Java interfaceQuestion: What are Access Specifiers available in Java?Answer: Access specifiers are keywords that determines the type of access to the member of a class. These are:Public Protected Private DefaultsQuestion: Describe the wrapper classes in Java.Answer: Wrapper class is wrapper around a primitive data type. An instance of a wrapper classFollowing table lists the primitive types and the corresponding wrapper classes:Primitive Wrapperboolean java .lang.Boolean byte j ava .lang.Bytechar java .lang.Character double ng.Double float ng.Floatint ng.lnteger long java .lang.Long short ng.Short void ngV oidQuestion: Read the following program:public class test {public static void main(String [] args) {int x = 3;int y = 1;if (x = y)System.out.println("Not equal");elseSystem.out.printl叫"Equal");What is the result?A. The output is equal?br>causes compilation to fall.B. The output in not Equal?br>C.An error at " if (x =γ)"D. The program executes but no output is show on console. Answer: CQuestion: what is the class variables ?Answer: When we create a number of objects of the same class,then each object will share a common copy of variables. That means that there is only one copy per class ,no matter how many objects are created from it. Class variables or static variables are declared with the statickeyword in a class,but mind it that it should be declared outside outside a class. These variables are stored in static memory. Class variables are mostly used for constants,variable that neverchange its initial value. Static variables are always called by the class name. This variable is created when the program sta内s i.e. it is created before the instance iscreated of class by using new operator and gets destroyed when the programs stops. The scope of the class variable is same a instance variable. The class variable can be defined anywhere at class level with the keyword static. It initial value is same as instance variable. When the class variable is defined asint then it's initial value is by default zero,when declared boolean its default value is false andnull for object references. Class variables are associated with the class,rather than with any object.Question: What is the difference between the instanceof and getclass,these two are same or not 7Answer: instanceof is a operator ,not a function while getClass is a method of ng.Objectclass. Consider a condition where we use if(o.getClassO.getNameO.equals("java.Iang.Math")){ } This method only checks if the classname we have passed is equal to java .lang.Math. The class ng.Math is loaded by the bootstrap Classloader. This class is an abstract class .This class loader is responsible for loading classes. Every Class object contains a reference to the Classloader that defines. getClassO method returns the runtime class of an object. It fetches thejava instance of the given fully qualified type name. The code we have written is not necessary,because we should not compare getClass.getNameO. The reason behind it is that if the two different class loaders load the same class but for the JVM,it will consider both classes as different classes so,we can't compare their names. It can only gives the implementing class but can't compare a interface,but instanceof operator can.The instanceof operator compares an object to a specified type. We can us.e it to test if an object is an instance of a class,an instance of a subclass,or an instance of a class that implements a particular interface. We should try to use instanceof operator in place of getClassO method. Remember instanceof opeator and getClass are not same. Try this example ,it will help you to better understand the difference between the tWO.Interface one{Class Two implements one { Class Three implements one {public class Test {public static void main(String args[]) {one test1 = new TwoO;one test2 = new Three();System.out.println(testilnstanceof one);//trueSystem.out.println(test2 instanceof one);//trueSystem.out.println(Test.get ClassO.equals(test2.getClass()));//false* 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 inheri tance. 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.gcO. JVM does not guarantee that GCwill 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 waitOA. 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 notifyAII() call. The method waitO 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 mainO 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 CLASSPATHenvironment 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 mainO,you could test it from a commandprompt 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 equalsO?A. I'd use the method equalsO to compare the values of the 5trings and the == to check if two variables point at the same instance of a 5tring object.* Q15. D oes it matter in what order catch statements for FileNotFoundException andIOExceptipon are written?A. Yes,it does. The FileNoFoundException is inherited from the IOException.Exception's subclasses have to be caught first.* Q16. Can an inner class declared inside of a method access local variables of this method? A. It's possible if these variables are final.* Q17. What can go wrong if you replace && with & in the following code:5tring a=null;if (a!=null && a.lengthO>10) {...}A. A single ampersand here would lead to a 队1ullPointerException* Q18. What's the main difference between a Vector and an ArrayListA. Java Vector class is internally synchronized and ArrayList is not.* Q19. When should the method invokeLaterObe used?A. This method is used to ensure that 5wing components are updatedthrough the event-dispatching thread* Q20. How can a subclass call a method or a constructor defined in a superclass?A. Use the following syntax: super.myMethodO; To call a constructor of the superclass ,just write superO;in the first line of the subclass's constructor.For senior-Ievel developers:忡Q21.What's the difference between a queue and a stack?A. 5tacks works by last-in-first-out rule(LlFO),while queues use the FIFO rule忡Q22. You can create an abstract class that contains only abstract methods. On the other hand,you can create an interface that declares the same methods. 50 can you use abstract classes instead of interfaces?A. Sometimes. But your class may be a descendent of another class and in this case the interface is your only option机Q23. What comes to mind when you hear about a young generation in Java? A. Garbage collection.时Q24. What comes to mind when someone mentions a shallow copy in Java?A.Object cloning.时Q25. If you're overriding the method equalsO of an object,which other method you might also consider?A. hashCodeO忡Q26. You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:Array List or LinkedList?A. ArrayList时Q27. How would you make a copy of an entire Java object with its state? A. Have this class implement Cloneable interface and call its method cloneO.忡Q28. How can you minimize the need of garbage collection and make the memory use more effective?e object pooling and weak object references.** Q29. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?A. If these classes are threads I'd consider notifyO or notifyAIIO. For regular classes you can use the Observer interface.时Q30. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?A. You do not need to specify any access level,and Java will use a default package access level.The J2EE questions are coming soon. Stay tuned for Yakov Fain on Live SYS-CON川/. Ask yourquestions to Yakov on the air!IBM java 英文面试题1.what is oracle.2.what is major differenece oracle8i and oracle9i.4.tell me some thing ur self.5.please tell me about oops.6.what is single inheritance.7.what is multiple inheritance.8.can java support multiple inheritance.9.what is interface1O.what is differenec between abstract class and interface.11.how to u prove that abstrace class cannot instantiate directly.12.what is differenece between string and stringbu仔er.13.what is immutable14.how to write a program using sort program.15 how to write a program using unsort program.16.what is legacy.17.what is legacy api18.what is legacy interface.19.what is main difference hashmap and hastable20.what is main difference between arraylist and vector.2 1.what is struts framework.22.what are distributed techonologies.23.what is advantage and disadvantage of distributed techonologies.24.what is main difference between jsp and servlets.25.what is difference between procedure and functions26.what is jdbc.27.what are type of drivers.28.what is type 4 driver.29.how to collect requuirements form u r client.30.which process use in ur project.31.what is deployment descriptor.32.what is heirarchy of files in struts.33.please draw struts frame wrok34.please draw j2ee architecture.35.please draw mvc-2 architecture.36.please draw that how design op module.37.how to find a file on linux.38.how to configure weblogic8.1on linux.39.why you use struts framework in ur project.ans:lnterface has only method declarations but no defn10.what is differenec between abstract class and interfaceans:ln abstract class some methods may contain definition,but in interface every method should be abstract11.how to u prove that abstrace class cannot instantiate directly. ans:As they dont have constructor they cant be instantiated12.what is differenece between string and stringbu仔er. ans:Strings are immutable where as string buffer can be modified13.what is immutable ans:Which cant be changed14.how to write a program using sort program.15 how to write a program using unsort program. ans: Both can be done using javascriptThis is for 50rtfunction SelectTextSort(obj) { // sort by text var N=obj.options.length;for (var i=O;i<N-1;i++) {for (var j=i吐;j<N;j++) {if ( obj.options[i].te对> obj.optionsÜ].text ) {var i1= (obj.options[i].selected == true ) ? true : false var j1= (obj.options[j].selected == true ) ? true : false var q1= obj.options[j].text;var q2 = obj.options[j].value; obj.optionsÜ].text = obj.options[i]坦xt; obj.options[j].value = obj.options[i].value; obj.options[i].text = q1;obj.options[i].value = q2;obj.options[i].selected =(j1&& true ) ? true : false obj.options[j].selected = (i1&& true ) ? true : falsereturn true16.what is legacy.17.what is legacy api18.what is legacy interface.ans: legacy is something that is old in terms of technology/ system19.what is main difference hashmap and hastable ans:Hash table is synchronised20.what is main difference between arraylist and vectorans:Vector is synchronised21.what is struts framework.22.what are distributed techonologiesdistributed technologies means any technology / s/w program that are having many components in multiple environments that interact with each other depending on the functional requirements and design.23.what is advantage and disadvantage of distributed techonologies.overdependance on single platform / single language is avoided. Application can be built flexible to meet requirements. Oivision of labour is possible. Best of all the technologies and platforms can be optimally utilized. Complexity of requirements can be reduced.25.what is difference between procedure and functions.' ans:Fuctions can return value ,procedures cant return value26.what is jdbcans:Connecting to OB from java program requires JOBC27.what are type of drivers.type1,2,3 ,429.how to collect requuirements form u r client.is not a job of a technical person. It is better for a BA to do it30.which process use in ur project. Generally u can say:Project related process: Analysis,Design,Sign-off Documents,Implementation,Integration,Testing,UATWork related process:Technical Design ,Work Allocation,Code Review Checklist,Unit Test Form will be prepared by theProject lead and given to the developer. Developer prepares the Unit Test CaseImplements Code,Performs TestSubmits Code through CVS / VSSSubmits documents along with Release Checklist to the tester / leader.31.what is deployment descriptor.ans:Which contains the infrnmation like which file to be used40.what is platfrom independentans:A language is said to be platform independent if it can be run on any machine with out modifying code41.what is awt and swing.ans:AWT are heavy weight components and swings are light weight components46.what is major concepts in oopsans:Abstraction,polymorphism,encapsulation,inheritance47.why u choose m时-2 architecture.ans:ln MVC-2 controller is servlet rather than JSP which makes it efficient48.what is implicit object.ans:lmplicit objects are a set of Java objects that the JSP Container makes available to developers in each page49.how many implicit objects in jspans:out,page,session,request,response,application,page context,config。

java考试选择题英文版

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英文面试题(含部分参考答案)-烽火通信1.what is oracle.2.what is major differenece oracle8i and oracle9i.4.tell me some thing ur self.5.please tell me about oops.6.what is single inheritance.7.what is multiple inheritance.8.can java support multiple inheritance.9.what is interface.10.what is differenec between abstract class and interface.11.how to u prove that abstrace class cannot instantiate directly.12.what is differenece between string and stringbuffer.13.what is immutable14.how to write a program using sort program.15 how to write a program using unsort program.16.what is legacy.17.what is legacy api18.what is legacy interface.19.what is main difference hashmap and hastable20.what is main difference between arraylist and vector.21.what is struts framework.22.what are distributed techonologies.23.what is advantage and disadvantage of distributed techonologies.24.what is main difference between jsp and servlets.25.what is difference between procedure and functions.26.what is jdbc.27.what are type of drivers.28.what is type 4 driver.29.how to collect requuirements form u r client.30.which process use in ur project.31.what is deployment descriptor.32.what is heirarchy of files in struts.33.please draw struts frame wrok.34.please draw j2ee architecture.35.please draw mvc-2 architecture.36.please draw that how design op module.37.how to find a file on linux.38.how to configure weblogic8.1 on linux.39.why you use struts framework in ur project.40.what is platfrom independent41.what is awt and swing.42.what is heavy wieght components.43.what is feature of weblgoic8.1.44.why you choose application server on linux and database server on aix.45.please tell me about ur project.46.what is major concepts in oops.47.why u choose mvc-2 architecture.48.what is implicit object.49.how many implicit objects in jsp—————————————————————————————————————————————————————————1. Oracle is an RDBMS product with DDL and DML from a company called Oracle Inc.2. Difference between 8i and 9i is given in the Oracle site3. Question not available4. Something5. oops is Object Oriented Programming6.what is single inheritance.ans:one class is inherited by only other one class7.what is multiple inheritance.ans:One class inheriting more than one class at atime8.can java support multiple inheritance.ans:No9.what is interface.ans:Interface has only method declarations but no defn10.what is differenec between abstract class and interface.ans:In abstract class some methods may contain definition,but in interface every method should be abstract11.how to u prove that abstrace class cannot instantiate directly.ans:As they dont have constructor they cant be instantiated12.what is differenece between string and stringbuffer.ans:Strings are immutable where as string buffer can be modified13.what is immutableans:Which cant be changed14.how to write a program using sort program.15 how to write a program using unsort program.ans: Both can be done using javascriptThis is for Sortfunction SelectTextSort(obj) { // sort by textvar N=obj.options.length;for (var i=0;ifor (var j=i+1;jif ( obj.options[i].text > obj.options[j].text ) {var i1= (obj.options[i].selected == true ) ? true : falsevar j1= (obj.options[j].selected == true ) ? true : falsevar q1 = obj.options[j].text;var q2 = obj.options[j].value;obj.options[j].text = obj.options[i].text;obj.options[j].value = obj.options[i].value;obj.options[i].text = q1;obj.options[i].value = q2;obj.options[i].selected = (j1 && true ) ? true : falseobj.options[j].selected = (i1 && true ) ? true : false}}}return true}16.what is legacy.17.what is legacy api18.what is legacy interface.ans: legacy is something that is old in terms of technology/ system19.what is main difference hashmap and hastableans:Hash table is synchronised20.what is main difference between arraylist and vector.ans:Vector is synchronised21.what is struts framework.22.what are distributed techonologies.distributed technologies means any technology / s/w program that are having many components in multiple environments that interact with each other depending on the functional requirements and design.23.what is advantage and disadvantage of distributed techonologies.overdependance on single platform / single language is avoided. Application can be built flexible to meet requirements. Division of labour is possible. Best of all the technologies and platforms can be optimally utilized. Complexity of requirements can be reduced.25.what is difference between procedure and functions.'ans:Fuctions can return value ,procedures cant return value26.what is jdbc.ans:Connecting to DB from java program requires JDBC27.what are type of drivers.type1,2,3,429.how to collect requuirements form u r client.is not a job of a technical person. It is better for a BA to do it.30.which process use in ur project.Generally u can say:Project related process: Analysis, Design, Sign-off Documents, Implementation, Integration, Testing, UAT Work related process:Technical Design, Work Allocation, Code Review Checklist, Unit Test Form will be prepared by the Project Lead and given tothe developer.Developer prepares the Unit Test CaseImplements Code, Performs TestSubmits Code through CVS / VSSSubmits documents along with Release Checklist to the tester / leader.31.what is deployment descriptor.ans:Which contains the infrnmation like which file to be used 不好意思,暂缺32到39的参考答案.40.what is platfrom independentans:A language is said to be platform independent if it can be run on any machine with out modifying code41.what is awt and swing.ans:AWT are heavy weight components and swings are light weight components46.what is major concepts in oops.ans:Abstraction,polymorphism,encapsulation,inheritance47.why u choose mvc-2 architecture.ans:In MVC-2 controller is servlet rather than JSP which makes it efficient48.what is implicit object.ans:Implicit objects are a set of Java objects that the JSP Container makes available to developers in each page49.how many implicit objects in jspans:out,page,session,request,response,application,page context,config转载请注明文章来源:笔试网/doc/2b1197711.html,—专业的笔试、面试资料搜索网站,原文网址:/doc/2b1197711.html,/shiti.aspx?id=536157。

java英语笔试试题及答案

java英语笔试试题及答案

java英语笔试试题及答案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英文笔试题
13.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 error 2) Compile time Exception 3) Runtime Exception 14.Which of the following statements are true? 答案(123) 1) System.out.println( -1 >>> 2);will output a result larger than 10 2) System.out.println( -1 >>> 2); will output a positive number 3) System.out.println( 2 >> 1); will output the number 1 4) System.out.println( 1 <<< 2); will output the number 4
3) 0 4) 5
8. 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++)

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试卷 英文

18—英语版Java程序设计模拟试题2Java程序设计模拟试题2(双语)一.选择题(每题2分,共40分)1.Which choice is the range of byte type( )a) -128 to 127b) (-2 power 8 )-1 to 2 power 8c) -255 to 256d) depends on the Java Virtual machine2.What will be printed when System.out.println(4 | 010) is called:( )a) 14 ; b) 0 ; c) 6 ; d) 123.Given this class:class A {public int x;private int y;class B {protected void method1() {}class C {private void method2() {}}}}class D extends A {public float z;}The mothod2() can access (3个):()a) the variable x in class A;b) the variable y in class Ac) the method1() in class B ; d) the variable z in class D4.Given a interface(2):interface A {int method1(int i);int method2(int j);}Which class implement the interface ()a)class B implements A {int method1() { }int method2() { }}b)class B {int method1(int i) { }int method2(int j) { }}c)class B implements A {int method1(int i) { }int method2(int j) { }}d)class B extends A {int method1(int i) { }int method2(int j) { }}e)class B implements A {int method2(int j) { }int method1(int i) { }}5.What can be printed when the following fragment running:()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");a) a b) b c) c d) d6.Which is correct about the following sentence:()String[][] s = new String[10][];a) the statement contains a error;b) s is a array of 10 rows and 10 columns;c) s is a array containing 10 arrays;d) the element value of s is “”;e)the array should be initialized before used7.What will occur when compiling and running the following class :()class Test {static int myArg = 1;public static void main(String[] args) {int myArg;System.out.println(myArg);}}a) the output result is 0;b) the output result is 1;c) Can not be compiled successfully because the local variable name is same to static variabled) Can not be compiled successfully,because the local variable must be initialized before used。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 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。

相关文档
最新文档