java基础题

1.内部类如何调用外部类的方法和属性?
2.写一个线程生产类的消费类的实例?
3.请解释一下java swing的MVC的工作过程?
4.有什么编程技巧可以提高java程序的性能?

1.java有哪些基本数据类型 String是不是,有何区别?
2.写一方法,实现字符串的反转?
3.写一方法,实现字符串的替换?
4.如何将数值型字符转换为数字(Integer,Double)?
5.如何取得年月日小时分秒?
6.如何取得从1970 年到现在的毫秒数?
7.如何获得某个日期当月的最后一天?
8.如何格式化日期?
9.如何列出某个目录下的所有文件?
10....................子目录?
11.Java 多态的实现(继承,重载,覆盖)?
12.编码转换,从GB2312 到 ISO-8859-1
13.statement 和 preparedStatement 之间的区别?
14.jsp和servlet 有哪些相同点和不同点,联系是什么??
15.如何获得servlet的实际路径?
16.写出jdbc连接数据库的过程?
17.cookie 和session 有什么作用?
18.MVC设计模式如何实现的?
19.petstore 的层次结构是怎么样的?
20.ArrayList 和Vector,LinkedList 的区别?
21.如何克隆对象?
22.多线程有几种表示方法,都是什么,同步有几种方法,是什么?
23.内部类的实现方式?
24.谈一谈javar 垃圾回收机制?
25.jsp有哪些内置对象,都是什么?
26.jsp有哪些动作,作用分别是什么?
27.说说servlet的生命周期?
28.Class.forname 的作用,为什么要用?
29,xml 有哪些解析技术,区别是什么?
30.用jdom解析xml文件时,如何解决中文问题,如何解析?
31.EJB2.0有哪些内容,分别在什么场合?
32.查询一个表中符合条件的记录的前几条或后几条?

//
public boolean testAns(String ans, int n){
        boolean rslt;
        if( ans.equalsIgnoreCase("YES") && n > 5)
                rslt = true;
        return rslt;
}
会出现什么情况??/
///
inner class的问题,更多的人感到迷惑。
比如,inner class是否能够有static的变量?

一般的说法是,static inner class能够有static的变量,而non-static inner
class则不能有static的变量。但是,如果这样:
class outer {
        class inner {
                static final int i = 999;
        }
}
编译通过。而你不能这么写:
                static final int i;
就是说,一定要在声明它的时候赋予初值, 因为i是final的,它的值不能再被改变。
关于inner class, 还有一个代码也很能说明一些问题。
public class TestClass
{
    public TestClass(int i) { }

    public void m1()
    {
        TestClass al = new TestClass(10)
                       {
                            public void actionPerformed(ActionEvent e)
                            {
                            }
                      };
    }
}
这说明了一下四个问题:
1. 类中的方法也可以有inner classes.(但是他们不能有static inner classes).
2. Inner class 能够继承包含它的外部class.
3. 匿名 inner class 可以继承一个 class 或者 implements 一个 interface。
4. 匿名 inner class 可以有初始化参数。(如果这个class继承的基类有相应的 constructor 的话。)
//
再来看看动态联编 ( dyanamic link )的问题。
考虑这段代码:
class base{
        public void whoami() {
                System.out.println("Base");
        }
}
class derived extends base{
        public void whoami() {
                System.out.println("Derived");
        }
}

class test{
        public static void main(String[] args) {
                base b = new base();
                derived d = new derived();
                b.whoami();
                d.whoami();
                base b2 = d;
                b2.whoami();
        }
}
当然大家很清楚,b.whoami()打印Base, 而d.whoami()打印Derived.但是,b2.whoami()打印什么呢?也就是说,b2.whoami()将调用那一个方法呢?是基类的还是派生类的?运行以后看到,调用的是派生类的方法。这是因为java是在运行过程中采用了动态联编的方法,在运行时刻来决定该reference指向的什么类的对象,从而决定调用哪一个类的方法,而不是根据reference的类型来决定调用哪一个类的方法。从而可以使我们通过这一机制来完成多样化的程序。(具体涉及到编程的方法问题,不在我们这篇文章的讨论范围,如果有需要,我会在其他文章中介绍。)
再来看另外一个类似的例子:
class base{
        int i = 100;
        public void print() {
                System.out.println(i);
        }
}
class derived extends base{
        int i = 999;
        public void print() {
                System.out.println(i);
        }
}

class test{
        public static void main(String[] args) {
                base b = new base();

                derived d = new derived();
                b.print();
                System.out.print(b.i);
                d.print();
                System.out.print(d.i);
                base b2 = d;
                b2.print();
                System.out.print(b2.i);
        }
}

很简单的,前面的调用:
                b.print();
打印100
                System.out.print(b.i);
打印100
                d.print();
打印999
                System.out.print(d.i);
打印999.
但是
                System.out.print(b2.i);
打印什么呢?结果是100, 而不是999。这是因为,在动态联编过程中,只是函数参与了,而对于类中的变量,则还是以静态的方式编译的,就是说,编译器是凭借reference的类型来决定类变量的。b2是base类型的reference, 所以b2.i
是基类中的变量的值。

关于动态联编,还有2个要注意的问题:
class base{
}
class derived extends base{
        public void print() {
                System.out.println("Derived");
        }
}

class test{
        public static void main(String[] args) {
                base b = new base();
                derived d = new derived();
                d.print();
                base b2 = d;
                b2.print();//出错
        }
}
为什么呢?因为在编译过程中,编译器会检查基类中是否有print()方法,如果没有,则会报错。注意:动态联编出现在运行过程中,而不是编译过程中。
class base{
        int i = 100;
        public void print() {
                System.out.println(i);
        }
}
class derived extends base{
        int i = 999;
        public void print() {
                System.out.println(i);
        }
}

class test{
        public static void main(String[] args) {
                base b = new base();
                derived d = new derived();
                b.print();
                System.out.print(b.i);
                d.print();
                System.out.print(d.i);
                base b2 = d;
                b2.print();
                System.out.print(b2.i);
                derived d2 = b;//出错
                d2.print();//出错
                System.out.print(d2.i);//出错
        }
}
这是因为,在编译过程中,derived类型的reference可以赋给base类型的reference.
而base类型的reference则不可以赋给derived类型的reference.如果要这么做,
则需要在赋值的过程中指定
               derived d2 = (derived)b;
编译才能通过。这和primitive types的赋值是一样的道理。而编译完成后在运行时刻还需要做进一步的检验,如果类型不能匹配,则会抛出
ClassCastException.
Exception in thread "main" java.lang.ClassCastException: base
     at test.main(a2.java:12)
///
记住这些关于java基础数据类型的规则:

  1。任何比int数据类型大的数值都不能被赋值给int或者比int小的数值类型(比如byte, char, short).只能用显式的类型转换的方法才能够赋值。

  2。如果常量的数值在该数值类型的表示范围之内,小于或者等于int的常量能够不用显式的类型转换的方法赋值给小的数据类型(比如short或者byte)。

  3。对于所有的数学操作符号(比如+ - * / %),它们的操作数都必须先被改变为int数值类型才能被操作。所有的计算结果都至少是int数据类型。

  4。复合操作符号(比如 +=, -=, *=, /=, %= 等等)有另外一种规则:

  比如 E1 op= E2相当于是 E1 = (T)((E1) op (E2)), 这里 T 是 E1的数据类型。

  注意:这时候所用到的隐藏式的类型转换可以是相同类型的转换或者是一个从大的数据类型到小的数据类型的类型转换。举例来说,如下的代码是正确的:


short x = 3;
x += 4.6;

 

  x的结果是7。这相当于是:


short x = 3;
x = (short)(x + 4.6);

 

流程控制和异常机制:
题目:
What will the following program print?

public class TestClass
{
  public static void main(String[] args)
  {
     int x = 1;
     int y = 0;
     if( x/y ) System.out.println("Good");
     else System.out.println("Bad");
  }
}

A. Good
B. Bad
C. Exception at runtime saying division by Zero.
D. It will not compile.
E. None of the above.

这一题,容易无选为C, 因为可能考虑到,y=0那么在运行的时候会出现ArithmeticException. 但是,要考虑到,这个程序在编译的时候是不能通过的,因为,Java和C++的不同之处之一是,C++在if()里面可以是任何的数值,非0即为真,0为假。但是,Java要求在if()里面必须是boolean类型的变量不能为其它的整数。所以,这一道题的答案是D.实际在编译器中编译一下这个程序我们可以看到:
C: emp>javac TestClass.java
TestClass.java:7: incompatible types
found : int
required: boolean
     if( x/y ) System.out.println("Good");
          ^
1 error

题目:
What will be the output of the following class...

class Test
{
   public static void main(String[] args)
   {
      int j = 1;
      try
      {
         int i = doIt() / (j = 2);
      } catch (Exception e)
      {
         System.out.println(" j = " + j);
      }
   }

   public static int doIt() throws Exception { throw new Exception("FORGET IT"); }
}

A. It will print j = 1;
B. It will print j = 2;
C. The value of j cannot be determined.
D. It will not compile.
E. None of the above.

这道题目容易错误的选择为D.
注意两点:
1、public static int doIt() throws Exception { throw new Exception("FORGET IT"); }这一语句编译是正确的,因为不论返回值是否为void, 只要有throw语句,可以没有return相应的返回值这一语句,因为throw就是一种返回方式。
2、如果在运行的时候,某一方法抛出一个异常,那么,后面的语句就马上被中断,而不会被执行。在我们的题目给出的例子中,doIt()抛出一个异常, 那么,后面的(j = 2)就不会被执行,程序转而执行catch()中的语句,即,println语句,所以应该打印的数值是1。

这道题目的答案是A.

题目:
What letters, and in what order, will be printed when the following program is compiled and run?

public class FinallyTest
{
   public static void main(String args[]) throws Exception
   {
       try
       {
          m1();
          System.out.println("A");
       }
       finally
       {
          System.out.println("B");
       }
       System.out.println("C");
   }

   public static void m1() throws Exception { throw new Exception(); }
}

A. It will print C and B, in that order.
B. It will print A and B, in that order.
C. It will print B and throw Exception.
D. It will print A, B, and C, in that order.
E. Compile time error.

这道题目容易错误的选择为C. 在m1()方法中抛出了一个异常,所以println("A")不会被执行。因为没有一个catch语句来捕获这个异常,所以main()方法将把这个异常抛出。所以println("C")不会被执行。但是finally语句必定会被执行,即使有一个return语句在try或者catch语句段中,只要不是System.exit()就行。所以println("B")将会被执行。
这道题目的答案是:C.

题目:
What will be the result of attempting to compile and run the following program?

public class TestClass
{
   public static void main(String args[])
   {
      Exception e = null;
      throw e;
   }
}
A. The code will fail to compile.
B. The program will fail to compile, since it cannot throw a null.
C. The program will compile without error and will throw an Exception when run.
D. The program will compile without error and will throw java.lang.NullPointerException when run.
E. The program will compile without error and will run and terminate without any output.

这道题目容易错误的选择答案D. 看起来,测试的重点在于,throw e这一语句,e已经被赋予了一个null值,所以,throw e将会导致一个NullPointerException的抛出。但是,在编译的时候,我们就可以知道,当一个函数中有throw语句的时候,要么这个throw 异常语句被包括在一个 try - catch的语句块之中,要么,这个函数要申明为throws 该异常。那么,要让这个程序编译能够通过,我们需要在main语句中加上,throws Exception。而题目所示的代码是不能被编译通过的。我们编译一下这段代码就可以看到:
C:Temp>javac TestClass.java
TestClass.java:6: unreported exception java.lang.Exception; must be caught or declare
d to be thrown
      throw e;
      ^
1 error

反过来,如果我们改正了这个错误,那么,由于e=null, throw e 的时候,就有一个NullPointerException出现了。这道题目的正确答案是 A.

语法基础

题目:
What will be the output of compiling and running the following program?

class CloneTest
{
   public static void main(String[] args)
   {
      int ia[ ][ ] = { { 1 , 2}, null };
      int ja[ ][ ] = (int[ ] [ ])ia.clone();
      System.out.print((ia == ja) + " ");
      System.out.println(ia[0] == ja[0] && ia[1] == ja[1]);
   }
}
A. It will not compile because Arrays cannot be cloned like this as clone() is not public.
B. It will not compile because either clone() should be in try-catch block or main should have throws clause.
C. It will print 'false false' when run.
D. It will print 'false true' when run.
E. It will print 'true true' when run.

这道题目容易错误的选择E. 其实,我们看看SDK文档中,类Object的方法clone()的说明,我们就可以知道,对于多维数组,clone是不完全的,也就是说,clone只是创建了一个新的数组,而一维以下的数组是共享的,所以ia 和ja 是不同的,但是ia[0]和ja[0]是相同的。另外,clone()在类Object中定义为protected属性,这是需要注意的。但是,一个array对象中的clone方法是覆盖过的,就象如下定义:
class A implements Cloneable
{
   public final int length = X;
   public Object clone()
   {
      try
      {
         return super.clone();
      }
      catch (CloneNotSupportedException e)
      {
         throw new InternalError(e.getMessage());
      }
   }
}


题目:
Consider the following code snippet:

  XXXX m ;
  switch( m )
  {
     case 32 : System.out.println("32"); break;
     case 64 : System.out.println("64"); break;
     case 128 : System.out.println("128"); break;
  }

What type can 'm' be of so that the above code compiles and runs as expected ?

A. int m;
B. long m;
C. char m;
D. byte m;
E. short m;

必须记住如下规则:
1、只有byte, char, short 和 int可以作为switch的变量。
2、这个switch中用到的变量类型必须能够接受所有的在case中的常量,即,这些常量在switch中用到的变量的范围之内。如果switch中用到的变量类型是char, 那么case中常量的数值不能大于65535, 因为char的范围是从0到65535.
3、所有的case中的值必须在编译的时候能确定,即,为常量。从题目中看,long是错误的,因为switch不能接受long 类型的变量。而byte也是错误的,因为128大于byte的范围(-128 到 127)。
所以,答案是A, C, E.

题目:
Given the following class definition:

class A
{
  protected int i;
  A(int i) { this.i = i; }
}


Which of the following would be a valid inner class for this class?

A. class B ( )
B. class B extends A { }
C. class B { B() { System.out.println(" i = " + i ) ; } }
D. class B { class A {} }
E. class A { }

这道题目也是容易让人费解。很容易错误的选择一个答案B. 而从测试的角度上来看,似乎测试的是我们对inner class的理解,那么从这个角度来看,答案B是正确的,一个inner class是可以继承它的上一级的外部的类的。但是,这个答案是错的。这是因为class A只提供了一个构造函数A(int i), 而根据规则,如果一个类提供了一个构造函数,编译器不会为该函数加上一个缺省的不带参数的构造函数。接下来,class B 继承了 class A, 但是没有提供任何的构造函数,根据规则,编译器会为该类提供一个缺省的不带任何参数的构造函数,而且,由于 class B 继承了 class A, 那么,编译器会为这个缺省提供的构造函数中加上一句语句来调用父类的不带参数的缺省构造函数。这个时候,错误就发生了。因为class A并没有这个缺省的构造函数。所以,从这个角度来看,这道题目测试的是构造函数,继承,缺省构造函数这方面的知识。我们尝试着把答案B写到程序中,来编译一下,看看结果:
class A
{
  protected int i;
  A(int i) { this.i = i; }
  class B extends A {}
}

C:Temp>javac test.java
test.java:5: cannot resolve symbol
symbol : constructor A ()
location: class A
  class B extends A {}
  ^
1 error
这道题目的答案是A, C.


申明和权限控制:

题目:
Consider following two classes:

//in file A.java
package p1;
public class A
{
      protected int i = 10;
      public int getI() { return i; }
}

//in file B.java
package p2;
import p1.*;
public class B extends p1.A
{
   public void process(A a)
   {
      a.i = a.i*2;
   }
   public static void main(String[] args)
   {
      A a = new B();
      B b = new B();
      b.process(a);
      System.out.println( a.getI() );
   }
}

What will be the output of compiling and running class B ?

A. It will print 10.
B. It will print 20.
C. It will not compile.
D. It will throw an exception at Runtime.
E. None of the above.
这道题目容易错误的选择为B. 实际上,虽然class B 继承了 class A, 而且i是一个protected属性的成员变量,但是,B 还是不能通过A的引用来存取i, 这是因为B并不在class A的实现之中。如果process()方法定义为process(B b), 那么,b.i是能够被存取到的,因为B在class B的实现之中。如果你有兴趣,可以参考JLS(Java Language Specification) 6.6.7节: http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#36191


题目:
What will the following program print ?

class Test
{
   public static void main(String[] args)
   {
      int i = 4;
      int ia[][][] = new int[i][i = 3][i];
      System.out.println( ia.length + ", " + ia[0].length+", "+ ia[0][0].length);
   }
}

A. It will not compile.
B. 3, 4, 3
C. 3, 3, 3
D. 4, 3, 4
E. 4, 3, 3
这道题目看起来象是考我们对于array分配空间的理解,实际上,是考我们对于一个语句的值的赋值顺序的理解。我们知道,在Java中,赋值的顺序是从左到右的,那么,对于第一个i它的值是4, 而对于第二个语句[i=3],这个时候,为了取得i=3的数值,必须先计算这个表达式,将3赋予给i, 然后才能得到这个表达式的值为3(这个语法和C++中是一样的,我就不多说了。)在下一个[i]中,i已经为3了,这很明显。需要注意的一点就是赋值和计算数值的顺序是从左到右的。答案为E.

题目:
What, if anything, is wrong with the following code?

abstract class TestClass
{
   transient int j;
   synchronized int k;

   final void TestClass(){}
   static void f()
   {
      k = j++;
   }
}

A. The class TestClass cannot be declared abstract.
B. The variable j can not be declared transient.
C. The variable k can not be declared synchronized.
D. The constructor TestClass() can not be declared final.
E. The method f() can not be declared static.

很明显,synchronized只能用于函数,而不能用于变量。而且,在abstract的类中,不能用static限制的函数调用了非static的变量k, 和j。所以,这道题目的答案是C, E.
编译一下也可以得到验证结果:
C:Temp>javac test.java
test.java:4: modifier synchronized not allowed here
   synchronized int k;
                    ^
test.java:9: non-static variable k cannot be referenced from a static context
      k = j++;
      ^
test.java:9: non-static variable j cannot be referenced from a static context
      k = j++;
          ^
3 errors

另外需要注意的是,如果定义这样的类:
abstract class TestClass
{
   abstract static void f();
}
编译的结果是:
C:Temp>javac test.java
test.java:7: illegal combination of modifiers: abstract and static
   abstract static void f();
                        ^
1 error
这是因为abstract和static不能在一起使用。


杂项:

题目:
Consider :

class A {}
class B extends A {}
class C extends B {}

Which of these boolean expressions correctly identifies when an object 'o' acutally refers to an object of class B and not A or C?

A. ( o instanceof B) && ( !(o instanceof A))
B. !(( o instanceof A)' '(o instaceof B ))
C. (o instanceof B) && ( !(o instaceof C ))
D. !( !(o instanceof B)' '( o instanceof C ))
E. ( o instanceof B) && !(( o instanceof A)' '( o instanceof C ))
这道题目从道理上来讲比较简单,但是还是容易出错。判断一个引用是否某一个类的实例,需要用instanceof来判断,而且,按照题目的要求,要求判断一个引用是class B的引用,而不是class A 或者 class C的引用,需要判断这个引用是B的引用,但是不是C的引用,而是不是A的引用则没有关系,因为只要它是B的引用就必定是A的引用。从这段分析可以看出,答案C是正确的。而答案D化简之后就是答案C,所以答案D也是正确的。

题目:
Which sequence of digits will the following program print?

import java.util.* ;
public class ListTest
{
   public static void main(String args[])
   {
      List s1 = new ArrayList( );
      s1.add("a");
      s1.add("b");
      s1.add(1, "c");
      List s2 = new LinkedList( s1.subList(1, 1) );
      s1.addAll(s2);
      System.out.println(s1);
   }
}

A. The sequence a, b, c is printed.
B. The sequence a, b, c, b is printed.
C. The sequence a, c, b, c is printed.
D. The sequence a, c, b is printed.
E. None of the above.

这一道题目的关键在subList()这个函数上。如果理解不清这个函数的用法,容易错误的选择答案C. 而看一看SDK文档说明,可以看到,subList返回的是一个半开集合,即,前面的参数指示的元素是包括进了被返回的子集合,而后面的参数指示的元素没有被包括进被返回的子集合,所以,当subList(1, 1)的时候,这个方法返回的是一个空集合。那么,根据题目,s1.add("a")加入了元素a, s1.add("b")加入了元素b, s1.add(1, "c")在位置1上加入了元素c, 而s1.addAll(s2)则加入了一个空集合,所以打印的结果应该是a, c, b.

题目:
What will the following program print?

public class InitTest
{
   public InitTest()
   {
      s1 = sM1("1");
   }
   static String s1 = sM1("a");
   String s3 = sM1("2");
   {
      s1 = sM1("3");
   }
   static
   {
      s1 = sM1("b");
   }
   static String s2 = sM1("c");
   String s4 = sM1("4");
    public static void main(String args[])
    {
        InitTest it = new InitTest();
    }
    private static String sM1(String s)
    {
       System.out.println(s); return s;
    }
}
A. The program will not compile.
B. It will print: a b c 2 3 4 1
C. It will print: 2 3 4 1 a b c
D. It will print: 1 a 2 3 b c 4
E. It will print: 1 a b c 2 3 4

这道题目容易错误的选择为A.
需要注意三点:
1、static的表达式和语句块是按照被定义的顺序来执行的。
2、instance的初始化表达式和语句块是按照被定义的顺序来执行的。
3、最后执行的才是创建函数。
所以,打印的结果是 a b c 2 3 4 1.

输入/输出

题目:
How many methods have to be provided by a class that is not abstract and that says it implements Externalizable interface?
A. None
B. 1
C. 2
D. 3
E. None of the above.

这一道题目考的是我们对Externalizable这个interface的了解。这个interface有两个方法(不是象Serializable一样是一个用来做标记的interface)
public void writeExternal(ObjectOutput out) throws IOException
  The object implements the writeExternal method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject method of ObjectOutput for objects, strings, and arrays.
Throws:
  IOException - Includes any I/O exceptions that may occur


public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
   The object implements the readExternal method to restore its contents by calling the methods of DataInput for primitive types and readObject for objects, strings and arrays. The readExternal method must read the values in the same sequence and with the same types as were written by writeExternal.
Throws:
  ClassNotFoundException - If the class for an object being restored cannot be found.


What type of parameter is given to the method renameTo() of class File?

A. File
B. FileDescriptor
C. char[]
D. String
E. All of the above.
这道题目也是测试我们是不是对File类的方法已经熟悉。容易引起误会的是,File的构造函数
可以接受几种不同的参数,如果对renameTo()方法不熟悉的话,容易想当然的认为这个方法也是重载
过的,可以接受几种不同的参数,而错误的选择答案E. 而我们看看文档的说明,就可以知道,renameTo()只接受一种参数,File.
该方法的说明如下:
public boolean renameTo(File dest)
   Renames the file denoted by this abstract pathname.
Parameters:
  dest - The new abstract pathname for the named file
Returns:
  true if and only if the renaming succeeded; false otherwise

Throws:
  SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.io.FileDescriptor) method denies write access to both the old and new pathnames .
  NullPointerException - If parameter dest is null.


操作符和赋值语句:

题目:
Consider that 'str' is a variable of class java.lang.String.

Which of the following lines of code may throw a NullPointerException in certain situations?
Or a tougher version of the question could be :

Which of the following lines of code are not an example of roboust design ?

A. if (( str != null ) | ( i == str.length() )
B. if (( str == null ) | ( i == str.length() )
C. if (( str != null)' '(i == str.length() )
D. if (( str != null )' '( i == str.length() )
E. if (( str == null)' '( i == str.length() )

考虑到||和&&的特性,即,如果从第一个部分就能判断出该表达式的结果,则会忽略掉后面的表达式,同时也不计算后面的表达式。那么这道题目的答案是A, B, C.

题目:
What will be the outpout of the following program?

public class TestClass
{
   public static void main(String args[ ] )
   {
      int i = 0 ;

      boolean bool1 = true ;
      boolean bool2 = false;
      boolean bool = false;
      bool = ( bool2 & method1(i++) ); //1
      bool = ( bool2 && method1(i++) ); //2

      bool = ( bool1 | method1(i++) ); //3
      bool = ( bool1' 'method1(i++) ); //4

      System.out.println(i);
   }

   public static boolean method1(int i)
   {
       return i>0 ? true : false;
   }
}

A. It will print 1.
B. It will print 2.
C. It will print 3.
D. It will print 4.
E. It will print 0.

考虑到||和&&的特性,即,如果从第一个部分就能判断出该表达式的结果,则会忽略掉后面的表达式,同时也不计算后面的表达式。那么这道题目的答案是B.需要注意的是,| 和 & 没有||和&&的特性.

java.util 包:

题目:
Given two collection objects referenced by c1 and c2, which of these statements are true?

A. c1.retainAll(c2) will not modify c1.
B. c1.removeAll(c2) will not modify c1.
C. c1.addAll(c2) will return a new collection object, containing elements from both c1 and c2.
D. For: c2.retainAll(c1); c1.containsAll(c2); 2nd statement will return true.
E. For: c2.addAll(c1); c1.retainAll(c2); 2nd statement will have no practical effect on c1.

这道题目的答案是D, E.

注意到SDK文档中关于这些函数的说明,有:
1. public boolean retainAll(Collection c)
Retains only the elements in this collection that are contained in the specified collection (optional operation). In other words, removes from this collection all of its elements that are not contained in the specified collection.

2. public boolean removeAll(Collection c)
Removes all this collection's elements that are also contained in the specified collection (optional operation). After this call returns, this collection will contain no elements in common with the specified collection.

3. public boolean containsAll(Collection c)
Returns true if this collection contains all of the elements in the specified collection.

4. public boolean addAll(Collection c)
Adds all of the elements in the specified collection to this collection (optional operation). The behaviour of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behavior of this call is undefined if the specified collection is this collection, and this collection is nonempty.)
答案则不难得到。需要注意的是,我们在学习Java的过程中,需要了解这些方法的作用,这样才能在需要的时候能够用到。

java.lang 包

题目:
Which of these parameter lists have a corresponding constructor in the StringBuffer class?
A. ()
B. (StringBuffer sb)
C. (char[] data)
D. (String str)
E. (int capacity)
这道题目也是测试我们对于StringBuffer的熟悉程度。容易引起误会的是,StringBuffer的有些方法,可以接受char[]数组,但是,构造函数却不接受这种参数,容易错误选择。StringBuffer只接受三种构造函数的形式,一个是没有任何参数,创建一个缺省容量为16的StringBuffer, 另外一种是接受一个String对象,把String的数值拷贝到StringBuffer对象中,第三种,是接受一个int类型的参数,构造一个容量为该参数大小的StringBuffer对象。这三个构造函数的说明如下:
StringBuffer()
   Constructs a string buffer with no characters in it and an initial capacity of 16 characters.
StringBuffer(int length)
   Constructs a string buffer with no characters in it and an initial capacity specified by the length argument.
StringBuffer(String str)
   Constructs a string buffer so that it represents the same sequence of characters as the string argument; in other words, the initial contents of the string buffer is a copy of the argument string.


线程:

题目:
Given the following program, which one of these statements is true?

public class TestClass extends Thread
{
   static Object lock1 = new Object();
   static Object lock2 = new Object();
   static volatile int i1, i2, j1, j2, k1, k2;

   public void run()
   {
      while (true)
      {
         workWithLocks();
         workWithoutLocks();
      }
   }

   void workWithLocks()
   {
      synchronized(lock1) { i1++ ; i2++; }
      synchronized(lock2) { k1++ ; k2++ ; }
      j1++; j2++;
   }

   void workWithoutLocks()
   {
      if (i1 != i2) System.out.println("i");
      if (j1 != j2) System.out.println("j");
      if (k1 != k2) System.out.println("k");
   }

   public static void main(String args[])
   {
      new TestClass().start();
      new TestClass().start();
   }
}
A. The program will fail to compile.
B. One cannot be certain whether any of the letters i, j and k will be printed during execution.
C. One can be certain that none of the letters i, j and k will ever be printed during execution.
D. One can be certain that the letters i and k will never be printed during execution.
E. One can be certain that the letter k will never be printed during execution.

这道题目更加让人费解。甚至出题的人给出的答案都不能让我信服。给出的答案是B, 而我的选择是D. 尝试运行一下这个程序就可以看到结果,打印出来的全是j.我的理由如下:

void workWithLocks()
   {
      synchronized(lock1) { i1++ ; i2++; }
      synchronized(lock2) { k1++ ; k2++ ; }
      j1++; j2++;
   }
中,由于i1, i2和k1, k2分别都是在一个同步的语句块中执行的,所以这两对数值总是保持相同。而j1, j2不是在同一同步的语句块中执行的,所以在多线程的情况下,可能有两个不同的线程分别执行,而且中间会被打断,导致j1, j2的值不一致。而且,
 void workWithoutLocks()
   {
      if (i1 != i2) System.out.println("i");
      if (j1 != j2) System.out.println("j");
      if (k1 != k2) System.out.println("k");
   }
就很明显,这个程序只会打印j, 而不会打印i和k. 编译,执行该程序的结果也是一样。


在最后,我留下一些练习题目,这些题目是我认为比较有价值的,供大家练习。
Question 1)
Why might you define a method as native?

1) To get to access hardware that Java does not know about
2) To define a new data type such as an unsigned integer
3) To write optimised code for performance in a language such as C/C++
4) To overcome the limitation of the private scope of a method

1) To get to access hardware that Java does not know about
3) To write optimised code for performance in a language such as C/C++

Question 2)
What will happen when you attempt to compile and run this code?

public class Mod{
public static void main(String argv[]){
    }
        public static native void amethod();

}

1) Error at compilation: native method cannot be static
2) Error at compilation native method must return value
3) Compilation but error at run time unless you have made code containing native amethod available
4) Compilation and execution without error

4) Compilation and execution without error

Question 3)
You want to find out the value of the last element of an array. You write the following code. What will happen when you compile and run it.?

public class MyAr{
public static void main(String argv[]){
        int[] i = new int[5];
        System.out.println(i[5]);
        }
}

1) An error at compile time
2) An error at run time
3) The value 0 will be output
4) The string "null" will be output

2) An error at run time

Question 4)
Which of the following are fields of the GridBagConstraints class?

1) ipadx
2) fill
3) insets
4) width

1) ipadx
2) fill
3) insets

Question 5)
What most closely matches the appearance when this code runs?

import java.awt.*;
public class CompLay extends Frame{
public static void main(String argv[]){
    CompLay cl = new CompLay();
    }

CompLay(){
    Panel p = new Panel();
    p.setBackground(Color.pink);
    p.add(new Button("One"));
    p.add(new Button("Two"));
    p.add(new Button("Three"));
    add("South",p);
    setLayout(new FlowLayout());
    setSize(300,300);
    setVisible(true);
    }
}

1) The buttons will run from left to right along the bottom of the Frame
2) The buttons will run from left to right along the top of the frame
3) The buttons will not be displayed
4) Only button three will show occupying all of the frame

2) The buttons will run from left to right along the top of the frame

The call to the setLayout(new FlowLayout()) resets the Layout manager for the entire frame and so the buttons end up at the top rather than the bottom.

Question 6)
Which statements are correct about the anchor field?

1) It is a field of the GridBagLayout manager for controlling component placement
2) It is a field of the GridBagConstraints class for controlling component placement
3) A valid setting for the anchor field is GridBagConstraints.NORTH
4) The anchor field controls the height of components added to a container

2) It is a field of the GridBagConstraints class for controlling component placement
3) A valid settting for the anchor field is GridBagconstraints.NORTH


Question 7)
How does the set collection deal with duplicate elements?

1) An exception is thrown if you attempt to add an element with a duplicate value
2) The add method returns false if you attempt to add an element with a duplicate value
3) A set may contain elements that return duplicate values from a call to the equals method
4) Duplicate values will cause an error at compile time

2) The add method returns false if you attempt to add an element with a duplicate value

Question 8)
What can cause a thread to stop executing?

1) The program exits via a call to System.exit(0);
2) Another thread is given a higher priority
3) A call to the thread's stop method.
4) A call to the halt method of the Thread class?

1) The program exits via a call to exit(0);
2) The priority of another thread is increased
3) A call to the stop method of the Thread class


Note that this question asks what can cause a thread to stop executing, not what will cause a thread to stop executing. Java threads are somewhat platform dependent and you should be carefull when making assumptions about Thread priorities. On some platforms you may find that a Thread with higher priorities gets to "hog" the processor.


Question 9)

What will happen when you attempt to compile and run this program

public class Outer{
public String name = "Outer";
public static void main(String argv[]){
        Inner i = new Inner();
        i.showName();
    }//End of main
        private class Inner{
        String name =new String("Inner");
                void showName(){
                        System.out.println(name);
                }
        }//End of Inner class
}

1) Compile and run with output of "Outer"
2) Compile and run with output of "Inner"
3) Compile time error because Inner is declared as private
4) Compile time error because of the line creating the instance of Inner

4) Compile time error because of the line creating the instance of Inner


This looks like a question about inner classes but it is also a reference to the fact that the main method is static and thus you cannot directly access a non static method. The line causing the error could be fixed by changing it to say

        Inner i = new Outer().new Inner();

Then the code would compile and run producing the output "Inner"

Question 10)
Which of the following statements are true?

1) At the root of the collection hierarchy is a class called Collection
2) The collection interface contains a method called enumerator
3) The interator method returns an instance of the Vector class
4) The Set interface is designed for unique elements

4) The Set is designed for unique elements.

Collection is an interface, not a class. The Collection interface includes a method called iterator. This returns an instance of the Iterator class which has some similarities with Enumerators.
The name set should give away the purpose of the Set interface as it is analogous to the Set concept in relational databases which implies uniquness.


Question 11)
Given the following variables which of the following lines will compile without error?

String s = "Hello";
long l = 99;
double d = 1.11;
int i = 1;
int j = 0;
1) j= i <<s;

2) j= i<<j;

3) j=i<<d;

4)j=i<<l;

2 4


Question 12)
Which of the following are methods of the Collection interface?
1) iterator
2) isEmpty
3) toArray
4) setText

123


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值