JAVA试题英文版(答案)

合集下载

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

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

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

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

java英文版答案

java英文版答案

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双语教学考试试卷及答案A

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

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

一、单项选择题(1~20每小题1分,21~30每小题2分,共40分) 1. Which are keywords in Java? A. Null B. TRUE C. sizeof D. implements 2. 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 the Frame might be changed? A. BorderLayout B. FlowLayout C. CardLayout D. GridLayout 5. Which are not Java primitive types? A. short B. Boolean C. byte D. 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 > 0 B. x > -3 C. x <= -3 D. 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);}}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");}else System.out.println("Test C");Which values of val will result in "Test C" being printed:面向对象程序设计(JAVA)第 3 页共 17 页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");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{public static void main(String args[]) {String word = "restructure";System.out.println(word.substring(2, 5));}面向对象程序设计(JAVA)第 5 页共 17 页}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);}}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();}public static void main(String args[]){new Test4();}}What is the result:面向对象程序设计(JAVA)第 7 页共 17 页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: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: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];}面向对象程序设计(JAVA)第 9 页共 17 页}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");} 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 {int var;Tester(double var) {this.var = (int)var;}Tester(int var) {this("hello");}面向对象程序设计(JAVA)第 11 页共 17 页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");}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】。

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) 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试题英文版(答案)

一.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 outer classD. From within the package bar, an instance of the inner class can be constructed with “new inner()”四.Exhibit(展览、陈列):1 public class enclosinggone{2 public class insideone{}3 }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(new java.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{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面试题(含答案)

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

IBM java 英文面试题(附参考答案)

IBM java 英文面试题(附参考答案)

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

Java笔试常见英语题(附答案)

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练习题含答案-answers to practise 1

JAVA练习题含答案-answers to practise 1

Chapter 1 Getting StartedMultiple Choice1)Java is an object-oriented programming language. An object-oriented language(a)Uses structured programming.(b)Views a program as consisting of objects which communicate through interactions.(c)Functionally breaks down problems into smaller, more manageable problems.(d)All of the above.Answer:B (see page 3)2)In Java, the equal sign is used as the ___________ operator.(a)increment(b)decrement(c)assignment(d)negationAnswer:C (see page 7)3)In Java, source code is compiled into object code called ______________.(a)Bit-code(b)Class code(c)Method code(d)Byte-codeAnswer:D (see page 9)4)The hardest kind of error to detect in a computer program is a:(a)Syntax error(b)Run-time error(c)Logic error(d)All of the aboveAnswer:C (see page 12)15)Identify the invalid Java identifier.(a)1Week(b)Week1(c)amountDue(d)amount_dueAnswer:A (see page 14)6)What is the value of the variable amountDue?double price = 2.50;double quantity = 5;double amountDue = 0;amountDue = price * quantity;(a)12(b)12.25(c)12.5(d)13Answer:C (see page 19)7)What is the value of 7.52e-5?(a)752000.0(b)0.0000752(c)0.000752(d)0.00752Answer:B (see page 22)8)What is the Java expression for 4a2 + 2b * c?(a)(4 * a) + (2 * b) * c(b)(4 * a * a) + ((2 * b) * c)(c)((4 * a * a) + (2 * b)) * c(d)(4 + a * a) + ((2 + b) * c)Answer:B (see page 25)9)What is the Java expression for 27xy?(a)27 + (x * y)(b)27 * (x + y)(c)27 * x * y(d)27x * yAnswer:C (see page 25)10)The value of the expression (int) 27.6 evaluates to:(a)28(b)27(c)26(d)None of the above.Answer:B (see page 20)⏹True/False1)Java began as a language for home appliances.Answer:True (see page 3)2)Applets were designed to run as stand-alone applications.Answer:False (see 5)3)The Java programming language allows you to concatenate two strings using the plus sign.Answer:True (see page 35)4)Java is an interpreted language.Answer:True (see page 9)5)Java does not require that a variable be declared before it is used within a program.Answer:False (see page 14)6) A variable of type boolean can be explicitly converted to that of type int.Answer:False (see page 21)7)The modulus operator, %, returns the remainder of integer division.Answer:True (see page 26)8)The result of integer division is truncated in Java.Answer:True (see page 27)⏹Short Answer/Essay1)There are two kinds of Java programs, applications and applets. Define and discuss each.Answer:An application is just a regular. An applet is a little Java program that runs in a Webbrowser. Applets and applications are almost identical. The difference is that applications aremeant to be run on your computer like any other program, whereas an applet is meant to be run froma Web browser. An applet can be sent to another location on the Internet and run there.2)What are the values of the variables a, b, c, and d after the execution of the following expressions?int a = 3;int b = 12;int c = 6;int d = 1;d = d * a;c = c + 2 * a;d = d - b / c;c = c * b % c;b = b / 2;Answer:a: 3b: 6c: 0d: 23)what is the output produced by the following code?class TestP{public static void main(String args[]){int x=5,y=32;float a=8.6f,b=4.0f;System.out.println("x="+x+"y="+y);System.out.println("\ta="+a+"\tb="+b);System.out.println("\nx+y="+x+y+"\ta*b="+a*b);}}Answer:x=5y=32a=8.6 b=4.0x+y=532 a*b=34.4。

Java面试题和答案(英文版)

Java面试题和答案(英文版)

Java面试题和答案(英文版)Q: What is the difference between an Interface and an Abstract class?A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.Q: What is the purpose of garbage collection in Java, and when is it used?A: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.Q: Describe synchronization in respect to multithreading.A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.Q: Explain different way of using thread?A: The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.Q: What are pass by reference and passby value?A: Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.Q: What is HashMap and Map?A: Map is Interface and Hashmap is class that implements that.Q: Difference between HashMap and HashTable?A: The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.Q: Difference between Vector and ArrayList?A: Vector is synchronized whereas arraylist is not.Q: Difference between Swing and Awt?A: AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.Q: What is the difference between a constructor and a method?A: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.Q: What is an Iterator?A: Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.Q: State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.A: public : Public class is visible in other packages, field is visible everywhere (class must be public too)private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package.Q: What is an abstract class?A: Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.Q: What is static in java?A: Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.Q: What is final?A: A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).Q: What if the main method is declared as private?A: The program compiles properly but at runtime it will give "Main method not public." message.[ Received from Sandesh Sadhale]Q: What if the static modifier is removed from the signature of the main method?A: Program compiles. But at runtime throws an error "NoSuchMethodError".[ Received from Sandesh Sadhale]Q: What if I write static public void instead of public static void?A: Program compiles and runs properly.[ Received from Sandesh Sadhale]Q: What if I do not provide the String array as the argument to the method?A: Program compiles but throws a runtime error "NoSuchMethodError".[ Received from Sandesh Sadhale]Q: What is the first argument of the String array in main method?A: The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.[ Received from Sandesh Sadhale]Q: If I do not provide any arguments on the command line, then the String array of Main method will be empty or null?A: It is empty. But not null.[ Received from Sandesh Sadhale]Q: How can one prove that the array is not null but empty using one line of code?A: Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.[ Received from Sandesh Sadhale]Q: What environment variables do I need to set on my machine in order to be able to run Java programs?A: CLASSPATH and PATH are the two variables.[ Received from Sandesh Sadhale]Q: Can an application have multiple classes having main method?A: Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.[ Received from Sandesh Sadhale]Q: Can I have multiple main methods in the same class?A: No the program fails to compile. The compiler says that the main method is already defined in the class.[ Received from Sandesh Sadhale]Q: Do I need to import ng package any time? Why ?A: No. It is by default loaded internally by the JVM.[ Received from Sandesh Sadhale]Q: Can I import same package/class twice? Will the JVM load the package twice at runtime?A: One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.[ Received from Sandesh Sadhale]Q: What are Checked and UnChecked Exception?A: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown.eg, IOException thrown by java.io.FileInputStream's read() method·Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.Q: What is Overriding?A: When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.Q: What are different types of inner classes?A: Nested top-level classes, Member classes, Local classes, Anonymous classesNested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class.Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety.Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block oftheir declaration. In order for the class to be useful beyond the declaration block, it would need to implement a more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.Q: Are the imports checked for validity at compile time? e.g. will the code containing an import such as ng.ABCD compile?A: Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbolsymbol : class ABCDlocation: package ioimport java.io.ABCD;[ Received from Sandesh Sadhale]Q: Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?A: No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.[ Received from Sandesh Sadhale]Q: What is the difference between declaring a variable and defining a variable?A: In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization.e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions. [ Received from Sandesh Sadhale]Q: What is the default value of an object reference declared as an instance variable?A: null unless we define it explicitly.[ Received from Sandesh Sadhale]Q: Can a top level class be private or protected?A: No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.[ Received from Sandesh Sadhale]Q: What type of parameter passing does Java support?A: In Java the arguments are always passed by value .[ Update from Eki and Jyothish Venu]Q: Primitive data types are passed by reference or pass by value?A: Primitive data types are passed by value.[ Received from Sandesh Sadhale]Q: Objects are passed by value or by reference?A: Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object .[ Update from Eki and Jyothish Venu]Q: What is serialization?A: Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.[ Received from Sandesh Sadhale]Q: How do I serialize an object to a file?A: The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.[ Received from Sandesh Sadhale]Q: Which methods of Serializable interface should I implement?A: The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.[ Received from Sandesh Sadhale]Q: How can I customize the seralization process? i.e. how can one have a control over the serialization process?A: Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.[ Received from Sandesh Sadhale]Q: What is the common usage of serialization?A: Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed.[ Received from Sandesh Sadhale]Q: What is Externalizable interface?A: Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.[ Received from Sandesh Sadhale]Q: When you serialize an object, what happens to the object references included in the object?A: The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.[ Received from Sandesh Sadhale]Q: What one should take care of while serializing the object?A: One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.[ Received from Sandesh Sadhale]Q: What happens to the static fields of a class during serialization?A: There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are1. Serialization ignores static fields, because they are not part of ay particular state state.2. Base class fields are only hendled if the base class itself is serializable.3. Transient fields.[ Received from Sandesh Sadhale Modified after P.John David comments.]Q: Does Java provide any construct to find out the size of an object?A: No there is not sizeof operator in Java. So there is not direct way to determine the size of an object directly in Java. [ Received from Sandesh Sadhale] TOPQ: Give a simplest way to find out the time a method takes for execution without using any profiling tool?A: Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.To put it in code...long start = System.currentTimeMillis ();method ();long end = System.currentTimeMillis ();System.out.println ("Time taken for execution is " + (end - start));Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing.[ Received from Sandesh Sadhale] TOPQ: What are wrapper classes?A: Java provides specialized classes corresponding to each of the primitive data types. These are called wrapper classes. They are e.g. Integer, Character, Double etc.[ Received from Sandesh Sadhale] TOPQ: Why do we need wrapper classes?A: It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object.[ Received from Sandesh Sadhale] TOPQ: What are checked exceptions?A: Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions. [ Received from Sandesh Sadhale] TOPQ: What are runtime exceptions?A: Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.[ Received from Sandesh Sadhale] TOPQ: What is the difference between error and an exception?A: An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).[ Received from Sandesh Sadhale] TOPQ: How to create custom exceptions?A: Your class should extend class Exception, or some more specific type thereof.[ Received from Sandesh Sadhale] TOPQ: If I want an object of my class to be thrown as an exception object, what should I do?A: The class should extend from Exception class. Or you can extend your class from some more precise exception type also.[ Received from Sandesh Sadhale] TOPQ: If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?A: One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well.[ Received from Sandesh Sadhale] TOPQ: How does an exception permeate through the code?A: An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.[ Received from Sandesh Sadhale] TOPQ: What are the different ways to handle exceptions?A: There are two ways to handle exceptions,1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions. [ Received from Sandesh Sadhale] TOPQ: What is the basic difference between the 2 approaches to exception handling.1> try catch block and2> specifying the candidate exceptions in the throws clause?When should you use which approach?A: In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.[ Received from Sandesh Sadhale] TOPQ: Is it necessary that each try block must be followed by a catch block?A: It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.[ Received from Sandesh Sadhale] TOPQ: If I write return at the end of the try block, will the finally block still execute?A: Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.[ Received from Sandesh Sadhale] TOPQ: If I write System.exit (0); at the end of the try block, will the finally block still execute?A: No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.[ Received from Sandesh Sadhale]Q: How are Observer and Observable used?A: Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.[Received from Venkateswara Manam] TOPQ: What is synchronization and why is it important?A: With respect to multithreading, synchronization is the capability to controlthe access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors.[ Received from Venkateswara Manam] TOPQ: How does Java handle integer overflows and underflows?A: It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.[ Received from Venkateswara Manam] TOPQ: Does garbage collection guarantee that a program will not run out of memory?A: Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.[ Received from Venkateswara Manam] TOPQ: What is the difference between preemptive scheduling and time slicing?A: Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.[ Received from Venkateswara Manam] TOPQ: When a thread is created and started, what is its initial state?A: A thread is in the ready state after it has been created and started.[ Received from Venkateswara Manam] TOPQ: What is the purpose of finalization?A: The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.[ Received from Venkateswara Manam] TOPQ: What is the Locale class?A: The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.[ Received from Venkateswara Manam] TOPQ: What is the difference between a while statement and a do statement?A: A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.[ Received from Venkateswara Manam] TOPQ: What is the difference between static and non-static variables?A: A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.[ Received from Venkateswara Manam] TOPQ: How are this() and super() used with constructors?A: This() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.[ Received from Venkateswara Manam] TOPQ: What are synchronized methods and synchronized statements?A: Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.[ Received from Venkateswara Manam] TOPQ: What is daemon thread and which method is used to create the daemon thread?A: Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.[ Received from Shipra Kamra] TOPQ: Can applets communicate with each other?A: At this point in time applets may communicate with other applets running in the same virtual machine. If the applets are of the same class, they can communicate via shared static variables. If the applets are of different classes, then each will need a reference to the same class with static variables. In any case the basic idea is to pass the information back and forth through a static variable.An applet can also get references to all other applets on the same page using the getApplets() method ofjava.applet.AppletContext. Once you get the reference to an applet, you can communicate with it by using its public members.It is conceivable to have applets in different virtual machines that talk to a server somewhere on the Internet and store any data that needs to be serialized there. Then, when another applet needs this data, it could connect to this same server. Implementing this is non-trivial.[ Received from Krishna Kumar ] TOPQ: What are the steps in the JDBC connection?A: While making a JDBC connection we go through the following steps :Step 1 : Register the database driver by using :Class.forName(" driver classs for that specific database" );Step 2 : Now create a database connection using :Connection con = DriverManager.getConnection(url,username,password);。

java英语笔试试题及答案

java英语笔试试题及答案

java英语笔试试题及答案Java英语笔试试题及答案1. What is the difference between a class and an object in Java?A class is a blueprint or template that defines the properties and methods of an object. An object is an instance of a class, created at runtime.2. What is the purpose of the 'public static voidmain(String[] args)' method in Java?The 'public static void main(String[] args)' method is the entry point of a Java application. It is the first methodthat gets executed when the program starts.3. What is the difference between a method and a function in Java?In Java, a method is a block of code that is used to perform a specific task. A function is a term that is often used interchangeably with method, but technically, a function can return a value whereas a method does not necessarily do so.4. What is the 'this' keyword used for in Java?The 'this' keyword in Java is a reference to the current object. It can be used to access instance variables and methods of the current object.5. What is an interface in Java?An interface in Java is a completely abstract class that can contain only abstract methods and constants. It is used to achieve abstraction and to define a contract for classes to implement.6. What is the difference between a checked exception and an unchecked exception in Java?A checked exception is a type of exception that a method must either handle with a try-catch block or declare it with the 'throws' keyword. An unchecked exception is not required to be handled or declared, and includes RuntimeException and its subclasses.7. What is the 'final' keyword used for in Java?The 'final' keyword in Java can be used in three different contexts: to declare a class as final (cannot be subclassed), to declare a method as final (cannot be overridden), or to declare a variable as final (cannot be reassigned).8. What is a constructor in Java?A constructor in Java is a special method that is used to initialize objects. It has the same name as the class and is called when an object is created.9. What is the purpose of the 'super' keyword in Java?The 'super' keyword in Java is used to refer to the parent class's methods and variables. It is often used in constructors to call a superclass's constructor.10. What is the difference b etween '==’ and 'equals()' inJava?The '==' operator is used to compare primitive data types by value and object references by reference, whereas the'equals()' method is used to compare objects by content, and it can be overridden to provide custom comparison logic.Answers:1. A class is a blueprint, an object is an instance of a class.2. It is the entry point of a Java application.3. A method is a block of code in Java, a function is a more general term and can return a value.4. It refers to the current object.5. An interface is an abstract class with only abstract methods and constants.6. Checked exceptions must be handled or declared, unchecked do not.7. It is used to declare classes, methods, or variables as final.8. It initializes objects.9. It refers to the parent class's methods and variables.10. '==' compares by value or reference, 'equals()' compares by content.。

java基础试题及答案英文

java基础试题及答案英文

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

Java英文题

Java英文题

Java英文题Multiple-Choice1.The name of a Java source file(a)has no restrictions(b)must be the same as the class it defines, ignoring case(c)must use the extension .class(d)must be the same as the class it defines, respecting case2.Which of the following statements is (are) true about the use of an asterisk (*) in a Javaimport statement?Ⅰ.It does not incur run-time overhead.Ⅱ.It can be used to import multiple packages with a sing le statement.Ⅲ.It can be used to import multiple classes with a single statement(a)I, II, and III(b)I and III only(c)I only(d)III only3.What is the name of the wrapper class for the type int?(a) INT (b) integer (c) Integer (d) Int4. A difference between the methods print and println of the classjava.io.PrintWriter is that(a) println inserts a new line at the beginning of its output, but print does not(b) print inserts a new line at the beginning of its output, but println does not(c) print appends a new line to the end of its output, butprintln does not(d) println appends a new line to the end of its output, but print does not5. Consider the following Java program segment.int x = 5;int y = 2;System.out.println(x + "1" + y);Which of the following statements is true about the program segment?(a)The output caused by the code will be 512.(b)The output caused by the code will be 5 1 2.(c)The output caused by the code will be 8.(d)The code will cause a compilation error.6. All Java exception classes are derived from the class(a) ng.RuntimeException(b) ng.Throwable(c) ng.Error(d) java.io.IOException7. What is the right way to handle abnormalities in input on Java?(a) By writing while loops to guard against bad input(b) By handling these problems by providing exception handlers(c) By using the class FileFilter which gracefully filters out bad input data(d) By always specifying the throws clause in every method header where file I/O isperformed8. Which of the following patterns of characters opens a Javadoc comment block?(a) /* (b) **/ (c) /** (d) //9. According to the Java code conventions, files that contain Java source code have the suffix_____, and compiled bytecode files have the suffix _____.(a) .class, .java (b) .class, .javac(c) .java, .class (d) .javac, .class10. As an aid in debugging a program in Java, print statements may be used to display whichof the following types of information?I.The names of methods being calledII.The values of the parameters of a methodⅢ. The values of the instance variables of a class(a) I and II only (b) I and III only(c) II and III only (d) I, II, and III1.In a UML class diagram's representation of a class, the top, middle, and lower rectangularcompartments respectively describe the _____ of the class.(a) name, attributes, and methods (b) name, methods, and constants(c) attributes, methods, and name (d) attributes, methods, and constants2. UML class diagrams can describe which of the following?I.The internal structure of classesⅡ. Relationships between classes(a) I and II (b) II only (c) None (d) I only3. Consider the following UML class diagram.According to the diagram, instances of the class named _____ have references to instances of the class named _____.(a) B, A (b) A, C (c) B, C (d) A, B4. Which of the following is true about association and aggregation in UML class diagrams?(a) Association is the opposite of aggregation.(b) Aggregation is a special form of association.(c) Association is a special form of aggregation.(d) Association and aggregation have no meaningful relationship.5. A binary association is said to exist between two classes when(a) one class belongs to the same package as the other class(b) an object of one class requires an object of the other class(c) an object of one class is instantiated in the same method as an object of the other class(d) one class is a subtype of the other class6. Consider the following UML class diagram.According to the diagram, which of the following statements is (are) true?I.ClassB is a specialization of ClassA.II.ClassA is a generalization of ClassC.Ⅲ. ClassC is involved in a self-containment loop.(a) II and III only (b) I and II only(c) I, II, and III (d) I and III only7. A collection typically models a _____ relationship.(a) one-to-one (b) many-to-many(c) zero-to-one (d) one-to-many8. Consider the following UML class diagram.Which of the following is (are) true about the system described by the diagram?I.An instance of Picture can contain a collection of instances of the class Shape. Ⅱ. An instance of Shape can contain a collection of instances of the class Picture.(a) II only (b) None (c) I only (d) I and II9. When using noun-phrase analysis to model a software system, which of the followingshould typically be eliminated from the list of potential classes?I.References to the software system itselfII.Nouns that imply roles between objectsⅢ. Synonyms to other nouns in the list(a) II and III only (b) I and III only(c) III only (d) I, II, and III10. The static model of a software system typically includes which of the following?I.Attributes of classesII.Actions that occur between classesⅢ. Structural relationships between classes(a) I and III only (b) II and III only(c) I, II, and III (d) I and II only1.The term class variable is a synonym for(a) a private data field(b) a static data field(c) a read-only variable(d) an instance variable2. Consider the following Java program segment.import java.io.*;public class Test {public Test( ) {System.out.println("default");}public Test( int i ) {System.out.println("non-default");}public static void main(String[] args) {Test t = new Test(2);}}Which of the following will be output during execution of the program segment?(a)The line of text "default"(b)The line of text "default" followed by the line of text "non-default"(c)The line of text "non-default"(d)The line of text "non-default" followed by the line of text "default"3. Which of the following categorizations can be applied to both the data fields and themethods in a Java class?(a) native and non-native(b) default and non-default(c) static and non-static(d) abstract and non-abstract4. Which of the following statements about class variables in Java is not true?(a) Class variables require the modifier static in the declarations.(b) All objects have their own copy of the class variable defined in the instantiated class.(c) Non-static methods in a class can access the class variable defined in the same class.(d) Class variables do not need the reference to the object of the instantiated class toaccess them.5. If a class contains a constructor, that constructor will be invoked(a) each time an object of that class goes out of scope(b) each time an object of that class is instantiated(c) once the first time an object of that class is instantiated(d) once at the beginning of any program that uses that class6. Which of the following statements about constructors in Java is true?(a) A class can define more than one constructor.(b) A constructor must be defined as public.(c) A constructor must be defined as static.(d) A class must define at least one constructor.7. If the method int sum(int a, int b) is defined in a Java class C, which of the following methods cannot coexist as a different method in class C?(a) int sum(int x, float y)(b) int sum(float a, int b)(c) int sum(int x, int y)(d) float sum(int x, float y)8. Consider the following Java class definitions.public class Object1 {protected String d(){return "Hi";}}public class Object2 extends Object1 {protected String d(){return super.d();}}Which of the following statements is (are) true regarding the definitions?I.Class Object2 inherits from class Object1.II.Class Object2 overrides method d.Ⅲ. Method d returns equivalent results when executed from either class.(a) I, II, and III (b) I and III only(c) III only (d) I and II only9. When a subclass defines an instance method with the same return type and signature asa method in its parent, the parent's method is said to be(a) private (b) hidden (c) overloaded (d) overridden10. Which is a Java access modifier used to designate that a particular data field will not beinherited by a subclass?(a) final (b) protected (c) private(d) default1. Consider the following Java program segment.String[] str = {"Three","Two","One"};for (int i = 0; i < str.length; ++i) {System.out.println(str[i]+"/");}What will be output upon execution of the program segment?(a) Three/Two/One/ (b) Three,Two,One(c) One,Two,Three (d) One/Two/Three/2. Consider the following Java program segment.int[] arr;arr = new int[3];arr[2]=19;arr[1]=17;arr[0]=15;Which of the following Java statements is syntactically correct and semantically identical to the program segment?(a)int[] arr= {15, 17, 19};(b)int[3] arr = {15, 17, 19};(c)int arr = {15, 17, 19};(d)int arr[3]= {15, 17, 19};3. Regarding the following declaration, what is the index of the element containing 45?int[] numbers = {-1, 45, 6, 132};(a) 0 (b) 1(c) 45 (d) 24.Legal Java statements to initialize an array reference include which of the following? I.int[] aobj = {0, 1, 2};II.int[4] aobj = {0, 1, 2};Ⅲ. int[] aobj = new int[3];(a) I and II only (b) I only(c) III only (d) I and III only5. If the length of a particular array is the value of LIMIT, whatis the index of the last itemin that array?(a) LIMIT (b) LIMIT – 1 (c) LIMIT / 2 (d) 06. Consider the Java program below.public class Arr{public static void main(String[] args) {int[] a = {1, 2, 3};System.out.println(a[1]);System.out.println(a[3]);}}Which of the following is true about the result of executing the program?(a)The number 1 is printed and there is no abnormal termination.(b)The number 3 is printed and a run-time exception terminates execution.(c)The number 2 is printed and there is no abnormal termination.(d)The number 2 is printed and a run-time exception terminates execution.7. In which of the following ways can items be added to a collection implemented byjava.util.ArrayList?I.Items can be inserted at the beginning of the collection.II.Items can be inserted between two existing items in the collection.Ⅲ. Items can be appended to the end of the collection.(a) I only (b) I, II, and III (c) I and III only (d) III only8. An object that contains methods that traverse a collectionlinearly from start to finish isknown as a(n)(a) int (b) iterator(c) loop (d) Exception9. Consider the following method call, where c is an instance of the classjava.util.ArrayList.c.size();This method call returns the number of(a)times that the method c.add has been called(b)bytes used by c(c)ArrayList objects that have been instantiated(d)elements in the ArrayList represented by c10. The class java.util.ArrayList implements a collection that(a) can grow to accommodate new items(b) can only store primitive variables such as int or Boolean(c) can only store instances of the class ng.String(d) cannot be accessed using an integer index1. The subclass of an abstract class must(a) be abstract(b) be abstract and implement all of the parent's abstract methods(c) be abstract or implement all of the parent's abstract methods(d) implement all of the parent's abstract methods2. Which of the following statements is (are) true about any abstract method in Java?I.It contains no definition.Ⅱ. It cannot be declared public.(a) I and II (b) I only (c) None (d) II only3. Consider the following Java program fragment.public void drive(Vehicle v) {...}...drive(obj);The method call drive(obj) is valid if obj is which of the following?I. A descendent of class VehicleII.An ancestor of class VehicleⅢ. An object of class Vehicle(a) I and III only (b) I, II, and III(c) III only (d) II and III only4. Which of the following statements is (are) true in Java?I.An abstract class may contain data fields.Ⅱ. Interfaces may contain data fields.(a)I and II (b) I only (c) None (d) II only5. Which of the following statements is (are) true about interfaces in Java?I.Interfaces can extend other interfaces.Ⅱ. Interfaces can contain data fields.(a) I only (b) None (c) II only (d) I and II6. Which of the following statements is (are) true in Java?I.All of the methods in an abstract class must be abstract.Ⅱ. All of the methods in an interface must be abstract.(a) None (b) I only (c) II only (d) I and II7. Which of the following statements is (are) true about all data fields in an interface in Java?I.They are implicitly public.II.They are implicitly final.Ⅲ. The y are implicitly static.(a) I and II only (b) I, II, and III(c) II and III only (d) II only8. A design pattern is typically used to(a) reduce the number of classes in the design of a program(b) ensure that code executes at optimal speed during runtime(c) allow the use of object-orientated concepts in a language that is not object-oriented(d) describe a practical solution to a common design problem9. The constructor of a class that adheres to the Singleton design pattern must have _____visibility.(a) public (b) protected (c) package (d) private10. The Strategy design pattern is likely to be useful when implementing which of thefollowing?I.An application that offers several alternate sorting algorithmsⅡ. A simple class to store the address of an organization of which only one instance can be instantiated(a) II only (b) I only (c) None (d) I and II1.Consider the following Java program segment.PrintWriter fileOut = new PrintWriter(new FileWriter("output.txt"));If the file output.txt already exists, which of the following events will occur when the program segment is executed?(a)The existing contents of output.txt will be erased.(b) A FileAlreadyExists exception will be raised.(c)The existing contents of output.txt will be preserved.(d)A run-time error will be generated.2.The model part of the Model-View-Controller (MVC) paradigm embodies the(a)automatic mechanism by which the user interface is displayed and by which eventsare communicated between the view and the controller(b)way in which the abstract domain knowledge of an application is presented to theuser(c)abstract domain knowledge of an application(d)list of abstract classes in an application3.Which of the following is true regarding the controller part in the Model-View-Controller(MVC) paradigm?(a)The controller is the list of abstract classes in an application.(b)The controller is the way in which the abstract domain knowledge of an applicationis presented to the user.(c)The controller is the abstract domain knowledge of an application.(d)The controller is the automatic mechanism by which the user interface is displayedand by which events are communicated between the model and the view.4.In Java, the default layout manager for a JFrame component is(a) GridLayout (b) GridBagLayout(c) BorderLayout (d) FlowLayout5. The view part of the Model-View-Controller (MVC)paradigm is the(a) list of abstract classes in an application(b) automatic mechanism by which the user interface is displayed and by which eventsare communicated between the model and the controller(c) way in which the abstract domain knowledge of an application is presented to theuser(d) abstract domain knowledge of an application6. Which of the following is (are) true regarding event handling in Java?I.When a GUI component is created, the component automatically has the abilityto generate events during user interaction.Ⅱ. Each Listener object must be registered with the specific component object or objects for which the Listener object is to respond.(a) None (b) II only (c) I and II (d) I only7. Which of the following is a Java event that is generated when a JButton component ispressed? b(a) ActionEvent (b) ButtonEvent(c) ClickEvent (d) WindowEvent8. What is the signature of the method specified in the Java ListSelectionListenerinterface?(a) void valueChanged (ListSelectionEvent lse)(b) void ListSelectionListener (ListSelectionEvent lse)(c) void valueChanged (ListSelectionListener lsl)(d) void actionPerformed (ListSelectionEvent lse)9. The ActionEvent class and ActionListener interface are available in the ____package of Java.(a) java.event (b) javax.event(c) javax.swing.event (d) java.awt.event10. Which of the following is a Java event that is generated when the close button on aFrame component is pressed?(a) WindowEvent (b) ExitEvent(c) CloseEvent (d) DisposeEvent。

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练习题含答案-answers to pratise 5

JAVA练习题含答案-answers to pratise 5

一、Multiple Choice1.Java is an object-oriented programming language. An object-orientedlanguage:(a) Uses structured programming.(b) Views a program as consisting of objects which communicatethrough interactions.(c) Functionally breaks down problems into smaller, more manageableproblems.(d) All of the above.2.In Java, the equal sign is used as the ___________ operator.(a) increment (b) decrement(c) assignment (d) negation3.In Java, source code is compiled into object code called______________.(a) Bit-code (b) Class code(c) Method code (d) Byte-code4.Identify the invalid Java identifier.(a) 1Week (b) Week1(c) amountDue (d) amount_due5.Which operator is used to concatenate two strings?(a) + (b) –(c) * (d) /6.Which statement or group of statements produces the output:“Java”, I’m coming!(a) System.out.print(“Java”, I’m coming!)(b) System.out.println(““Java””,I’m coming!);(c) System.out.println(“\“Java\”, I\’m coming!”);(d) System.out.print(““Java”, I’m coming!”);7.When the number of repetitions are unknown in advance, you shoulduse a ___________ statement.(a) while or do…while (b) only while(c) for (d) None of the above8.A method that performs some action other than returning a value iscalled a __________ method.(a) null (b) void(c) public (d) private9.A variable whose meaning is confined to a method definition is called:(a) instance variable (b) local variable(c) global variable (d) none of the above10.I n Java, a comments block is delimited by:(a) ( ) (b) /* */(c) “ “(d) { }11.I n Java, call-by-value is only used with:(a) objects (b) primitive types(c) this (d) all of the above12.T wo methods that are expected to be in all Java classes are:(a) getName and setName (b) toString and equals(c) compareTo and charAt (d) toLowerCase and toUpperCase13.A ll of these are methods of Java’s Math class except:(a) pow (b) min (c) random (d) toString14.n ull can be used:(a) to indicate a variable has no real value(b) in a Boolean expression with ==(c) as a placeholder(d) all of the above15.A static method is one that can be used with a_____________.(a) instance variable (b)local variable(c) global variable (d)the class name as a calling object16.T The Math method that returns the nearest whole number that is greater than or equal to its argument is :(a) round (b) c eil (c) floor (d) all of the above17.W itch package in the following is the default package that each java program will import first?(a) java.util (b) ng(c) java.Math (d)java.IO18.T he parameter this refers to(a) instance variables (b)local variables(c) global variables (d)the calling object19.T he name of a method and the list of ________ types in the heading of the method definition is called the method signature.(a) parameter (b) argument (c) return (d) primitive20.R ead the following code:switch(m){ case 0: System.out.println("case 0");case 1: System.out.println("case 1");case 2: break;default: System.out.println("default"); }which one will get the output "default"A、 0B、 1C、 2D、 321.T he statement: System.out.printf("%6.2f", 597.7231); displays:(a) 597.723 (b)597.72 (c)000597.72 (d None of the above22.T he Object class contains the method:(a) getClass() (b) toString()(c) equals() (d) all of the abov23.W hen using a compound Boolean expression joined by an && (AND) in an if statement:(a) Both expressions must evaluate to true for the statement to execute.(b) The first expression must evaluate to true and the second expression must evaluate to false for the statement to execute. (c) The first expression must evaluate to false and the second expression must evaluate to true for the statement to execute. (d) Both expressions must evaluate to false for the statement to execute.24.T he looping mechanism that always executes at least once is the _____________ statement.(a) if…else (b) do…while (c) while (d) for25.W hat will happen if you try to compile and run the following class?public class Test {static int myArg = 1;public static void main(String[] args) {int myArg;System.out.println(myArg);}}a) This code compiles and displays 0 in the standard output when run.b) This code compiles and displays 1 in the standard output when run.c) This code does not compile because you cannot define a localvariable named the same as a static variable.d) This code does not compile because the local variable is used beforeit is initialized.26.A static method:a).cannot be invoked with a calling object.b).can be invoked using the class name in place of a calling object.c).must be a void method.d).all of the abovee).none of the above.27.A, B, and C are variables of type int. Which of the following programsegments would NOT have the effect of interchanging the values of the variables A and B?a) C=A; A=B; B=C;b) C=A; B=A; A=B;c) A=A+B; B=A-B; A=A-B;d) C=B; B=A; A=C;二、True or false1.Java began as a language for home appliances. ( )2.The Scanner class has a method next that allows an entire line ofstring text to be read.( )3.Syntax errors in programs are detected by the compiler. ( )4.The equality operator (==) may be used to test if two string objectscontain the same value.( )5.Java supports operator overloading.( )6.A main method can be placed inside a class definition.( )7.Java is an object-oriented programming language.( )8.Every Java method definition must contain a return statementsomewhere in it. ( )9.To use a static method of a class, there must first be an instanceof the class. ( )三、The valueΠcan be approximated by the following equationπ/4=1-1/3+1/5-1/7+……+1/(2*n-1)write a program that output the value of π. When π>3.14 and π<3.14159 the program will stop and output the result。

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

一.Which two demonstrate an “is a” relationship? (Choose Two)A. public interface Person { }//语法错了public class Employee extends Person { }B. public interface Shape { }//语法错了public class Employee extends Sha pe { }C. public interface Color { }//语法错了public class Employee extends Color { }D. public class Species { }public class Animal{private Species species;}E. interface Component { }Class Container implements Component (Private Component[ ] children;二.which statement is true?A. An anonymous inner class may be declared as finalB. An anonymous inner class can be declared as privateC. An anonymous inner class can implement mutiple interfacesD. An anonymous inner class can access final variables in any enclosing scope (不能)E. Construction of an instance of a static inner class requires an instance of the encloing outer class构造一个静态的内部类对象需要构造包含它的外部类的对象三. Given:1. package foo;2.3. public class Outer (4. public static class Inner (5. )6. )Which statement is true?A. An instance of the Inner class can be constructed with “new Outer.Inner ()”B. An instance of the inner class cannot be constructed outside of package foo他们都是public的,只要在外部import就行C. An instance of the inner class can only be constructed from within the outerclassD.From within the package bar, an instance of the inner class can be constructed with “new inner()”四.Exhibit(展览、陈列):1 public class enclosinggone{2 public class insideone{}3 }4 public class inertest{5 public static void main (String[] args){6 enclosingone eo = new enclosingone();7 //insert code here8 }}Which statement at line 7 constructs an instance of the inner class?A. InsideOne ei = eo.new InsideOne(); 写程序试出来B. Eo.InsideOne ei = eo.new InsideOne();C InsideOne ei = EnclosingOne.new InsideOne();D.EnclosingOne InsideOne ei = eo.new InsideOne();五.1) interface Foo{2) int k=0;3) }4) public class Test implements Foo{5) public static void main(String args[]){6) int i;7) Test test =new Test();8) i=test.k;9) i=Test.k;10) i=Foo.k;11) }12) }What is the result?A. Compilation succeeds.B. An error at line 2 causes compilation to fail.C. An error at line 9 causes compilation to fail.D. An error at line 10 causes compilation to fail.E. An error at line 11 causes compilation to fail.六.//point Xpublic class Foo{public static void main(String[] args){PrintWriter out=new PrintWriter(newjava.io.OutputStreamWriter(System.out),true);out.println("Hello");}}which statement at point X on line 1 allows this code to compile and run?在point X这个位置要填入什么代码才能使程序运行A.import java.io.PrintWriterB.include java.io.PrintWriterC.import java.io.OutputStreamWriterD.include java.io.OutputStreamWriterE.No statement is needed本来两个都要import,但是后者OutputStreamWriter指定了包结构java.io.OutputStreamWriter七.what is reserved words in java? 保留字而非关键字A. runB.defaultC. implementD. import八. which three are valid declaraction of a float?(float作为整数是可以的,其余几个都是double)A. float foo=-1;B. float foo=1.0;C. float foo=42e1;.D. float foo=2.02f;E. float foo=3.03d;F. float foo=0x0123;九. Given:8. int index = 1;9. boolean[] test = new boolean[3]; (数组作为对象缺省初始化为false)10. boolean foo= test [index];What is the result?A. foo has the value of 0B. foo has the value of nullC. foo has the value of trueD. foo has the value of falseE. an exception is thrownF. the code will not compile十. Given:1. public class test(2. public static void main(String[]args){3. String foo = args [1];4. String foo = args [2];5. String foo = args [3];6. }7. }And the command line invocation:Java TestWhat is the result?A. baz has the value of “”B. baz has the value of nullC. baz has the value of “red”D. baz has the value of “blue”E. bax has the value of “green”F. the code does not compileG. the program throws an exception(此题题目出错了,重复定义了变量foo,如果没有重复的话,应选G,因为只传递了0-2三个数组元素,而题目中需要访问args [3],所以会抛出数组越界异常)十一.int index=1;int foo[]=new int[3];int bar=foo[index]; //bar=0int baz=bar+index; //baz=1what is the result?A. baz has a value of 0B. baz has value of 1C. baz has value of 2D. an exception is thrownE. the code will not compile十二.1)public class Foo{2)public static void main(String args[]){3)String s;4)System.out.println("s="+s);5)}6)}what is the result?A. The code compiles and “s=” i s 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 an d 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"子类总要去调用父类的构造函数,有两种调用方式,自动调用(无参构造函数),主动调用带参构造函数。

相关文档
最新文档