`
sakakokiya
  • 浏览: 490864 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

30道Java 1.4模拟经典题(1)

阅读更多
1. What will happen when you attempt to compile and run the following code?
(Assume that the code is compiled and run with assertions enabled.)
public class AssertTest{
public void methodA(int i){
assert i >= 0 : methodB();
System.out.println(i);
}
public void methodB(){  //无返回值
System.out.println(”The value must not be negative”);
}
public static void main(String args[]){
AssertTest test = new AssertTest();
test.methodA(-10);
}
}
A.it will print -10
B.it will result in AssertionError showing the message-“the value must not be negative”.
C.the code will not compile.
D.None of these.
C is correct. An assert statement can take any one of these two forms -
assert Expression1;
assert Expression1 : Expression2;
Note that, in the second form; the second part of the statement must be an expression- Expression2. In this code, the methodB() returns void, which is not an expression and hence it results in a compile time error. The code will compile if methodB() returns any value such as int, String etc.
Also, in both forms of the assert statement, Expression1 must have type boolean or a compile-time error occurs.
2. What will happen when you attempt to compile and run the following code?
public class Static{
static{
int x = 5;  //在static内有效
}
static int x,y;   //初始化为0
public static void main(String args[]){
       x-;   //-1
myMethod();
       System.out.println(x + y + ++x);
}
public static void myMethod(){
y = x++ + ++x;  //y=-1+1  x=1
}
}
A.compiletime error
B.prints: 1
C.prints: 2
D.prints: 3
E.prints: 7
F.prints: 8
D is the correct choice. The above code will not give any compilation error. Note that “Static” is a valid class name. Thus choice A is incorrect.
In the above code, on execution, first the static variables (x and y) will be initialized to 0. Then static block will be called and finally main() method will be called. The execution of static block will have no effect on the output as it declares a new variable (int x).
The first statement inside main (x-) will result in x to be -1. After that myMethod() will be executed. The statement “y = x++ + ++x;” will be evaluated to y = -1 + 1 and x will become 1. In case the statement be “y =++x + ++x”, it would be evaluated to y = 0 + 1 and x would become 1. Finally when System.out is executed “x + y + ++x” will be evaluated to “1 + 0 + 2″ which result in 3 as the output. Thus choice D is correct.
3. Given the following code, what will be the output?
class Value{
public int i = 15;
}
public class Test{
public static void main(String argv[]){
       Test t = new Test();
t.first();
   }
public void first(){
       int i = 5;
       Value v = new Value();
v.i = 25;
second(v, i);
   System.out.println(v.i);
}
public void second(Value v, int i){
i = 0;
       v.i = 20;
Value val = new Value();
       v = val;
   System.out.println(v.i + ” ” + i);
}
}
A.15 0 20
B.15 0 15
C.20 0 20
D.0 15 20
A is correct. When we pass references in Java what actually gets passed is the value of that reference (i.e. memory address of the object being referenced and not the actual object referenced by that reference) and it gets passed as value (i.e a copy of the reference is made). Now when we make changes to the object referenced by that reference it reflects on that object even outside of the method being called but any changes made to the reference itself is not reflected on that reference outside of the method which is called. In the example above when the reference v is passed from method first() to second() the value of v is passed. When we assign the value val to v it is valid only inside the method second() and thus inside the method second() what gets printed is 15 (initial value of i in the object referenced by val), then a blank space and then 0 (value of local variable i). After this when we return to the method first() v actually refers to the same object to which it was referring before the method second() was called, but one thing should be noted here that the value of i in that object (referred by v inside the method first()) was changed to 20 in the method second() and this change does reflect even outside the method second(), hence 20 gets printed in the method first(). Thus overall output of the code in consideration is
15 0
20
4. What will happen when you attempt to compile and run the following code?
class MyParent {
int x, y;
MyParent(int x, int y){
this.x = x;
this.y = y;
}
public int addMe(int x, int y){
return this.x + x + y + this.y;
}
public int addMe(MyParent myPar){
return addMe(myPar.x, myPar.y);
}
}
class MyChild extends MyParent{
int z;
MyChild (int x, int y, int z){
super(x,y);
this.z = z;
}
public int addMe(int x, int y, int z){
return this.x + x + this.y + y + this.z + z;
}
public int addMe(MyChild myChi){
return addMe(myChi.x, myChi.y, myChi.z);
}
public int addMe(int x, int y){
return this.x + x + this.y + y;
}
}
public class MySomeOne{
public static void main(String args[]){
MyChild myChi = new MyChild(10, 20, 30);
MyParent myPar = new MyParent(10, 20);
int x = myChi.addMe(10, 20, 30);
int y = myChi.addMe(myChi);
int z = myPar.addMe(myPar);
System.out.println(x + y + z);
}
}
A.300
B.240
C.120
D.180
E.compile error
F.none of the above
A is the correct choice. In the above code, MyChild class overrides the addMe(int x, int y) method of the MyParent class. And in both the MyChild and MyParent class, addMe() method is overloaded. There is no compilation error anywhere in the above code.
On execution, first, the object of MyChild class will be constructed. Please note that there is a super() call from the constructor of MyChild class, which will call the constructor of MyParent class. This will cause the value of z variable of MyChild class to be 30 and x, y variables of MyParent class will become 10 and 20 respectively. The next statement will again call the constructor of MyParent class with same x and y values. This is followed by execution of addMe() method of MyChild class with x as 10, y as 20 and z as 30. Also x and y are inherited by MyChild class from the MyParent class. Thus in the addMe() method of the MyChild class, the value of this.x will be 10, this.y will be 20 and this.z will be 30. The return value of this method will be “10 + 10 + 20 + 20 + 30 + 30″, which is equal to 120. Thus x will become 120.
This is followed by the invocation of the other addMe() method which takes object reference of the MyChild class. From this method, the method which was called earlier is invoked. This call is exactly the same as the earlier one. Thus the value of y will also be 120 like x.
Now the addMe() method of MyParent class is invoked. This method invokes another addMe() method of the same class. Its equivalent to the invocation of addMe(int x, int y) method with x as 10 and y as 20. Also the value of instance variables x and y of My Parent class is 10 and 20 respectively. The value of z will be evaluated to “10 + 10 + 20 + 20″, which is equal to 60. Thus the value of x, y and z after all the invocations will be 120, 120 and 60 respectively. As a result of this finally, “120 + 120 + 60″ which is equal to 300 will be printed. Thus A is the correct choice.
5. The class AssertionError has “is -a” relationship with these classes (choose two)
A.RuntimeException
B.Error
C.VirtualMachineError
D.IllegalAccessException
E.Throwable
B and E are correct. The class AssertionError is an Error, which denotes an “incorrect condition” as opposed to an “unusual condition” (Exception).  Since, the class Error descends from Throwable, AssertionError also has “is-a” relationship with Throwable. Here is the hierarchy ?Cjava.lang.Object
 |
 +-java.lang.Throwable
       |
       +-java.lang.Error
             |
             +-java.lang.AssertionError
Want to know more?
You can find more information about this as an answer to the question - “Why is AssertionError a subclass of Error rather than RuntimeException?” at - http://java.sun.com/j2se/1.4/docs/guide/lang/assert.html #design-faq-error
6. What will be the result of executing the following code?
1. boolean a = true;
2. boolean b = false;
3. boolean c = true;
4. if (a == true)
5.   if (b == true)
6.       if (c == true) System.out.println(”Some things are true in this world”);
7.       else System.out.println(”Nothing is true in this world!”);
8.   else if (a && (b = c))   //这里是赋值,不是比较
System.out.println(”It's too confusing to tell what is true and what is false”);
9.   else  System.out.println(”Hey this won't compile”);
A.The code won’t compile.
B.“some things are true in this world” will be printed
C.“hey this won’t compile” will be printed
D.None of these
D is correct. This is a very good question to test the concepts of execution flow in case of if conditions. The rule for attaching else statements with if conditions is the same as attaching close brackets with open brackets. A close bracket attaches with the closest open bracket, which is not already closed. Similarly an else statement attaches with the closest if statement, which doesn't have an else statement already, attached to it. So the else statement at line 7 attaches to the if statement at line 6. The else statement at line 8 attaches to the if statement at line 5. The else statement at line 9 attaches to the if statement at line 8.
Now let's look at the execution. At line 4 since a is equal to true the execution falls to line 5. At line 5 since b is not true the execution goes to the corresponding else statement at line 8. Now it evaluates the condition inside the if statement. Please note here that an assignment statement also has a value equal to the value being assigned, hence (b = c) evaluates to true and subsequently a && (b = c) evaluates to true and “It's too confusing to tell what is true and what is false” will be printed. Hence the correct answer is choice D.
7. What will happen when you attempt to compile and run the following code?
interface MyInterface{}
public class MyInstanceTest implements MyInterface{
static String s;
public static void main(String args[]){
MyInstanceTest t = new MyInstanceTest();
if(t instanceof MyInterface){
System.out.println(”I am true interface”);
}else {
System.out.println(”I am false interface”);
}
if(s instanceof String){
System.out.println(”I am true String”);
}else {
System.out.println(”I am false String”);
}
}
}
A.compile time error
B.runtime error
C.prints: “I am true interface” followed by “I am true String”
D.prints: “I am false interface” followed by “I am false String”
E.prints: “I am true interface” followed by “I am false String”
F.prints: “I am false interface” followed by “I am true String”
E is the correct choice. The “instanceof” operator tests the class of an object at
runtime. It returns true if the class of the left-hand argument is the same as, or
is some subclass of, the class specified by the right-hand operand.
The right-hand operand may equally well be an interface. In such a case, the test
 determines if the object at left-hand argument implements the specified interface.
In the above case there will not be any compiletime or runtime error. The result of
 ”t instance of MyInterface” will be true as “t” is the object of MyInstanceTest
 class which implements the MyInstance interface. But the result of “s instanceof
 String” will be false as “s” refers to null. Thus the output of the above program
 will be : “I am true interface” followed by ” I am false String”. Thus choice E is
 correct and others are incorrect.
8. What results from attempting to compile and run the following code?
public class Ternary{
public static void main(String args[]){
int a = 5;
System.out.println(”Value is - ” + ((a < 5) ? 9.9 : 9));
}
}
A.print:Value is -9
B.print:Value is -5
C.Compilation error
D.None of these
D is correct. The code compiles successfully. In this code the optional value for
the ternary operator, 9.0(a double) and 9(an int) are of different types. The
 result of a ternary operator must be determined at the compile time, and here the
  type chosen using the rules of promotion for binary operands, is double.
   Since the result is a double, the output value is printed in a floating point
   format. The choice of which value to be printed is made on the basis of the
   result of the comparison “a < 5″ which results in false, hence the variable “a”
   takes the second of the two possible values, which is 9, but because the result
   type is promoted to double, the output value is actually written as 9.0, rather
   than the more obvious 9, hence D is correct.
9. In the following pieces of code,
A and D will compile without any error. True/False?
A: StringBuffer sb1 = “abcd”;
B: Boolean b = new Boolean(”abcd”);
C: byte b = 255;
D: int x = 0×1234;
E: float fl = 1.2;
True
False
The code segments B and D will compile without any error.
 A is not a valid way to construct a StringBuffer, you need to creat
  a StringBuffer object using “new”.
  B is a valid construction of a Boolean
  (any string other than “true” or “false” to the Boolean constructor will
  result in a Boolean with a value of “false”).
   C will fail to compile because the valid range for a byte is -128 to +127 (
   ie, 8 bits,signed). D is correct, 0×1234 is the hexadecimal representation
   in java. E fails to compile because the compiler interprets 1.2 as
   a double being assigned to a float (down-casting), which is not valid.
   You either need an explicit cast (as in “(float)1.2″) or “1.2f”,
    to indicate a float.
10. Considering the following code, Which variables may be referenced correctly
at line 12?
1.public class Outer
2.{
3.public int a = 1;
4.private int b = 2;
5.public void method(final int c)
6.{
7.int d = 3;
8.class Inner
9.{
10.private void iMethod(int e)
11. {
12.
13.}
14.}
15.}
16.}
a b c d e
A, B, C and E are correct. Since Inner is not a static inner class,
it has a reference to an enclosing object, and all the variables of that object are
 accessible. Therefore A and B are correct, even if b is private.
  Variables in the enclosing method are only accessible when they are marked as
  final hence c is accessible but not d. E is obviously
  correct as it is a parameter to the method containing line 12 itself.
11. What will be the result of executing the following code?
public static void main(String args[]){
   char digit = ‘a';
   for (int i = 0; i < 10; i++){
     switch (digit){
       case ‘x' :{
       int j = 0;
   System.out.println(j);
       }
       default :{
       int j = 100;
   System.out.println(j);
       }
     }
  }
  int i = j;
  System.out.println(i);
}
A.100 will be printed 11 times.
B.100 will be printed 10 times and then there will be a runtime exception
C.The code will not compile because the variable i cannot be declared twice within the mani() method.
D.The code will not compile because the variable j cannot be declared twice within the switch statement.
E.None of these.
E is correct. The code will not compile. There is no problem with the declaration
of another variable i as both the variables are in disjoint blocks
(first one is inside the for loop and its scope ends with the for loop,
whereas the second is outside the for loop) and,
therefore, different scopes and hence valid. The problem is with the variable j.
The two declarations of the variable j are perfectly valid as they are in disjoint
 blocks and, therefore, different scopes. The error is that both the declarations
 of j are not available outside the case or default statement,
 whereas we are trying to assign it to the variable i.
 Therefore the compiler objects and reports variable j not found.
12. Which of the following collection classes from java.util package are Thread safe?
A.Vector
B.ArrayList  //与Vector类似,只是不同步
C.HashMap
D.Hashtable
A and D are correct. Vector and Hashtable are two collection classes that are inherently thread safe or synchronized; whereas, the classes ArrayList and HashMap are unsynchronized and must be “wrapped” via Collections.SynchronizedList or Collections.synchronizedMap if synchronization is desired.
13. What will happen when you attempt to compile and run the following code?
class MyThread extends Thread{
public void run(){
System.out.println(”MyThread: run()”);
}
public void start(){
System.out.println(”MyThread: start()”);
}
}
class MyRunnable implements Runnable{
public void run(){
System.out.println(”MyRunnable: run()”);
}
public void start(){
System.out.println(”MyRunnable: start()”);
}
}
public class MyTest {
public static void main(String args[]){
MyThread myThread  =  new MyThread();
MyRunnable myRunnable = new MyRunnable();
Thread thread  =  new Thread(myRunnable);
myThread.start();
thread.start();
}
}
A.prints: MyThread: start() followed by MyRunnable: run()
B.prints: MyThread: run() followed by MyRunnable: start()
C.prints: MyThread: start() followed by MyRunnable: start()
D.prints: MyThread: run() followed by MyRunnable: run()
E.compile time error
F.None of the above
A is the correct choice. In the above code there is not any compilation error. Thus choice E is incorrect. Inside main() method, objects of MyThread and MyRunnable class are created followed by creation of  Thread with object of MyRunnable class.
Note that MyThread class extends Thread class and overrides the start() method of the Thread class. Thus on execution of “myThread.start()” statement, the start() method of the MyThread class will be executed and as a result “MyThread:start()” will be printed. Had the start() method not there in MyThread class, the start() method of the Thread class would be called which in turn would call the run() method of the MyThread class.
On execution of “thread.start();”, the start() method of the Thread class would be called which in turn will call the run() method of the class which is passed to Thread constructor (i.e. MyRunnable class). Thus “MyRunnable:run()” will be printed out. Thus choice A is correct.
14. What will be the result of executing the following code?
// Filename; SuperclassX.java
package packageX;
public class SuperclassX{
protected void superclassMethodX(){}
int superclassVarX;
}
// Filename SubclassY.java
1.package packageX.packageY;
2.
3.public class SubclassY extends SuperclassX
4.{
5.SuperclassX objX = new SubclassY();
6.SubclassY objY = new SubclassY();
7.void subclassMethodY()
8.{
9.objY.superclassMethodX();
10.int i;
11.i = objY.superclassVarX;
12.}
13.}
A.Compile error at line 5.
B.Compile error at line 9.
C.Runtime exception at line 11.
D.None of these
D is correct. When no access modifier is specified for a member, it is only accessible by another class in the package where its class is defined. Even if its class is visible in another package, the member is not accessible there. In the question above the variable superclassVarX has no access modifier specified and hence it cannot be accessed in the packageY even though the class SuperclassX is visible and the protected method superclassMethodX() can be accessed. Thus the compiler will raise an error at line 11.
15. Consider the class hierarchy shown below:
     FourWheeler
(implements DrivingUtilities)
/ / \ \
   /  /   \  \
 /   /     \   \
/    /       \    \
   /     /         \     \
 Car  Truck        Bus  Crane
Consider the following code below:
1.DrivingUtilities du;
2.FourWheeler fw;
3.Truck myTruck = new Truck();
4.du = (DrivingUtilities)myTruck;
5.fw = new Crane();
6.fw = du;
Which of the statements below are true?
A.Line 4 will not compile because an interface cannot refer to an object.
B.The code will compile and run.
C.The code will not compile without an explicit cast at line 6, because going down the hierarchy without casting is not allowed.
D.The code at line 4 will compile even without the explicit cast.
E.The code will compile if we put an explicit cast at line 6 but will throw an exception at runtime.
C and D are correct. A and B are obviously wrong because there is nothing wrong in an interface referring to an object. C is correct because an explicit cast is needed to go down the hierarchy. D is correct because no explicit cast is needed at line 4, because we are going up the hierarchy. E is incorrect because if we put an explicit cast at line 6, the code will compile and run perfectly fine, no exception will be thrown because the runtime class of du (that is Truck) can be converted to type FourWheeler without any problem.
分享到:
评论

相关推荐

    建立在 Greenfoot 框架之上的基于 Java 的城市模拟游戏

    建立在 Greenfoot 框架之上的基于 Java 的城市模拟游戏。 文件 CitySim-master.zip 具有以下条目。 +libs/commons-dbutils-1.4.jar//from w w w . java 2 s . c om +libs/guava-12.0.jar .gitignore Animation...

    sun认证模拟题1.4

    下载后解压缩得到几个 JAR 文件 下载后 Windows 下可以双击运行, 点击最大化后, 然后点击 Mark 按钮就可以看到正确答案和解释了. 运行: java -jar Final.jar 这样的命令即可运行.

    powermock-legacy:PowerMock-Legacy 是 PowerMock for Java 1.4 的复刻版

    是 1.3 的一个分支,它可以帮助您模拟 Java 1.4 中的对象和类。要求Java 1.4(我假设你已经安装了它) JUnit 3.8.1(最后一个适用于 jvm 1.4) Mockito 1.8.0 for jvm 1.4(James Carr 编译的) RetroTranslator ...

    java采购管理系统源码-retrotranslator:Retrotranslator是使Java应用程序兼容Java1.4、Java1.3

    1.4、Java 1.3 和其他环境兼容的工具。 它支持所有 Java 5.0 语言功能以及 J2SE 1.4 和 J2SE 1.3 上 Java 5.0 API 的重要部分。 在其他 Java 环境中,仅支持不依赖于新 API 的 Java 5.0 功能。 Retrotranslator 使用...

    java面试题以及技巧

    │ │ │ 经典的104-147模拟题.rar │ │ │ │ │ ├─035 │ │ │ 2003.10.5.15.51.43.TestKing%20310-035%20Edt9.rar │ │ │ Desktop_.ini │ │ │ TestKing 310-035 Edt4.0.pdf │ │ │ TestKing 310-035 ...

    java面试题及技巧4

    │ │ │ 经典的104-147模拟题.rar │ │ │ │ │ ├─035 │ │ │ 2003.10.5.15.51.43.TestKing%20310-035%20Edt9.rar │ │ │ Desktop_.ini │ │ │ TestKing 310-035 Edt4.0.pdf │ │ │ TestKing 310-035 ...

    java面试题及技巧3

    │ │ │ 经典的104-147模拟题.rar │ │ │ │ │ ├─035 │ │ │ 2003.10.5.15.51.43.TestKing%20310-035%20Edt9.rar │ │ │ Desktop_.ini │ │ │ TestKing 310-035 Edt4.0.pdf │ │ │ TestKing 310-035 ...

    java面试题以及技巧6

    │ │ │ 经典的104-147模拟题.rar │ │ │ │ │ ├─035 │ │ │ 2003.10.5.15.51.43.TestKing%20310-035%20Edt9.rar │ │ │ Desktop_.ini │ │ │ TestKing 310-035 Edt4.0.pdf │ │ │ TestKing 310-035 ...

    Thinking in Java 中文第四版+习题答案

    A.1.4 JNI和Java违例 A.1.5 JNI和线程处理 A.1.6 使用现成代码 A.2 微软的解决方案 A.3.1 @dll.import引导命令 A.3.2 com.ms.win32包 A.3.3 汇集 A.3.4 编写回调函数 A.3.5 其他J/Direct特性 A.4 本原接口(RNI) A....

    java面试题目与技巧1

    │ │ │ 经典的104-147模拟题.rar │ │ │ │ │ ├─035 │ │ │ 2003.10.5.15.51.43.TestKing%20310-035%20Edt9.rar │ │ │ Desktop_.ini │ │ │ TestKing 310-035 Edt4.0.pdf │ │ │ TestKing 310-035 ...

    JAVA上百实例源码以及开源项目

    笔者当初为了学习JAVA,收集了很多经典源码,源码难易程度分为初级、中级、高级等,详情看源码列表,需要的可以直接下载! 这些源码反映了那时那景笔者对未来的盲目,对代码的热情、执着,对IT的憧憬、向往!此时此...

    JAVA上百实例源码以及开源项目源代码

    Applet钢琴模拟程序java源码 2个目标文件,提供基本的音乐编辑功能。编辑音乐软件的朋友,这款实例会对你有所帮助。 Calendar万年历 1个目标文件 EJB 模拟银行ATM流程及操作源代码 6个目标文件,EJB来模拟银行ATM...

    java模拟qq源码

    (1)将光盘\TM\02\EQ文件夹拷贝到Eclipse的工作空间中。 (2)启动Eclipse。 (3)选择“文件”/“导入”菜单项,展开“常规”节点,选择“现有项目到工作空间中”子节点,如图1.1所示。 图1.1 “导入”窗口 (4...

    深入Java虚拟机(原书第2版).pdf【附光盘内容】

    1.4 java体系结构的代价 1.5 结论 1.6 资源页 第2章 平台无关 2.1 为什么要平台无关 2.2 java的体系结构对平台无关的支持 2.2.1 java平台 2.2.2 java语言 2.3.3 java class文件 2.2.4 可伸缩...

    java 编程入门思考

    A.1.4 JNI和Java违例 A.1.5 JNI和线程处理 A.1.6 使用现成代码 A.2 微软的解决方案 A.3 J/Direct A.3.1 @dll.import引导命令 A.3.2 com.ms.win32包 A.3.3 汇集 A.3.4 编写回调函数 A.3.5 其他J/Direct特性 A.4 本原...

    Java初学者入门教学

    A.1.4 JNI和Java违例 A.1.5 JNI和线程处理 A.1.6 使用现成代码 A.2 微软的解决方案 A.3 J/Direct A.3.1 @dll.import引导命令 A.3.2 com.ms.win32包 A.3.3 汇集 A.3.4 编写回调函数 A.3.5 其他J/Direct特性 A.4 本原...

    java自学之道

    第2章 Java经典练习题 2.1 斐波那契数列 2.2 判断素数 2.3 水仙花数 2.4 分解质因数 2.5 杨辉三角 2.6 学习成绩查询 2.7 求最大公约数与最小公倍数 2.8 完全平方数 2.9 统计字母、空格、数字和其它字符个数 2.10 求...

    java联想(中文)

    A.1.4 JNI和Java违例 A.1.5 JNI和线程处理 A.1.6 使用现成代码 A.2 微软的解决方案 A.3 J/Direct A.3.1 @dll.import引导命令 A.3.2 com.ms.win32包 A.3.3 汇集 A.3.4 编写回调函数 A.3.5 其他J/Direct特性 A.4 本原...

    java程序设计实验指导代码

    第1章 Java语言概述和开发环境 1.1 预备知识 1.2 实验1 JDK 5.0路径设置 1.3 实验2 在DOS环境下编译和运行Application和Applet程序 1.4 实验3 在JBuilder 2005中配置JDK 5.0编译环境 1.5 实验4 在JBuilder 2005...

    基于java电脑彩票销售管理系统的设计软件程序源码+WORD毕业论文文档.zip

    基于java电脑彩票销售管理系统的设计软件程序源码+WORD毕业论文文档. 电脑彩票销售管理系统主要用于实现彩票销售,电脑彩票销售管理系统的设计与实现根据所需要的功能, 划分为前后台2个用户,即前台会员用户功能和...

Global site tag (gtag.js) - Google Analytics