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

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

阅读更多
16. What results from the following code?
1.class MyClass
2.{
3.void myMethod(int i) {System.out.println(”int version”);}
4.void myMethod(String s) {System.out.println(”String version”);}
5.public static void main(String args[])
6.{
7.MyClass obj = new MyClass();
8.char ch = ‘c';
9.obj.myMethod(ch);
10.}
11.}
A.Line 4 will not compile as void method can’t e overridden.
B.An exception at line 9.
C.Line 9 will not compile as there is no version of myMethod which takes a char as argument.
D.The code compiles and produces output: int version
E.The code compiles and produces output: String version
D is correct. A is incorrect as void methods can be overridden without any problem. B is incorrect as char ch declaration is valid. C is incorrect as char type in java is internally stored as integer and there is a method which takes int as an input. D is correct, on line 9 char ch is widened to an int and passed to int version of the myMethod(). E is incorrect as int version of myMethod() is called.
17. What is the result when you compile and run the following code?
public class ThrowsDemo { 
     static void throwMethod() { 
             System.out.println(”Inside throwMethod.”); 
             throw new IllegalAccessException(”demo”); 
     }
     public static void main(String args[]) { 
          try { 
                throwMethod(); 
          } catch (IllegalAccessException e) { 
                System.out.println(”Caught ” + e); 
          } 
      } 
}
A.compile error
B.runtime error
C.compile successfully, nothing is printed.
D.inside throwMethod followed by caught: java.lang.IllegalAccessException: demo
A is correct. Exception :java.lang.IllegalAccessExcption must be caught or placed in the throws clause of the throwMethod(), i.e. the declaration of throwMethod() be changed to “static void throwMethod() throws IllegalAccessExcption”. Thus compilation error will occur.
18. What will be printed when you execute the following code?
class X {
Y b = new Y();
   X() {
System.out.print(”X”);
}
}
class Y {
    Y() {
System.out.print(”Y”);
}
}
public class Z extends X {
      Y y = new Y();
       Z() {
System.out.print(”Z”);
}
       public static void main(String[] args) {
            new Z();
       }
}
A.Z
B.YZ
C.XYZ
D.YXYZ
D is correct. A difficult but a fundamental question, please observe carefully. Before any object is constructed the object of the parent class is constructed(as there is a default call to the parent's constructor from the constructor of the child class via the super() statement). Also note that when an object is constructed the variables are initialized first and then the constructor is executed. So when new Z() is executed , the object of class X will be constructed, which means Y b = new Y() will be executed and “Y” will be printed as a result. After that constructor of X will be called which implies “X” will be printed. Now the object of Z will be constructed and thus Y y = new Y() will be executed and Y will be printed and finally the constructor Z() will be called and thus “Z” will be printed. Thus YXYZ will be printed.
19. What will happen when you attempt to compile and run the following code snippet?
Boolean b = new Boolean(”TRUE”);   //不区分大小写
if(b.booleanValue()){
System.out.println(”Yes : ” + b);
}else{
System.out.println(”No : ” + b);
}
A.The code will not compile.
B.It will print ?C Yes: true
C.It will print ?C Yes: TRUE
D.It will print ?C No: false
E.It will print ?C No: FALSE
B is the correct choice. The wrapper class Boolean has the following constructor -public Boolean(String s) It allocates a Boolean object representing the value true if the string argument is not null and is equal, ignoring case, to the string “true”. Otherwise, allocate a Boolean object representing the value false.E.g.
new Boolean(”TRUE”) produces a Boolean object that represents true.
new Boolean(”anything”) produces a Boolean object that represents false.
The internal toString() representation of this object produces the boolean value string in lower case, hence it prints “Yes : true” instead of “Yes : TRUE”.
20. What is the result when you compile and run the following code?
public class Test{
public void method(){
for(int i = 0; i < 3; i++) {
       System.out.print(i);
       }
       System.out.print(i);
}
}
A. 0122
B. 0123
C. compile error
D. none of these
C is correct. The code on compilation will give compile time error because the scope of variable i is only within “for” loop.
21. What will happen when you attempt to compile and run the following code?
int Output = 10;
boolean b1 = false;
if((b1 == true) && ((Output += 10) == 20)){
   System.out.println(”We are equal ” + Output);
}else{
   System.out.println(”Not equal! ” + Output);
}
A.compile error
B.compile and output of “we are equal 10”
C.compile and output of “not equal!20”
D.compile and output of “not equal!10”
22. What will be the result of executing the following code?
Given that Test1 is a class.
1. Test1[] t1 = new Test1[10];
2. Test1[][] t2 = new Test1[5][];
3. if (t1[0] == null)
4. {
5.t2[0] = new Test1[10] ;
6.t2[1] = new Test1[10];
7.t2[2] = new Test1[10];
8.t2[3] = new Test1[10];
9.t2[4] = new Test1[10];
10. }
11. System.out.println(t1[0]);
12. System.out.println(t2[1][0]);
A. The code will not compile because the array t2 is not initialized in an unconditional statement before use.
B. The code will compile but a runtime exception will be thrown at line 12.
C. The code will compile but a runtime exception will be thrown at line 11.
D. None of these
D is correct. Though we cannot use local variables without initializing them (compilation error), there is an exception to it. In case of arrays initialization is supposed to be complete when we specify the leftmost dimension of the array. The problem occurs at runtime if we try to access an element of the array which has not been initialized (specification of size). In the question above the array t2 is initialized before use, therefore there will be no problem at runtime also and the lines 11 and 12 will both print null.
23. What will happen when you attempt to compile and run the following code?
class Base{
int i = 99;
public void amethod(){
       System.out.println(”Base.amethod()”);
    }
    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()
 -1
 Derived.amethod()
B. Derived.amethod()
  99
  Derived.amethod()
C. 99
D. 99
  Derived.amethod()
E. compile time error.
B is correct. The reason is that this code creates an instance of the Derived class but assigns it to a reference of a the Base class. In this situation a reference to any of the fields such as i will refer to the value in the Base class, but a call to a method will refer to the method in the class type rather than its reference handle. But note that if the amethod() was not present in the base class then compilation error would be reported as at compile time, when compiler sees the statement like b.amethod(), it checks if the method is present in the base class or not. Only at the run time it decides to call the method from the derived class.
24. What will be the output on compiling/running the following code?
public class MyThread implements Runnable {
  String myString = “Yes “;
  public void run() {
    this.myString = “No “;
  }
  public static void main(String[] args)  {
    MyThread t = new MyThread();
    new Thread(t).start();
    for (int i=0; i < 10; i++)
     System.out.print(t.myString);
  }
}
A. compile error
B. prints: yes yes yes yes yes yes and so on
C. prints: no no no no no no no no and so on
D. prints: yes no yes no ye no ye no and so on
E. the output cannot be determinated
E is correct. Please note that there will not be any compilation error when the above code is compiled. Also note that calling start() method on a Thread doesn't start the Thread. It only makes a Thread ready to be called. Depending on the operation system and other running threads, the thread on which start is called will get executed. In the above case it is not guaranteed that the thread will be executed(i.e. run() method will be called), always before “for” loop is executed. Thus the output cannot be determined.
25. Multiple objects of MyClass (given below) are used in a program that uses multiple Threads to create new integer count. What will happen when other threads use the following code?
class MyClass{
static private int myCount = 0;
int yourNumber;
private static synchronized int nextCount(){
return ++myCount;   //myCount为static
}
public void getYourNumber(){
yourNumber = nextCount();
}
}
A. the code ill give ompilation error
B. the code ill give runtime error
C. each thread will get a unique number
D. the uniqueness of the number different Threads can’t be guaranteed.
C is correct. The use of synchronized ensures that the number generated will not be duplicated, no matter how many Threads are trying to create the number. Thus D is incorrect. A and B are incorrect as the above code will not give any compiletime or runtime error.
26. Which of the following lines will print false?
1.public class MyClass
2.{
3.static String s1 = “I am unique!”;
4.public static void main(String args[])
5.{
6.String s2 = “I am unique!”;
7.String s3 = new String(s1);
8.System.out.println(s1 == s2);
9.System.out.println(s1.equals(s2));
10.System.out.println(s3 == s1);
11.System.out.println(s3.equals(s1));
12.System.out.println(TestClass.s4 == s1);
13.}
14.}
15.
16.class TestClass
17.{
18.static String s4 = “I am unique!”;
19.}
A. line 10 and 12
B. line 12 only
C. line 8 and 10
D. none of these
D is correct. Only line 10 will print false. Strings are immutable objects. That is, a string is read only once the string has been created and initialized, and Java optimizes handling of string literals; only one anonymous string object is shared by all string literals with the same contents. Hence in the above code the strings s1, s2 and s4 refer to the same anonymous string object, initialized with the character string: “I am unique!”. Thus s1 == s2 and TestClass.s4 will both return true and obviously s1.equals(s2) will return true. But creating string objects using the constructor String(String s) creates a new string, hence s3 == s1 will return false even though s3.equals(s1) will return true because s1 and s3 are referring to two different string objects whose contents are same.
27. What is displayed when the following code is compiled and executed?
String s1 = new String(”Test”);
String s2 = new String(”Test”);
if (s1==s2) System.out.println(”Same”);
if (s1.equals(s2)) System.out.println(”Equals”);
A. same equal
B. equals
C. same
D. compile but nothing is displayed upon exception
E. the code fails to compile.
B is correct. Here s1 and s2 are two different object references, referring to  different objects in memory. Please note that operator == checks for the memory address of two object references being compared and not their value. The “equals()” method of String class compares the values of two Strings. Thus s1==s2 will return “false” while s1.equals(s2) will return “true”. Thus only “Equals” will be printed.
28. What is displayed when the following is executed?
class Parent{
private void method1(){
System.out.println(”Parent's method1()”);
}
public void method2(){
System.out.println(”Parent's method2()”);
method1();
}
}
class Child extends Parent{
public void method1(){
System.out.println(”Child's method1()”);
}
public static void main(String args[]){
Parent p = new Child();
p.method2();
}
}
A. compile time error
B. run time error
C. prints: parent’s method2()  parent’s method1()
D. prints: parent’s method2()  child’s method1()
C is correct. The code will compile without any error and also will not give any run time error. The variable p refers to the Child class object. The statement p.method2() on execution will first look for method2() in Child class. Since there is no method2() in child class, the method2() of Parent class will be invoked and thus “Parent's method2()” will be printed. Now from the method2() , there is a call to method1(). Please note that method1() of Parent class is private, because of which the same method (method1() of Parent class) will be invoked. Had this method(method1() of Parent class) been public/protected/friendly (default), Child's class method1() would be called. Thus C is correct answer.
29. What will happen when you attempt to compile and run the following code snippet?
String str = “Java”;
StringBuffer buffer = new StringBuffer(str);
if(str.equals(buffer)){
System.out.println(”Both are equal”);
}else{
System.out.println(”Both are not equal”);
}
A. it will print ?C both are not equal
B. it will print ?C both are equal
C. compile time error
D. Runtime error
A is the correct choice. The equals method overridden in String class returns true if and only if the argument is not null and is a String object that represents the same sequence of characters as this String object. Hence, though the contents of both str and buffer contain “Java”, the str.equals(buffer) call results in false.
The equals method of Object class is of form -public boolean equals(Object anObject). Hence, comparing objects of different classes will never result in compile time or runtime error.
30. What will happen when you attempt to compile and run the following code?
public class MyThread extends Thread{
String myName;
MyThread(String name){
myName = name;
}
public void run(){
for(int i=0; i<100;i++){
System.out.println(myName);
}
}
public static void main(String args[]){
try{
MyThread mt1 = new MyThread(”mt1″);
MyThread mt2 = new MyThread(”mt2″);
mt1.start();
// XXX
mt2.start();
}catch(InterruptedException ex){}
}
}
A. compile error
B. mt1.join();
C. mt1.sleep(100);
D. mt1.run()
E. nothing need
Choice A and B are correct. In its current condition, the above code will not compile as “InterruptedException” is never thrown in the try block. The compiler will give following exception: “Exception java.lang.InterruptedException is never thrown in the body of the corresponding try statement.”
Note that calling start() method on a Thread doesn't start the Thread. It only makes a Thread ready to be called. Depending on the operating system and other running threads, the thread on which start is called will get executed. After making the above code to compile (by changing the InterruptedException to some other type like Exception), the output can't be predicted (the order in which mt1 and mt2 will be printed can't be guaranteed). In order to make the MyThread class prints “mt1″ (100 times) followed by “mt2″ (100 times), mt1.join() can be placed at //XXX position. The join() method waits for the Thread on which it is called to die. Thus on calling join() on mt1, it is assured that mt2 will not be executed before mt1 is completed. Also note that the join() method throws InterruptedException, which will cause the above program to compile successfully. Thus choice A and B are correct.
分享到:
评论

相关推荐

    建立在 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面试题以及技巧

    │ │ Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)考试提纲.txt │ │ ucertify_prepkit_features.pdf │ │ vmspec.2nded.html.zip │ │ 一些其它网站的java基础精华贴.txt │ │ 新建 文本...

    java面试题及技巧4

    │ │ Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)考试提纲.txt │ │ ucertify_prepkit_features.pdf │ │ vmspec.2nded.html.zip │ │ 一些其它网站的java基础精华贴.txt │ │ 新建 文本...

    java面试题及技巧3

    │ │ Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)考试提纲.txt │ │ ucertify_prepkit_features.pdf │ │ vmspec.2nded.html.zip │ │ 一些其它网站的java基础精华贴.txt │ │ 新建 文本...

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

    2. Java的学习 3. 目标 4. 联机文档 5. 章节 6. 练习 7. 多媒体 8. 源代码 9. 编码样式 10. Java版本 11. 课程和培训 12. 错误 13. 封面设计 14. 致谢 第1章 对象入门 1.1 抽象的进步 1.2 对象的接口 1.3 实现方案的...

    java面试题以及技巧6

    │ │ Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)考试提纲.txt │ │ ucertify_prepkit_features.pdf │ │ vmspec.2nded.html.zip │ │ 一些其它网站的java基础精华贴.txt │ │ 新建 文本...

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

    《深入Java虚拟机(原书第2版)》,原书名《Inside the Java Virtual Machine,Second Edition》,作者:【美】Bill Venners,翻译:曹晓钢、蒋靖,出版社:机械工业出版社,ISBN:7111128052,出版日期:2003 年 9 ...

    java面试题目与技巧1

    │ │ Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)考试提纲.txt │ │ ucertify_prepkit_features.pdf │ │ vmspec.2nded.html.zip │ │ 一些其它网站的java基础精华贴.txt │ │ 新建 文本...

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

    java模拟掷骰子2个 1个目标文件,输出演示。 java凭图游戏 一个目标文件,简单。 java求一个整数的因子 如题。 Java生成密钥的实例 1个目标文件 摘要:Java源码,算法相关,密钥  Java生成密钥、保存密钥的实例源码...

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

    java模拟掷骰子2个 1个目标文件,输出演示。 java凭图游戏 一个目标文件,简单。 java求一个整数的因子 如题。 Java生成密钥的实例 1个目标文件 摘要:Java源码,算法相关,密钥  Java生成密钥、保存密钥的实例源码...

    java模拟qq源码

    (6)在项目上单击鼠标右键,依次选择“新建”/“文件夹”命令,新建一个“lib”文件夹,然后,将JavaDB数据库驱动文件“derby.jar”拷到该文件夹中。在该文件上单击鼠标右键,选择“构建路径”/“添加至构建路径”...

    java 编程入门思考

    2. Java的学习 3. 目标 4. 联机文档 5. 章节 6. 练习 7. 多媒体CD-ROM 8. 源代码 9. 编码样式 10. Java版本 11. 课程和培训 12. 错误 13. 封面设计 14. 致谢 第1章 对象入门 1.1 抽象的进步 1.2 对象的接口 1.3 ...

    Java初学者入门教学

    2. Java的学习 3. 目标 4. 联机文档 5. 章节 6. 练习 7. 多媒体CD-ROM 8. 源代码 9. 编码样式 10. Java版本 11. 课程和培训 12. 错误 13. 封面设计 14. 致谢 第1章 对象入门 1.1 抽象的进步 1.2 对象的接口 1.3 ...

    java联想(中文)

    2. Java的学习 3. 目标 4. 联机文档 5. 章节 6. 练习 7. 多媒体CD-ROM 8. 源代码 9. 编码样式 10. Java版本 11. 课程和培训 12. 错误 13. 封面设计 14. 致谢 第1章 对象入门 1.1 抽象的进步 1.2 对象的接口 1.3 ...

    java程序设计实验指导代码

    4.3 实验2 鸽巢原理的模拟 4.4 实验3 矩阵相乘问题 4.5 实验4 "速算24"游戏 第5章 类和对象 5.1 预备知识 5.2 实验1 对象的创建和使用 5.3 实验2 类的静态成员与实例成员 5.4 实验3 变量的作用域和this关键字 ...

    java自学之道

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

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

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

Global site tag (gtag.js) - Google Analytics