JAVA双语教学考试试卷及答案A
- 格式:docx
- 大小:41.28 KB
- 文档页数:18
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. Java语言的特点是什么?A. 面向过程B. 面向对象C. 编译型语言D. 解释型语言答案:B2. 在Java中,用哪个关键字可以定义一个类?A. publicB. classC. voidD. int答案:B3. 下列哪个是Java的合法标识符?A. 2classB. class#2C. _class2D. class:2答案:C4. Java中的main()方法必须定义为什么类型的参数?A. intB. StringC. voidD. None答案:D5. 在Java中,哪个关键字用于实现异常处理?A. tryB. catchC. throwD. All of the above答案:D二、多选题6. 下列哪些是Java的基本数据类型?A. intB. StringC. floatD. boolean答案:A, C, D7. 在Java中,哪些是合法的数组初始化方式?A. int[] arr = new int[10];B. int arr[] = {1, 2, 3};C. int arr = {1, 2, 3};D. int arr = new int[3]{1, 2, 3};答案:A, B8. 下列哪些是Java的控制流语句?A. if-elseB. switch-caseC. forD. try-catch答案:A, B, C三、简答题9. 简述Java的垃圾回收机制。
答案:Java的垃圾回收机制是一种自动内存管理功能,它周期性地执行,回收不再使用的对象所占用的内存空间。
垃圾回收器会跟踪每个对象的引用,当对象的引用计数为0时,即没有任何引用指向该对象,垃圾回收器就会在下一次执行时回收该对象占用的内存。
10. 什么是Java的接口?它有什么作用?答案:Java中的接口是一种完全抽象的类,它不包含任何实现代码,只包含常量和抽象方法的声明。
java期末考试题及答案A卷一、选择题(每题2分,共20分)1. Java语言属于以下哪种类型的编程语言?A. 编译型语言B. 解释型语言C. 汇编语言D. 机器语言答案:B2. 下列哪个是Java语言的关键字?A. classB. functionC. includeD. define答案:A3. 在Java中,哪个关键字用于定义一个类?A. classB. structC. interfaceD. enum答案:A4. Java程序的入口点是:A. main()B. start()C. init()D. run()答案:A5. 以下哪个是Java的集合框架中的一种接口?A. ListB. ArrayC. VectorD. String答案:A6. Java中,哪个关键字用于定义私有方法?A. publicB. privateC. protectedD. default答案:B7. 在Java中,哪个类提供了对基本数据类型的包装?A. java.utilB. ngC. java.ioD. 答案:B8. Java中的异常处理是通过以下哪个关键字实现的?A. tryB. catchC. finallyD. all of the above答案:D9. 在Java中,哪个关键字用于实现多态?A. extendsB. implementsC. overrideD. abstract答案:A10. 下列哪个不是Java的访问控制修饰符?A. publicB. privateC. staticD. protected答案:C二、简答题(每题5分,共10分)1. 请简述Java语言的特点。
答案:Java是一种面向对象的编程语言,具有跨平台、安全性高、健壮性等特点。
它支持多线程,自动垃圾回收,并且拥有丰富的API 库。
2. 请说明Java中的继承机制。
答案:Java中的继承机制允许一个类(子类)继承另一个类(父类)的属性和方法。
面向对象程序设计(JAVA ) 第 1 页 共 18 页A 卷注意事项:请将各题答案按编号顺序填写到答题卷上,答在试卷上无效。
一、单项选择题(1~20每小题1分,21~30每小题2分,共40分)1. Which are keywords in Java?A. NullB. TRUEC. sizeofD. implements2. Consider the following code:Integer s = new Integer(9);Integer t = new Integer(9); Long u = new Long(9);Which test would return true?A. (s.equals(new Integer(9))B. (s.equals(9))C. (s ==u)D. (s ==t)3. Which statement of assigning a long type variable to a hexadecimal value is correct?A. long number = 345L;B. long number = 0345;C. long number = 0345L;D. long number = 0x345L;4. Which layout manager is used when the frame is resized the buttons's position in theFrame might be changed? A. BorderLayout B. FlowLayout C. CardLayout D. GridLayout 5. Which are not Java primitive types?A. shortB. BooleanC. byteD. float 6. Given the following code:if (x>0) { System.out.println("first"); }else if (x>-3) { System.out.println("second"); } else { System.out.println("third"); }Which range of x value would print the string "second"?A. x > 0B. x > -3C. x <= -3D. x <= 0 & x > -3 7. Given the following code:public class Person{ int arr[] = new int[10];public static void main(String a[]) { System.out.println(arr[1]); } }班 级 学 号 姓 名密封装订线 密封装订线 密封装订线Which statement is correct?A. When compilation some error will occur.B. It is correct when compilation but will cause error when running.C. The output is zero.D. The output is null.8.Short answer:The decimal value of i is 13, the octal i value is:A. 14B. 015C. 0x14D. 0129. A public member vairable called MAX_LENGTH which is int type, the value of thevariable remains constant value 100. Use a short statement to define the variable.A. public int MAX_LENGTH=100;B. final int MAX_LENGTH=100;C. final public int MAX_LENGTH=100;D. public final int MAX_LENGTH=100.10.W hich correctly create an array of five empty Strings?A. String a [] = {"", "", "", "", "", ""};B. String a [5];C. String [5] a;D. String [] a = new String[5]; for (int i = 0; i < 5; a[i++] = null);11.G iven the following method body:{if (sometest()) {unsafe();}else {safe();}}The method "unsafe" might throw an IOException (which is not a subclass ofRunTimeException). Which correctly completes the method of declaration when added at line one?A. public void methodName() throws ExceptionB. public void methodname()C. public void methodName() throw IOExceptionD. public IOException methodName()12.W hat would be the result of attempting to compile and run the following piece of code?public class Test {static int x;public static void main(String args[]){System.out.println("Value is " + x);}}面向对象程序设计(JAVA)第 2 页共 18 页A. The output "Value is 0" is printed.B. An object of type NullPointerException is thrown.C. A "possible reference before assignment" compiler error occurs.D. An object of type ArrayIndexOutOfBoundsException is thrown.13.W hat is the return-type of the methods that implement the MouseListener interface?A. booleanB. BooleanC. voidD. Point14.S elect valid identifier of Java:A. #passB. 3d_gameC. $chargeD. this15.G iven a TextField that is constructed like this:TextField t = new TextField(30);Which statement is true?A. The displayed width is 30 columns.B. The displayed string can use multiple fonts.C. The displayed line will show exactly thirty characters.D. The maximum number of characters in a line will be thirty.16.W hich declares an abstract method in an abstract Java class?A. public abstract method();B. public abstract void method();C. public void abstract Method(};D. public abstract void method() {}17.What happens when this method is called with an input of "Java rules"?1. public String addOK(String S) {2. S += " OK!";3. return S;4. }Select one correct answerA. The method will return "Java rules OK!".B. A runtime exception willbe thrown.C. The method will return "OK!";D. The method will return"Java rules".18.W hich of the following are Java keywords?A. arrayB. booleanC. IntegerD. Long19.A ssume that val has been defined as an int for the code below.if(val > 4){System.out.println("Test A");}else if(val > 9){System.out.println("Test B");}面向对象程序设计(JAVA)第 3 页共 18 页else System.out.println("Test C");Which values of val will result in "Test C" being printed:A. val < 4B. val between 4 and 9C. val = 10D. val > 920.W hich of the following are valid definitions of an application's main ( ) method?A. public static void main( );B. public static void main( String args );C. public static void main( String args [] );D. public static voidmain( Graphics g );21.A fter the declaration:char[] c = new char[100];what is the value of c[50]?A. 50B. ""C. '\u0032'D. '\u0000'22.W hich of the following statements assigns "Hello Java" to the String variable s ?A. String s = "Hello Java";B. String s [] = "Hello Java";C. new String s = "Hello Java";D. String s[] = new String ("HelloJava");23.I f arr[] contains only positive integer values, what does this function do?public int guessWhat(int arr[]){int x = 0;for(int i = 0; i < arr.length; i++)x = x < arr[i] ? arr[i] : x;return x;}A. Returns the index of the highest element in the arrayB. Returns true/false if there are any elements that repeat in the arrayC. Returns how many even numbers are in the arrayD. Returns the highest element in the array24.W hich of the following are legal declarations of a two–dimensional array of integers?A. int[5][5] a = new int[][];B. int a = new int[5,5];C. int a[][] = new int [5][5];D. int[][]a = new [5]int[5];25.I f val = 1 in the code below:switch (val){case 1: System.out.print("P");case 2:case 3: System.out.print ("Q") ;break;case 4: System.out.print("R");面向对象程序设计(JAVA)第 4 页共 18 页default: System.out.print ("S");}A. PB. PQC. QSD. PQRS26.G iven the following code:1. public class Test {2. int m, n;3. public Test() { }4. public Test(int a) { m=a; }5. public static void main(String arg[]) {6. Test t1,t2;7. int j,k;8. j=0; k=0;9. t1=new Test();10. t2=new Test(j,k);11. }12. }Which line would cause one error during compilation?A. line 3B. line 5C. line 6D. line 1027.F or the code:m = 0;while( ++m < 2 )System.out.println(m);Which of the following are printed to standard output?A. 0B. 1C. 2D. 328.C onsider the following code: What will happen when you try to compile it?public class InnerClass{public static void main(String[]args){}public class MyInner{ }}A. It will compile fine.B. It will not compile, because you cannot have a public inner class.C. It will compile fine, but you cannot add any methods, because then it will fail tocompile.D. It will compile fail.29.What is the result of executing the following code:public class Test{面向对象程序设计(JAVA)第 5 页共 18 页public static void main(String args[]) {String word = "restructure";System.out.println(word.substring(2, 5));}}A. restB. esC. strD. st30.What will be written to the standard output when the following program is run?public class Test {public static void main(String args[]) {System.out.println(9 ^ 2);}}A. 11B. 7C. 18D. 031.When call fact(3), What is the result?int fact(int n){if(n<=1)return 1;elsereturn n*fact(n-1);}A. 2B. 6C. 3D. 032.What is the result of executing the following code:String s=new String("abcdefg");for(int i=0;i<s.length();i+=2){System.out.print(s.charAt(i));}A. acegB. bdfC. abcdefgD. abcd33.What is the result of executing the following code:public class Test {public static void changeStr(String str){str="welcome";}public static void main(String[] args) {String str="12345";changeStr(str);System.out.println(str);}面向对象程序设计(JAVA)第 6 页共 18 页}Please write the output result :A. welcomeB. 12345C. welcome12345D. 12345welcome34.What is the result of executing the following code:1. public class Test {2. static boolean foo(char c) {3. System.out.print(c);4. return true;5. }6. public static void main( String[] argv ) {7. int i =0;8. for ( foo('A'); foo('B')&&(i<2); foo('C')){9. i++ ;10. foo('D');12. }13. }14. }What is the result?A. ABDCBDCBB. ABCDABCDC. Compilation fails.D. An exception is thrown at runtime.35.W hat will happen when you attempt to compile and run the following code?public final class Test4{class Inner{void test(){if (Test4.this.flag);elsesample();}}private boolean flag=false;public void sample(){System.out.println("Sample");}public Test4(){(new Inner()).test();}面向对象程序设计(JAVA)第 7 页共 18 页public static void main(String args[]){new Test4();}}What is the result:A. Print out “Sample”B. Program produces no output but termiantes correctly.C. Program does not terminate.D. The program will not compile36.W hat is the result of executing the following fragment of code:class Base {Base(){amethod();}int i = 100;public void amethod(){System.out.println("Base.amethod()");}}public class Derived extends Base{int i = -1;public static void main(String argv[]) {Base b = new Derived();System.out.println(b.i);b.amethod();}public void amethod() {System.out.println("Derived.amethod()");}}A. Derived.amethod()B. Derived.amethod()-1 100Derived.amethod() Derived.amethod()C. 100D. Compile time errorDerived.amethod()37.What is the result of executing the following code:面向对象程序设计(JAVA)第 8 页共 18 页public class Test {String s1="menu";public static void main(String args[]) {int z=2;Test t=new Test();System.out.println(t.s1+z);}}A. menu2B. 2C. 2menuD. menu38.What is the result of executing the following code:public class Test implements A {int x=5;public static void main(String args[]) {Test c1 = new Test();System.out.println(c1.x+A.k);}}interface A {int k= 10;}A. 5B. 10C. 15D. 10539.What is the result of executing the following code:import java.util.Arrays;public class Test {public static void main(String[] unused) {String[] str = {"xxx", "zzz","yyy","aaa"};Arrays.sort(str);int index=Arrays.binarySearch(str,"zzz");if(index==-1)System.out.println("no");elseSystem.out.println("yes");}}A. noB. xxxC. 0D. yes40.What is the result of executing the following code:面向对象程序设计(JAVA)第 9 页共 18 页int b[][]={{2, 3, 4}, {5, 6}, {7, 8}};int sum=0;for(int i=0;i<b.length;i++) {for(int j=0;j<b[i].length;j++) {sum+=b[i][j];}}System.out.println("sum="+sum);A. 9B. 11C. 15D. 3541.What is the result of executing the following code:public class Test{static void leftshift(int i, int j){i<<=j;}public static void main(String args[]){int i=4, j=2;leftshift(i,j);System.out.println(i);}}A. 2B. 4C. 8D. 1642.What is the result of executing the following code:public class Test {int x=2;int y;public static void main(String args[]) {int z=3;Test t=new Test();System.out.println(t.x+t.y+z);}}A. 5B. 23C. 2D. 343.W hat is the result of executing the following fragment of code:boolean flag = false;if (flag = true) {System.out.println("true");面向对象程序设计(JAVA)第 10 页共 18 页} else {System.out.println("false");}A. trueB. falseC. An exception is raisedD. Nothing happens44.I n the following applet, how many buttons will be displayed?import java.applet.*;import java.awt.*;public class Q16 extends Applet {Button okButton = new Button("Ok");public void init() {add(okButton);add(okButton);add(okButton);add(new Button("Cancel"));add(new Button("Cancel"));add(new Button("Cancel"));add(new Button("Cancel"));setSize(300,300);}}A. 1 Button with label "Ok" and 1 Button with label "Cancel".B. 1 Button with label "Ok" and 4 Buttons with label "Cancel".C. 3 Buttons with label "Ok" and 1 Button with label "Cancel".D. 4 Buttons with label "Ok" and 4 Buttons with label "Cancel".45.What is the result of executing the following code:1. class StaticStuff {2. static int x = 10;3.static { x += 5; }4. public static void main(String args[]){5.System.out.println("x = " + x);6. }7. static { x /= 5; }8. }A. x = 10B. x = 15C. x = 3D. x=546.What will appear in the standard output when you run the Tester class?class Tester {面向对象程序设计(JAVA)第 11 页共 18 页int var;Tester(double var) {this.var = (int)var;}Tester(int var) {this("hello");}Tester(String s) {this();System.out.println(s);}Tester() {System.out.println("good-bye");}public static void main(String args[]) {Tester t = new Tester(5);}}A. "hello"B. "good-bye"C. "hello" followed by "good-bye" D "good-bye" followed by "hello"47.What letters are written to the standard output with the following code?class Unchecked {public static void main(String args[]){try {method();} catch(Exception e) { }}static void method() {try {wrench();System.out.println("a");} catch(ArithmeticException e) {System.out.println("b");} finally {System.out.println("c");}面向对象程序设计(JAVA)第 12 页共 18 页System.out.println("d");}static void wrench() {throw new NullPointerException();}}Select all valid answers.A. "a"B. "b"C. "c"D. "d"48.Given this code snippet:try {tryThis();return;} catch(IOException x1) {System.out.println("exception 1");return;} catch(Exception x2) {System.out.println("exception 2");return;} finally {System.out.println("finally");}what will appear in the standard output if tryThis() throws a IOException?A. "exception 1" followed by "finally"B. "exception 2" followed by "finally"C. "exception 1"D. "exception 2"二、填空题(每空1分,共10分)1.JVM指的是Java【1】。
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;}}。
word 格式-可编辑-感谢下载支持B 卷注意事项:请将各题答案按编号顺序填写到答题卷上,答在试卷上无效。
一、 单选题(本题共40小题,每小题1分,共40分)1. What is the return-type of the methods that implement the MouseListener interface?A. booleanB. BooleanC. voidD. Point 2. Select valid identifier of Java:A. %passwdB. 3d_gameC. $chargeD. this3. Which declares an abstract method in an abstract Java class?A. public abstract method();B. public abstract void method();C. public void abstract Method(};D. public abstract void method() {}4. Which statement about listener is true?A. Most component unallow multiple listeners to be added.B. If multiple listener be add to a single component, the event only affected one listener.C. Component don’t allow multiple listeners to be add.D. The listener mechanism allows you to call an addXxxxListener method as many times as is needed, specifying as many different listeners as your design require.5. Which method you define as the starting point of new thread in a class from which new the thread canbe excution?A. public void start()B. public void run()C. public void int()D. public static void main(String args[])6. Which statement is correctly declare a variable a which is suitable for refering to an array of 50 stringempty object? A. String [] aB. String aC. char a[][]D. String a[50]7. Which cannot be added to a Container?A. a MenuB. a ComponentC. a ContainerD. an Applet8. Which is the main() method’s return of a application?A. StringB. byteC. charD. void9. Which is corrected argument of main() method of application?A. String argsB. String ar[]C. Char args[][]D. StringBuffer arg[]10. Float s=new Float(0.9F);Float t=new Float(0.9F); Double u=new Double(0.9); Which expression’s result is true? A. s ==t B. s.equals(t) C. s ==u D. t.equals(u) 11. Which are not Java keyword?A. gotoB. nullC. FALSED. const12. Run a corrected class: java –cs AClass a b c <enter> Which statement is true? A. args[0]=”-cs”;B. args[1]=”a b c”;C. args[0]=”java”;D. args[0]=”a”;班 级 学 号 姓 名密封装订线 密封装订线 密封装订线13.Short answer:The decimal value of i is 12, the octal i value is:A. 14B. 014C. 0x14D. 01214.Short answer:The decimal value of i is 7, the hexadecimal i value is:A.7B. 07C. 0x7D. x0715.Which is the range of char?A. -27~27-1B. 0~216-1C. 0~216D. 0~2816.Which statement is true about an inner class?A. It must be anonymousB. It can not implement an interfaceC. It is only accessible in the enclosing classD. It can access any final variables in any enclosing scope.17.What is written to the standard output given the following statement:(4|7);Select the right answer:A.4B.5C.6D.718.A class design requires that a particular member variable must be accessible for direct access by anysubclasses of this class. but otherwise not by classes which are not members of the same package.What should be done to achieve this?A. The variable should be marked publicB. The variable should be marked privateC. The variable should be marked protectedD. The variable should have no special access modifier19.main方法是Java Application程序执行的入口点,关于main方法的方法头以下哪项是合法的()?A)public static void main()B)public static void main(String args[] )C)public static int main(String [] arg )D)public void main(String arg[] )20.下面哪种注释方法能够支持javadoc命令:A)/**...**/ B)/*...*/ C)// D)/**...*/21.Java Application源程序的主类是指包含有()方法的类。
注意事项:请将各题答案按编号顺序填写到答题卷上,答在试卷上无效。
-、单项选择题(1~20每小题1分,21*30每小题2分,共40分)Which statement of assigning a long type variable to a hexadecimal value is correct? A. long number = 345L; B. long number = 0345; C. long number = 0345L; D. long number = 0x345L; Which layout manager is used when the frame is resized the buttons's position in the Frame might be changed? A. BorderLayout B. FlowLayout C. CardLayout D. GridLayout Which are not Java primitive types?A. shortB. BooleanC. byteD. float Given the following code:if (x>0) { System.out.println("first n); }else if (x>-3) { System.out.println(M second H); } else { System.out.println(Mthird H); }Which range of x value would print the string usecond 11?A. x > 0B. x > -3C. x <= -3D. x <= 0 & x > -37. Given the following code: public class Person{ int arr| | = new int| 10]; public static voidmain(String a| ]) {System.out.println(arr| 11);Which statement is correct?I2. Which are keywords in Java? A. Null B ・TRUEConsider the following code: Integer s = new Integer(9); Integer t = new Integer(9); Long u = new Long(9);Which test would return true? A. (s.equals(new Integer(9))C. sizeofB. (s.equals(9)) D. (s==t)D. implements0|Pg' 曲4. un I5.A. When compilation some error will occur.B・ It is correct when compilation but will cause error when running.C.The output is zero.D.The output is null.8.Short answer:The decimal value of i is 13, the octal i value is:A. 14B. 015C. 0x14D. 0129.A public member vairable called MAX_LENGTH which is int type, the value of thevariable remains constant value 100. Use a short statement to define the variable.A. public int MAX_LENGTH=100;B. final int MAX_LENGTH=100;C.final public int MAX_LENGTH=100;D. public final int MAX_LENGTH=100.10.Which correctly create an array of five empty Strings?A. String a [] = f "};B. String a [5];C. String [5] a;D.String [] a = new String[5]; for (int i = 0; i < 5; a[i++] = null);11 .Given the following method body:{if (sometest()) {unsafe();}else {safe();}}The method "unsafe” might throw an IOException (which is not a subclass ofRunTimeException). Which correctly completes the method of declaration when added at line one?A. public void methodName() throws ExceptionB・ public void methodname()C.public void methodName() throw IOExceptionD.public IOException methodName()12.What would be the result of attempting to compile and run the following piece of code?public class Test { static int x;public static void main(String args[J){System.out.println(H Value is 11 + x);A.The output n Value is 0H is printed.B.An object of type NullPointerException is thrown.C.A "possible reference before assignment11 compiler error occurs.D.An object of type ArraylndexOutOfBoundsException is thrown.13.What is the return-type of the methods that implement the MouseListener interface?C.The displayed line will show exactly thirty characters.D.The maximum number of characters in a line will be thirty.16.Which declares an abstract method in an abstract Java class?A. public abstract method();B. public abstract void method();C. public void abstract Method(}; D・ public abstract void method() {}17.What happens when this method is called with an input of n Java rules11?1.public String addOK(String S) {2.S + 二” OK!”;3.return S;4.}Select one correct answerA. The method will return u Java rules OK!H.be thrown.C. The method will return "OK!”;n Java rules11.18.Which of the following are Java keywords? B. A runtime exception will D. The method will returnA. arrayB. booleanC. IntegerD. Long19.Assume that val has been defined as an int for the code below.if(val >4){System.out.println(H Test A n);}else if(val > 9){System.out.println(u Test B n);else System.out.println(H Test C H);Which values of val will result in ”Test C” being printed:A.val < 4B. val between 4 and 9C. val = 10D. val > 920.Which of the following are valid definitions of an application's main () method?A. public static void main();B. public static void main( String args );C. public static void main( String args [] );D. public static voidmain( Graphics g );21.After the declaration:char[] c = new char[100];what is the value of c[50]?A. 50B. ””C. ‘\u0032’D. ,\u0000,22.Whic h of the following statements assigns "Hello Java” to the String variable s ?A. String s = "Hello Java";B. String s [] = "Hello Java";C. new String s = "Hello Java”;D. String s[] = new String ("HelloJava");23.If arr[] contains only positive integer values, what does this function do?public int guessWhat(int arr[]){int x = 0;for(int i = 0; i < arr.length; i++)x = x < arr[i] ? arr[i] : x;return x;}A. Returns the index of the highest element in the arrayB・ Returns true/false if there are any elements that repeat in the arrayC.Returns how many even numbers are in the arrayD.Returns the highest element in the array24. Which of the following are legal declarations of a two-dimensional array of integers?A. int[5][5] a = new int[][];B. int a = new int[5,5];C. int a[J[] = new int [5][5];D. int[][]a = new [5]int[5];25.If val = 1 in the code below:switch (val){case 1: System.out.print(n P M);case 2:case 3: System.out.print (n Q H);break;case 4: System.out.print(n R n);default: System.out.print (n S u);}A. PB. PQC. QSD. PQRS26.Given the following code:Which line would cause one error during compilation?A. line 3B. line 5C. line 6D. line 1027.For the code:m = 0;while( ++m < 2 )System.out.println(m);Which of the following are printed to standard output?A. 0B. 1C. 2D. 328.Consider the following code: What will happen when you try to compile it?public class InnerClass{public static void main(String[Jargs){}public class Mylnnerf }}A. It will compile fine.B・ It will not compile, because you cannot have a public inner class.C.It will compile fine, but you cannot add any methods, because then it will fail tocompile.D.It will compile fail.29.What is the result of executing the following code:public class Test{public static void main(String args[]) {String word 二 M restructure M;System.out.println(word.substring(2, 5)); } }A. restB. esC. strD. st30. What will be written to the standard output when the following program is run? public classTest {public static void main(String argsfl) {System.out.println(9 A2);3L When call fact(3), What is the result?int fact(int n){if(n<=l) return 1; elsereturn n^fact(n-l);} A. 2 B. 6 C. 332. What is the result of executing the following code: String s=newString(H abcdefg H);for(int i=0;i<s.length();i+=2){System.out.print(s.char At(i));}A. acegB. bdfC. abcdefg 33- What is the result of executing the following code: public class Test {public static void changeStr(String str){ str=n welcome H;public static void main(String[] args) { String st —” 12345”; changeStr(str); System.out.println(str);Please write the output result : A. welcome B. 12345 C. welcomel2345D. 12345welcome 34. What is the result of executing the following code:1. public class Test {A. 11B. 7C. 18D. 0D. 0D. abed2.static boolean foo(char c) {3.System.out.print(c);4.return true;5.}6.public static void main( String[] argv ) {7.int i=0;& for ( foo(A); foo('B')&&(i<2); foo(C)){9.i++ ;10.foo(D);12.}13.}14.}What is the result?A. ABDCBDCBB. ABCDABCDC. Compilation fails.D. An exception is thrown at runtime.35.What will happen when you attempt to compile and run the following code?public final class Test4{class Inner{void test(){if (Test4.this.flag);elsesample();}}private boolean flag=false;public void sample(){System.out.println(H Sample H);}public Test4(){(new Inner()).test();public static void main(String args[]){ new Test4();What is the result:A. Print out "Sample^B・ Program produces no output but termiantes correctly.C.Program does not terminate.D.The program will not compile36.What is the result of executing the following fragment of code: class Base {Base(){amethod();}int i= 100;public void amethod(){System.o u 匚println(n Base.amethod()H);}}public class Derived extends Base{int i = -1;public static void main(String argv[]) { Base b = new Derived();System.out.println(b.i); b.amethod();public void amethod()System.out.println(H Derived.amethod()n);A. Derived.amethod()Derived.amethod()C. 100Derived.amethod()B.Derived.amethod()100Derived.amethod()D. Compile time errorpublic class Test {String sl=n menu n;public static void main(String args[]) { int z=2;Test t=new Test();System.out.println(t.sl+z);38. What is the result of executing the following code: public class Testimplements A {int x=5;public static void main(String args[]) {Test cl = new Test();System.out.println(c l.x+A.k);} }interface A {intk= 10; } A. 5B. 10C. 1539- What is the result of executing the following code: import java.util.Arrays;public class Test {public static void main(String[] unused) {String[] str = {"xxx”,”zzz",”yyy”,”aaa"};Arrays.sort(str);int index=Arrays.binarySearch(str,H zzz n); if(index==-l)System.out.println(H no H); elseSystem.out.println(H yes H); } } A. noB. xxxC. 0D. yesA. menu2B. 2C. 2menu D ・ menuD. 105int b[][]={{2,3,4},{5,6},{7,8}};int sum=O;for(int i=O;ivb」ength;i++) { for(int j=O;j<b[i]」ength;j++) { sum+=b[i]U];}}System.out.println(',sum=,,4-sum);A. 9B. 11C. 1541.What is the result of executing the following code: public class Test{static void leftshift(int i, int j){i«=j;}public static void main(String args[]){int i=4, j=2;leftshift(ij);System.out.println(i);}}A. 2B.4C. 842.What is the result of executing the following code: public class Test {int x=2;int y;public static void main(String args[]) {int z=3;Test t=new Test();System, out. println(t.x+t.y+z);}}A. 5B. 23C. 243.What is the result of executing the following fragment of code:boolean flag = false;if (flag 二true) {System.out.println(n true H);D. 35D. 16D. 3} else {System.o u 匸println(H false n);}A. trueB. falseC. An exception is raisedD. Nothing happens44.In the following applet, how many buttons will be displayed?import java.applet.*;import java.awt.*;public class Q16 extends Applet {Button okButton = new Button("Ok n);public void init() {add(okButton);add(okButton);add(okButton);add(new Button("Cancel H));add(new Button("Cancel H));add(new Button("Cancel H));add(new Button("Cancel H));setSize(300,300);}}A.1 Button with label "Ok" and 1 Button with label "Cancel”.B.1 Button with label "Ok" and 4 Buttons with label "Cancel'1.C.3 Buttons with label "Ok” and 1 Button with label "CanceF'.D.4 Buttons with label "Ok" and 4 Buttons with label "Ca ncel”.45• What is the result of executing the following code:1.class StaticStuff {2.static int x = 10;3.static { x += 5; }4.public static void main(String args[]){5.System.out.println(H x = n + x);6・}7. static { x /= 5; }8. }A. x = 10B. x = 15C. x = 3D. x=546.What will appear in the standard output when you run the Tester class?class Tester {int var;Tester(double var) {this.var = (int)var;}Tester(int var) {this(n hello");}Tester(String s) {this();System.out.println(s);}Tester() {System.out.println(n good-bye n);}public static void main(String args[]) {Tester t = new Tester(5);}}A. “hello”B. H good-bye nC."hello" followed by "good-bye" D "good-bye" followed by "hello"47.What letters are written to the standard output with the following code? class Unchecked {public static void main(String args[]){method();} catch(Exception e) { }}static void method() {try {wrench();System.out.println(H a n);} catch(ArithmeticException e) {System.out.println(n b n);} finally {System.out.println(n c H);System.out.println(n d n);}static void wrench() {throw new NullPointerException(); } }Select all valid answers. A. H a n B. n b H C. ”c” D. ”d”48. Given this code snippet :try {tryThis(); return;} catch(IOException xl) {System.out.println(n exception l n); return;} catch(Exception x2) {System.out.println(n exception 2n); return; } finally {System.out.println(n finally H);}what will appear in the standard output if tryThis() throws a IOException? A. "exception 1" followed by "finally" B. "exception 2" followed by "finally" C. "exception 1” D. "exception 2"二、填空题(每空1分,共10分) Java 中的字符变量在内存中占【2】位(bit)。
java考试试题及答案一、选择题(每题2分,共20分)1. Java中,下列哪个关键字用于定义一个接口?A. classB. interfaceC. abstractD. interface答案:B2. 下列哪个选项是Java中定义方法的语法?A. public void myMethod();B. public void myMethod;C. public void myMethod{}D. public void myMethod()答案:A3. 在Java中,下列哪个选项不是基本数据类型?A. intB. doubleC. StringD. char答案:C4. 下列哪个关键字用于抛出异常?A. throwB. throwsC. exceptionD. catch答案:B5. 在Java中,下列哪个选项是正确的继承关系?A. class A extends BB. class A implements BC. class A implements AD. class A extends B implements C答案:D6. 下列哪个选项是Java中正确的包声明?A. package com.example;B. package com.example:C. package com.example;D. package com.example;答案:A7. 在Java中,下列哪个选项是正确的数组初始化方式?A. int[] myArray = new int[10];B. int[] myArray = {10};C. int[] myArray = new int[]{1, 2, 3};D. All of the above答案:D8. 下列哪个选项是Java中正确的方法重载?A. public void print(int i);B. public int print(int i);C. public void print();D. All of the above答案:D9. 在Java中,下列哪个关键字用于定义一个类?A. classB. interfaceC. abstractD. enum答案:A10. 下列哪个选项是Java中正确的泛型声明?A. List<String> list = new ArrayList<>();B. List<String> list = new ArrayList<String>();C. List list = new ArrayList<>();D. List<String> list = new ArrayList<Object>();答案:A二、填空题(每题2分,共20分)1. 在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 ) 第 1 页 共 18 页A 卷注意事项:请将各题答案按编号顺序填写到答题卷上,答在试卷上无效。
一、单项选择题(1~20每小题1分,21~30每小题2分,共40分)1. Which are keywords in Java?A. NullB. TRUEC. sizeofD. implements2. Consider the following code:Integer s = new Integer(9);Integer t = new Integer(9); Long u = new Long(9);Which test would return true?A. (s.equals(new Integer(9))B. (s.equals(9))C. (s ==u)D. (s ==t)3. Which statement of assigning a long type variable to a hexadecimal value is correct?A. long number = 345L;B. long number = 0345;C. long number = 0345L;D. long number = 0x345L;4. Which layout manager is used when the frame is resized the buttons's position in theFrame might be changed? A. BorderLayout B. FlowLayout C. CardLayout D. GridLayout 5. Which are not Java primitive types?A. shortB. BooleanC. byteD. float 6. Given the following code:if (x>0) { System.out.println("first"); }else if (x>-3) { System.out.println("second"); } else { System.out.println("third"); }Which range of x value would print the string "second"?A. x > 0B. x > -3C. x <= -3D. x <= 0 & x > -3 7. Given the following code:public class Person{ int arr[] = new int[10];public static void main(String a[]) { System.out.println(arr[1]); } }班 级 学 号 姓 名密封装订线 密封装订线 密封装订线Which statement is correct?A. When compilation some error will occur.B. It is correct when compilation but will cause error when running.C. The output is zero.D. The output is null.8.Short answer:The decimal value of i is 13, the octal i value is:A. 14B. 015C. 0x14D. 0129. A public member vairable called MAX_LENGTH which is int type, the value of thevariable remains constant value 100. Use a short statement to define the variable.A. public int MAX_LENGTH=100;B. final int MAX_LENGTH=100;C. final public int MAX_LENGTH=100;D. public final int MAX_LENGTH=100.10.W hich correctly create an array of five empty Strings?A. String a [] = {"", "", "", "", "", ""};B. String a [5];C. String [5] a;D. String [] a = new String[5]; for (int i = 0; i < 5; a[i++] = null);11.G iven the following method body:{if (sometest()) {unsafe();}else {safe();}}The method "unsafe" might throw an IOException (which is not a subclass ofRunTimeException). Which correctly completes the method of declaration when added at line one?A. public void methodName() throws ExceptionB. public void methodname()C. public void methodName() throw IOExceptionD. public IOException methodName()12.W hat would be the result of attempting to compile and run the following piece of code?public class Test {static int x;public static void main(String args[]){System.out.println("Value is " + x);}}面向对象程序设计(JAVA)第 2 页共 18 页A. The output "Value is 0" is printed.B. An object of type NullPointerException is thrown.C. A "possible reference before assignment" compiler error occurs.D. An object of type ArrayIndexOutOfBoundsException is thrown.13.W hat is the return-type of the methods that implement the MouseListener interface?A. booleanB. BooleanC. voidD. Point14.S elect valid identifier of Java:A. #passB. 3d_gameC. $chargeD. this15.G iven a TextField that is constructed like this:TextField t = new TextField(30);Which statement is true?A. The displayed width is 30 columns.B. The displayed string can use multiple fonts.C. The displayed line will show exactly thirty characters.D. The maximum number of characters in a line will be thirty.16.W hich declares an abstract method in an abstract Java class?A. public abstract method();B. public abstract void method();C. public void abstract Method(};D. public abstract void method() {}17.What happens when this method is called with an input of "Java rules"?1. public String addOK(String S) {2. S += " OK!";3. return S;4. }Select one correct answerA. The method will return "Java rules OK!".B. A runtime exception willbe thrown.C. The method will return "OK!";D. The method will return"Java rules".18.W hich of the following are Java keywords?A. arrayB. booleanC. IntegerD. Long19.A ssume that val has been defined as an int for the code below.if(val > 4){System.out.println("Test A");}else if(val > 9){System.out.println("Test B");}面向对象程序设计(JAVA)第 3 页共 18 页else System.out.println("Test C");Which values of val will result in "Test C" being printed:A. val < 4B. val between 4 and 9C. val = 10D. val > 920.W hich of the following are valid definitions of an application's main ( ) method?A. public static void main( );B. public static void main( String args );C. public static void main( String args [] );D. public static voidmain( Graphics g );21.A fter the declaration:char[] c = new char[100];what is the value of c[50]?A. 50B. ""C. '\u0032'D. '\u0000'22.W hich of the following statements assigns "Hello Java" to the String variable s ?A. String s = "Hello Java";B. String s [] = "Hello Java";C. new String s = "Hello Java";D. String s[] = new String ("HelloJava");23.I f arr[] contains only positive integer values, what does this function do?public int guessWhat(int arr[]){int x = 0;for(int i = 0; i < arr.length; i++)x = x < arr[i] ? arr[i] : x;return x;}A. Returns the index of the highest element in the arrayB. Returns true/false if there are any elements that repeat in the arrayC. Returns how many even numbers are in the arrayD. Returns the highest element in the array24.W hich of the following are legal declarations of a two–dimensional array of integers?A. int[5][5] a = new int[][];B. int a = new int[5,5];C. int a[][] = new int [5][5];D. int[][]a = new [5]int[5];25.I f val = 1 in the code below:switch (val){case 1: System.out.print("P");case 2:case 3: System.out.print ("Q") ;break;case 4: System.out.print("R");面向对象程序设计(JAVA)第 4 页共 18 页default: System.out.print ("S");}A. PB. PQC. QSD. PQRS26.G iven the following code:1. public class Test {2. int m, n;3. public Test() { }4. public Test(int a) { m=a; }5. public static void main(String arg[]) {6. Test t1,t2;7. int j,k;8. j=0; k=0;9. t1=new Test();10. t2=new Test(j,k);11. }12. }Which line would cause one error during compilation?A. line 3B. line 5C. line 6D. line 1027.F or the code:m = 0;while( ++m < 2 )System.out.println(m);Which of the following are printed to standard output?A. 0B. 1C. 2D. 328.C onsider the following code: What will happen when you try to compile it?public class InnerClass{public static void main(String[]args){}public class MyInner{ }}A. It will compile fine.B. It will not compile, because you cannot have a public inner class.C. It will compile fine, but you cannot add any methods, because then it will fail tocompile.D. It will compile fail.29.What is the result of executing the following code:public class Test{面向对象程序设计(JAVA)第 5 页共 18 页public static void main(String args[]) {String word = "restructure";System.out.println(word.substring(2, 5));}}A. restB. esC. strD. st30.What will be written to the standard output when the following program is run?public class Test {public static void main(String args[]) {System.out.println(9 ^ 2);}}A. 11B. 7C. 18D. 031.When call fact(3), What is the result?int fact(int n){if(n<=1)return 1;elsereturn n*fact(n-1);}A. 2B. 6C. 3D. 032.What is the result of executing the following code:String s=new String("abcdefg");for(int i=0;i<s.length();i+=2){System.out.print(s.charAt(i));}A. acegB. bdfC. abcdefgD. abcd33.What is the result of executing the following code:public class Test {public static void changeStr(String str){str="welcome";}public static void main(String[] args) {String str="12345";changeStr(str);System.out.println(str);}面向对象程序设计(JAVA)第 6 页共 18 页}Please write the output result :A. welcomeB. 12345C. welcome12345D. 12345welcome34.What is the result of executing the following code:1. public class Test {2. static boolean foo(char c) {3. System.out.print(c);4. return true;5. }6. public static void main( String[] argv ) {7. int i =0;8. for ( foo('A'); foo('B')&&(i<2); foo('C')){9. i++ ;10. foo('D');12. }13. }14. }What is the result?A. ABDCBDCBB. ABCDABCDC. Compilation fails.D. An exception is thrown at runtime.35.W hat will happen when you attempt to compile and run the following code?public final class Test4{class Inner{void test(){if (Test4.this.flag);elsesample();}}private boolean flag=false;public void sample(){System.out.println("Sample");}public Test4(){(new Inner()).test();}面向对象程序设计(JAVA)第 7 页共 18 页public static void main(String args[]){new Test4();}}What is the result:A. Print out “Sample”B. Program produces no output but termiantes correctly.C. Program does not terminate.D. The program will not compile36.W hat is the result of executing the following fragment of code:class Base {Base(){amethod();}int i = 100;public void amethod(){System.out.println("Base.amethod()");}}public class Derived extends Base{int i = -1;public static void main(String argv[]) {Base b = new Derived();System.out.println(b.i);b.amethod();}public void amethod() {System.out.println("Derived.amethod()");}}A. Derived.amethod()B. Derived.amethod()-1 100Derived.amethod() Derived.amethod()C. 100D. Compile time errorDerived.amethod()37.What is the result of executing the following code:面向对象程序设计(JAVA)第 8 页共 18 页public class Test {String s1="menu";public static void main(String args[]) {int z=2;Test t=new Test();System.out.println(t.s1+z);}}A. menu2B. 2C. 2menuD. menu38.What is the result of executing the following code:public class Test implements A {int x=5;public static void main(String args[]) {Test c1 = new Test();System.out.println(c1.x+A.k);}}interface A {int k= 10;}A. 5B. 10C. 15D. 10539.What is the result of executing the following code:import java.util.Arrays;public class Test {public static void main(String[] unused) {String[] str = {"xxx", "zzz","yyy","aaa"};Arrays.sort(str);int index=Arrays.binarySearch(str,"zzz");if(index==-1)System.out.println("no");elseSystem.out.println("yes");}}A. noB. xxxC. 0D. yes40.What is the result of executing the following code:面向对象程序设计(JAVA)第 9 页共 18 页int b[][]={{2, 3, 4}, {5, 6}, {7, 8}};int sum=0;for(int i=0;i<b.length;i++) {for(int j=0;j<b[i].length;j++) {sum+=b[i][j];}}System.out.println("sum="+sum);A. 9B. 11C. 15D. 3541.What is the result of executing the following code:public class Test{static void leftshift(int i, int j){i<<=j;}public static void main(String args[]){int i=4, j=2;leftshift(i,j);System.out.println(i);}}A. 2B. 4C. 8D. 1642.What is the result of executing the following code:public class Test {int x=2;int y;public static void main(String args[]) {int z=3;Test t=new Test();System.out.println(t.x+t.y+z);}}A. 5B. 23C. 2D. 343.W hat is the result of executing the following fragment of code:boolean flag = false;if (flag = true) {System.out.println("true");面向对象程序设计(JAVA)第 10 页共 18 页} else {System.out.println("false");}A. trueB. falseC. An exception is raisedD. Nothing happens44.I n the following applet, how many buttons will be displayed?import java.applet.*;import java.awt.*;public class Q16 extends Applet {Button okButton = new Button("Ok");public void init() {add(okButton);add(okButton);add(okButton);add(new Button("Cancel"));add(new Button("Cancel"));add(new Button("Cancel"));add(new Button("Cancel"));setSize(300,300);}}A. 1 Button with label "Ok" and 1 Button with label "Cancel".B. 1 Button with label "Ok" and 4 Buttons with label "Cancel".C. 3 Buttons with label "Ok" and 1 Button with label "Cancel".D. 4 Buttons with label "Ok" and 4 Buttons with label "Cancel".45.What is the result of executing the following code:1. class StaticStuff {2. static int x = 10;3. static { x += 5; }4. public static void main(String args[]){5. System.out.println("x = " + x);6. }7. static { x /= 5; }8. }A. x = 10B. x = 15C. x = 3D. x=546.What will appear in the standard output when you run the Tester class?class Tester {面向对象程序设计(JAVA)第 11 页共 18 页int var;Tester(double var) {this.var = (int)var;}Tester(int var) {this("hello");}Tester(String s) {this();System.out.println(s);}Tester() {System.out.println("good-bye");}public static void main(String args[]) {Tester t = new Tester(5);}}A. "hello"B. "good-bye"C. "hello" followed by "good-bye" D "good-bye" followed by "hello"47.What letters are written to the standard output with the following code?class Unchecked {public static void main(String args[]){try {method();} catch(Exception e) { }}static void method() {try {wrench();System.out.println("a");} catch(ArithmeticException e) {System.out.println("b");} finally {System.out.println("c");}面向对象程序设计(JAVA)第 12 页共 18 页System.out.println("d");}static void wrench() {throw new NullPointerException();}}Select all valid answers.A. "a"B. "b"C. "c"D. "d"48.Given this code snippet:try {tryThis();return;} catch(IOException x1) {System.out.println("exception 1");return;} catch(Exception x2) {System.out.println("exception 2");return;} finally {System.out.println("finally");}what will appear in the standard output if tryThis() throws a IOException?A. "exception 1" followed by "finally"B. "exception 2" followed by "finally"C. "exception 1"D. "exception 2"二、填空题(每空1分,共10分)1.JVM指的是Java【1】。