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 static void 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型的。 <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 "throws"?
|
|
<8> & | 可以用在int和boolean上。^(异或只能用在int上)。 && || 只能用在boolean上,作用同& |,但是与其不同在于&& ||有短路运算,而位操作没有。 <9> Hashtable implements Map,Cloneable,Serializible |
|
实例变量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 = "Hello World"; public void init() { add(new Label(text)); new Sample("a"); } public Sample (String s) { add(new Label("hahahahahah")); } }
========================================================== 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("a");去掉,将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("haha"); //调用有参 } 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("true"); }else{ System.out.println("false"); } | true 注意陷阱!是”=”不是”==” faintttttt! |
public class Test { public static void test() { this.print(); } public static void print() { System.out.println("Test"); } public static void main(String args []) { test(); } } |
编译错误提示:non-static variable this cannot be referenced from a static context |
1.StringBuffer sb = new StringBuffer("abc"); 2.String s = new String("abc"); 3.sb.append("def"); 4.s.append("def"); 5.sb.insert(1, "zzz"); 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 = " Finance " ; //department 是Manager的一个特殊属性// illegal 声明变量e后,你能访问的对象部分只是Employee的部分;Manager的特殊部分是隐藏的。这是因为编译器应意识到,e 是一个Employee,而不是一个Manager。但重写的方法除外 | ☆多态性、虚拟方法调用 |
在你接收父类的一个引用时,你可以通过使用instanceof运算符判定该对象实际上是你所要的子类,并可以用类型转换该引用的办法来恢复对象的全部功能。 为什么说“恢复对象的全部功能”,就是因为上一格所描述的,子类对象赋给父类句柄后,该句柄不能访问子类的那些特殊属性和方法,要用就要重新造型。 这其实是多态参数的后续应用,形成这样一个链条:传入多态参数——instanceof判断类型——casting——恢复功能 Marcus Mork Test 3 的57题大体体现了这个意思 | ☆多态性、虚拟方法调用 |
Employee e = new Manager(); e.getDetails(); 在此例中,Manager 重写了Employee的getDetail()方法。被执行的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 code="Sample.class" width=200 height=200></applet> //是code不是name </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()àupdate()à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("i = " + i + " j = " + j + " "); } } } } | 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[i]); } } 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("Hello.txt"); }catch (FileNotFoundException fne) { System.out.println("No such file found"); return -1; //(*) 这句话最后被执行!!! }catch(IOException ioe) { }finally{ System.out.println("Doing finally"); } return 0; } } | 注意此题输出的顺序!-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 "main" java.lang.ClassCastException: Base |
Once created, some Java objects are "immutable", 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("Base"); // } } class Sub extends Base { void speak() { System.out.println("Sub"); } } 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+=".TXT"; return fname; } public static void main(String args[]){ String theFile="Program.java"; String s = setFileType(theFile); System.out.println("Created "+theFile); System.out.println("Created "+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="http://www.lanw.com"+’/ ’+"default.htm"; 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("Sample"); } 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("Done the test"); } /* This is another comment */ System.out.println ("The end"); } } | 又踩地雷了!!,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("Pausing"); din.readChar(); System.out.println("Continuing"); 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 "Pausing" and "Continuing" after a key is hit | 4 throws 和throw不必一定成对出现 |
public class Outer{ public String name = "Outer"; 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("Inner"); 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("Val = " + 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("abcd"); return; }finally { System.out.println("123456"); } } } | 可怕的程序阿 输出: 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("123"); √ 3) Byte b = new Byte(); b = 123; 4) Byte b = new Byte((int)123.4); 5) Byte b = new Byte(0x123); | 两个构造方法 Byte(byte value)
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前不能有任何modifier:public、private、protected均会提示错误 //因为下面类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("aaa"); } } | 1 接口怎么可能是void?
Interface任何情况下不能用protected和private修饰,,除非嵌套在一个接口或类中
Interface任何情况下不能用protected和private修饰
一个文件中只能有一个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; while( m++ < 2 ) System.out.print( m +” ”); 输出:1 2 for(int i=0;i<2;i++){ if(m++<2) System.out.print( m +” ”); 输出:1 2 } 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("第 "+i+" 次循环开始"); System.out.println("after 1 i++, i="+i); i++2; System.out.println("after 2 i++, i="+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 |
在继承的情况下,如果父类的方法抛出异常,那么子类的重置方法抛出异常不应该比父类多。子类的方法只能抛出父类异常的子集。子类也可以不抛出异常。 对于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 在清除垃圾之前,系统会调用finalize方法,这是顶级类Object中的finalize方法。 System类中的runFinalization方法能够强制调用finalize方法, 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("i = " + i); } } 4) class B { class A {} } | 13 |
class SuperEx { String r; String s; public SuperEx(){ System.out.println("系统无参"); } public SuperEx(String a,String b) { r = a; s = b; } public void aMethod() { System.out.println("r :" + 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("Hi","Tom"); SuperEx b = new NewSuper("Hi","Bart"); a.aMethod(); b.aMethod(); } public void aMethod() { System.out.println("r :" + r + " s:" + 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("begin to catch ArithmeticException "); //输出 return; //System.exit(1); finally{ System.out.println("in finally no matter if Exception occurs");//输出 } System.out.println("构造方法结束!"); //这句话不会被执行到! } public static void main(String[] arfg) { TestFinally tf=new TestFinally(); System.out.println("in main()!"); //这句话会被执行到! } } | 输出: 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 = "constructor"; } 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 "constructor" in the standard output 5) this code runs and writes "null" in the standard output | 5
如果go()声明为static则出错,原因是静态方法不能引用非静态的变量 |
paint()的类型?public ? | 1.2的内容 |
public class Test2 extends Object implements Runnable { String s1 = "Earth "; String s2 = "Moon"; public void run() { synchronized (s1) { //可以替换成synchronized(this),或synchronized(“hi”) for (int i=0; i < 2; i++) { s1.concat(" to Moon "); System.out.print(s1); s2.concat(" to Earth "); 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>>>31得1,可见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 = "Hello"; int y = 9; x += y; 2) String x = "Hello"; int y = 9; if (x == y) {} 3) String x = "Hello"; int y = 9; x = x + y; 4) String x = "Hello"; 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 "Equal" when run? (Choose one or more.) 1) int x = 100; float y = 100.0F; if (x == y){ System.out.println("Equal");} 2) int x = 100; Integer y = new Integer(100); if (x == y) { System.out.println("Equal");} 3) Integer x = new Integer(100); Integer y = new Integer(100); if (x == y) { System.out.println("Equal");} //包裹类。无输出。 4) String x = new String("100"); String y = new String("100"); if (x == y) { System.out.println("Equal");} //无输出 5) String x = "100"; //可能被认为是基本数据类型了 String y = "100"; //可能被认为是基本数据类型了 if (x == y) { System.out.println("Equal");} //Equal | 15 包裹类 ==
奇怪的是,4和5不是一样的吗? 可能是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("Hi","Tom"); Aa b = new Bb("Hi","Bart"); } } | 这段程序可以编译通过
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("Hi","Tom"); // 6 Aa b = new Bb("Hi","Bart"); // 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("Before:"+cou); TestConSon tt=new TestConSon(); System.out.println("After:"+cou); } } | 这体输出: Before:0 After:2
先调用父类的构造函数 |
Animal | Mammal | --------------------------------------------------------------- | | | | Dog Cat Raccoon SwampThing (implements (implements Washer) Washer) ü interface Washer {} ü class Animal {} ü class Mammal extends Animal {} ü class Dog extends Mammal {} ü class Cat extends Mammal implements Washer {} ü class Raccoon extends Mammal implements Washer {} ü 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("Success"); //不能加这句话 } 1catch (MalformedURLException e) { System.out.println("Bad URL"); //捕获到 } /* 这段话不能加,因为try块中没有任何可能抛出此异常 catch (StreamCorruptedException e) { System.out.println("Bad file contents"); }*/ catch (Exception e) { System.out.println("General exception"); //1已经捕获到,所以此处没有输出 } finally { System.out.println("Doing finally part"); } System.out.println("Carrying on"); } } | 输出: 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方法不能比父类的更私有
//Exception比IOException范围大,错。 |
import java.lang.Math; //可以不写这行 public class Te{ public static void main(String[] a){ Math myMath = new Math(); System.out.println("cosine of 0.123 = " + myMath.cos(0.123)); } } | 提示错误: Math() has private access in java.lang.Math
不能创建实例 可用System.out.println("cosine of 0.123 = " + Math.cos(0.123)); |
import java.io.*; public class Test1 { public static void main(String[] a){ String s = "abcde";//改成String s = new String("abcde");不影响结果 StringBuffer s1 = new StringBuffer("abcde"); if (s.equals(s1)) System.out.println("s.equals(s1)"); if (s1.equals(s)) System.out.println("s1.equals(s)"); } } | 本题不会出现编译错误 且可以运行, 无输出
因为类型不一致 |
class XXX { public static void main(String[] args) { String s1 = "abcde"; String s2 = "abcde"; s1.toUpperCase(); if (s1 == s2) System.out.println("YES"); else System.out.println("NO"); } } |
当然是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("b = " + b); 7. } 8. catch (Exception e) { 9. System.out.println("TROUBLE!"); 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 "b = 0". 4) The code compiles and prints "b = -2". 5) The code compiles and prints "b = -3". | 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的存取控制范围小于父类object中toString()的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("p="+p); //-100 System.out.println("j="+j); //-100 | int型不会越界么? 会,只有32位
Int*int好像总也不会出错! |
编译错误中提示unreachable statement的几种情况 1. int a(){ return 1; //1)方法的return语句之后 System.out.println("hi"); //compile error } 2. if (c.x==4){ throw new ArithmeticException(); //2)throw语句之后 System.out.println("Test"); // compile error } 3. loop2: for(int n=1;n<3;n++){ for(int c=1;c<3;c++){ if (c==2) { break loop2; //3)break、continue语句之后 System.out.println("hi"); //compile error } } } |
unreachable statement
while(false){…} //compile error
while(true){…} //ok.
将System.out.println("hi");放到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.
| 1 23错在哪里??? there are 7 possible for causing thread to stop executing: |
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("0", 10) returns 0 parseInt("473", 10) returns 473 parseInt("-0", 10) returns 0 parseInt("-FF", 16) returns -255 parseInt("1100110", 2) returns 102 parseInt("99", 8) throws a NumberFormatException parseInt("Kona", 10) throws a NumberFormatException ??????? parseInt("Kona", 27) returns 411787 ??????? (2) public static int parseInt(String s) 一个参数 | wrapper class中的几个方法!
Character、Byte、Float、Double、Short无getXxx
|
3. 静态方法:static Xxxxx getXxxxx()有三种形式:以getFloat(……)为例 |
|
public class T{ static void main(String[] arg){ final StringBuffer s=new StringBuffer("hi,"); s.append("mm"); System.out.println(s.toString()); //输出:hi,mm } } | 虽然StringBuffer 对象s被声明为final,但是用append()方法能够改变s包含的内容 |
public class T{ static void main(String[] arg){ StringBuffer a = new StringBuffer ("A"); StringBuffer b = new StringBuffer ("B"); operate (a,b); System.out.println(a + "," +b); //StringBuffer对象居然可以用+号连接! } static void operate (StringBuffer x, StringBuffer y) { x.append (y); y = x; } } //输出:AB,B A. The code compiles and prints “A,B”. | 一道很特别的题! |
transient保证了该对象实例不被序列化? | 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("hi,mm"); } public static void main( String[] args) { new Tes(); } } | Compile error!! 改成注释后面的可以运行但是什么输出都没有!
//构造函数不能是static |
public class Tes { static Tes(){ // static void Tes() { System.out.println("hi,mm"); } public static void main( String[] args) { new Tes(); } } | 左边程序有编译错误,提示:modifier static not allowed here 但是如果加上一个返回类型,则不会有编译错误,因为编译器认为Tes()不是构造方法,而是一个普通方法了 |
13. Given: package foo; public class Outer { Which statement is true? A. An instance of the Inner class can be constructed with “new Outer.Inner ()” | 1
4为什么不对? Outer$Inner.class |
20. Given: 1. public class test( And the command line invocation: What is the result? A. baz has the value of “” | 答案是F 验证一下?? 的确如此! 提示: foo is already defined in main(java.lang.String[]) 重复定义了!
如果改成//后的样子,那么编译通过运行时: 1)java Test a b c d //ok 2)java Test a b c //抛出异常 // ArrayIndexOutOfBoundsException |
23. Which will declare a method that forces a subclass to implement it? A. Public double methoda(); ----------------------------------------------------------------------------------------------- abstract class A { abstract void m(); } public abstract class B extends A { public static void main(String[] a){ System.out.println("hahahaha"); } } | D ? 这题显然有问题!!参看下面的例子
abstract类的子类可以是abstract! 本题可以有输出:hahahaha
当然,如果B不写abstract关键字会有编译错误,因为他继承了一个abstract method! |
41. Given: 1. public class X { 2. public object m () { When is the float object created in line 3, eligible for garbage collection? A. Just after line 5 | 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. | 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{ |
想知道测试一下! 实现一个接口必须实现其中的所有方法,因此这里没有实现public void run() 但是系统提示C:第一句有错! |
147. Which interface does java.util.Hashable implement? A. java.util.Map | A Cloneable, Map, Serializable
|
128. Given: 1. public class Test { What is the result? A.Compilation will fail | B |
127. Which two declarations prevent the overriding of a method? (Choose Two) A. final void methoda() {} | AD final方法不能被override! 严格来说,static方法也不能! |
101. Which statement is true? A. The Error class is a RuntimeException. | 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 | A |
sortedMap sortedList都是接口 |
|
‘/u101’//非法 ‘/u1010’ //合法 ‘/u10100’ //非法 “/u101” //非法 “/u1010” //合法 “/u10100”//合法,相当于‘/u1010’和字符串“0” |
|
90. Given: 1. public class foo { What is the result? A. The code compiles and “s=” is printed. | 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ßchar型,这些数据类型都是32及32位以上的数据类型 | 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("main() caught SubEx"); } catch (IOException x) { System.out.println( "main() caught IOException"); } catch (Exception x) { System.out.println( "main() caught Exception"); } } static void thud() throws IOException { try { throw new SubEx(); } catch (SubEx x) { System.out.println("thud() caught SubEx"); throw new IOException(); //只会抛给调用thud()的方法而不会抛到下一个3catch处,也就是说 //一个try只会对应一个catch和一个finally.切记!! } 3catch (IOException x) { System.out.println( "thud() caught IOException"); throw new IOException(); } catch (Exception x){ System.out.println( "thud() caught Exception"); } } } | 1) "main() caught SubEx" 2) "main() caught IOException" 3) "main() caught Exception" 4) "thud() caught SubEx" 5) "thud() caught IOException" 这道题一定要注意 输出是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("111"); throw new Exception();//(*) }catch(Exception e ){ System.out.println("222222222222"); } } } | 这段程序会有编译错误!! 有两种解决办法: 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("Doing finally"); } }//有输出!! | 2??????
接口也不能实例化(抽象的) |
How many String objects exist as a result of running the code listed below? 1. String s1 = "abc"; 2. String s2 = s1; 3. String s3 = "abc"; 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 = "/""; //输出 ” 2) String s = /"abcde/"; //换成” /"abcde/"” 3) String s = "/u3456/ufde6/u0/u1234"; //换成"/u3456/ufde6/u0000/u1234"即可 4) String s = "/"/"/"////"; //输出 “””// | 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("DONE WAITING"); 13. } 14. catch (InterruptedException e) { 15. System.out.println("INTERRUPTED"); 16. } 17. catch (Exception e) { 18. System.out.println("OTHER EXCEPTION"); 19. } 20. finally { 21. System.out.println("FINALLY"); 22. } 23. } 24. System.out.println("ALL DONE"); 25. } 26. } Mutiple: 1) Compiler error. 2) The application compiles but doesn't print anything. 3) The application prints "DONE WAITING". 4) The application prints "INTERRUPTED". 5) The application prints "OTHER EXCEPTION". | 2 |
1) float f=1/3; //合法 5)int i=2+'2'; //合法 |
|
Integer没有setValue方法,包裹类均immutable |
|
char 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 |
public class Droitwich{
class one{
private class two{
public void main(){
System.out.println("two");
}
}
}
} | 很奇怪的一道题 此题可以编译通过! 虽然嵌套了很多层! 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;//特别注意 | 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(); | 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 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 解释:Answer to Question 52) | 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 "Is a" or "Has a" relationship. Thus in this case any of the job titles mentioned will always refer to something that "Is a" employee. However the employee "has a" job title that might change. One of the important points is to ask yourself when creating a class "Could this change into another class at some point in the future". 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 ="Agg"; 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 "Agg"? 1) System.out.println(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 = "Hello"; int y = 9; x += y; 2) String x = "Hello"; int y = 9; if (x == y) {} 3) String x = "Hello"; int y = 9; x = x + y; 4) String x = "Hello"; 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("What a fancy method"); } } //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 "What a fancy method" when run | 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 = "Marcus";//String的两种定义方式 String s2 = new String("Marcus"); if(s == s2){ System.out.println("we have a match"); }else{ System.out.println("Not equal"); } } } 1) Compile time error caused by private constructor | 3
String的两种定义方式用==比较返回false! |
Q5. What will happen when you attempt to compile and run the following code with the command line "hello there" 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 | 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("This is the default output"); break; case 10: System.out.println("ten"); case 20: System.out.println("twenty"); break; } } } 1) None of these options 2) Compile time error target of switch must be an integral type 3) Compile and run with output "This is the default output" 4) Compile and run with output of the single line "ten" | 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. | 234 |
Q8. Which of the following methods are members of the Vector class and allow you to input a new element? 1) addElement | 1 |
char c = 'c'; int i = 10; c=c+i; //编译错误 i=i+c; //ok char c = 'c'; char i = 10; int c2=c+i;//char和char相加(运算)必须返回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="hi"; String s=s1+i; //ok!!输出:hi10.45 |
|