??xml version="1.0" encoding="utf-8" standalone="yes"?>
4.if (a="a") ~译? if(a=false)~译ok,原因是a=false的a代表了个boolean?br />
6.q种写法Outer.Inner i = new Outer().new Inner(); OK!
7.文g? 8 默认是int, 8.0默认是double
8.八进制是 0开?不是O(英文o)
9.byte -128~127 ,-128是二q制的多?br />
11. -1>>32q是-1, -1>>>32Z么还?1
12. char c='c'; String s ="s"; s+=c;l果?sc!!!
13. boolean b1=true; boolean b2=true; System.out.println(b1|b2); l果是true.~译没错!
java的默认import包有哪些
AWT
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. 所有组件flowLayout会被压羃为它们的最尺?br />
2. BorderLayout的North,South,West,East,Center是q个样子,四个单词大小写区?必须q么?否则?br />
2.1如果只是add,而不写东南西北中,默认是中
2.2如果不加componentC,那中q着
2.3如果某个方位有个component,如果你还往上面加component,后来的会覆盖原来?br />
3. applet,panel默认布局是flowlayout
4. frame,dialog默认布局是borderlayout
5. 各种awecȝl承关系,frame,window,component,...
6. window,frame,dialog不能被嵌入到容器?注意:window!
7. action event作用于button和textfeild的回车时?br />
8. item event作用于list,choice,checkbox的选择改变时刻
9. 如果容器不可?新layout理器后前的component跟随这个新的layout变化,如果容器可见,q些component不受后来的layout影响
10.gridLayout里的component寸一?br />
11.gridBagLayout?component可以占用多个grid
12.System.exit();在Applet里面不允许调?
AWT事g
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1.事gcL
(symantic)语义事g:ActionEvent,AdjustEvent,ItemEvent,TextEvent
低事g:ComponentEvent,ContainerEvent,FocusEvent,InputEvent,KeyEvent,MouseEvent,PaintEvent,WindowEvent
2.监听?
ActionListener,AdjustListener,CompentListener,ContainerListener,FocusListener,ItemListener,
KeyListener,MouseListener,MouseMotionListener,TextListener,WindwosListener, ?1个Listener,
七个adpter,的4个是ActionLisenter,AdjustListener,ItemListener,TextListener,它们只有一个方?
3,鼠标MouseListener?个方?clicked,pressed,released,entered,exited
4.鼠标MouseMotionListener?个方?mouseDragged,mouseMoved
cd对象(Class and Object)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0.最外层的类可以声明成final: "$file a":< final class a{}> ok!,但是不能是private和static?
1.overload是同c里同样的方法名,override是父子的l承
2.override的返回结果必M?否则~译错哦
The return type of an overriding method is identical to the return type of the method it overrides.
2.1 override的modifier可以扩大,但是不能~小.比如父类private void test(){} 子类:public void test(){} ,没问?如果反了,死翘?
3.super.super(),?错的,没这么写?br />
4.static和非static之间永远无法override!
5. 看程?br />
public class A{
void test1() throws BaseEx{hi();}
void hi(){System.out.println("say hi,a");}
}
class AA extends A{
void hi(){System.out.println("say hi,aa");}
}
class test{
static void main(String b[]) throws Exception{
A a = new AA();
a.test1();
}
}
l果?"say hi,aa",q说明什么说?Ҏ永远跟着cȝ原来面目??变量恰恰相反!
6.一个非抽象ҎL也别想override成一个抽象方?br />
7.override的子cȝҎ抛出的的异常只能是父cL法抛出异常的子异常类,或者无!
8.构造器不能是native,final,static,synchronized?可以是public,private,什么都没有?呵呵
9.构造器函数里还可以写return?但后面什么都不许?甚至null(q不是废话吗,哈哈)
10.构造器不能q回?q大安知道,但如果有?构造器"反g,别紧?它就不是构造器?只是个普通函?br />
11.super();this();q两个函数只能在构造函数里调用.
12,成员变量声明时候赋?比构造函数还?int i=1; ealier than Test(){}
13.Ҏ的参数变量可以是final.
14. hashCodeq回一个int
15. void wait() throws InterruptException wait扔InterruptException异常
16. java.lang.Void 是void的包装类
17. Byte,Interger,Double...所有的跟数有关的包装类都是l承于Number
接口Interface)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1.接口的所有方法默认都是public,abstract和non-static?br />
2.接口的所有变量默认都是public,static,final?所?接口的变量不能改?在它的实现类?
3.接口的实现类实现的方法必d接口的方法抛出同L异常,不许是子c?q和override不一?同样,如果接口Ҏ没有?实现Ҏ也不能抛.
4.实现cd现的Ҏ必须昑ּ的声明成public,什么都不写都不??!!
5.接口不能声明成final,要不它怎么被实现呢(q好像又是废话啊
6.一个类实现两个接口,如果两个接口有相同的Ҏ,实现cd实现q个Ҏ,没问题的.
内嵌cInner Class)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1.内嵌cd以访问outercȝM变量,包括U有?
2.静态innerc?只能讉KoutercȝMstatic变量
2.1内嵌cd以是final,abstract?br />
3.我靠,Ҏ内的内嵌cM能ؓstatic: void test(){ static class A{}} XXXXX!!!!
4.我靠,Ҏ内的内嵌cM不能带Q何modifier,void test(){ public class A{}} XXXXX!!!!
5.我靠,Ҏ内的内嵌cd能访问方法内的final变量,但是,可以讉KoutercȝM变量.
6.匿名cM能有构造器,但声明时候带参数,相当于构造器的参C?
class ABC{}
class ABCD{private ABCD(int i){}}
ABC test3(){return new ABC(){};}
ABCD test4(){return new ABCD(3){};}
interface iii{}
iii test5(){return new iii(){};}
//class BCD extends ABCD{} compile error,因ؓ,
看上面就知道,new iii(){};实际上匿名类实现了iii接口;new ABC(){};实际上是匿名cȝ承了ABC.
8.
class A {private A(){System.out.println("a!");}}
class B extends A{}
我靠,没错!B实例的时候会d调用父类A的构?即是private?看来也没问题!!!
9.内部cd以有synchronizedҎ,那么锁是q个内部c?跟外部类没一点关p?内外分别?在锁的问题上.
10.外部cM能通过this被访?thisq时候应该指的是内部c?享用外部cȝ成员q接用,不用加Q何限定词
11.如何用this呢请?
class Outer{ int i;
class Inner{
class InnerInner{
void Test(){
Outer.this.i=1;
}
}
}
}
看见了吧,cd.this.变量?可以引用到i,W一ơ看到吧,嘿嘿,孤陋寡闻.
12.注意q两U写法都可以
Class Outer.Inner i = new Outer().new Inner();
或? Class o= new Outer(); Class Outer.Inner i=o.new Inner();
U程Thread)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ȝThread的API!!!!
1.U程启动必须通过start函数.
2.run函数不许也只能是public?
3.U程有优先??0,通过Thread.setPriority(int);来改?不能过10,否则会出现运行异?br />
4.U程优先U默认是5,即NORM_PRIORITY.NORM_PRIORITY是Thread的静态变量吗
5.Thread.yeild();是静态方?所?使用格式是Thread.yield();她强q当前的q程攑ּCUP.
6.sleep(1000),是说U程睡觉1U?然后,q入Ready状?注意,不是q行状?它还要等OS来调度来获得CUP.
java.lang.*;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1.数组的科? int ia[][]={{1,2},null}; int ib[][]=(int[][])ia.clone();
2.什么是NaN然后看ceil(NaN),floor(NaN),...
3.Math.floor(-1.1f);//-2.0
Math.ceil(-1.1f);//-1.0
Math.round(-1.6d)//-2
4.0=<1
5.Math,Interger,Boolean...{类型包装类都是final?不可l承
6.int round(float); long round(double);?round永远q回不了数?br />
7.static double ceil(double)
8.static double floor(double)注意Qceil,floor的只有这个double版本,什么都转成double!
9.static double sin(double 弧度); q有cos,tan
10. new String; 可以是byte[];char[];String;StringBuffer
11. String的一些函? int length(); char charAt(int); String toUpperCase(); String toLowerCase();
12. String("Abc").equals(String("abc"))不相{的,不然׃会有boolean equalsIgnoreCase(String)函数
13."012345678"是一个串的顺序号?indexOf('1'),indexOf("1")都返?,subString(1,5)?345,嘿嘿:?[)"的感?br />
14, trim()qtab都退?"\t\n java ",trim()一下就只剩?java"?br />
15. 关于对象的科?d喳API
16. "abcd".trim(),"abcd" + new String("ef")都是合理的写?br />
17. StringBuffer?个构造器: ()初始化容量ؓ16,(int 初始化容?,(String),初始化容量ؓ串长加上16
18. StringBuffer的一些函? String toString(); append();reverse();insert();delete(int start,int end);deleteCharAt(int);setLength(int newLength);
19. String s=""; StringBuffer sb=new StringBuffer(); if (s==sb){}~译?因ؓ,s,sbcd不一?不能比较
集合:
1.各接口和cȝ关系,只有最后一个是c?br />
Collection:List:vector,ArrayList,LinkedList
Map:SortedMap:TreeMap
Collection:Set:SortedSet:TreeSet
Map:HashTable
Collection:Set:HashSet
基础Base)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1.java application的main可以不是public?但必Lstatic?br />
2.一个文件只能有一个publicc?而且q得跟文件名一?包括大小?br />
3.变量只能是字?$,_开?接下来的W二个可以是,数字
4.ch\u0061r='a'; char \u0063='b'; char c='\u0063';都是合法?br />
5.1e-5d,合法.e-5d不合?必须有前面的pL
6.int[] i[]={null{1,2}}正确! int i[]={1,2,3,} 正确!","和没有的效果一?br />
7.局部array,跟变量一?使用前要初始?br />
8.mainҎ可以为final
操作W和分配W?Operator and Assignment)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1.System.out.printl(1+2+"3");//33 System.out.printl("1"+2+3);//123
2.int i=0; i=i++;i=i++;i=i++; l果,i=0!
3.int i[]; index=0; i[index]=index=5; l果?i[0]=5;!!!
4.byte b=10;可以,因ؓ,10可以被自动从int转成byte
5.接下?byte b=b+10;不可?!因ؓ,10+b后的int无法被自动从int转成byte,问我,我也不知道ؓ什??
6.byte b1 = 4; byte b2 = 6; b1 = b1 + b2;?~译?b1 + b2?必须强制转成byte,b1x1+b2);
7.XOR 一L?Q不一样ؓ1 1,1=0;0,0=0;1,0/0,1=1
8. x == Float.NaN~译错,应该是Float.IsNaN
9. x == Double.POSITIVE_INFINITY~译可以
10.-1?111.... 1111,<<永远双Ӟ>>正补Ӟ负补一Q?gt;>>恒补?br />
10.1 -1>>多少位都?1 ; 1<<31变成了最负?1000....0000
11.最大正数是01111....1111
12.最负数是1000....0000(-2147483648)
13. a instanceof b,b必须是类/接口Q不能是实例
--------补充------------------------------
1. byte,short,char 都存?var = -var;~译错误,因ؓ,q时候的-var已经自动转成个intcd?br />
2. int/0会扔出ArithmeticException
double,float/0得INF或?INF
0/0得NaN
3. int a-b-c;是不W合命名规则的变量名~译会出?
4. char a='\u0001';? char b=\u0001;~译?
5. boolean b1,b2,b3,b4,b5;
b1 = b2==b3;
b1 = b2<=b3 && b4==b5;
b1 = b2==b3==true
都是对的!?变?
b1 = b2==b3==b4 XXXXXXX~译?
6. 1>>1 ?
7. %= <<= =>> =>>>都是合法W号
8. --1-10*4 q种写法没错,是 (--1)-10*4
9. k=1;++k + k++ + +k ;l果?,相当?(++2)+(2++)+(+3)
10.标号不能标示声明.
hi:
if {
break hi;
//break hi1;不行,不能向后调{
}
//hi1:不行,不能攑֜声明?br />
int i;
hi1:
i=1;
11.public static void main(String s[]) throws Exception{}可以?main可以扔出异常
12. hi:
if(b==true){break hi;}
break 标号Q可以用在if里面.别的M都不?包括break,continue 标号.
13.int x = i*-j; 我靠,没问题的!!!~译没错! int x = i*j++ + +i++; q个也没问题,
变量修饰W?Modifier)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1.最外面一层的cM能声明成protect和pravite?br />
2.同一个类的两个实例之间可以访问彼此的U有Ҏ和私有变??br />
3.protect和无修饰W的具体区别关于外包可以讉K被子c访问的是哪?br />
4.成员变量被修饰成final?必须声明时候就赋初值或者在构造器里面赋初?别指望她可以得到default?
5.抽象Ҏ不能是static?!!
6.静态方法将随着cȝ变化而变?看例?
class Parent{
static void test(){System.out.println("hi,parent")};
}
class Child extends Parent{
static void test(){System.out.println("hi,child")};
}
Parent p = new Child();
p.test(); //打出来的是hi,parent!
7.静态方法可以通过cȝ实例调用.
new Child().test(); ?Child.test(); 都OK!
8.transient只能用在cȝ成员变量?不能用在Ҏ?
9.transient变量不能是final和static?br />
10.nativeҎ可以是private,abstractd?/p>
程控制 转型和上?Converting and Casting) I/O
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1。不可到辄语句声明为错Qwhile(false){} ;for(;false{};if(false){}都无法编?br />
2。for(W一部分;的第一部分可以用来声明或者赋|但不能两者都
3。byte b; switch
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Binary operators convert the smaller(less precise) operand to the type of the larger(more precise) operand.
All operators will convert things smaller than ints to ints or larger. This includes char 's!
1.byte,char,short默认转成int
2.byte->short->int->long->float->double
char^
q是默认可以转型的方?反了必须要显式cast! 特别注意:long->float是默认的,别看long64,float32,嘿嘿
q有是看得出来,char?byte,short之间无法互相默认转换
3.float f=1/3; OK!float f=1.0/3.0;~译出错,因ؓ1.0/3.0l果是double?噢噢~,错喽!!
4.int i=1; byte b=i;?需要显式cast.
final i=1; byte b=i;ok! 我也不知道ؓ什?final可?而且,据我实验只有int和byte的关p这?其他不行.
5.int i[]; Object[] obj=i;? Object obj=i;? 数组只能转成Object,而不能是Object[]
6.int i[]; Object[] obj;i=(int[])obj; ? 对象可以通过昑ּ来{成一个数l?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1.Filecȝ一些重要方?isFile();isDirectory();String[] list();exists();getAbsolutePath();getParent();
2.通过delete();mkdir();rename(File newname);可以操纵文g,但是却改变不了文件的内容
2.1 FilecL法改变当前目?除非重新创徏一个File对象.
3.InputStreamReader(InputStream in,String encodingName);
OutputStreamReader(OutputStream in,String encodingName);
Encoding: 8859_1是Latin-1,包含ASCII
4.关闭close一个流,p动调用了flush.
5.System.in,System.out,System.err,由JVM自动创徏
6.RandomAccessFile(File file,String mode);mode?r,rw
]]>
1:Set
public interface Set extends Collection
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
2:SortedSet
public interface SortedSet extends Set.
A set that further guarantees that its iterator will traverse the set in ascending element order, sorted according to the natural ordering of its elements (see Comparable), or by a Comparator provided at sorted set creation time.
3:HashSet
public class HashSet extends AbstractSet implements Set, Cloneable, Serializable
This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.
4:TreeSet
public class TreeSet extends AbstractSet implements SortedSet, Cloneable, Serializable
This class implements the Set interface, backed by a TreeMap instance. This class guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements (see Comparable), or by the comparator provided at set creation time, depending on which constructor is used.
5:LinkedHashSet:
public class LinkedHashSet extends HashSet implements Set, Cloneable, Serializable
Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)
5:Map
public interface Map
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
6:SortedMap
public interface SortedMap extends Map
A map that further guarantees that it will be in ascending key order, sorted according to the natural ordering of its keys (see the Comparable interface), or by a comparator provided at sorted map creation time. (This interface is the map analogue of the SortedSet interface.)
7:HashMap(允许key和value为NULL)
public class HashMap extends AbstractMap implements Map, Cloneable, Serializable
Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time
8:TreeMap
public class TreeMap extends AbstractMap implements SortedMap, Cloneable, Serializable
Red-Black tree based implementation of the SortedMap interface. This class guarantees that the map will be in ascending key order, sorted according to the natural order for the key's class (see Comparable), or by the comparator provided at creation time, depending on which constructor is used.
9:HashTable(不允许key和value为NULL)
public class Hashtable extends Dictionary implements Map, Cloneable, Serializable.
This class implements a hashtable, which maps keys to values. Any non-null object can be used as a key or as a value.
9:LinkedHashMap
public class LinkedHashMap extends HashMap
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)
9:IdentityHashMap
public class IdentityHashMap extends AbstractMap implements Map, Serializable, Cloneable
This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). (In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).)
This class is not a general-purpose Map implementation! While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.
10:List
public interface List extends Collection
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all.
11:ArrayList
public class ArrayList extends AbstractList implements List, Cloneable, Serializable
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)
12:LinkedList
public class LinkedList extends AbstractSequentialList implements List, Cloneable, Serializable
Linked list implementation of the List interface. Implements all optional list operations, and permits all elements (including null). In addition to implementing the List interface, the LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack, queue, or double-ended queue (deque).
13:Vector
public class Vector extends AbstractList implements List, Cloneable, Serializable
The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.
14:Collection
public interface Collection
The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. The SDK does not provide any direct implementations of this interface: it provides implementations of more specific subinterfaces like Set and List. This interface is typically used to pass collections around and manipulate them where maximum generality is desired.
15:Collections
public class Collections extends Object
This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few other odds and ends.
What will happen when you attempt to compile and run the following code?
class MyThread extends Thread
{
public void run()
{
System.out.println("MyThread: run()");
}
public void start()
{
System.out.println("MyThread: start()");
}
}
class MyRunnable implements Runnable
{
public void run()
{
System.out.println("MyRunnable: run()");
}
public void start()
{
System.out.println("MyRunnable: start()");
}
}
public class MyTest
{
public static void main(String args[])
{
MyThread myThread
MyRunnable myRunnable = new MyRunnable();
Thread thread
myThread.start();
thread.start();
}
}
Choices:
a. Prints : MyThread: start() followed by MyRunnable:run()
b. Prints : MyThread: run() followed by MyRunnable:start()
c. Prints : MyThread: start() followed by MyRunnable:start()
d. Prints : MyThread: run() followed by MyRunnable:run()
e. Compile time error
f. None of the above
――――――――――――――?/p>
A is the correct choice. In the above code there is not any compilation error. Thus choice E is incorrect. Inside main() method, objects of MyThread and MyRunnable class are created followed by creation of Thread with object of MyRunnable class. Note that MyThread class extends Thread class and overrides the start() method of the Thread class. Thus on execution of "myThread.start()" statement, the start() method of the MyThread class will be executed and as a result "MyThread:start()" will be printed. Had the start() method not there in MyThread class, the start() method of the Thread class would be called which in turn would call the run() method of the MyThread class. On execution of "thread.start();", the start() method of the Thread class would be called which in turn will call the run() method of the class which is passed to Thread constructor (i.e. MyRunnable class). Thus "MyRunnable:run()" will be printed out. Thus choice A is correct.
What will be the output on compiling/running the following code?
public class MyThread implements Runnable
{
}
Choices:
a. Compilation Error
b. Prints : Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes and so on.
c. Prints : No No No No No No No No No No and so on.
d. Prints : Yes No Yes No Yes No Yes No Yes No and so on.
e. The Output cannot be determined.
E is correct. Please note that there will not be any compilation error when the above code is compiled. Also note that calling start() method on a Thread doesn't start the Thread. It only makes a Thread ready to be called. Depending on the operation system and other running threads, the thread on which start is called will get executed. In the above case it is not guaranteed that the thread will be executed(i.e. run() method will be called), always before "for" loop is executed. Thus the output cannot be determined.
Multiple objects of MyClass (given below) are used in a program that uses
multiple Threadsto create new integer count. What will happen when other threads
use the following code?
class MyClass
{
static private int myCount = 0;
int yourNumber;
private static synchronized int nextCount()
{
return ++myCount;
}
public void getYourNumber()
{
yourNumber = nextCount();
}
}
Choices:
a. The code will give compilation error.
b. The code will give runtime error.
c. Each thread will get a unique number.
d. The uniqueness of the number among different Threads can't be guaranteed.
――――――――――――?/p>
C is correct. The use of synchronized ensures that the number generated will not be duplicated, no matter how many Threads are trying to create the number. Thus D is incorrect. A and B are incorrect as the above code will not give any compiletime or runtime error.
What will happen when you attempt to compile and run the following code?
public class MyThread extends Thread
{
String myName;
MyThread(String name)
{
myName = name;
}
public void run()
{
for(int i=0; i<100;i++)
{
System.out.println(myName);
}
}
public static void main(String args[])
{
try
{
MyThread mt1 = new MyThread("mt1");
MyThread mt2 = new MyThread("mt2");
mt1.start();
// XXX
mt2.start();
}
catch(InterruptedException ex)
{
}
}
}
Choices:
a.The above code in its current condition will not compile.
b. In order to make the MyThread class prints "mt1" (100 times) followed by
"mt2" (100 times), mt1.join(); can be placed at //XXX position.
c. In order to make the MyThread class prints "mt1" (100 times) followed by
"mt2" (100 times), mt1.sleep(100); can be placed at //XXX position.
d. In order to make the MyThread class prints "mt1" (100 times) followed by
"mt2" (100 times), mt1.run(); can be placed at //XXX position.
e. In order to make the MyThread class prints "mt1" (100 times) followed by
"mt2" (100 times), there is no need to write any code.
―――――――――――――?/p>
A and B are correct. In its current condition, the above code will not compile as "InterruptedException" is never thrown in the try block. The compiler will give following exception: "Exception java.lang.InterruptedException is never thrown in the body of the corresponding try statement." Note that calling start() method on a Thread doesn't start the Thread. It only makes a Thread ready to be called. Depending on the operating system and other running threads, the thread on which start is called will get executed. After making the above code to compile (by changing the InterruptedException to some other type like Exception), the output can't be predicted (the order in which mt1 and mt2 will be printed can't be guaranteed). In order to make the MyThread class prints "mt1" (100 times) followed by "mt2" (100 times), mt1.join() can be placed at //XXX position. The join() method waits for the Thread on which it is called to die. Thus on calling join() on mt1, it is assured that mt2 will not be executed before mt1 is completed. Also note that the join() method throws InterruptedException, which will cause the above program to compile successfully. Thus choice A and B are correct.
What will happen when you attempt to compile and run the following code?
public class MyThread extends Thread{
String myName;
MyThread(String name){
myName = name;
}
public void run(){
for(int i=0; i<100;i++){
System.out.println(myName);
}
}
public static void main(String args[]){
try{
MyThread mt1 = new MyThread("mt1");
MyThread mt2 = new MyThread("mt2");
mt1.start();
// XXX
mt2.start();
}catch(InterruptedException ex){}
}
}
A. compile error
B. mt1.join();
C. mt1.sleep(100);
D. mt1.run()
E. nothing need
Choice A and B are correct. In its current condition, the above code will not compile as "InterruptedException" is never thrown in the try block. The compiler will give following exception: "Exception java.lang.InterruptedException is never thrown in the body of the corresponding try statement."
Note that calling start() method on a Thread doesn't start the Thread. It only makes a Thread ready to be called. Depending on the operating system and other running threads, the thread on which start is called will get executed. After making the above code to compile (by changing the InterruptedException to some other type like Exception), the output can't be predicted (the order in which mt1 and mt2 will be printed can't be guaranteed). In order to make the MyThread class prints "mt1" (100 times) followed by "mt2" (100 times), mt1.join() can be placed at //XXX position. The join() method waits for the Thread on which it is called to die. Thus on calling join() on mt1, it is assured that mt2 will not be executed before mt1 is completed. Also note that the join() method throws InterruptedException, which will cause the above program to compile successfully. Thus choice A and B are correct.
Multiple objects of MyClass (given below) are used in a program that uses multiple Threads to create new integer count. What will happen when other threads use the following code?
class MyClass{
static private int myCount = 0;
int yourNumber;
private static synchronized int nextCount(){
return ++myCount;
}
public void getYourNumber(){
yourNumber = nextCount();
}
}
A. the code ill give ompilation error
B. the code ill give runtime error
C. each thread will get a unique number
D. the uniqueness of the number different Threads can’t be guaranteed.
C is correct. The use of synchronized ensures that the number generated will not be duplicated, no matter how many Threads are trying to create the number. Thus D is incorrect. A and B are incorrect as the above code will not give any compiletime or runtime error.
What will be the output on compiling/running the following code?
public class MyThread implements Runnable {
}
A. compile error
B. prints: yes yes yes yes yes yes and so on
C. prints: no no no no no no no no and so on
D. prints: yes no yes no ye no ye no and so on
E. the output cannot be determinated
E is correct. Please note that there will not be any compilation error when the above code is compiled. Also note that calling start() method on a Thread doesn't start the Thread. It only makes a Thread ready to be called. Depending on the operation system and other running threads, the thread on which start is called will get executed. In the above case it is not guaranteed that the thread will be executed(i.e. run() method will be called), always before "for" loop is executed. Thus the output cannot be determined.
Which statements about thread are true?
A. Once a thread is created, it can star running immediately.
B. To use the start() method makes a thread runnable, but it does not
necessarily start immediately.
C. When a thread stops running because of pre-emptive, it is placed at
the front end of the runnable queue.
D. A thread may cease to be ready for a variety of reasons.
(bd)
题目Q有关线E的哪些叙述是对的?/p>
A. 一旦一个线E被创徏Q它q卛_始运行?/p>
B. 使用start()Ҏ可以使一个线E成为可q行的,但是它不一定立卛_始运行?/p>
C. 当一个线E因为抢先机制而停止运行,它被攑֜可运行队列的前面?/p>
D. 一个线E可能因Z同的原因停止QceaseQƈq入qA状态?/p>
一个新创徏的线Eƈ不是自动的开始运行的Q必调用它的start()Ҏ使之线E放?/p>
可运行态(runnable
stateQ,q只是意味着该线E可为JVM的线E调度程序调度而不是意味着它可以立卌行?/p>
U程的调度是抢先式的Q而不是分旉片式的。具有比当前q行U程高优先的线E可以?/p>
前线E停止运行而进入就l状态,不同优先U的U程间是抢先式的Q而同U线E间是轮转式?/p>
。一个线E停止运行可以是因ؓ不同原因Q可能是因ؓ更高优先U线E的抢占Q也可能是因?/p>
调用sleep()ҎQ而即使是因ؓ抢先而停止也不一定就q入可运行队列的前面Q因为同U线
E是轮换式的Q它的运行可能就是因换,而它因抢占而停止后只能在轮换队列中排队而不
能排在前面?/p>
Which two CANNOT directly cause a thread to stop executing? (Choose Two)
A.Existing from a synchronized block
B.Calling the wait method on an object
C.Calling notify method on an object
D.Calling read method on an InputStream object
E.Calling the SetPriority method on a Thread object
AnswerQAC。同55?/p>
Which two statements are true? (Choose Two)
A. The program prints “ABBCAD”
B. The program prints “CDDACB”
C. The program prints “ADCBADBC”
D. The output is a non-deterministic point because of a possible deadlock condition
E. The output is dependent on the threading model of the system the program is running on.
AnswerQDE
What will happen when you attempt to compile and run the following code?
public class Test{
}
A. Compile time error, no matching notify within the method.
B. Compile and run but an infinite looping of the while method.
C. Compilation and run without any output.
E. Runtime Exception "IllegalMonitorStatException".
Answer: E
Note: The wait/notify protocol can only be used within code that is synchronized. In this case calling code does not have a lock on the object(not synchronized) and will thus cause an Exception at runtime.
1.10 What is the result of compiling and executing the following code?
public class ThreadTest extends Thread {
}
A. The code fails to compile in the main() method.
B. The code fails to compile in the run() method.
C. Only the text "In run" will be displayed.
D. The text "In run" followed by "Leaving run" will be displayed.
E. The code compiles correctly, but nothing is displayed.
Answer: D
Which of the following will definitely stop a thread from executing?A. wait()B. notify()C. yield()D. suspend()E. sleep()Answer: ACDE
Which of the following will definitely stop a thread from executing?
A. wait()
B. notify()
C. yield()
D. suspend()
E. sleep()
Answer: ACDE
A. You can only obtain a mutually exclusive lock on methods in a class that extends Thread or implements runnable.
B. You can obtain a mutually exclusive lock on any object.
C. You can't obtain a mutually exclusive lock on any object.
D. Thread scheduling algorithms are platform dependent.
Answer: BD
8:
Consider the following statement:
Thread myThread = new Thread();
Which of the following statements are true regarding myThread?
A. The thread myThread is now in a runnable state.
B. The thread myThread has a priority of 5.
C. On calling the start() method on myThread, the run method in the Thread class will be executed.
D. On calling the start() method on myThread, the run method in the calling class will be executed.
Answer: C
Note: the priority of myThread will be inherited from the Thread that called the constructor.
What is the effect of issuing a wait() method on an objectQ(MutipleQ?/p>
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.
ANSWER 1)
10:
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
3) At the moment when a thread is notified, it automatically gets the lock of the object for which it was waiting.
ANSWER 1
3. What will happen when you attempt to compile and run the following code?
class MyParent
{
int x, y;
MyParent(int x, int y)
{
this.x = x;
this.y = y;
}
public int addMe(int x, int y)
{
return this.x + x + y + this.y;
}
public int addMe(MyParent myPar)
{
return addMe(myPar.x, myPar.y);
}
}
class MyChild extends MyParent
{
int z;
MyChild (int x, int y, int z)
{
super(x,y);
this.z = z;
}
public int addMe(int x, int y, int z)
{
return this.x + x + this.y + y + this.z + z;
}
public int addMe(MyChild myChi)
{
return addMe(myChi.x, myChi.y, myChi.z);
}
public int addMe(int x, int y)
{
return this.x + x + this.y + y;
}
}
public class MySomeOne
{
public static void main(String args[])
{
MyChild myChi = new MyChild(10, 20, 30);
MyParent myPar = new MyParent(10, 20);
int x = myChi.addMe(10, 20, 30);
int y = myChi.addMe(myChi);
int z = myPar.addMe(myPar);
System.out.println(x + y + z);
}
}
Choices:
a. 300
b. 240
c. 120
d. 180
e. Compilation error
f. None of the above
―――――――――――?/p>
A is the correct choice. In the code, MyChild class overrides the addMe(int x, int y) method of the MyParent class. And in both the MyChild and MyParent class, addMe() method is overloaded. There is no compilation error anywhere in the above code. On execution, first, the object of MyChild class will be constructed. Please note that there is a super() call from the constructor of MyChild class, which will call the constructor of MyParent class. This will cause the value of z variable of MyChild class to be 30 and x, y variables of MyParent class will become 10 and 20 respectively. The next statement will again call the constructor of MyParent class with same x and y values. This is followed by execution of addMe() method of MyChild class with x as 10, y as 20 and z as 30. Also x and y are inherited by MyChild class from the MyParent class. Thus in the addMe() method of the MyChild class, the value of this.x will be 10, this.y will be 20 and this.z will be 30. The return value of this method will be "10 + 10 + 20 + 20 + 30 + 30", which is equal to 120. Thus x will become 120. This is followed by the invocation of the other addMe() method which takes object reference of the MyChild class. From this method, the method which was called earlier is invoked. This call is exactly the same as the earlier one. Thus the value of y will also be 120 like x. Now the addMe() method of MyParent class is invoked. This method invokes another addMe() method of the same class. Its equivalent to the invocation of addMe(int x, int y) method with x as 10 and y as 20. Also the value of instance variables x and y of My Parent class is 10 and 20 respectively. The value of z will be evaluated to "10 + 10 + 20 + 20", which is equal to 60. Thus the value of x, y and z after all the invocations will be 120, 120 and 60 respectively. As a result of this finally, "120 + 120 + 60" which is equal to 300 will be printed. Thus A is the correct choice.
Given the code below, and making no other changes, which access modifiers
(public, protected or private) can legally be placed before myMethod() on line 3?
If line 3 is left as it is, which keywords can legally be placed before myMethod
on line 8?
1.class HumptyDumpty
2.{
3.void myMethod() {}
4.}
5.
6.class HankyPanky extends HumptyDumpty
7.{
8.void myMethod() {}
9.}
Choices:
a. private or nothing(i.e. leaving it as it is) on line 3.
Nothing(i.e. leaving it as it is) or protected or public
on line 8.
b. public or protected on line 3. private or nothing(i.e. leaving it
as it is) on line 8.
c. nothing(i.e. leaving it as it is) or protected or public on
line 3. private or nothing(i.e. leaving it as it is) on line 8.
d. None of the above.
A is correct. The basic principle is that a method cannot be overridden to be more private. Since the method is being overridden to be friendly(default modifier) it can only be private or friendly in the superclass. Secondly if the method in superclass is left as it is(i.e. friendly access) the method in subclass can be friendly, protected or public.
What results from the following code?
1.class MyClass
2.{
3.void myMethod(int i) {System.out.println("int version");}
4.void myMethod(String s) {System.out.println("String version");}
5.public static void main(String args[])
6.{
7.MyClass obj = new MyClass();
8.char ch = 'c';
9.obj.myMethod(ch);
10.}
11.}
Choices:
a. Line 4 will not compile as void methods can't be overridden.
b. An exception at line 9.
c. Line 9 will not compile as there is no version of myMethod which takes a char as argument.
d. The code compiles and produces output: int version.
e. The code compiles and produces output: String version.
―――――――――?/p>
D is correct. A is incorrect as void methods can be overridden without any problem. B is incorrect as char ch declaration is valid. C is incorrect as char type in java is internally stored as integer and there is a method which takes int as an input. D is correct, on line 9 char ch is widened to an int and passed to int version of the myMethod(). E is incorrect as int version of myMethod() is called.
What is displayed when the following is executed?
class Parent
{
private void method1()
{
System.out.println("Parent's method1()");
}
public void method2()
{
System.out.println("Parent's method2()");
method1();
}
}
class Child extends Parent
{
public void method1()
{
System.out.println("Child's method1()");
}
public static void main(String args[])
{
Parent p = new Child();
p.method2();
}
}
Choices:
a. Compile time error
b. Run time error
c. prints : Parent's method2()
d. prints : Parent's method2()
――――――?/p>
C is correct. The code will compile without any error and also will not give any run time error. The variable p refers to the Child class object. The statement p.method2() on execution will first look for method2() in Child class. Since there is no method2() in child class, the method2() of Parent class will be invoked and thus "Parent's method2()" will be printed. Now from the method2() , there is a call to method1(). Please note that method1() of Parent class is private, because of which the same method (method1() of Parent class) will be invoked. Had this method(method1() of Parent class) been public/protected/friendly (default), Child's class method1() would be called. Thus C is correct answer.
What is displayed when the following is executed?
class Parent{
private void method1(){
System.out.println("Parent's method1()");
}
public void method2(){
System.out.println("Parent's method2()");
method1();
}
}
class Child extends Parent{
public void method1(){
System.out.println("Child's method1()");
}
public static void main(String args[]){
Parent p = new Child();
p.method2();
}
}
A. compile time error
B. run time error
C. prints: parent’s method2()
D. prints: parent’s method2()
C is correct. The code will compile without any error and also will not give any run time error. The variable p refers to the Child class object. The statement p.method2() on execution will first look for method2() in Child class. Since there is no method2() in child class, the method2() of Parent class will be invoked and thus "Parent's method2()" will be printed. Now from the method2() , there is a call to method1(). Please note that method1() of Parent class is private, because of which the same method (method1() of Parent class) will be invoked. Had this method(method1() of Parent class) been public/protected/friendly (default), Child's class method1() would be called. Thus C is correct answer.
1) class Person {
2) public void printValue(int i, int j) { }
3) public void printValue(int i){ }
4) }
5) public class Teacher extends Person {
6) public void printValue() { }
7) public void printValue(int i) {}
8) public static void main(String args[]){
9) Person t = new Teacher();
10) t.printValue(10);
11) }
12) }
Which method will the statement on line 10 call?
A. on line 2
B. on line 3
C. on line 6
D. on line 7
译
W十行的声明调用哪些方法?/p>
{案 D
解析 变量t是一个Person对象Q但是它是用Teacher实例化的Q这个问题涉及到java?/p>
~译时多态和q行时多态的问题Q就~译时多态来_t实际上是一个Personc,q涉及到c?/p>
型的自动转换Q将一个子cȝ实例赋值给一个父cȝ变量是不用进行强制类型{换,反之则需
要进行强制类型{换,而且被赋值的变量实际上应该是一个子cȝ对象Q,如果对t调用了子
cM新增的方法则造成~译旉误编译将不能通过Q而在q行Ӟq行时系l将Ҏt实际?/p>
向的cd调用对应的方法,对于本例来说Qt.print(10)调用t实际指向的Teachercȝ对应
Ҏ。在java中,可以用一个子cȝ实例实例化父cȝ一个变量,而变量在~译时是一个父c?/p>
实例Q在q行时可能是一个子cd例?/p>
35、public class Parent {
public int addValue( int a, int b) {
int s;
s = a+b;
return s;
}
}
class Child extends Parent {
}
Which methods can be added into class Child?
A. int addValue( int a, int b ){// do something...}
B. public void addValue (){// do something...}
C. public int addValue( int a ){// do something...}
D. public int addValue( int a, int b )throws MyException {//do
something...}
(bc)
题目Q哪些方法可以加入类Child中?/p>
此题涉及Ҏ重蝲QoverloadQ,Ҏ重写QoverrideQ以及类z时方法重写的规则
。方法重载的规则是:一、参数列表必M同,个数的不同完全可以,如果个数相同则参数类
型的不同不能引v歧意Q例如int
和long,float和double׃能作为唯一的类型不同;二、返回值可以不同,但是不能是重?/p>
时唯一的不同点Q这点和c++中不同,c++中返回类型必M_。方法重写发生在cȝ承时Q?/p>
子类可以重写一个父cM已有的方法,必须在返回类型和参数列表一h才能说是重写Q否?/p>
是重蝲Qjava中方法重写的一个重要而且Ҏ被忽略的规则是重写的Ҏ的访问权限不能比
被重写的Ҏ的访问权限低Q重写的另一个规则是重写的方法不能比被重写的Ҏ抛弃(thro
ws)更多U类的异常,其抛弃的异常只能,或者是其子c,不能以抛弃异常的个数来判断种
c,而应该是异常cdơ结果上的种cR此题中{案a的错误就是重写的讉K权限比被重写?/p>
Ҏ的低Q而b,c都属于重载,d的错误在于比被重写的Ҏ抛弃了更多种cȝ异常?/p>
Which of the following lines will print false?
1.public class MyClass
2.{
3.static String s1 = "I am unique!";
4.public static void main(String args[])
5.{
6.String s2 = "I am unique!";
7.String s3 = new String(s1);
8.System.out.println(s1 == s2);
9.System.out.println(s1.equals(s2));
10.System.out.println(s3 == s1);
11.System.out.println(s3.equals(s1));
12.System.out.println(TestClass.s4 == s1);
13.}
14.}
15.
16.class TestClass
17.{
18.static String s4 = "I am unique!";
19.}
Choices:
a. Lines 10 and 12
b. Line 12 only
c. Line 8 and 10
d. None of these
―――――――――?/p>
D is correct. Only line 10 will print false. Strings are immutable objects. That is, a string is read only once the string has been created and initialized, and Java optimizes handling of string literals; only one anonymous string object is shared by all string literals with the same contents. Hence in the above code the strings s1, s2 and s4 refer to the same anonymous string object, initialized with the character string: "I am unique!". Thus s1 == s2 and TestClass.s4 will both return true and obviously s1.equals(s2) will return true. But creating string objects using the constructor String(String s) creates a new string, hence s3 == s1 will return false even though s3.equals(s1) will return true because s1 and s3 are referring to two different string objects whose contents are same.
What is displayed when the following code is compiled and executed?
String s1 = new String("Test");
String s2 = new String("Test");
if (s1==s2)
if (s1.equals(s2))
Choices:
a. Same
Equals
b. Equals
c. Same
d. The code compiles, but nothing is displayed upon execution.
e. The code fails to compile.
B is correct. Here s1 and s2 are two different object references, referring to different objects in memory. Please note that operator == checks for the memory address of two object references being compared and not their value. The "equals()" method of String class compares the values of two Strings. Thus s1==s2 will return "false" while s1.equals(s2) will return "true". Thus only "Equals" will be printed.
Given the following code, what will be the output?
class Value
{
public int i = 15;
}
public class Test
{
public static void main(String argv[])
{
t.first();
public void first()
{
v.i = 25;
second(v, i);
}
public void second(Value v, int i)
{
i = 0;
Value val = new Value();
}
}
Choices:
a. 15 0
b. 15 0
c. 20 0
d. 0 15
――――――――――――――?/p>
A is correct. When we pass references in Java what actually gets passed is the value of that reference (i.e. memory address of the object being referenced and not the actual object referenced by that reference) and it gets passed as value (i.e a copy of the reference is made). Now when we make changes to the object referenced by that reference it reflects on that object even outside of the method being called but any changes made to the reference itself is not reflected on that reference outside of the method which is called. In the example above when the reference v is passed from method first() to second() the value of v is passed. When we assign the value val to v it is valid only inside the method second() and thus inside the method second() what gets printed is 15 (initial value of i in the object referenced by val), then a blank space and then 0 (value of local variable i). After this when we return to the method first() v actually refers to the same object to which it was referring before the method second() was called, but one thing should be noted here that the value of i in that object (referred by v inside the method first()) was changed to 20 in the method second() and this change does reflect even outside the method second(), hence 20 gets printed in the method first(). Thus overall output of the code in consideration is 15 0 20
interface MyInterface
{
}
public class MyInstanceTest implements MyInterface
{
static String s;
public static void main(String args[])
{
MyInstanceTest t = new MyInstanceTest();
if(t instanceof MyInterface)
{
System.out.println("I am true interface");
}
else
{
System.out.println("I am false interface");
}
if(s instanceof String)
{
System.out.println("I am true String");
}
else
{
System.out.println("I am false String");
}
}
}
Choices:
a. Compiletime error
b. Runtime error
c. Prints : "I am true interface" followed by " I am true String"
d. Prints : "I am false interface" followed by " I am false String"
e. Prints : "I am true interface" followed by " I am false String"
f. Prints : "I am false interface" followed by " I am true String"
―――――――――――?/p>
E is the correct choice. The "instanceof" operator tests the class of an object at runtime. It returns true if the class of the left-hand argument is the same as, or is some subclass of, the class specified by the right-hand operand. The right-hand operand may equally well be an interface. In such a case, the test determines if the object at left-hand argument implements the specified interface. In the above case there will not be any compiletime or runtime error. The result of "t instance of MyInterface" will be true as "t" is the object of MyInstanceTest class which implements the MyInstance interface. But the result of "s instanceof String" will be false as "s" refers to null. Thus the output of the above program will be : "I am true interface" followed by " I am false String". Thus choice E is correct and others are incorrect.
What will happen when you attempt to compile and run the following code snippet?
String str = "Java";
StringBuffer buffer = new StringBuffer(str);
if(str.equals(buffer)){
System.out.println("Both are equal");
}else{
System.out.println("Both are not equal");
}
A. it will print – both are not equal
B. it will print – both are equal
C. compile time error
D. Runtime error
A is the correct choice. The equals method overridden in String class returns true if and only if the argument is not null and is a String object that represents the same sequence of characters as this String object. Hence, though the contents of both str and buffer contain "Java", the str.equals(buffer) call results in false.
The equals method of Object class is of form -public boolean equals(Object anObject). Hence, comparing objects of different classes will never result in compile time or runtime error.
10. Which of the following statements are true?
A. The equals() method determines if reference values refer to the same
object.
B. The == operator determines if the contents and type of two separate
objects match.
C. The equals() method returns true only when the contents of two
objects match.
D. The class File overrides equals() to return true if the contents and
type of two separate objects match.
译
下面的哪些叙qCؓ真?/p>
A. equals()Ҏ判定引用值是否指向同一对象?/p>
B. == 操作W判定两个分立的对象的内容和cd是否一致?/p>
C. equals()Ҏ只有在两个对象的内容一致时q回true?/p>
D. cFile重写Ҏequals()在两个分立的对象的内容和cd一致时q回true?/p>
{案 A,D
解析 严格来说q个问题的答案是不确定的Q因为equals()Ҏ是可以被重蝲的,但是
按照java语言的本意来_如果没有重写QoverrideQ新cȝequals()Q则该方法和
==
操作W一样在两个变量指向同一对象时返回真Q但是java推荐的是使用equals()Ҏ来判?/p>
两个对象的内Ҏ否一P像Stringcȝequals()Ҏ所做的那样Q判定两个String对象?/p>
内容是否相同Q?=操作W返回true的唯一条g是两个变量指向同一对象。从q个意义上来?/p>
选择l定的答案。从更严格的意义来说正确{案应该只有d?/p>
Use the operators "<<", ">>", which statements are true?
A. 0000 0100 0000 0000 0000 0000 0000 0000<<5 gives
B. 0000 0100 0000 0000 0000 0000 0000 0000<<5 gives
C. 1100 0000 0000 0000 0000 0000 0000 0000>>5 gives
D. 1100 0000 0000 0000 0000 0000 0000 0000>>5 gives
译
使用"<<"?">>"操作W的哪些陈述是对的?/p>
{案 A,C
解析 Java的移位操作符一共有三种Q分别是”>>”,”>>>”,”<<”,执行的操作分?/p>
是有W号右移Q无W号右移Q左U,有符号右Uȝ意思是说移入的最高位和原最高符号位相同
Q无W号右移是移入位始终补零Q左UL最低位始终补零Q最高位被舍弃。移位操作符另一?/p>
非常值得注意的特Ҏ其右操作数是取模q算的,意思是说对于一个int型数据而言Q对它移
?2位的l果是保持不变而非变成Ӟ卻Ia>>32的结果是a而不?Q同理,对long型数是对
x作数?4的模Qa>>64==aQ还有一炚w要注意的是移位操作符”>>>”只对int型和long?/p>
有效Q对byte或者short的操作将D自动cd转换Q而且是带W号的?/p>
String s= "hello";
String t = "hello";
char c[] = {'h','e','l','l','o'} ;
Which return true?
A. s.equals(t);
B. t.equals(c);
C. s==t;
D. t.equals(new String("hello"));
E. t==c.
(acd)
题目Q哪些返回true?/p>
q个在前面第10题的equals()Ҏ?=操作W的讨论中论q过?=操作W比较的是操?/p>
W两端的操作数是否是同一个对象,而String的equals()Ҏ比较的是两个String对象的内?/p>
是否一P其参数是一个String对象时才有可能返回trueQ其它对象都q回假。需要指出的?/p>
׃s和tq使用new创徏的,他们指向内存池中的同一个字W串帔RQ因此其地址实际上是
相同的(q个可以从反~译一个简单的试E序的结果得刎ͼ限于幅不列出测试代码和反编
译的分析Q,因此{案c也是正确的?/p>
Class Teacher and Student are subclass of class Person.
Person p;
Teacher t;
Student s;
p, t and s are all non-null.
if(t instanceof Person) { s = (Student)t; }
What is the result of this sentence?
A. It will construct a Student object.
B. The expression_r is legal.
C. It is illegal at compilation.
D. It is legal at compilation but possible illegal at runtime.
(c)
题目Q类Teacher和Student都是cPerson的子c?/p>
…
p,t和s都是非空?/p>
…
q个语句D的结果是什?/p>
A. 构造一个Student对象?/p>
B. 表达式合法?/p>
C. ~译旉法?/p>
D. ~译时合法而在q行时可能非法?/p>
instanceof操作W的作用是判断一个变量是否是x作数指出的类的一个对象,׃ja
va语言的多态性得可以用一个子cȝ实例赋值给一个父cȝ变量Q而在一些情况下需要判?/p>
变量到底是一个什么类型的对象Q这时就可以使用instanceof了。当左操作数是右操作数指?/p>
的类的实例或者是子类的实例时都返回真Q如果是一个子cȝ实例赋值给一个父cȝ变量Q?/p>
用instanceof判断该变量是否是子类的一个实例时也将q回真。此题中的if语句的判断没有问
题,而且返回真Q但是后面的cd转换是非法的Q因为t是一个Teacher对象Q它不能被强?/p>
转换Z个Student对象Q即使这两个cL共同的父cR如果是t转换Z个Person对象则可
以,而且不需要强制{换。这个错误在~译时就可以发现Q因此编译不能通过?/p>
1. What will happen when you attempt to compile and run the following code?
public class Static
{
static
{
int x = 5;
}
static int x,y;
public static void main(String args[])
{
}
public static void myMethod()
{
y = x++ + ++x;
}
}
Choices:
a. Compiletime error
b. prints : 1
c. prints : 2
d. prints : 3
e. prints : 7
f. prints : 8
―――――――――――――――――――?/p>
1) D is the correct choice. The above code will not give any compilation error. Note that "Static" is a valid class name. Thus choice A is incorrect. In the above code, on execution, first the static variables (x and y) will be initialized to 0. Then static block will be called and finally main() method will be called. The execution of static block will have no effect on the output as it declares a new variable (int x). The first statement inside main (x--) will result in x to be -1. After that myMethod() will be executed. The statement "y = x++ + ++x;" will be evaluated to y = -1 + 1 and x will become 1. In case the statement be "y =++x + ++x", it would be evaluated to y = 0 + 1 and x would become 1. Finally when System.out is executed "x + y + ++x" will be evaluated to "1 + 0 + 2" which result in 3 as the output. Thus choice D is correct.
Considering the following code, Which variables may be referenced correctly at line 12?
1.public class Outer
2.{
3.public int a = 1;
4.private int b = 2;
5.public void method(final int c)
6.{
7.int d = 3;
8.class Inner
9.{
10.private void iMethod(int e)
11. {
12.
13.}
14.}
15.}
16.}
Choices:
a. a
b. b
c. c
d. d
e. e
A, B, C and E are correct. Since Inner is not a static inner class, it has a reference to an enclosing object, and all the variables of that object are accessible. Therefore A and B are correct, even if b is private. Variables in the enclosing method are only accessible when they are marked as final hence c is accessible but not d. E is obviously correct as it is a parameter to the method containing line 12 itself.
What will be the result of executing the following code?
// Filename; SuperclassX.java
package packageX;
public class SuperclassX
{
protected void superclassMethodX()
{
}
int superclassVarX;
}
// Filename SubclassY.java
1.package packageX.packageY;
2.
3.public class SubclassY extends SuperclassX
4.{
5.SuperclassX objX = new SubclassY();
6.SubclassY objY = new SubclassY();
7.void subclassMethodY()
8.{
9.objY.superclassMethodX();
10.int i;
11.i = objY.superclassVarX;
12.}
13.}
Choices:
a.Compilation error at line 5
b. Compilation error at line 9
c. Runtime exception at line 11
d. None of these
―――――――?/p>
D is correct. When no access modifier is specified for a member, it is only accessible by another class in the package where its class is defined. Even if its class is visible in another package, the member is not accessible there. In the question above the variable superclassVarX has no access modifier specified and hence it cannot be accessed in the packageY even though the class SuperclassX is visible and the protected method superclassMethodX() can be accessed. Thus the compiler will raise an error at line 11.
class FourWheeler implements DrivingUtilities
class Car extends FourWheeler
class Truck extends FourWheeler
class Bus extends FourWheeler
class Crane extends FourWheeler
----------------------------------------------------------------------
Consider the following code below:
1.DrivingUtilities du;
2.FourWheeler fw;
3.Truck myTruck = new Truck();
4.du = (DrivingUtilities)myTruck;
5.fw = new Crane();
6.fw = du;
Which of the statements below are true?
Choices:
a. Line 4 will not compile because an interface cannot refer to an object.
b. The code will compile and run.
c. The code will not compile without an explicit cast at line 6, because going
down the hierarchy without casting is not allowed.
d.The code at line 4 will compile even without the explicit cast.
e.The code will compile if we put an explicit cast at line 6 but will throw an exception at runtime.
――――――――――?/p>
C and D are correct. A and B are obviously wrong because there is nothing wrong in an interface referring to an object. C is correct because an explicit cast is needed to go down the hierarchy. D is correct because no explicit cast is needed at line 4, because we are going up the hierarchy. E is incorrect because if we put an explicit cast at line 6, the code will compile and run perfectly fine, no exception will be thrown because the runtime class of du (that is Truck) can be converted to type FourWheeler without any problem.
What will be printed when you execute the following code?
class X
{
Y b = new Y();
{
System.out.print("X");
}
}
class Y
{
{
System.out.print("Y");
}
}
public class Z extends X
{
{
System.out.print("Z");
}
{
}
Choices:
a. Z
b. YZ
c. XYZ
d. YXYZ
――――――――?/p>
D is correct. A difficult but a fundamental question, please observe carefully. Before any object is constructed the object of the parent class is constructed(as there is a default call to the parent's constructor from the constructor of the child class via the super() statement). Also note that when an object is constructed the variables are initialized first and then the constructor is executed. So when new Z() is executed , the object of class X will be constructed, which means Y b = new Y() will be executed and "Y" will be printed as a result. After that constructor of X will be called which implies "X" will be printed. Now the object of Z will be constructed and thus Y y = new Y() will be executed and Y will be printed and finally the constructor Z() will be called and thus "Z" will be printed. Thus YXYZ will be printed.
What will happen when you attempt to compile and run the following code?
class Base
{
int i = 99;
public void amethod()
{
{
}
public class Derived extends Base
{
int i = -1;
public static void main(String argv[])
{
{
}
Choices:
a. Derived.amethod()
-1
Derived.amethod()
b. Derived.amethod()
99
c.Derived.amethod()
99
d. Derived.amethod()
e.Compile time error
―――――――?/p>
B is correct. The reason is that this code creates an instance of the Derived class but assigns it to a reference of a the Base class. In this situation a reference to any of the fields such as i will refer to the value in the Base class, but a call to a method will refer to the method in the class type rather than its reference handle. But note that if the amethod() was not present in the base class then compilation error would be reported as at compile time, when compiler sees the statement like b.amethod(), it checks if the method is present in the base class or not. Only at the run time it decides to call the method from the derived class.
Given the following code fragment:
1) public void create() {
2) Vector myVect;
3) myVect = new Vector();
4) }
Which of the following statements are true?
A. The declaration on line 2 does not allocate memory space for the
variable myVect.
B. The declaration on line 2 allocates memory space for a reference to a
Vector object.
C. The statement on line 2 creates an object of class Vector.
D. The statement on line 3 creates an object of class Vector.
E. The statement on line 3 allocates memory space for an object of class
Vector
译
l出下面的代码片断。。。下面的哪些陈述为true(??
A. W二行的声明不会为变量myVect分配内存I间?/p>
B. W二行的声明分配一个到Vector对象的引用的内存I间?/p>
C. W二行语句创Z个Vectorcd象?/p>
D. W三行语句创Z个Vectorcd象?/p>
E. W三行语句ؓ一个Vectorcd象分配内存空间?/p>
{案 A,D,E
解析
SL-275中指出:要ؓ一个新对象分配I间必须执行new
Xxx()调用Qnew调用执行以下的操作:
1Qؓ新对象分配空间ƈ其成员初始化ؓ0或者null?/p>
Q执行到W二步后a=10Q?/p>
3Q执行构造函数?/p>
4Q变量被分配Z个到内存堆中的新对象的引用?/p>
Which of the following statements about variables and their scopes
are true?
A. Instance variables are member variables of a class.
B. Instance variables are declared with the static keyword.
C. Local variables defined inside a method are created when the method
is executed.
D. Local variables must be initialized before they are used.
(acd)
题目Q下面关于变量及其范围的陈述哪些是对的?/p>
A. 实例变量是类的成员变量?/p>
B. 实例变量用关键字static声明?/p>
C. 在方法中定义的局部变量在该方法被执行时创?/p>
D. 局部变量在使用前必被初始化?/p>
cM有几U变量,分别是:局部变量(英文可以为:local\automatic\temporary\stac
k
variableQ是定义在方法里的变量;实例变量Q英文ؓQinstance
variableQ是在方法外而在cd明内定义的变量,有时也叫成员变量Q类变量Q英文ؓQcl
ass
variableQ是用关键字static声明的实例变量,他们的生存期分别是:局部变量在定义该变
量的Ҏ被调用时被创建,而在该方法退出后被撤销Q实例变量在使用new
Xxxx()创徏该类的实例时被创建,而其生存期和该类的实例对象的生存期相同;cd量在?/p>
c被加蝲时被创徏Q不一定要用new
Xxxx()创徏Q所有该cȝ实例对象׃n该类变量Q其生存期是cȝ生存期。Q何变量在使用
前都必须初始?但是需要指出的是局部变量必L式初始化Q而实例变量不必,原始cd?/p>
实例变量在该cȝ构造方法被调用时ؓ它分配的~省的|整型?Q布型是falseQ而Q?/p>
型是0.0fQ引用类型(cȝ型)的实例变量的~省值是nullQ没有进行实际的初始化,对它?/p>
使用引起NullPointExceptionQ,cd量的规则和实例变量一P不同的是cd量的初始?/p>
是在c被加蝲时?/p>
public class Parent {
int change() {…}
}
class Child extends Parent {
}
Which methods can be added into class Child?
A. public int change(){}
B. int chang(int i){}
C. private int change(){}
D. abstract int chang(){}
(ab)
题目Q哪些方法可被加入类Child?/p>
需要注意的是答案D的内容,子类可以重写父类的方法ƈ之声明为抽象方法,但是q引发的问题是类必须声明为抽象类Q否则编译不能通过Q而且抽象Ҏ不能有方法体Q也是Ҏ声明后面不能带上那两个大括号Q{}Q,q些D都不能满?/p>
当已l分配的内存I间不再需要时Q换句话说当指向该内存块的句柄超Z使用范围的时候,该程序或其运行环境就应该回收该内存空_以节省宝늚内存资源?/p>
以上q种E序设计的潜在危险性在Javaq样以严谨、安全著U的语言中是不允许的。但是Java语言既不能限制程序员~写E序的自由性,又不能把声明对象的部分去除(否则׃是面向对象的E序语言了)Q那么最好的解决办法是从JavaE序语言本n的特性入手。于是,Java技术提供了一个系l的线E(ThreadQ,卛_圾收集器U程QGarbage Collection ThreadQ,来跟t每一块分配出ȝ内存I间Q当Java 虚拟机(Java Virtual MachineQ处于空闲@环时Q垃圾收集器U程会自动检查每一快分配出ȝ内存I间Q然后自动回收每一快可以回收的无用的内存块?/p>
下面介绍垃圾攉器的特点和它的执行机Ӟ 垃圾攉器的主要特点有: 1Q垃圾收集器的工作目标是回收已经无用的对象的内存I间Q从而避免内存渗漏体的生,节省内存资源Q避免程序代码的崩溃?/p>
2Q垃圾收集器判断一个对象的内存I间是否无用的标准是Q如果该对象不能再被E序中Q何一?zd的部?所引用Q此时我们就_该对象的内存I间已经无用。所?zd的部?Q是指程序中某部分参与程序的调用Q正在执行过E中Q尚未执行完毕?/p>
3Q垃圾收集器U程虽然是作Z优先U的U程q行Q但在系l可用内存量q低的时候,它可能会H发地执行来挽救内存资源。当然其执行与否也是不可预知的?/p>
4Q垃圾收集器不可以被强制执行Q但E序员可以通过调用System. gcҎ来徏议执行垃圾收集器?/p>
5Q不能保证一个无用的对象一定会被垃圾收集器攉Q也不能保证垃圾攉器在一DJava语言代码中一定会执行。因此在E序执行q程中被分配出去的内存空间可能会一直保留到该程序执行完毕,除非该空间被重新分配或被其他Ҏ回收。由此可见,完全d地根l内存渗漏体的生也是不可能的。但是请不要忘记QJava的垃圾收集器毕竟使程序员从手工回收内存空间的J重工作中解׃出来。设想一个程序员要用C或C++来编写一D?0万行语句的代码,那么他一定会充分体会到Java的垃圾收集器的优点! 6Q同h有办法预知在一l均W合垃圾攉器收集标准的对象中,哪一个会被首先收集?/p>
7Q@环引用对象不会媄响其被垃圾收集器攉?/p>
8Q可以通过对象的引用变量Qreference variablesQ即句柄handlesQ初始化为null|来暗C垃圾收集器来收集该对象。但此时Q如果该对象q接有事件监听器Q典型的 AWTlgQ,那它q是不可以被攉。所以在设一个引用变量ؓnullg前,应注意该引用变量指向的对象是否被监听Q若有,要首先除ȝ听器Q然后才可以赋空倹{?/p>
9Q每一个对象都有一个finalize( )ҎQ这个方法是从Objectcȝ承来的?/p>
10Qfinalize( )Ҏ用来回收内存以外的系l资源,像是文件处理器和网l连接器。该Ҏ的调用顺序和用来调用该方法的对象的创建顺序是无关的。换句话_书写E序时该Ҏ的顺序和Ҏ的实际调用顺序是不相q的。请注意q只是finalize( )Ҏ的特炏V?/p>
11Q每个对象只能调用finalize( )Ҏ一ơ。如果在finalize( )Ҏ执行时生异常(exceptionQ,则该对象仍可以被垃圾攉器收集?/p>
12Q垃圾收集器跟踪每一个对象,攉那些不可到达的对象(卌对象没有被程序的M"zȝ部分"所调用Q,回收其占有的内存I间。但在进行垃圾收集的时候,垃圾攉器会调用finalize( )ҎQ通过让其他对象知道它的存在,而不可到达的对象再?复苏"为可到达的对象。既然每个对象只能调用一ơfinalize( )ҎQ所以每个对象也只可?复苏"一ơ?/p>
13Qfinalize( )Ҏ可以明确地被调用Q但它却不能q行垃圾攉?/p>
14Qfinalize( )Ҏ可以被重载(overloadQ,但只有具备初始的finalize( )Ҏ特点的方法才可以被垃圾收集器调用?/p>
15Q子cȝfinalize( )Ҏ可以明确地调用父cȝfinalize( )ҎQ作子类对象的最后一ơ适当的操作。但Java~译器却不认是一ơ覆盖操作(overridingQ,所以也不会对其调用q行查?/p>
16Q当finalize( )Ҏ未被调用时QSystem. runFinalization( )Ҏ可以用来调用finalize( )ҎQƈ实现相同的效果,Ҏ用对象进行垃圾收集?/p>
17Q当一个方法执行完毕,其中的局部变量就会超Z用范_此时可以被当作垃圾收集,但以后每当该Ҏ再次被调用时Q其中的局部变量便会被重新创徏?/p>
18QJava语言使用了一U?标记交换区的垃圾攉法"。该法会遍历程序中每一个对象的句柄Qؓ被引用的对象做标讎ͼ然后回收未做标记的对象。所谓遍历可以简单地理解?查每一??/p>
19QJava语言允许E序员ؓMҎdfinalize( )ҎQ该Ҏ会在垃圾攉器交换回收对象之前被调用。但不要q分依赖该方法对pȝ资源q行回收和再利用Q因Ҏ调用后的执行l果是不可预知的?/p>
通过以上对垃圾收集器特点的了解,你应该可以明垃圾收集器的作用,和垃圾收集器判断一块内存空间是否无用的标准。简单地_当你Z个对象赋gؓnullq且重新定向了该对象的引用者,此时该对象就W合垃圾攉器的攉标准?/p>
判断一个对象是否符合垃圾收集器的收集标准,q是SUN公司E序员认证考试中垃圾收集器部分的重要考点Q可以说Q这是唯一的考点Q。所以,考生在一D늻定的代码中,应该能够判断出哪个对象符合垃圾收集器攉的标准,哪个不符合。下面结合几U认证考试中可能出现的题型来具体讲解: Object obj = new Object ( ) ; 我们知道Qobj为Object的一个句柄。当出现new关键字时Q就l新建的对象分配内存I间Q而obj的值就是新分配的内存空间的首地址Q即该对象的?L别注意,对象的值和对象的内Ҏ不同含义的两个概念:对象的值就是指其内存块的首地址Q即对象的句柄;而对象的内容则是其具体的内存?。此时如果有 obj = nullQ则obj指向的内存块此时无用了Q因Z面再没有调用该变量了?/p>
请再看以下三U认证考试时可能出现的题型Q?/p>
E序D?Q?/p>
1Qfobj = new Object ( ) ; 2Qfobj. Method ( ) ; 3Qfobj = new Object ( ) ; 4Qfobj. Method ( ) ; 问:q段代码中,W几行的fobj W合垃圾攉器的攉标准Q?/p>
{:W?行。因为第3行的fobj被赋了新|产生了一个新的对象,x了一块新的内存空_也相当于为第1行中的fobj赋了null倹{这U类型的题在认证0考试中是最单的?/p>
E序D?Q?/p>
1QObject sobj = new Object ( ) ; 2QObject sobj = null ; 3QObject sobj = new Object ( ) ; 4Qsobj = new Object ( ) ; 问:q段代码中,W几行的内存I间W合垃圾攉器的攉标准Q?/p>
{:W?行和W?行。因为第2行ؓsobj赋gؓnullQ所以在此第1行的sobjW合垃圾攉器的攉标准。而第4行相当于为sobj赋gؓnullQ所以在此第3行的sobj也符合垃圾收集器的收集标准?/p>
如果有一个对象的句柄aQ且你把a作ؓ某个构造器的参敎ͼ?new Constructor ( a )的时候,即你给a赋gؓnullQa也不W合垃圾攉器的攉标准。直到由上面构造器构造的新对象被赋空值时Qa才可以被垃圾攉器收集?/p>
E序D?Q?/p>
1QObject aobj = new Object ( ) ; 2QObject bobj = new Object ( ) ; 3QObject cobj = new Object ( ) ; 4Qaobj = bobj; 5Qaobj = cobj; 6Qcobj = null; 7Qaobj = null; 问:q段代码中,W几行的内存I间W合垃圾攉器的攉标准Q?/p>
{:W?行。注意这c题型是认证考试中可能遇到的最N型了?/p>
?-3分别创徏了Objectcȝ三个对象QaobjQbobjQcobj ?Q此时对象aobj的句柄指向bobjQ所以该行的执行不能使aobjW合垃圾攉器的攉标准?/p>
?Q此时对象aobj的句柄指向cobjQ所以该行的执行不能使aobjW合垃圾攉器的攉标准?/p>
?Q此时仍没有M一个对象符合垃圾收集器的收集标准?/p>
?Q对象cobjW合了垃圾收集器的收集标准,因ؓcobj的句柄指向单一的地址I间。在W?行的时候,cobj已经被赋gؓnullQ但由cobj同时q指向了aobjQ第5行)Q所以此时cobjq不W合垃圾攉器的攉标准。而在W?行,aobj所指向的地址I间也被赋予了空值nullQ这p明了Q由cobj所指向的地址I间已经被完全地赋予了空倹{所以此时cobj最l符合了垃圾攉器的攉标准。但对于aobj和bobjQ仍然无法判断其是否W合攉标准?/p>
MQ在Java语言中,判断一块内存空间是否符合垃圾收集器攉标准的标准只有两个: 1Q给对象赋予了空值nullQ以下再没有调用q?/p>
2Q给对象赋予了新|既重新分配了内存I间?/p>
最后再ơ提醒一下,一块内存空间符合了垃圾攉器的攉标准Qƈ不意味着q块内存I间׃定会被垃圾收集器攉?/p>
]]>
J2SE 1.4在语a上提供了一个新Ҏ,是assertion(断言)功能Q它是该版本在Java语言斚w最大的革新。在软g开发中Qassertion是一U经典的调试、测试方式,本文深入解析assertion功能的用以及其设计理念Qƈl出相关的例子?/p>
assertion(断言)在Y件开发中是一U常用的调试方式Q很多开发语a中都支持q种机制Q如CQC++和Eiffel{,但是支持的Ş式不相同,有的是通过语言本n、有的是通过库函数等。另外,从理Z来说Q通过assertion方式可以证明E序的正性,但是q是一相当复杂的工作Q目前还没有太多的实跉|义?/p>
在实CQassertion是在程序中的一条语句,它对一个boolean表达式进行检查,一个正程序必M证这个boolean表达式的gؓtrueQ如果该gؓfalseQ说明程序已l处于不正确的状态下Q系l将l出警告或退出。一般来_assertion用于保证E序最基本、关键的正确性。assertion查通常在开发和试时开启。ؓ了提高性能Q在软g发布后,assertion查通常是关闭的。下面简单介l一下Java中assertion的实现?/p>
1Q?/strong>1) 语法表示
在语法上Qؓ了支持assertionQJava增加了一个关键字assert。它包括两种表达式,分别如下Q?/p>
1.
2.
在两U表辑ּ中,expression_r1表示一个boolean表达式,expression_r2表示一个基本类型或者是一个对?Object) Q基本类型包括boolean,char,double,float,int和long。由于所有类都ؓObject的子c,因此q个参数可以用于所有对象?/p>
1Q?/strong>2) 语义含义
在运行时Q如果关闭了assertion功能Q这些语句将不vM作用。如果打开了assertion功能Q那么expression_r1的值将被计,如果它的gؓfalseQ该语句强抛Z个AssertionError对象。如果assertion语句包括expression_r2参数Q程序将计算出expression_r2的结果,然后这个结果作为AssertionError的构造函数的参数Q来创徏AssertionError对象Qƈ抛出该对象;如果expression_r1gؓtrueQexpression_r2不被计?/p>
一U特D情冉|Q如果在计算表达式时Q表辑ּ本n抛出ExceptionQ那么assert停止运行,而抛个Exception?/p>
1Q?/strong>3) 一?/strong>assertion例子
下面是一些Assert的例子?/p>
1.
2.
3.
4.
1Q?/strong>4) ~译
׃assert是一个新关键字,使用老版本的JDK是无法编译带有assert的源E序。因此,我们必须使用JDK1.4(或者更?的Java~译器,在用Javac命oӞ我们必须加上-source 1.4作ؓ参数?source 1.4表示使用JDK 1.4版本的方式来~译源代码,否则~译׃能通过Q因为缺省的Javac~译器用JDK1.3的语法规则?/p>
一个简单的例子如下Q?/p>
javac
1Q?/strong>5) q行
׃带有assert语句的程序运行时Q用了新的ClassLoader和Classc,因此Q这U程序必dJDK1.4(或者更高版?的JRE下运行,而不能在老版本的JRE下运行?/p>
1. 首先Q我们认为assertion是必要的。因为,如果没有l一的assertion机制QJavaE序通常使用if-then-else或者switch-case语句q行assertion查,而且查的数据cd也不完全相同。assertion机制让JavaE序员用l一的方式处理assertion问题Q而不是按自己的方式处理。另外,如果用户使用自己的方式进行检查,那么q些代码在发布以后仍然将起作用,q可能会影响E序的性能。而从语言a层次支持assertion功能Q这把assertionҎ能带来的负面媄响降到最?/p>
Java是通过增强一个关键字assert实现支持assertionQ而不是用一个库函数支持Q这说明Java认ؓassertion对于语言本n来说是非帔R要的。实际上Q在Java的早期的规范中,Java是能够支持assert的,但是׃一些实现的限制Q这些特性从规范中除M。因此,assert的再ơ引入应该是恢复了Java对assert的支持。C语言是通过Assert.h函数库实现断a的支持?/p>
Java的assertion的开启也和C语言不太一P我们都知道在C语言中,assertion的开启是在编译时候决定的。当我们使用debug方式~译E序时候,assertion被开启,而用release方式~译时候,assertion自动被关闭。而Java的assertion却是在运行的时候进行决定的。其实,q两U方式是各有优缺炏V如果采用编译时军_方式Q开发h员将处理两种cd的目标码Qdebug版本和release版本Q这加大了文管理的隑ֺQ但是提高了代码的运行效率。Java采用q行时决定的方式Q这h有的assertion信息置于目标代码中Q同一目标代码可以选择不同方式q行Q增强目标代码的灉|性,但是它将牺牲因ؓassertion而引起一部分性能损失。Java专家组认ؓQ所牺牲的性能相当,因此java采用了运行时军_方式?/p>
另外Q我们注意到AssertionError作ؓError的一个子c,而不是RuntimeException。关于这一点,专家l也q行了长期的讨论。Error代表一些异常的错误Q通常是不可以恢复的,而RuntimeException该错误在q行时才发生的特炏VAssertionError通常为非常关键的错误Q这些错误往往是不Ҏ恢复的,而且assertion机制也不鼓励E序员对q种错误q行恢复。因此,Zassertion的含义,Java专家组选择了让AssertError为Error的子cR?/p>
在本节,我们考虑assertion与承的关系Q研Iassert是如何定位的。如果开启一个子cȝassertionQ那么它的父cȝassertion是否执行Q?/p>
下面的例子将昄如果一个assert语句在父c,而当它的子类调用它时Q该assert为false。我们看看在不同的情况下Q该assertion是否被处理?/p>
class Base { } class Derived { } q行命o 含义 l果 Java Derived 不启用assertion Base Method Java -ea Derived 开启所有assertion Java.lang.AssertionError:Assertion Failed:This is base Java -da Derived 关闭所有assertion Base Method Java -ea:Base Derived 仅打开Base的assertion Java.lang.AssertionError:Assertion Failed:This is base Java -ea:Derived Derived 仅打开Derived的assertion Base Method 从这个例子我们可以看出,父类的assert语句只有在父类的assert开启才起作用,如果仅仅开启子cȝassertQ父cȝassert仍然不运行。例如,我们执行java -ea:Derived Derived的时候,Basecȝassert语句q不执行。因此,我们可以认ؓQassert语句不具有承功能?/p>
assertion的用是一个复杂的问题Q因涉及到E序的风|assertionq用的目标,E序的性质{问题。通常来说Qassertion用于查一些关键的|q且q些值对整个E序Q或者局部功能的完成有很大的影响Qƈ且这U错误不Ҏ恢复的。assertion表达式应该短、易懂,如果需要评估复杂的表达式,应该使用函数计算。以下是一些用assertion的情늚例子Q这些方式可以让javaE序的可靠性更高?/p>
1. 2. 3. 4. 5. 6. 7. 8. 9. assert 通过q种方式Q我们可以对函数计算完的l果q行查?/p>
10. 11. 12. 13. 在这个系l中Q在一些可能媄响这U^衡关pȝҎ的前后,我们都可以加上assert验证Qassert isBalance():"balance is destoried"; assertion为开发h员提供了一U灵zd调试和测试机Ӟ它的使用也非常简单、方ѝ但是,如何规范、系l地使用assertion(特别是在Java语言?仍然是一个亟待研I的问题§1.1.2
§1.1.3
Derived Method
Derived Method
Java.lang.AssertionError:Assertion Failed:This is derived§1.1.4
§1.1.5
In the following pieces of code, A and D will compile without any error. True/False?
A: StringBuffer sb1 = "abcd";
B: Boolean b = new Boolean("abcd");
C: byte b = 255;
D: int x = 0x1234;
E: float fl = 1.2;
Choices:
A. True
B. False
――――――――――――――――――――――――――――――?/p>
{案 B. The code segments B and D will compile without any error. A is not a valid way to construct a StringBuffer, you need to creat a StringBuffer object using "new". B is a valid construction of a Boolean (any string other than "true" or "false" to the Boolean constructor will result in a Boolean with a value of "false"). C will fail to compile because the valid range for a byte is -128 to +127 (ie, 8 bits,signed). D is correct, 0x1234 is the hexadecimal representation in java. E fails to compile because the compiler interprets 1.2 as a double being assigned to a float (down-casting), which is not valid. You either need an explicit cast (as in "(float)1.2") or "1.2f", to indicate a float.
What will be the result of executing the following code?
Given that Test1 is a class.
1. Test1[] t1 = new Test1[10];
2. Test1[][] t2 = new Test1[5][];
3. if (t1[0] == null)
4. {
5.t2[0] = new Test1[10]
6.t2[1] = new Test1[10]
7.t2[2] = new Test1[10]
8.t2[3] = new Test1[10]
9.t2[4] = new Test1[10]
10. }
11. System.out.println(t1[0]);
12. System.out.println(t2[1][0]);
Choices:
a. The code will not compile because the array t2 is not initialized in an unconditional statement before use.
b. The code will compile but a runtime exception will be thrown at line 12.
c. The code will compile but a runtime exception will be thrown at line 11.
d. None of these.
――――――――――――――――――――?/p>
D is correct. Though we cannot use local variables without initializing them (compilation error), there is an exception to it. In case of arrays initialization is supposed to be complete when we specify the leftmost dimension of the array. The problem occurs at runtime if we try to access an element of the array which has not been initialized (specification of size). In the question above the array t2 is initialized before use, therefore there will be no problem at runtime also and the lines 11 and 12 will both print null.
Which declarations of identifiers are legal?
A. $persons
B. TwoUsers
C. *point
D. this
{案 A,B,E
解析 Java的标识符可以以一个Unicode字符Q下滑线Q_Q,元W($Q开始,后箋?/p>
W可以是前面的符号和数字Q没有长度限Ӟ大小写敏感,不能是保留字?/p>
Which of the following answer is correct to express the value 8 in octal number?
A. 010
B. 0x10
C. 08
D. 0x8
译
下面的哪些答案可以用以表C八q制??/p>
{案 A
解析 八进制g0开_?x开头的为十六进制|八进制中不能出现数字8Q最大只??/p>
Which are not Java keywords?
A. TRUE
B. sizeof
C. const
D. super
E. void
译
哪些不是Java关键字?/p>
{案 A,B
解析
BQ不是,Java中不需要这个操作符Q所有的cdQ原始类型)的大都是固定的?/p>
C、D、E都是Q需要说明的是const是java中未被用的关键字?/p>
Which statements about Java code security are true? A. The bytecode verifier loads all classes needed for the execution of a program. B. Executing code is performed by the runtime interpreter. C. At runtime the bytecodes are loaded, checked and run in an interpreter. D. The class loader adds security by separating the namespaces for the classes of the local file system from those imported from network sources. ―――――――――――――?/p>
{案 BCD 题目Q下面有关java代码安全性的叙述哪些是对的?/p>
A. 字节码校验器加蝲查询执行需要的所有类?/p>
B. q行时解释器执行代码?/p>
C. 在运行时Q字节码被加载,验证然后在解释器里面q行?/p>
D. cd载器通过分离本机文gpȝ的类和从|络导入的类增加安全性?/p>
SL275中描q的JavaE序q行的过E是q样的:cd载器Qclass loaderQ加载程序运行所需要的所有类Q它通过区分本机文gpȝ的类和网l系l导入的cd加安全性,q可以限制Q何的Ҏ伊木马程序,因ؓ本机cLL先被加蝲Q一旦所有的c被加蝲完,执行文g的内存划分就固定了,在这个时候特定的内存地址被分配给对应的符号引用,查找表(lookuo tableQ也被徏立,׃内存划分发生在运行时Q解释器在受限制的代码区增加保护防止未授权的讉KQ然后字节码校验器(byte code verifierQ进行校验,主要执行下面的检查:cȝ合JVM规范的类文g格式Q没有违反访问限Ӟ代码没有造成堆栈的上溢或者下溢,所有操作代码的参数cd都是正确的,没有非法的数据类型{换(例如整型数转换成对象类型)发生Q校验通过的字节码被解释器QinterpreterQ执行,解释器在必要旉过q行时系l执行对底层g的合适调用。后三个{案是SL275中的原话?/p>
Which fragments are correct in Java source file? A. package testpackage; public class Test{//do something...} B. import java.io.*; package testpackage; public class Test{// do something...} C. import java.io.*; class Person{// do something...} public class Test{// do something...} D. import java.io.*; import java.awt.*; public class Test{// do something...} ------------------------ {案 ACD Which of the following statements are legal? A. long l = 4990; B. int i = 4L; C. float f = 1.1; D. double d = 34.4; E. double t = 0.9F. ---------------------------- {案 ADE §1.1.6
§1.1.7
§1.1.8
§1.1.9