设为首页 收藏本站
查看: 1321|回复: 0

[经验分享] amay's notes for 1.4(SCJP经典笔记)

[复制链接]

尚未签到

发表于 2015-11-26 09:15:29 | 显示全部楼层 |阅读模式
System.out.println(010);
输出八进制数010的十进制值8
注意是数字0开头,不是字母o
16进制以0x或0X开头

class ValHold{
        public int i = 10;
}
public class ObParm{
        public void amethod(){
                ValHold v = new ValHold();
                another(v);
                System.out.println(v.i);
        }
        public void another(ValHold v){
                v.i = 20;
                ValHold vh = new ValHold();
v =vh;
                System.out.println(v.i);
        }
        public static void main(String[] argv){
                ObParm o = new ObParm();
                o.amethod();
        }
}
此题的答案是
10
20
为什么不是
10
10呢?
这样解释吧,按照sun官方的说法:当一个引用变量作为参数传递给一个方法时, 在这个方法内可以改变变量的值,即改变引用指向的对象,(本题中将vh赋给v)但是方法的调用结束后,改变量恢复原来的值,即变量仍然指向原来的对象。 (即another(v)调用结束之后,v又回复到第一次ValHold v = new ValHold();时指向的地址空间。)
但是如果在方法内改变了引用指向的对象的数据(属性),那么当方法的调用结束后,尽管引用仍然指向原来的对象,这个对象的某个属性已经被改变了(v的i值在 执行v.i=20的时候就已经被改变了,所以调用another结束后,v.i已经变成了20)

重载overload方法不能用返回值判断,而应当以参数判断(有无参数、参数类型、参数个数、参数排列顺序)


public class InOut{
   String s= new String("Between");
   public void amethod(final int iArgs) {
      int iam;
      class Bicycle{
            Bicycle() {
                    System.out.println(s); //这两句话可以,也就是说可以访问s
                    System.out.println(iArgs); //final int 常量
                    //System.out.println(iOther);
            }
       }
       new Bicycle();
   }
   public void another(){
int iOther;
   }
   public static void main(String[] args) {
       InOut inout= new InOut();
       inout.amethod(22);
   }
}
Inner class
Inner class能够存取外部类的所有实例变量----无论这些实例变量有什么样的存取控制符(比如private),就像类中的方法能够存取方法所在类的所有变量一样;


如果inner class定义在方法中,则inner class能够存取方法所在的类中的实例变量,也能存取该方法中的局部变量,但该局部变量必须是final,也就是只能访问方法中的常量.
(上面所说的都是普通内部类,不是静态内部类的情况)



float f=1/3;
float f=10; //输出10.0
int i=1/3;
int x = (int)(1.23);
double d=999d; 都是合法的表达式
如果将float f=1/3;       改成float f=1/3f;
f=0.0

i=0

d=999.0
f= 0.33333334

Integer没有setValue方法。


instanceof Tests whether an instance derives from a particular class or interface。注意:实现了某接口的类的对象也是该接口的实例;某类的对象也是该类父类的实例。


Interfaces cannot have constructors接口没有构造函数
接口中的所有数据成员都是static final,即静态常量(这两个关键字可以不写)但必须给常量赋初值;
接口中的所有方法都只有定义没有实现细节,并且全部为public(可以不写出来),所以接口中的方法全部是抽象方法
接口比抽象类更抽象

Runnable接口只有run()一个方法
注意:不带参数

X位的数据类型的范围在-2x-1~2x-1-1
特例:字符char型表示单个16位Unicode字符,所以它的取值范围0~216-1


class Base{
public void Base(){
    System.out.println("Base");
}
}
public class In extends Base{
public static void main(String argv[]){
    //System.out.println(99);     //    (*)
In i=new In();
//i.Base();    显式调用Base()有输出,可见加了返回类型后,
Base()是一个普通的方法,不再是构造方法了
}
}
运行结果:Compilation and no output at runtime
构造方法没有返回值,但是如果你在构造方法前加了void关键字,左边的程序将可以通过编译,也可以运行,但是没有输出Base.(很奇怪)
然而如果你将左边打*的行的注释去掉,则可以输出99,但没有输出Base.
调用有输出,

native修饰的方法没有方法体,用一个分号“;”代替大括号。
如:static native void amethod();
static      void amethod(){ }


一个文件只能有一个外部public类,而且文件名要以这个类命名
但是如果将public删除(即没有public方法了),程序仍然能正确运行而且有输出


1)static methods do not have access to the implicit variable called this
静态方法不能存取隐式变量this
2) A static method may be called without creating an instance of its class
3) A static method may not be overriden to be non-static
静态方法不能覆盖为非静态方法
静态方法

main不是java关键字!!


缺省构造函数没有返回类型


Interface中只有数据和方法的声明,它只是提供一个框架。所以其中的方法不存在存取接口中定义的静态常量的问题。


4) The size of a string can be retrieved using the length property
这句话是错误的,计算字符串的长度的length()是一个方法,不是property!
而数组则有一个length成员域,它不是方法!,如int[] myarray = new int[3]
myarray.length返回myarray的长度
int[] array=new int[10];
array.length=15;//compile error
数组的长度一旦确定就不能改变!

1.如果在一个方法中声明一个基本类型变量,那么在使用这个变量之前,它必须被赋值!
2.如果在类体中,方法之外定义基本类型变量, 则可以不赋初值,系统自动采用该类型的缺省值;
3.对于基本数据类型的数组,无论是在方法中,还是在方法之外,如果未赋初值,系统都会为它赋相应基本类型的缺省值。而如果数组是对象数组,则初值为null。
初值问题

非静态inner classes cannot have static declarations
non-static inner classes 不能有静态的方法、变量等。
内部类可以有任何的存取控制符例如protected, public, private.
Inner class

class A {
       public staticvoid a() {
       System.out.println("super!");
       }
}
class TestStatic extends A {
       public static void a() {
              System.out.println("child!");
       }
       public static void main( String[] args) {
              A obj = new TestStatic();
        System.out.println(obj);
              obj.a();
       }
}
有static,输出
TestStatic@1fcc69   //可见obj是子类对象
super!
如果将static去掉,则输出   (表示父类的同名方法被重置override了)
TestStatic@1fcc69
child!















按sun的说法,静态方法不能被override,只是被隐藏(hidden)了

yield()方法无参数,yield()只能使同优先级的线程有执行的机会
sleep(long millis[,int nanos])方法有参数。


call to super must be first statement in constructor!
而且,切记super方法只能在构造方法中写,其他方法中一概不能写!


1) A program can suggest that garbage collection be performed but not force it
2)不同的java开发环境的垃圾处理机制不太一样。
garbage collection

non-static variable cannot be referenced from a static context
static variable

public class Inc{
       public static void main(String argv[]){
                Inc inc = new Inc();
                int i =0;
                inc.fermin(i);
                i = i++;
                System.out.println(i);
        }
        void fermin(int i){
                i++;
        }
}



睁大眼睛看仔细
结果是0   !!

对基本类型是传值,pass a copy

Swicth语句中的判断条件必须是int和它以下的数据类型即short、char、byte
public class Agg{
static public int i=10;   //*
public static void main(String argv[]){
        switch(i){
                case 1:
                    System.out.println("one");
                default:
                    System.out.println("default");
                case 10:
                    System.out.println("ten");
        }
}
}

public class Testswitch {
       public static void main( String[] args) {
              int x=Integer.parseInt(args[0]);
switch (x) {
     case 4:
         System.out.println(4);
     case 3:
     case 2:
         System.out.println(2);
     case 1:
         System.out.println(1);
}
}
}

public class Testswitch {
       public static void main( String[] args) {
              int x=Integer.parseInt(args[0]);
switch (x) {
          case 1:
              System.out.println(1);
          case 2:
          case 3:
              System.out.println(3);
          case 4:
              System.out.println(4);
}
}
}
奇怪的switch!
1)      如果有匹配的值,无论default预放哪里都没关系。
2)      如果无匹配值,即,将case10去掉,则会执行default
3)      如果将case 1放到case10后,则case10及case1都会有输出!
4)如果i=4,输出:
   default
ten
5)如果将default放case10后,输出
   default
可见无匹配值时,从default语句开始往下都有输出,直到遇到break或结束。
5)总结:从匹配的地方开始下面的语句都有输出,直到遇到break或程序结束。这个匹配的地方包括default,参见第4点。





java Testswitch 3
输出
2
1





java Testswitch 1
1
3
4
原因是:没有加break;语句!!
没有break则从匹配的地方开始往下全部有输出!只到遇到break

goto 和const虽然是java关键字,但是目前还未用于Java语言。


构造方法不能加static关键字


Public void init() {
   Thread t = new Thread() {
      //some codes
   }; //匿名内部类象语句一样被定义,所以要加分号!
   t.start();
}
创建了Thread的一个实例,其实是创建了Thread的子类的一个实例,这个子类我们并没有给他命名,但是我们已经给出了这个子类的定义。
匿名内部类没有构造方法!Java隐式的调用其父类的构造方法!
In Java, anonymous classes are often used to perform simple event handling for user interface.
Anonymous Classes
As you can see, the new expression states that it is creating an instance of class Thread. Actually, it’s creating a subclass of Thread that we have not named, although we have supplied a definition for this subclass.
Anonymous classes cannot have constructors, Java invokes their superclass constructor implicitly.

public class Testinner {
       int t=10;
       public void a() {
              final int u =90;
              class InMethod {    //方法中内部类
                     InMethod() {    //内部类的构造方法
                            System.out.println("u="+u); //封装方法内的变量必须是final
才能访问到!
                            System.out.println("t="+t);   //外部类的变量可以任意访问!
                     }
              }
              new InMethod();
//必须在方法a()中创建内部类对象之后,
// Testinner对象才能通过 a()访问到InMethod
       }
       public static void main (String[] args) {
              Testinner t= new Testinner();
              t.a();
       }
}
方法中的内部类的演示程序
输出:u=90
t=10

方法中的内部类不可以是static的!

如果一个内部类是静态的(当然只能是类中的内部类啦),那么这个类就自动的成为顶级(top-level)类即普通的类。

静态内部类中的方法(无论是静态的方法还是非静态的方法)只能直接访问外部类中的静态成员,要访问外部类中的非静态成员,则必须创建外部类的对象。
静态内部类的问题
static inner class

<1> 42e1 是double型的。
<2> 0x0123 是int型的。
<3>  Given an ActionEvent, how to identify the affected component?
用getSource()方法,记住!(1.4不要求awt)
<4>  StringBuffer中的方法是append,String中的方法是concat,并且,试图在其他方法中通过调用该方法改变String是徒劳的。
<5> system.exit(int value),也就是说只要是int都能使虚拟机退出,System.exit('a');同样的是合法的.


<6> which four types of objects can be thrown use &quot;throws&quot;?
A.Error  B.Event  C.Object  D.Excption
E.Throwable  F.RuntimeException
Ans are : A D E F

<7> which two are equivalent?
A.  3/2      // 1
B.  3<2     // false
C.  3*4     //12
D.  3<<2   //12
E.  3*2^2   //6^2=5
F.  3<<<2 (迷惑人的地方,并没有<<<操作符)
ans: c,d



<8> &  |  可以用在int和boolean上。^(异或只能用在int上)。
&& || 只能用在boolean上,作用同& |,但是与其不同在于&& ||有短路运算,而位操作没有。
<9> Hashtable implements Map,Cloneable,Serializible
<10> which two interfaces provide the capability to store objects using a key-value pair?
A. java.util.Map
B. java.util.Set
C. java.util.List
D. java.util.SortedSet
E. java.util.SortedMap
F. java.util.Collection
Ans: A,E



实例变量instance variables 和局部变量local variables的区别:
1)实例变量能够在类定义的整个代码中使用(比如类中所有的方法中),他一般系统会自动为他赋缺省值;
2)局部变量则没有缺省值。


Method init is a special applet method that is normally the first method defined by the programmer in an applet and is guaranteed to be the first method called in every applet. Method init is called once during an applet’s execution. The method normally initializes the applet’s instance variables (if they need to be initialized to a value other than their default value) and performs any tasks that need to be performed once at the beginning of an applet’s execution.


import java.applet.Applet;
import java.awt.*;
public class Sample extends Applet {
private String text = &quot;Hello World&quot;;
public void init() {
    add(new Label(text));
    new Sample(&quot;a&quot;);
}
public Sample (String s) {
    add(new Label(&quot;hahahahahah&quot;));
}
}

==========================================================
class First {
public First (String s) {
    System.out.println(s);
}
//public First() {}        //加上这条语句则正常运行!
}                        //由于Second类初始化调用父类无参数的构造函数
public class Second extends First {
public static void main(String args []) {
    new Second();
}
}
Applet中的public void init()方法
Applet中可以有构造函数
Init()中缺省调用无参构造函数(无论这个无参构造函数是系统提供的,还是用户自己写的),因此如果要写带参数的构造方法,那么用户必须显式的写出无参构造方法,因为用户自己写了有参构造方法之后,系统将不再提供无参构造方法,但是init()缺省一定要调用无参的构造方法,init()找不到无参的构造方法,这样在运行时将会出错。

左这种情况也是编译能够通过,但运行报错。提示:加载:无法实例化 Sample.class。

将new Sample(&quot;a&quot;);去掉,将public Sample (String s)改成无参public Sample(),则先输出hahahah,再输出Hello World,可见无参构造方法自动调用且是先执行的
==============
此程序则是编译错误!不是到运行是才有错误
Second.java:7: cannot resolve symbol
symbol : constructor First ()
location: class First
public class Second extends First {
       ^

如果要调用无参数的的构造方法(已经定义了一些有参的构造方法),那么必须显式的写出无参构造方法。
public class Test8 {
       public static void main( String[] args) {
              new Test8(); //调用无参
       }
       Test8(String s) {
       }
       //Test8() {
       //}
} 编译错误,去掉注释即可

public class Test8 {
       public static void main( String[] args) {
              new Test8(&quot;haha&quot;); //调用有参
       }
       Test8(String s) {
       }
       //Test8() {
       //}
} 可以通过编译和运行
构造方法

What is the effect of issuing a wait() method on an object?(Mutiple)
1) If a notify() method has already been sent to that object then it has no effect
2) The object issuing the call to wait() will halt until another object sends a notify() or notifyAll() method
3) An exception will be raised
4) The object issuing the call to wait() will be automatically synchronized with any other objects using the receiving object.
2
1为什么不对呢?

In order to cause the paint(Graphics) method to execute, which of the following is the most appropriate method to call?(Mutiple)
1) paint()
2) repaint()
3) paint(Graphics)
4) update(Graphics)
5) None ?you should never cause paint(Graphics) to execute
2

2) <param name=age value=33>给applet传参数


What is the result of executing the following fragment of code:
boolean flag = false;
if (flag = true) {
   System.out.println(&quot;true&quot;);
}else{
   System.out.println(&quot;false&quot;);
}
true
注意陷阱!”=”不是”==”
faintttttt!

public class Test {
public static void test() {
    this.print();
}
public static void print() {
    System.out.println(&quot;Test&quot;);
}
public static void main(String args []) {
    test();
}
}

编译错误提示:non-static variable this cannot be referenced from a static context

1.StringBuffer sb = new StringBuffer(&quot;abc&quot;);
2.String s = new String(&quot;abc&quot;);
3.sb.append(&quot;def&quot;);
4.s.append(&quot;def&quot;);
5.sb.insert(1, &quot;zzz&quot;);
6.s.concat(sb);
7.s.trim();
第四句第六句非法!

boolean a=false; boolean b=true; int c=2;
可以System.out.println(a | b);输出
可以System.out.println(a || b);有点费解!位运算符不是用于对整数的二进制进行布尔运算吗?
不可以System.out.println(a | 2);提示说布尔型不能和int型或
可见布尔型可以和布尔型进行位运算|、&、^

但布尔型不能和其它类型的数据位运算,会出现编译错误!

Which of the following are legal names for variables.(Mutiple)
1) _int
2) %large
3) $fred
4) Integer   //Long、Double等包装器类似,都不是关键字
5) 2much
134

public class Test8 {
     public static void main(String [] args){
         Base b = new Subclass();
         System.out.println(b.x);
         System.out.println(b.method());
     }
}
class Base{
     int x = 2;
     int method(){
         return x;
     }
}
class Subclass extends Base{
     int x = 3;
     int method(){
         return x;
     }
}
多态性、虚拟方法调用

结果是
2
3
而不是
3
3
参看下面的几格解释

Employee e = new Manager()
e.department = &quot; Finance &quot; ; //department Manager的一个特殊属性// illegal
声明变量e后,你能访问的对象部分只是Employee的部分;Manager的特殊部分是隐藏的。这是因为编译器应意识到,e 是一个Employee,而不是一个Manager但重写的方法除外
多态性、虚拟方法调用

在你接收父类的一个引用时,你可以通过使用instanceof运算符判定该对象实际上是你所要的子类,并可以用类型转换该引用的办法来恢复对象的全部功能。
为什么说恢复对象的全部功能,就是因为上一格所描述的,子类对象赋给父类句柄后,该句柄不能访问子类的那些特殊属性和方法,要用就要重新造型。
这其实是多态参数的后续应用,形成这样一个链条:传入多态参数——instanceof判断类型——casting——恢复功能
Marcus Mork Test 3 57题大体体现了这个意思
多态性、虚拟方法调用

Employee e = new Manager();
e.getDetails();
    在此例中,Manager 重写了EmployeegetDetail()方法。被执行的e.getDetails()方法来自对象的真实类型:Manager。事实上,执行了与变量的运行时类型(即,变量所引用的对象的类型)相关的行为,而不是与变量的编译时类型相关的行为。这是面向对象语言的一个重要特征。它也是多态性的一个特征,并通常被称作虚拟方法调用——动态绑定
上述两个例子表明,属性不能虚拟调用,而方法可以,因为属性不能重写,哈哈。
多态性、虚拟方法调用

Which of the following applet tags are mandatory (select all the correct answers). Mutiple:
1) CODE
2) WIDTH
3) HEIGHT
4) PARAM
5) ARCHIVE
举例
<html>
<title>Sample Applet</title>
<body>
<applet codecode不是name=&quot;Sample.class&quot; width=200 height=200></applet> //
</body>
</html>
123

name也是<applet></applet>之间合法的标签或标签的属性,但我不知道怎么用。

抽象类中的抽象方法不能是final,但是非抽象方法前加final可以编译通过
因为abstract和final相互排斥,前者专用于继承,后者禁止继承
抽象类中的抽象方法不能为static
          非抽象方法可以为static

Abstract方法不能用final,static修饰
非abstract方法在abstract类中可以用final,static

包裹类Integer、 String 、Float、 Double等都是final类,不能被继承!
Integer i=new Integer(“6”);如果字符串不是数字,会产生运行异常(不会出现编译错误)
但是对于boolean,这个规则不适用。当字符串时(大小写无关),Boolean对象代表的数值为true,其他字符串均
如:Boolean b = new Boolean(“afiwou”); 代表false
    Boolean b = new Boolean(“tRue”); 是true




抽象类中可以有构造方法!
接口中不能定义构造方法!

abstract class
interface

              int a[] = {1,2,3};
           int []b[] = {{1,2,3},{1,2,3}};
           int d[2] = {1,2,3}; //illegle
           int d[] = {1,2,3};
           int []e = {0,0,0};
           char c[] = {'a', 'b'};   //初始化时中括号都是空的。
数组的初始化!
与数组的定义不一样!P213

protected void finalize() throws Throwable
valid declaration for the finalize() method

Which of the following statements are true regarding the graphical methods paint(), repaint() and update(). Mutiple:
1) paint() schedules a call to repaint().
2) repaint() schedules a call to update().
3) update() calls paint().
4) update() schedules a call to repaint().
5) repaint() calls paint() directly.


23
repaint()&agrave;update()&agrave;paint()

public class Test8 {
       public static void main(String[] args) {
       loop1:
              for(int i = 0; i < 3; i++){
          loop2:
             for(int j = 0; j < 3; j++){
                 if (i == j){
                     break loop2;
                 }
                 System.out.print(&quot;i = &quot; + i + &quot; j = &quot; + j + &quot; &quot;);
             }
          }
       }
}
i = 1 j = 0 i = 2 j = 0 i = 2 j = 1

then不是java 关键字!
reserved words

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);
    }
}
Mutiple:
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 i
3
这道题挺特别的
Mine继承了MineBase的抽象方法,且没有覆盖它,因此,Mine中有抽象方法,故Mine必须定义为抽象类

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(&quot;Hello.txt&quot;);
      }catch (FileNotFoundException fne) {
           System.out.println(&quot;No such file found&quot;);
           return -1;      //(*) 这句话最后被执行!!!
      }catch(IOException ioe) {
      }finally{
           System.out.println(&quot;Doing finally&quot;);
      }
      return 0;
}
}
注意此题输出的顺序!-1在最后!
No such file found
Doing finally
-1

在返回前执行finally块

请人解释一下!
如果将(*)注释掉,则本题会输出:
No such file found
Doing finally
0


class Base {}
class Sub extends Base {}
class Sub2 extends Base {}

public class Test9{
public static void main(String argv[]){
    Base b = new Base();
    Sub2 s = (Sub) b; //编译通过, 运行异常
}
}
编译通过
运行异常:
Exception in thread &quot;main&quot; java.lang.ClassCastException: Base

Once created, some Java objects are &quot;immutable&quot;, meaning they can not have their contents changed. Which of the following classed produce immutable objects? Mutiple: 13
1) java.lang.Double
2) java.lang.StringBuffer
3) java.lang.Boolean
4) java.lang.Math
1) 所有的包裹类具有和String一样的immutable特性,其实可以将String也理解成包裹类
2) 包裹类及String类都重置了equals方法,因此只要数值相等,包裹类和String类对象都返回true.
3) 包裹类实现了toString方法,它可直接输出该类对象代表的数值

class Base {
       //void speak() {
       //     System.out.println(&quot;Base&quot;);
       //     }
       }
class Sub extends Base {
       void speak() {
              System.out.println(&quot;Sub&quot;);
              }
       }
public class Test9{
public static void main(String argv[]){
    Base b = new Sub(); // m
b.speak(); //编译时b会试图去调用Base的speak()方法,
//但是Base无speak()方法,所以出错
}
}
但是如果去掉Base中的注释,则实际运行的结果却是输出Sub, 即它并没有调用父类的speak(),这就是动态绑定了,即编译的时候它检查的是父类的方法,运行的时候调用的却是子类的方法









如果m改成:
Sub b = new Sub();
则无论父类有没有speak()都无关紧要拉,肯定调用子类的那个。

如果方法声明为static则调用父类的,因为static方法是不能override的,只是隐藏了

16>>4=1 or 0?
当然不是0!!
相当于16除以2的4次方,得1啊,哈哈
…0001 0000 >>4
…0000 0001

import java.io.*;
public class Test9{
   public static String setFileType(String fname){ //必须是static哦,否则
     int p=fname.indexOf('.');                   //下面调用会出编译错误
     if(p>0) fname=fname.substring(0,p);
     fname+=&quot;.TXT&quot;;
     return fname;
   }
   public static void main(String args[]){
     String theFile=&quot;Program.java&quot;;
     String s = setFileType(theFile);
     System.out.println(&quot;Created &quot;+theFile);
     System.out.println(&quot;Created &quot;+s);
   }
}
输出如下
Created Program.java
Created Program.TXT


考察了String的immutable性质
还是很费解!

     char A=(char)4096;    //输出问号 ?
    byte A=(byte)4096; //输出0
//这两句话居然能通过编译且可以运行!faint!!!!!!!!!!
    byte A=(byte)4094; //输出-2
int b=(int)4094.86;   //输出4094
boolean b=(boolean)4096 //则有编译错误


Which of the following statements will cause a compiler error?
Mutiple:
1) float F=4096.0;
2) double D=4096.0;
3) byte B=4096;
4) char C=4096; //可以通过编译,且可以运行
13

char的范围:0-215-1

1)任意类的两个对象t1,t2,t1.equals(t2); // 返回false
如果t1=t2; 则t1.equals(t2)和t1==t2均返回true
因为两个引用实际上指向了同一对象,因此引用值引用所代表的对象都相等,==和equals方法均返回true,对于任何类都是如此
2)对于同种包裹类对象
Object A=new Long(7);或Long A=new Long(7);
    Long L=new Long(7);
A.equals(L);            //返回true
A==L;                 //返回false
3)对于不同包裹类对象
   Integer A=new Integer(7);或Object A=new Integer(7);
    Long L=new Long(7);
A.equals(L);            //返回false
A==L    //编译错误,提示Integer和Long是incomparable types
4)String对于字符串对象,只要他们的内容完全一致,equals返回true,但==返回false
equals()

可见包裹类比较特殊:
·同一个包裹类的对象,只要值相等,equals返回true
·不同包裹类的对象,即便值相等,equals返回false


2)和4)是一致的!

       String s=&quot;http://www.lanw.com&quot;+’/ ’+&quot;default.htm&quot;;
       System.out.println(s);
输出:http://www.lanw.com/default.htm
//如果是’/’会有编译错误

System.out.println();既可以输出字符串,也可以输出字符,还可以输出两者的组合,如上格。
System.out.println(‘c’) //合法
System.out.println(‘cer’) //不合法


public final class Test4 {
private boolean flag = false;
  class Inner {
    void test() {
        if(Test4.this.flag); {
            sample();
        }
    }
}
public void sample() {
    System.out.println(&quot;Sample&quot;);
}
public Test4() {
    (new Inner()).test();
}
public static void main(String args []) {
    new Test4();
}
}
输出Sample
这道题好无耻!!


注意左边的那行,if语句后加了个分号。

public class Test5{
public static void main (String args []){
   /* This is the start of a comment
   if (true) {
      Test5 = new test5();
      System.out.println(&quot;Done the test&quot;);
   }
   /* This is another comment */
   System.out.println (&quot;The end&quot;);
}
}
又踩地雷了!!,faint
中间那一大段变态的话已经被注释掉了

Why might you define a method as native?
Mutiple:
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
public class Mod{
public static void main(String argv[]){
    }
        public static native void amethod();
} //此代码能运行通过
13
native
BP30: indicates the method is not written in Java but in some platform-dependent language

Thread类中没有halt()方法


修饰类的构造方法的关键字只能是: public protected private 构造方法,没有返回值,如果加了返回值,则这个方法就不是构造方法而是一个普通方法了。


public class Arg{
    String[] MyArg;
    public static void main(String argv[]){
        MyArg=argv;   //错 non-static variable MyArg cannot be
//referenced from a static context
    }
    public void amethod(){
        System.out.println(argv[1]);   //错cannot resolve symbol argv
    }                              //argv只能在main中使用
}
一道错误百出的题

import java.io.*;
class Base{
public static void amethod() throws FileNotFoundException{
                     //这里面居然也可以是空的
}
}
public class ExcepDemo extends Base{
public static void main(String argv[]){
       ExcepDemo e = new ExcepDemo();
}
public static void amethod(){ }     //我以为这里一定要抛出异常呢
protected ExcepDemo(){
    try{
        DataInputStream din = new DataInputStream(System.in);
        System.out.println(&quot;Pausing&quot;);
        din.readChar();
        System.out.println(&quot;Continuing&quot;);
        this.amethod();
    }catch(IOException ioe) {}
}
}
Mutiple:
1) Compile time error caused by protected constructor
2) Compile time error caused by amethod not declaring Exception
3) Runtime error caused by amethod not declaring Exception
4) Compile and run with output of &quot;Pausing&quot; and &quot;Continuing&quot; after a key is hit
4
throws 和throw不必一定成对出现

public class Outer{
public String name = &quot;Outer&quot;;
public static void main(String argv[]){
        //Inner myinner = new Inner();    //直接用这句话创建会编译错误
        Outer myouter=new Outer();     //先创建外部类的对象
        Outer.Inner myinner=myouter.new Inner();
        myinner.showName();
}//End of main
//下面这段代码用来测试这种n烦的办法
public void amethod(){
     Outer myouter=new Outer();   
     Outer.Inner myinner=myouter.new Inner();
     myinner.showName();
} //非静态方法访问非静态内部类
private class Inner{
     String name =new String(&quot;Inner&quot;);
     void showName(){
          System.out.println(name);
     }
}//End of Inner class
}
1关于在静态方法中访问非静态内部类的问题

2在非静态方法访问非静态内部类直接创建该内部类的对象:
new Inner().showName();
当然也可以采取左边这种n烦的办法。我自己测试过

3假设private class Inner改成static private class Inner, 那么在静态方法中访问静态内部类也是直接创建该内部类的对象,即Inner myinner = new Inner(),或者Outer.Inner myinner = new Outer.Inner()也行得通哦

4可见这种n烦的方法在上面三种情况下都是可以用的。


import java.awt.event.*;
import java.awt.*;
public class MyWc extends Frame implements WindowListener{
       public static void main(String argv[]){
        MyWc mwc = new MyWc();
    }/*
    public void windowClosing(WindowEvent we){
        System.exit(0);
    }//End of windowClosing*/
    public void MyWc(){
        setSize(300,300);
        setVisible(true);
    }
}//End of class
Mutiple:
1) Error at compile time
2) Visible Frame created that that can be closed
3) Compilation but no output at run time
4) Error at compile time because of comment before import statements
一道满是陷阱的题!!
首先如果你的注意力在构造函数上,那么void型的构造函数显然已经不是构造方法,而是一个普通的无返回类型的普通方法,因此你可能会想到3

但是其实问题不在于此而是MyWc实现了WindowListener接口,而不是WindowAdapter类,因此MyWc必须实现WindowListener接口的所有方法!!faint阿,因此答案是1


静态变量不能在方法中定义,切记切记!
静态成员是类的属性,

1) At the root of the collection hierarchy is a class called Collection
collection是接口啊啊啊啊啊


              int q=0;//或int q;
        for (int p = 0, q = 0; p < 5; p++){
           System.out.println(&quot;Val = &quot; + p + q);
        }
这段代码编译会出错,提示:
q is already defined
有点奇怪哦

public int amethod(int p){
//
}
private float amethod(int p) {
//
}

方法的overload不能以返回值类型来判断,因此如果定义两个同名方法仅有返回值类型不同会出现编译错误。
返回值类型和修饰符不同仍然会出现编译错误,也就是说:只能是参数列表不同才可以通过编译。
不要想当然!!

resume() suspend()方法虽然已经不推荐使用,但是出警告信息后仍然可以运行!
不要想当然!!

注意String类的方法substring()不能写成subString()
s=”0123456789”;
s.substring(0,6)=”012345”
s.substring(6)=”6789”


transient volatile是干什么的?
volatile是修饰变量的,用在线程中


可以这样写Map mymap=new HashMap();
不可以这样Map mymap = new Map();
因为Map是接口,不能实例化,HashMap是实现了Map接口的类。


public class Test{
       public static void main(String[] args) {
              amethod();
       }
       static void amethod(){
              try{
                     System.out.println(&quot;abcd&quot;);
                     return;
              }finally {
                     System.out.println(&quot;123456&quot;);
              }
       }
}
可怕的程序阿
输出:
abcd
123456
说明:
1.try块后面不一定要跟catch,try后面只需catch和finally中的任意一个或者both.
2.return语句可以这样写.return不能阻止执行finally中的代码,如果将return改成System.out.exit(0)则不会执行finally中的代码了

1) Byte b = new Byte(123); // Byte b = new Byte(123);
2) Byte b = new Byte(&quot;123&quot;);
3) Byte b = new Byte();
b = 123;
4) Byte b = new Byte((int)123.4);
5) Byte b = new Byte(0x123);
两个构造方法
Byte(bytevalue)
         
Byte(String s)

All Listener interfaces are declared as public and void. (Only One)
1) True
2) False
//将接口文件单独定义保存Myface1.java
public interface Myface1 { //此处只能是public或什么都不写
       int i=9;
       void a();
       void b();
}
//下面的程序在同一个文件中C.java
interface Myface{
//interface前不能有任何modifierpublicprivateprotected均会提示错误
//因为下面类C声明为public,同一个文件中只能有一个public置顶
       int i=9;
       void a();
}
public class C implements Myface{
       C() {
       }
       public void a(){}   
//此处的public是必需的,否则会提示a() in C cannot implement a() in Myface; //attempting to assign weaker access privileges;
       public static void main(String[] ar){
              System.out.println(&quot;aaa&quot;);
       }
}
1
接口怎么可能是void?

Interface任何情况下不能用protectedprivate修饰,,除非嵌套在一个接口或类中




Interface任何情况下不能用protectedprivate修饰

一个文件中只能有一个public的接口或类!



class Father{ //改成protected class Father {会出编译错误
       1void a(){};
       2void b(){};
     void c(){}
}
3public class SonOne extends Father{
       protected void a(){};
       4public void b(){};
     //private void c(){}   //加这句话会出现编译错误
}
继承中子类和子类方法
的存取控制符

左边的程序没问题

类只能用public 或缺省什么都不写来修饰
类中的方法,子类override父类的方法子类方法的存取控制范围要比父类大或相同。

public class FinalTest {
       final int p;
       final int q=3;
       FinalTest(){
              p=1;
       }
       FinalTest(int i){
              p=i;
              //q=i; //(*)如果去掉注释会有编译错误
       }
}
关于给常量赋初值的问题
1.此题能够编译通过
2.如果定义的常量未赋初值则可以在构造方法中给他赋值
3.但是如果定义时已经给常量赋值,如q,则不能再为他赋值,如(*)

Which of the following classes override the equals() method.(Mutiple)
1) String 2) Integer 3) Double
4) Date   5) File
12345

Which of the following are valid methods for the Applet class.(Mutiple)
1) start()    2) stop()   3) init()
4) destroy() 5) kill()
1234

abs acos asin   atan   atan2 cos sin   tan   sqrt   pow   
exp log    ceil   floor   max   min    random   rint   round
IEEEremainder   toDegrees    toRadians(弧度)
关于math类中的所有函数
除了最后一行的三个函数有大写子母外,其他函数全部是小写字母

Consider the two statements:
       1. boolean passingScore = false && grade == 70;
       2. boolean passingScore = false & grade == 70;
The expression grade == 70 is evaluated:
Mutiple: ________________
1) in both 1 and 2
2) in neither 1 nor 2
3) in 1 but not 2
4) in 2 but not 1
5) invalid because false should be FALSE
4

短路运算&& ||

3) int[]a[] = new int[5][5]; //legal
4) int[][]a = new[5]int[5]; //illegal
二维数组

int m=0;
http://onexin.iyunv.com/source/plugin/onexin_bigdata/file:///C:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/msohtml1/01/clip_image001.gif       while( m++ < 2 )
   System.out.print( m +” ”);     输出:1 2
http://onexin.iyunv.com/source/plugin/onexin_bigdata/file:///C:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/msohtml1/01/clip_image001.gif       for(int i=0;i<2;i++){
if(m++<2)
System.out.print( m +” ”);    输出:1 2
}
http://onexin.iyunv.com/source/plugin/onexin_bigdata/file:///C:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/msohtml1/01/clip_image001.gif       for(int i=0;i<2;i++,m++)
     System.out.print( m+” ” );    输出:0 1
可是:
              for(int i=1;i<10;i++)
                     i++;
              System.out.println(i);   输出11 ????

public class Test15{
       public static void main(String[] args) {
              int i;
              for(i=1;i<6;i++1) {
                            System.out.println(&quot;第 &quot;+i+&quot; 次循环开始&quot;);
                            System.out.println(&quot;after 1 i++, i=&quot;+i);
                            i++2;
                            System.out.println(&quot;after 2 i++, i=&quot;+i);
                     }
              System.out.println(i);    //11
       }
}
一个值得注意的问题









第 1 次循环开始
after 1 i++, i=1
after 2 i++, i=2
第 3 次循环开始
after 1 i++, i=3
after 2 i++, i=4
第 5 次循环开始
after 1 i++, i=5
after 2 i++, i=6
7
我认为
先执行i++2
一次循环结束时执行i++1
所以7是结束循环时执行i++1

http://onexin.iyunv.com/source/plugin/onexin_bigdata/file:///C:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/msohtml1/01/clip_image001.gif       在继承的情况下,如果父类的方法抛出异常,那么子类的重置方法抛出异常不应该比父类多。子类的方法只能抛出父类异常的子集。子类也可以不抛出异常。
http://onexin.iyunv.com/source/plugin/onexin_bigdata/file:///C:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/msohtml1/01/clip_image001.gif       对于RuntimeException,上面的规则不适用,父类方法抛出ArithmeticException,子类的方法可以抛出范围更广的异常。参看下例!
重置方法抛出异常的规则

import java.io.*;
class Super {
       int methodOne( int a, long b ) throws IOException { }
       float methodTwo( char a, int b )       { }
}
public class Sub extends Super{ }
Which of the following are legal method declarations to add to the class Sub? Assume that each method is the only one being added.
Mutiple: ________________
1) public static void main( String args[] ){ }
2) float methodTwo(){ }
3) long methodOne( int c, long d ){ } //错误!提示返回类型不匹配!
4) int methodOne( int c, long d ) throws ArithmeticException{ }
5) int methodOne( int c, long d ) throws FileNotFoundException{ } //参考上一格
125



如果将
3)long methodOne( int c, long d ){}
改成:int methodOne( int c, long d ){}就可以。子类可以不抛出父类抛出的异常


Which of the following statements about Java's garbage collection are true?
Mutiple: ________________
1) The garbage collector can be invoked explicitly using a Runtime object.
2) The finalize method is always called before an object is garbage collected.
3) Any class that includes a finalize method should invoke its superclass' finalize method.   ?
4) Garbage collection behavior is very predictable.
123
http://onexin.iyunv.com/source/plugin/onexin_bigdata/file:///C:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/msohtml1/01/clip_image001.gif       在清除垃圾之前,系统会调用finalize方法,这是顶级类Object中的finalize方法。
http://onexin.iyunv.com/source/plugin/onexin_bigdata/file:///C:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/msohtml1/01/clip_image001.gif       System类中的runFinalization方法能够强制调用finalize方法,
http://onexin.iyunv.com/source/plugin/onexin_bigdata/file:///C:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/msohtml1/01/clip_image001.gif       gc方法强制调用垃圾回收功能

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?
Select all valid answers.
Mutiple: ________________
1) class B {}
2) class B extends A {}
3) class B {
   B() {
      System.out.println(&quot;i = &quot; + i);
   }
}
4) class B {
     class A {}
}
13

     class SuperEx {
          String r;
          String s;
          public SuperEx(){
              System.out.println(&quot;系统无参&quot;);
          }
          public SuperEx(String a,String b) {
               r = a;
               s = b;
          }
          public void aMethod() {
               System.out.println(&quot;r :&quot; + r);
          }
     }
     public class NewSuper extends SuperEx {
          public NewSuper(String a,String b) {
               super(a,b);
          }
          public static void main(String args []) {
               SuperEx a = new SuperEx(&quot;Hi&quot;,&quot;Tom&quot;);
               SuperEx b = new NewSuper(&quot;Hi&quot;,&quot;Bart&quot;);
               a.aMethod();
               b.aMethod();
          }
          public void aMethod() {
               System.out.println(&quot;r :&quot; + r + &quot; s:&quot; + s);
          }
     }
???????????????????????





r :Hi
r :Hi s:Bart


2) A try block can be followed either by a catch block or a finally block, or both
try(后面可以跟catch和finally任意一个,也可以同时跟两个)
3) A catch block must always be associated with a try block
但是如果有一个catch语句,前面一定得有try语句
4) A finally can never stand on its own (that is, without being associated with try block) finally语句不能脱离try单独存在。

Try catch语句中,如果遇到return;则finally语句块仍然会执行,但是紧接在finally块之后的语句将不会被执行!
如果遇到System.exit(1);则finaly语句块和紧接在finally块之后的语句将不会被执行!参看下一格
关于finally块

public class TestFinally {
       public TestFinally (){ //构造方法
              try{
                     if (true)
                            throw new ArithmeticException();
              }      
              catch (ArithmeticException e){
                 System.out.println(&quot;begin to catch ArithmeticException &quot;); //输出
                     return;
                 //System.exit(1);                  
              finally{
                 System.out.println(&quot;in finally no matter if Exception occurs&quot;);//输出
              }
           System.out.println(&quot;构造方法结束!&quot;); //这句话不会被执行到!
       }
       public static void main(String[] arfg) {
              TestFinally tf=new TestFinally();
              System.out.println(&quot;in main()!&quot;); //这句话会被执行到!
       }
}
输出:
begin to catch ArithmeticException
in finally no matter if Exception occurs
in main()!



如果将return;改成System.exit(1);则只输出
begin to catch ArithmeticException
可见整个程序都退出了!

class Mystery {
String s;
public static void main(String[] args) {
    Mystery m = new Mystery();
    m.go();
}
void Mystery() {
    s = &quot;constructor&quot;;
}
void go() {
    System.out.println(s);
}
}
Select the one right answer. Mutiple: ________________
1) this code will not compile
2) this code compiles but throws an exception at runtime
3) this code runs but nothing appears in the standard output
4) this code runs and &quot;constructor&quot; in the standard output
5) this code runs and writes &quot;null&quot; in the standard output
5



如果go()声明为static则出错,原因是静态方法不能引用非静态的变量

paint()的类型?public ?
1.2的内容

public class Test2 extends Object implements Runnable {
   String s1 = &quot;Earth &quot;;
   String s2 = &quot;Moon&quot;;
   public void run() {
     synchronized (s1) {
//可以替换成synchronized(this),synchronized(“hi”)
       for (int i=0; i < 2; i++) {
        s1.concat(&quot; to Moon &quot;);
        System.out.print(s1);
        s2.concat(&quot; to Earth &quot;);
        System.out.println(s2);
       }
     }
   }
public static void main(String[] args) {
     Test2 t = new Test2();
     new Thread(t).start();
     new Thread(t).start();
}
}
Synchronized的用法是?

输出:同步了
Earth Moon
Earth Moon
Earth Moon
Earth Moon

Which of the following expressions results in a positive value in x? (Choose one.)
1) int x = -1; x = x >>> 5;
2) int x = -1; x = x >>> 32; //x>>>32运算后x=-1不是正数。X>>>33是正数//2147483647; x>>>311可见32是个很特殊的数
3) byte x = -1; x = x >>> 5; //x>>>5之后是int型,不能赋给byte型的x
4) int x = -1; x = x >> 5;    //-1
移位运算之无符号右移

Which of the following expressions are legal? (Choose one or more.)
1) String x = &quot;Hello&quot;; int y = 9; x += y;
2) String x = &quot;Hello&quot;; int y = 9; if (x == y) {}
3) String x = &quot;Hello&quot;; int y = 9; x = x + y;
4) String x = &quot;Hello&quot;; int y = 9; y = y + x;
5) String x = null;int y = (x != null) && (x.length() > 0) ? x.length() : 0;
135

Which of the following code fragments would compile successfully and print &quot;Equal&quot; when run? (Choose one or more.)
1) int x = 100; float y = 100.0F;
   if (x == y){ System.out.println(&quot;Equal&quot;);}
2) int x = 100; Integer y = new Integer(100);
   if (x == y) { System.out.println(&quot;Equal&quot;);}
3) Integer x = new Integer(100);
   Integer y = new Integer(100);
   if (x == y) { System.out.println(&quot;Equal&quot;);} //包裹类。无输出。
4) String x = new String(&quot;100&quot;);
   String y = new String(&quot;100&quot;);
   if (x == y) { System.out.println(&quot;Equal&quot;);} //无输出
5) String x = &quot;100&quot;; //可能被认为是基本数据类型了
String y = &quot;100&quot;; //可能被认为是基本数据类型了
if (x == y) { System.out.println(&quot;Equal&quot;);} //Equal
15
包裹类 ==

奇怪的是,45不是一样的吗?
可能是5那样定义被认为是基本数据类型了。
记住就行了


class Aa {
       public Aa(String a,String b) {   }
}
public class Bb extends Aa {
    public Bb(String a,String b) {
           super(a,b);
    }
    public static void main(String args []) {
        Aa a = new Aa(&quot;Hi&quot;,&quot;Tom&quot;);
        Aa b = new Bb(&quot;Hi&quot;,&quot;Bart&quot;);
    }
}
这段程序可以编译通过

1)如果去掉super(a,b);则会出现编译错误,提示找不到Aa中的无参构造函数
此时要么加super(a,b),要么给Aa写无参构造函数。
我不理解!!!????


class Aa {
       public Aa(String a,String b) {
}
//1public Aa() { }
}
public class Bb extends Aa {
    public Bb(String a,String b) {
           super(a,b);
}
//2public Bb() {   }
//5public Bb() {   super();   }
    public static void main(String args []) {
        Aa a = new Aa(&quot;Hi&quot;,&quot;Tom&quot;);   // 6
        Aa b = new Bb(&quot;Hi&quot;,&quot;Bart&quot;);   // 7调用子类有参
        //Aa a1 = new Aa();   3 //调用父类的无参
        //Aa b 1= new Bb();   4 //调用子类的无参
   }
}
这段程序可以编译通过

1)有参构造函数
如果去掉super(a,b);则会出现编译错误,提示找不到Aa中的无参构造函数;此时要么加super(a,b),要么给Aa写无参构造函数。
如果不写7,即,调用父类代参数的构造方法,则仍然要么加super(a,b),要么给Aa写无参构造函数。

可见这个与是否创建对象无关。参看下一格

2)无参构造函数
现在在上面程序的基础上,如果要显式调用无参构造函数,则
1.调用父类的无参,如3,则必须写1
2.调用子类的无参,如4,
则必须写12
或15

与创建对象有关


class Aa {
       public Aa(String a,String b) { }
    public Aa(){ }    //a
}
public class Bb extends Aa {
    public Bb(String a,String b) {
           super(a,b);   //b
    }
    public static void main(String args []) { //没有创建任何对象
    }
}
上格的第1)点补充
a和b各取其一,或both才能通过编译

说明与是否创建对象无关!


Consider the following class definition:
1. public class Test extends Base {
2.   public Test(int j) {
3.   }
4.   public Test(int j, int k) {
5.     super(j, k);
6.   }
7. }
Which of the following forms of constructor must exist explicitly in the definition of the Base class?
Mutiple:
1) Base() { }
2) Base(int j) { }
3) Base(int j, int k) { }
4) Base(int j, int k, int l) { }
13

stringBuffer类和String类有很多相似之处,有很多同名的方法,可以将StringBuffer类理解为String类的mutable版本。
String类有非常多的构造方法,注意看。


类,方法、变量、对象都可以用final修饰。
final?

volatile:Tells the compiler a variable may changes asynchronously due to threads. 声明一个变量为volatile使编译器forego optimizations(居先最优化)that might turn the variable into a constant(可以使变量转换成常量) and eliminate the possibility of it changing asynchronously(消除异步被改变的可能性)

transient int i = 41;是一个合法的表达式可见transient可以修饰变量
volatile和transient关键字

静态初始化块总是最先被执行,无论其代码放在最前还是最后。


在继承关系中,子类方法重载父类方法时,子类方法的存取控制符级别要和父类一样或高于。举例
class Abclass {
       protected void a(){}
       }
public class Abb extends Abclass{
       public void a(){} //如果public改成protected可以,改成private则不行!
       public static void main(String[] ar){}
}
重置
子类要比父类存取范围高
(即,不能更私有)

Which modifier or modifiers should be used to denote a variable that should not be written out as part of its class's persistent state? (Choose the shortest possible answer.)
1) private
2) protected
3) private protected
4) transient
5) private transient
4

????

class TestConFather {
       static int cou=0;
       TestConFather() {
              cou++;
       }
}
public class TestConSon extends TestConFather {
       TestConSon() {
              cou++;
       }
       public static void main(String[] a) {
              System.out.println(&quot;Before:&quot;+cou);
              TestConSon tt=new TestConSon();
              System.out.println(&quot;After:&quot;+cou);
       }
}
这体输出:
Before:0
After:2


先调用父类的构造函数

                   Animal
                     |
                   Mammal
                     |
---------------------------------------------------------------
|           |              |               |
Dog        Cat          Raccoon       SwampThing
         (implements    (implements
            Washer)       Washer)
&uuml;   interface Washer {}
&uuml;   class Animal {}
&uuml;   class Mammal extends Animal {}
&uuml;   class Dog extends Mammal {}
&uuml;   class Cat extends Mammal implements Washer {}
&uuml;   class Raccoon extends Mammal implements Washer {}
&uuml;   class SwampThing extends Mammal {}
public class Test14 {
       public static void main(String[] a) {
              //----------------------------------
              Dog rover,fido;
              Animal anim;
              rover =new Dog();
              anim=rover;     //理解成Animal anim = new Dog();
              fido =(Dog)anim; //这段话能够通过编译和运行!!!!!
        //fido =anim;不能通过编译
              //----------------------------------
              Washer wawa=new Cat();
              SwampThing pogo;
              pogo=(SwampThing)wawa;
//这句话能够通过编译,但不能运行
//两个毫不相干的类对象,居然能够通过编译?
//经另外测试,任意两个不相干的类对象cast是会出现编译错误的,
//所以,上面的类可能是继承了同一个类的缘故?
       }
}
ClassCast问题
























//---------------------------------------


java.lang.ClassCastException

Math类不能用于继承,定义public final class Math


import java.io.*;
import java.net.*;
public class Test15 {
       public static void main(String[] a) {   
              try {
                     throw new MalformedURLException();     
                     //System.out.println(&quot;Success&quot;); //不能加这句话
              }
              1catch (MalformedURLException e) {
                     System.out.println(&quot;Bad URL&quot;); //捕获到
              }
              /* 这段话不能加,因为try块中没有任何可能抛出此异常
              catch (StreamCorruptedException e) {
                     System.out.println(&quot;Bad file contents&quot;);
              }*/
              catch (Exception e) {
                     System.out.println(&quot;General exception&quot;);
//1已经捕获到,所以此处没有输出
              }
              finally {
                     System.out.println(&quot;Doing finally part&quot;);
              }
              System.out.println(&quot;Carrying on&quot;);
       }
}
输出:
Bad URL
Doing finally part
Carrying on

//throw后不能有任何语句,否则系统提示不能到达该语句。编译错误。








// MalformedURLException已经被捕获,此处不会再有输出

//多个catch语句,要求子类异常在前面,否则其无法捕获,编译出错

//catch语句不能放在finally块后,否则提示无匹配的try

1. public class Test1 {
2.   public float aMethod(float a, float b) throws IOException { }
3. }
1. public class Test2 extends Test1 {
2.
3. }
Which of the following methods would be legal (individually) at line 2 in class Test2?
1) float aMethod(float a, float b) { }
2) public int aMethod(int a, int b) throws Exception { }//此处不是override
3) public float aMethod(float a, float b) throws Exception { }//编译错误
4) public float aMethod(float p, float q) { }     //子类可以不抛出异常
答案是24

选项3)错在抛出的异常范围比父类同名方法的大了,
子类重载方法抛出的异常的应当是父类方法抛出的异常的子类,子类也可以不抛出异常
选项1)错在子类override方法不能比父类的更私有

//ExceptionIOException范围大,错。

import java.lang.Math; //可以不写这行
public class Te{
public static void main(String[] a){
     Math myMath = new Math();
     System.out.println(&quot;cosine of 0.123 = &quot; + myMath.cos(0.123));
}
}
提示错误:
Math() has private access in java.lang.Math

不能创建实例
可用System.out.println(&quot;cosine of 0.123 = &quot; + Math.cos(0.123));

import java.io.*;
public class Test1 {
       public static void main(String[] a){
              String s = &quot;abcde&quot;;//改成String s = new String(&quot;abcde&quot;);不影响结果
              StringBuffer s1 = new StringBuffer(&quot;abcde&quot;);
              if (s.equals(s1))
                     System.out.println(&quot;s.equals(s1)&quot;);
              if (s1.equals(s))
                     System.out.println(&quot;s1.equals(s)&quot;);
       }
}
本题不会出现编译错误
且可以运行,
无输出

因为类型不一致

class XXX {
   public static void main(String[] args) {
     String s1 = &quot;abcde&quot;;
     String s2 = &quot;abcde&quot;;
     s1.toUpperCase();
     if (s1 == s2)
       System.out.println(&quot;YES&quot;);
     else
       System.out.println(&quot;NO&quot;);
   }
}

当然是yes拉,ft, immutable!

What statement or statements below are true concerning the following code?
1. class X {
2.   public static void main(String[] a) {
3.     try {
4.       short s = 0x00FD;
5.       byte b = (byte)s;
6.       System.out.println(&quot;b = &quot; + b);
7.     }
8.     catch (Exception e) {
9.       System.out.println(&quot;TROUBLE!&quot;);
10.     }
11.   }
12. }
1) It generates a compiler error at line 5.
2) If the cast on line 5 were omitted, then line 5 would not compile.
3) The code compiles and prints &quot;b = 0&quot;.
4) The code compiles and prints &quot;b = -2&quot;.
5) The code compiles and prints &quot;b = -3&quot;.
25


s=15*16+13=253
byte型虽然是-128~127,但是之间相当于有128+127+1=256个数(包括0
因此byte b = (byte)s;之后,
b=253+(-256)=-3

Which of the statements below are true? (Choose none, some, or all.)
1) UTF characters are all 8 bits.
2) UTF characters are all 16 bits.
3) UTF characters are all 24 bits.
4) Unicode characters are all 16 bits.
5) Bytecode characters are all 16 bits.
4

UTF是什么?

class Xaa{
       protected String toString() {
              return super.toString();
       }
}
会有编译错误,protected的存取控制范围小于父类objecttoString()public

这种错误再也不要犯了!!!

What is the effect of attempting to compile the following code and then execute the Child application?
1. public class Papa {
2.   int i;
3.   Papa(int j) { i = j; }
4. }
5.
6. class Child extends Papa {
7.   Child() { i = 5; }   //此处会出编译错误
8.   public static void main(String[] args) {
9.     new Child();   //而不是在创建对象的时候
10.   }
11. }








需要定义父类构造函数Papa(){ }

class Xaa{
       Xaa( int i ) { }
}
public class Xaextends Xaa {
       Xa (){}       //编译错误
}
还是无参构造函数!!!!!
提示找不到父类无参构造函数

-1 >> 65535得多少?是不是-1
右移后前面补1(符号位),还是全1

ceil() floor() abs() max() min() sqrt()都是返回double型,
round()是取整int
千万要注意赋值的精度问题
(编译出错)

Switch的判断条件必须是int和它以下的数据类型
不包括long型,可以是char

如果是float型,是编译错还是运行错???


              int i=0x7fffffff;
              int p=i*100;
              long j=i*100;
              System.out.println(&quot;p=&quot;+p); //-100
              System.out.println(&quot;j=&quot;+j);   //-100
int型不会越界么?
会,只有32

Int*int好像总也不会出错!

编译错误中提示unreachable statement的几种情况
1. int a(){
              return 1;                       //1)方法的return语句之后
              System.out.println(&quot;hi&quot;); //compile error
       }
2. if (c.x==4){
              throw new ArithmeticException(); //2)throw语句之后
              System.out.println(&quot;Test&quot;); // compile error
       }
3. loop2: for(int n=1;n<3;n++){
                     for(int c=1;c<3;c++){
                            if (c==2) {
                                   break loop2;        //3)breakcontinue语句之后
                                   System.out.println(&quot;hi&quot;); //compile error
                            }
                     }                           
              }

unreachable statement

while(false){…} //compile error

while(true){…} //ok.




将System.out.println(&quot;hi&quot;);放到if语句外,编译ok

package wee.sick;
public class Test18{
       public static void main(String[] args) {
              Test18 a =new Test18();
       }
}
可以编译
为什么会有运行错误????
java.lang.NoClassDefFoundError: Test18 (wrong name: wee/sick/Test18)
F:/wee/sick/

线程中可以显式调用run()方法。不知道与调用start()有什么区别???
显式调用时不具有多线程的特点,只是顺序执行。参看P317


Pick all the true statements below.
1) If a thread wants to call wait() on an object, the thread must own that object's lock.
2) There is a method that you can call on an instance of the Thread class that puts the instance to sleep for a specified number of milliseconds.
3) At the moment when a thread is notified, it automatically gets the lock of the object for which it was waiting.

sleep(long millis)
          Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.

1
23错在哪里???
there are 7 possible for causing thread to stop executing:
1/exiting from synchronized block
2/calling the wait method on the object/
3/calling read method on the InputStream object
4/priorer thread enters ready state/
5/calling system.exit(0)
6/The thread executes a sleep() call
7/A call to the thread's stop method


String s; char c;
s=”//”;    //legal,输出/
s=”/”;    //illegal, 编译错误
c=’//’;    //legal,输出/
c=’/’;     //illegal, 编译错误
关于转义字符

class Base {
       static final int S=10;    //静态常量定义的时候就要赋初值
       static float M=10.3f;   
       Base(){}
}                     //ok!
class Base {
       static final int S;
       static float M;
       S=10;
       M=10.3f;
       Base(){}
}                    //compile error!
class Base {
       final int S;
       static float M;
    static final int S2;
       Base(){
              S=10;        //常量(不能是静态)可以在构造函数中赋值
        S2=10;        //error
              M=10.3f;               //ok,可以给静态变量赋值
        final int n=10; //ok, 构造方法中可以有定义局部常量
        static int i=5;   //compile error,构造方法中不能定义静态常量或变量
       }
}
类中静态变量的初始化问题



--------------------------------------------------







构造方法中能做的:
1.给类变量(包括static)赋值
2.定义局部非静态变量或常量

构造方法中不能做的:
1.给类静态常量赋值
2.定义局部静态常量或变量

任何非静态方法中都不能定义静态变量!构造函数也是

1.每个包裹类都有doubleValue() 、floatValue()、 intValue()、 longValue()方法,他们无参数,返回对应的基本类型数据
2.静态方法:parseXxxx(……)
parseInt(……)、parseDouble(……)、parseByte(……)等。
以parseInt为例:
(1)   public static int parseInt(String s,int radix)其中radix表示数的进制
例如:
parseInt(&quot;0&quot;, 10) returns 0
parseInt(&quot;473&quot;, 10) returns 473
parseInt(&quot;-0&quot;, 10) returns 0
parseInt(&quot;-FF&quot;, 16) returns -255
parseInt(&quot;1100110&quot;, 2) returns 102
parseInt(&quot;99&quot;, 8) throws a NumberFormatException
parseInt(&quot;Kona&quot;, 10) throws a NumberFormatException ???????
parseInt(&quot;Kona&quot;, 27) returns 411787 ???????
(2)   public static int parseInt(String s) 一个参数
wrapper class中的几个方法!

CharacterByteFloatDoubleShortgetXxx


3.静态方法:static Xxxxx getXxxxx()有三种形式:以getFloat(……)为例


public class T{
       static void main(String[] arg){
              final StringBuffer s=new StringBuffer(&quot;hi,&quot;);
              s.append(&quot;mm&quot;);
              System.out.println(s.toString()); //输出:hi,mm
       }
}
虽然StringBuffer对象s被声明为final,但是用append()方法能够改变s包含的内容

public class T{
       static void main(String[] arg){
              StringBuffer a = new StringBuffer (&quot;A&quot;);
              StringBuffer b = new StringBuffer (&quot;B&quot;);
              operate (a,b);
              System.out.println(a + &quot;,&quot; +b);
             //StringBuffer对象居然可以用+号连接!
       }
static void operate (StringBuffer x, StringBuffer y) {
              x.append (y);
              y = x;
       }
}     //输出:AB,B
A. The code compiles and prints “A,B”.
B. The code compiles and prints “A,A”
.
C. The code compiles and prints “B,B”
.
D. The code compiles and prints “AB,B”
.
E. The code compiles and prints “AB,AB”
.
F. The code does not compile because “+” cannot be overloaded for StringBuffer

一道很特别的题!

transient保证了该对象实例不被序列化?
volatile和c++上一样,允许外界条件改变它的值?

chinajavaworld

abstract interface Myface {
       int i=4;
       public abstract void m();
}
public class T implements Myface {
       public void m(){}
}
interface可以显式的用public abstract修饰
interface中的方法可以显式的用public abstract修饰
另:本代码如果保存成T.java则不能在abstract interface Myface前加public,因为一个文件中只能有一个public的类或接口

public class OuterClass{
       private double d1=1.0;
       public abstract class Inner1{ //内部类可以定义成abstract
        public abstract double methoda();
      }  //-------内部类还可以在内部被继承-------
       class AnotherInner extends Inner1 {
              public double methoda(){return 1.0;}
       } //-------------------------------------------------
      public static void main(String[] args){
       }  //------------内部类可以继承外部类-------------
       public class Inner2 extends OuterClass{
       }      
}


内部类可以定义成abstract


内部类还可以在内部被继承





内部类可以继承外部类


public class Tes {
       static Tes(){   // static void Tes() {
              System.out.println(&quot;hi,mm&quot;);
       }
       public static void main( String[] args) {
              new Tes();
       }
}
Compile error!!
改成注释后面的可以运行但是什么输出都没有!

//构造函数不能是static

public class Tes {
       static Tes(){   // static voidTes() {
              System.out.println(&quot;hi,mm&quot;);
              }
       public static void main( String[] args) {
              new Tes();
       }
}
左边程序有编译错误,提示:modifier static not allowed here
但是如果加上一个返回类型,则不会有编译错误,因为编译器认为Tes()不是构造方法,而是一个普通方法了

13. Given:
package foo;
public class Outer {
    public static class Inner {
    }
}

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
C. An instance of the inner class can only be constructed from within the outer class
D. From within the package bar, an instance of the inner class can be constructed with “new inner()”

1

4为什么不对?
Outer$Inner.class

20. Given:
1. public class test(
2.   public static void main(String[]args){
3.      String foo = args [1];
4.      String foo = args [2];
// String foo2 = args [2];
5.      String foo = args [3]; // String foo3 = args [3];
6.   }
7. }

And the command line invocation:
Java Test red green blue

What is the result?
A. baz has the value of “”
B. baz has the value of null
C. 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 compile
G. the program throws an exception

答案是F
验证一下??
的确如此!
提示:
foo is already defined in main(java.lang.String[])
重复定义了!

如果改成//后的样子,那么编译通过运行时:
1java Test a b c d     //ok
2java Test a b c //抛出异常
//ArrayIndexOutOfBoundsException

23. 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){}

-----------------------------------------------------------------------------------------------
abstract class A {
       abstract void m();
}
public abstract class B extends A {
       public static void main(String[] a){
              System.out.println(&quot;hahahaha&quot;);
       }
}
D
?
这题显然有问题!!参看下面的例子




abstract类的子类可以是abstract
本题可以有输出:hahahaha

当然,如果B不写abstract关键字会有编译错误,因为他继承了一个abstract method!

41. Given:
1. public class X {
2.   public object m ()  {
3.     object o = new float (3.14F);
4.     object [] oa = new object [1];
5.     oa[0]= o;
6.     o = null;
7.     return oa[0];
8.   }
9. }

When is the float object created in line 3, eligible for garbage collection?
A. Just after line 5
B. Just after line 6
C. Just after line 7 (that is, as the method returns)
D. Never in this method

D

对象还有引用存在
oa[0]

78. Which two statements are true regarding the creation of a default constructor? (Choose Two)
A. The default constructor initializes method variables.
B. The compiler always creates a default constructor for every class.
C.The default constructor invokes the no-parameter constructor of the superclass.
D.The default constructor initializes the instance variables declared in the class.
E. When a class has only constructors with parameters, the compiler does not create a default constructor.

CE

1.char c='a';
2.int i=5;
3.c+=i; //compile ok,类似于c=5;的赋值方式
4.c = c+i;//compile error,转化成int在赋值
为什么第3行不错??


还有c>>=i; //ok

135.
1)public class Foo implements Runnable{
2)  public void run(Thread t){
        System.out.println(&quot;Running&quot;);
      }
    public static void main(String[] args){
       new Thread(new Foo()).start();
     }
}
   what is the result?
   A.An Exception is thrown
   B.The program exits without printing anything
   C.An error at line 1 causes complication to fail
   D.An error at line 2 causes complication to fail
   E.&quot;Running&quot; is pinted and the program exits


想知道测试一下!
实现一个接口必须实现其中的所有方法,因此这里没有实现public void run()
但是系统提示C:第一句有错!

147. Which interface does java.util.Hashable implement?
A. java.util.Map
B. java.util.List
C. java.util.Hashable
D. java.util.Collection

A
Cloneable, Map, Serializable



128. Given:
1. public class Test {
2. public static void main (String args[]) {
3.   class Foo {
4.     public int i = 3;
5.    }
6.    Object o = (Object) new Foo();
7.    Foo foo = (Foo)o;
8.    System.out.printIn(foo. i);
9.    }
10. }

What is the result?
A.Compilation will fail
B.Compilation will succeed and the program will print “3”
C.Compilation will succeed but the program will throw a ClassCastException at line 6  
D.Compilation will succeed but the program will throw a ClassCastException at line 7

B

127. Which two declarations prevent the overriding of a method? (Choose Two)
A. final void methoda()  {}
B. void final methoda() {}
C. static void methoda() {}
D. static final void methoda() {}
E. final abstract void methoda() {}

AD
final方法不能被override!
严格来说,static方法也不能!

101. Which statement is true?
A. The Error class is a RuntimeException.
B. No exceptions are subclasses of Error.
C. Any statement that may throw an Error must be enclosed in a try block.
D. Any statement that may throw an Exception must be enclosed in a try block.
E. Any statement that may throw a runtimeException must be enclosed in a try block.

B

public class Test {
       static void m(){
              class B{ }
}    //静态方法中可以定义内部类
       public static void main(String[]args){
              m();
    }
}
静态方法中可以定义内部类

105. Which statement is true for the class java.util.ArrayList?
A. The elements in the collection are ordered. //List
B. The collection is guaranteed to be immutable.
C. The elements in the collection are guaranteed to be unique. //Set
D. The elements in the collection are accessed using a unique key. //Map
E. The elements in the collections are guaranteed to be synchronized. //Vector

A

sortedMap sortedList都是接口


‘/u101’//非法
‘/u1010’           //合法
‘/u10100’ //非法
“/u101” //非法
“/u1010”           //合法
“/u10100”//合法,相当于/u1010和字符串“0”


90. Given:
1. public class foo {
2.   static String s;
3.   public static void main (String[]args) {
4.     system.out.printIn (“s=” + s);   //注意s必须为
static
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.

B

Which of the following code fragments generate compiler errors?
Mutiple:
1) boolean boo = true; int i = boo;
2) byte b = 5; char c = b;
3) char c1 = 'a'; short s = c1;//提示损失精度
4) long lon = 1L; float f = lon;
5) float f1 = 2L; long lon1 = f1;
但是char型可以赋给下列数据类型:
double float long int&szlig;char型,这些数据类型都是3232位以上的数据类型
1235
byte,long int short float double都不能赋给char型,
提示:possible loss of precision会损失精度.
只有char型数据是无符号的
boolean型赋给char型错误提示:
incompatible types
即:任何基本数据类型的数据都不能赋给char型

import java.io.IOException;
class SubEx extends IOException { }
class A {
   public static void main(String[] args) {
     try {
       thud();
     } catch (SubEx x) {
       System.out.println(&quot;main() caught SubEx&quot;);
     } catch (IOException x) {
       System.out.println( &quot;main() caught IOException&quot;);
     } catch (Exception x) {
       System.out.println( &quot;main() caught Exception&quot;);
     }
   }
   static void thud() throws IOException {
     try {
       throw new SubEx();
     } catch (SubEx x) {
       System.out.println(&quot;thud() caught SubEx&quot;);
       throw new IOException();
//只会抛给调用thud()的方法而不会抛到下一个3catch处,也就是说
//一个try只会对应一个catch和一个finally.切记!!
     } 3catch (IOException x) {
       System.out.println( &quot;thud() caught IOException&quot;);
       throw new IOException();
     } catch (Exception x){
       System.out.println( &quot;thud() caught Exception&quot;);
     }
   }
}
1) &quot;main() caught SubEx&quot;
2) &quot;main() caught IOException&quot;
3) &quot;main() caught Exception&quot;
4) &quot;thud() caught SubEx&quot;
5) &quot;thud() caught IOException&quot;
这道题一定要注意
输出是24

如果一个方法m() throws AException,那么无论在这个方法中是否会产生异常或方法中的异常已经在方法内部解决,调用m()的方法都必须设置try-catch来捕获AException.





抛出的异常必须被catch,
catch()中的异常类型必须是try中可能发生的异常,如果两者毫无关系会有编译错误。


import java.io.IOException;
public class Tests{
       public static void main(String[] args) {
              try{
                     throw new IOException();
              }catch(IOException e){
                     System.out.println(&quot;111&quot;);
                     throw new Exception();//*
              }catch(Exception e ){
                     System.out.println(&quot;222222222222&quot;);
              }
       }
}
这段程序会有编译错误!!
有两种解决办法:
1. 去掉(*)
2. 在main方法声明throws Exception.
因为只能catch一个exception

What happens when you attempt to compile the following code?
1. class A { static void foo(int i) {}; }
2. class B extends A { void foo(int i) {}; }
Only One:
1) Compiler error at line 1.
2) Compiler error at line 2.
3) No compiler error.
2

static方法不能override为non-static

main(String[] arg)如果不写void会有编译错误
如果不写public static[]会有运行错误
关于main()

True or false: It is legal to instantiate a class that contains abstract methods, provided you do not call any of those abstract methods.
1) True
2) False
抽象类不能被实例化,但是下面的程序是可以的!
abstract class Y{
    public static void main(String[] a){
        System.out.println(&quot;Doing finally&quot;);
    }
}//有输出!!
2??????



接口也不能实例化(抽象的)

How many String objects exist as a result of running the code listed below?
1. String s1 = &quot;abc&quot;;
2. String s2 = s1;
3. String s3 = &quot;abc&quot;;
1) None 2) 1   3) 2   4) 3
2

String中的函数trim()只能去掉字符串头尾的空格!


Which of the following is/are legal assignments of a literal value to a String variable? Choose all correct options.
Mutiple:
1) String s = &quot;/&quot;&quot;; //输出 ”
2) String s = /&quot;abcde/&quot;; //换成” /&quot;abcde/&quot;”
3) String s = &quot;/u3456/ufde6/u0/u1234&quot;; //换成&quot;/u3456/ufde6/u0000/u1234&quot;即可
4) String s = &quot;/&quot;/&quot;/&quot;////&quot;; //输出 “””//
14

必须用双引号括起

Consider the following line of code:
boolean[] b = new boolean[25];
After this line executes, which of the following statements is/are true? Choose all correct options.
1) b[4] is undefined.
2) b[25] does not exist.
3) b[25] is false.
4) b[24] is false.
5) b.size = 25. //b.length=25

24





Ft,没有size这个属性

1. class Z {
2.   public static void main(String[] args) {
3.     new Z();
4.   }
5.
6.   Z() {
7.     Z alias1 = this;
8.     Z alias2 = this;
9.     synchronized(alias1) {
10.       try {
11.         alias2.wait();
12.         System.out.println(&quot;DONE WAITING&quot;);
13.       }
14.       catch (InterruptedException e) {
15.         System.out.println(&quot;INTERRUPTED&quot;);
16.       }
17.       catch (Exception e) {
18.         System.out.println(&quot;OTHER EXCEPTION&quot;);
19.       }
20.       finally {
21.         System.out.println(&quot;FINALLY&quot;);
22.       }
23.     }
24.     System.out.println(&quot;ALL DONE&quot;);
25.   }
26. }
Mutiple:
1) Compiler error.
2) The application compiles but doesn't print anything.
3) The application prints &quot;DONE WAITING&quot;.
4) The application prints &quot;INTERRUPTED&quot;.
5) The application prints &quot;OTHER EXCEPTION&quot;.
2

1) float f=1/3; //合法
2) int i=1/3;   //合法
3) float f=1.01;
4) double d=999d; //double d=999.0d都是合法的表达式

5)int i=2+'2'; //合法


Integer没有setValue方法,包裹类均immutable


char c='1';
System.out.println(c>>1);

移位运算符可以用于long int char short byte
合法!!

Which of the following most closely describes the process of overriding?
1) A class with the same name replaces the functionality of a class defined earlier in the hierarchy
2) A method with the same name completely replaces the functionality of a method earlier in the hierarchy
3) A method with the same name but different parameters gives multiple uses for the same method name
4) A class is prevented from accessing methods in its immediate ancestor

2

public class Droitwich{
        class one{
                private class two{
                        public void main(){
                           System.out.println(&quot;two&quot;);
                        }
                }
        }
}
很奇怪的一道题
此题可以编译通过!
虽然嵌套了很多层!
The main method is not declared as public static void main, and assuming that the commandline was java Droitwich it would not be invoked anyway.

class Base{
static int oak=99;
}
public class Doverdale extends Base{
public static void main(String argv[]){
        Doverdale d = new Doverdale();
        d.amethod();
    }
    public void amethod(){
        //Here
    }      
}
Which of the following if placed after the comment //Here, will compile and modify the value of the variable oak?
1) super.oak=1;//特别注意
2) oak=33;
3) Base.oak=22;
4) oak=50.1; //
possible loss of precision
123


Given a reference called t to a class which extends Thread, which of the following will cause it to give up cycles to allow another thread to execute.
1) t.yield();
2) Thread.yield();
3) yield(100); //Or some other suitable amount in milliseconds
4) yield(t);

12
注意yield()不能带参数!!

Question 52)
You have been asked to create a scheduling system for a hotel and catering organsiation. You have been given the following information and asked to create a set of classes to represent it.
On the catering side of the organsiation they have
Head Chefs
Chefs
Apprentice Chefs

The system needs to store an employeeid, salary and the holiday entitlement.
How would you best represent this information in Javae been given the following information and asked to create a set of classes to represent it.
How would you best represent this information in Java?
1) Create classes for Head Chef, Chef, Apprentice Chef and store the other values in fields
2) Create an employee class and derive sub classes for Head Chef, Chef, Apprentice Chef and store the other values in fields.
3) Create and employee class with fields for Job title and fields for the other values.
4) Create classes for all of the items mentioned and create a container class to represent employees

解释:Answer to Question 52)
3) Create and employee class with fields for Job title and fields for the other values.

These questions can appear tricky as the whole business of designing class structures is more art than science. It is asking you to decide if an item of data is best represented by the &quot;Is a&quot; or &quot;Has a&quot; relationship. Thus in this case any of the job titles mentioned will always refer to something that &quot;Is a&quot; employee.   
However the employee &quot;has a&quot; job title that might change.
One of the important points is to ask yourself when creating a class &quot;Could this change into another class at some point in the future&quot;. Thus in this example an apprentice chef would hope one day to turn into a chef and if she is very good will one day be head chef. Few other mock exams seem to have this type of questions but they di come up in the real exam.

Question 57)Given the following code
class Base {}
class Agg extends Base{
    public String getFields(){
         String name =&quot;Agg&quot;;
         return name;
    }
}
public class Avf{
public static void main(String argv[]){
        Base a = new Agg();
        //Here
    }
}
What code placed after the comment //Here will result in calling the getFields method resulting in the output of the string &quot;Agg&quot;?
1) System.out.println(a.getFields());
2) System.out.println(a.name);
3) System.out.println((Base) a.getFields());
4) System.out.println( ((Agg) a).getFields());
//注意可以这样写!!
此题非常值得关注!!
The Base type reference to the instance of the class Agg needs to be cast from Base to Agg to get access to its methods.The method invoked depends on the object itself, not on the declared type. So, a.getField() tries to invoke a getField method in Base which does not exist. But the call to ((Agg)a).getField() will invoke the getField() in the Agg class. You will be unlucky to get a question as complex as this on the exam.
这题稍难
因为父类中不存在方法getFields();
因此在编译的时候,1和3都会出现编译错误!只有4在编译的时候就直接调用Agg的getFields方法。
这也是动态绑定的一种情况

Q1.Which of the following expressions are legal? (Choose one or more.)
1) String x = &quot;Hello&quot;; int y = 9; x += y;
2) String x = &quot;Hello&quot;; int y = 9; if (x == y) {}
3) String x = &quot;Hello&quot;; int y = 9; x = x + y;
4) String x = &quot;Hello&quot;; int y = 9; y = y + x;
5) String x = null;int y = (x != null) && (x.length() > 0) ? x.length() : 0;
135
值得注意

String x = null; //
int i=x.length();
System.out.println(i); //这段代码可以通过编译,运行时抛出NullPointerException
一个赋值为null的字符串还可以用length运算符

Q2. Which modifier or modifiers should be used to denote a variable that should not be written out as part of its class's persistent state? (Choose the shortest possible answer.)
Mutiple:
1) private
2) protected
3) private protected
4) transient
5) private transient
4

Q3.Give the following code
//File P1.java
package MyPackage;
class P1{
void afancymethod(){
        System.out.println(&quot;What a fancy method&quot;);
    }
}
//File P2.java
public class P2 extends P1{
    public static void main(String argv[]){
           P2 p2 = new P2();
           p2.afancymethod();
    }
}
1) Both compile and P2 outputs &quot;What a fancy method&quot; when run
2) Neither will compile
3) Both compile but P2 has an error at run time
4) P1 compiles cleanly but P2 has an error at compile time

4

The package statement in P1.java is the equivalent of placing the file in a different directory to the file. P2.java and thus when the compiler tries to compile P2 an error occurs indicating that superclass P1 cannot be found.


Q4. Give the following code
public class StrEq{
public static void main(String argv[]){
        StrEq s = new StrEq();
    }
    private StrEq(){
         String s = &quot;Marcus&quot;;//String的两种定义方式
         String s2 = new String(&quot;Marcus&quot;);
         if(s == s2){
               System.out.println(&quot;we have a match&quot;);
          }else{
               System.out.println(&quot;Not equal&quot;);
          }
    }
}
1) Compile time error caused by private constructor
2) Output of &quot;we have a match&quot;
3) Output of &quot;Not equal&quot;
4) Compile time error by attempting to compare strings using ==

3

String的两种定义方式用==比较返回false!

Q5. What will happen when you attempt to compile and run the following code with the command line &quot;hello there&quot;
public class Arg{
String[] MyArg;
        public static void main(String argv[]){
            MyArg=argv;//在静态方法中不能访问类的非静态变量
        }
        public void amethod(){
                System.out.println(argv[1]);
              //argv[]只能在main()中引用啊!,ft
        }
}
1) Compile time error
2) Compilation and output of &quot;hello&quot;
3) Compilation and output of &quot;there&quot;
4) None of the above

1

Q6. What will happen when you attempt to compile and run the following code?
public class MySwitch{
public static void main(String argv[]){
        MySwitch ms= new MySwitch();
        ms.amethod();
    }
public void amethod(){
        int k=10;
        switch(k){
        default: //Put the default at the bottom, not here
            System.out.println(&quot;This is the default output&quot;);
            break;
         case 10:
            System.out.println(&quot;ten&quot;);
         case 20:
            System.out.println(&quot;twenty&quot;);
            break;
       }
    }
}
1) None of these options
2) Compile time error target of switch must be an integral type
3) Compile and run with output &quot;This is the default output&quot;
4) Compile and run with output of the single line &quot;ten&quot;
1

应当输出
ten
twenty

Q7. Which of the following statements about threading are true?
1) You can only obtain a mutually exclusive lock on methods in a class that extends Thread or implements runnable.
2) You can obtain a mutually exclusive lock on any object.
3) A thread can obtain a mutually exclusive lock on an object by calling a synchronized method of that object.
4) Thread scheduling algorithms are platform dependent.

234

Q8. Which of the following methods are members of the Vector class and allow you to input a new element?
1) addElement
2) insert
3) append
4) addItem

1

char c = 'c';
int i = 10;
c=c+i; //编译错误
i=i+c; //ok
char c = 'c';
char i = 10;
int c2=c+i;//charchar相加(运算)必须返回int型及以上类型!
         //byte型也是如此!                int long float double
String s = 'c'; //compile error
可以String s= aString+ primitivedata
不能String s= primitivedata + primitivedata;
例如:
      double i = 10.45;
String s1=&quot;hi&quot;;
String s=s1+i;   //ok!!输出:hi10.45

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-143717-1-1.html 上篇帖子: 计算机仿真中的HLA技术中的餐馆例子分析 (1) Production 下篇帖子: 设计模式系列——简单工厂模式
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表