5.關于Thread的,很多人都說Thread考的多,而且難一點,可能我沒碰到難題吧 Thread部分我沒錯 class a implements Runnable{ private int x; private int y; public void run(){ for(;;){ x++; y++; System.out.println(" x="+x+" y="+y); System.out.println(當前Thread的名字); } } } class b{ public static void main(String[] args){ a aa = new a(); new Thread(aa).start(); new Thread(aa).start(); } } 給幾個選項,問你運行結果 補充:此題的正確答案是---有可能輸出x!=y的結果并且輸出顯示的是兩個線程在運行! 不會出現相同的x和y的值! 下面也是一道類似的題,你可以看看應該選哪個? ************************************************** class Happy implements Runnable{ private int x; private int y; public synchronized void run() { x++; y++; System.out.println(x+" "+y); } public static void main(String args[]) { Happy that=new Happy(); (new Thread(that)).start(); (new Thread(that)).start(); } } What happens when this code compiles and run? a) will print x ,y in order 11 22 b) will print x ,y twice in order 11 22 11 22 c) will print x ,y in order 12 12 d) will print x ,y order is unpredictable. e) Compilation error. f) Runtime Exception. ***********************************************************
6.非常碰巧,上面這道題改了一下又出現在我的考題里面 //前面一樣 synchronized(this){ x++; y++; } System.out.println...//后面一樣 同樣是給你幾個選項,問運行結果 這個是同步的,上面那個有可能輸出x!=y的結果,這個就不會了! 大家要注重5,6都只有一個aa,也就是不會出現相同的x或y. 補充:正確答案是----永遠輸出x=y并且輸出顯示的是兩個線程在運行! 不會出現相同的x和y的值! 假如Thread的構造體中不僅僅是一個aa,也就是另外用類a再new一個實例bb, 并且new Thread(bb).start();的話,那運行結果就不一樣了!就會出現相同的x和y的值! (5和6我第一次考題都碰到了,第二次好象也有!SUN題庫會經常出現的,祝你好運?。?br />大家可以把下面我提供的完整程序去認真的編譯運行驗證一下! //大家將注釋掉的和未注釋的程序分別運行! ******************************************************** public class TestThread { public static void main(String args[]) { Xyz r = new Xyz(); //Xyz p = new Xyz(); Thread t1 = new Thread(r); Thread t2 = new Thread(r); //Thread w1 = new Thread(p); //Thread w2 = new Thread(p);
7.還有一個很經典的thread題,也是真題, Thread1 synchronized(a){ synchronized(b){ } } Thread2 synchronized(b){synchronized(a){ } } 都start();問結果,結果是--不確定的!可能deadlock,并且結果和當前Thread的執行機的環境有關! 就是大家很常見的那道題 a,b是StringBuffer();Thread1,2是用 new Thread(){ public void run(){ //.... } }.start(); 方式定義,一字不變。 真實的程序如下: ******************************************************** public class SyncTest { public static void main(String[] args) { final StringBuffer s1= new StringBuffer(); final StringBuffer s2= new StringBuffer();
new Thread () { public void run() { synchronized(s1) { s1.append("A"); synchronized(s2) { s2.append("B"); System.out.print(s1); System.out.print(s2); } } } }.start();
new Thread() { public void run() { synchronized(s2) { s2.append("C"); synchronized(s1) { s1.append("D"); System.out.print(s2); System.out.print(s1); } } } }.start();
} } /* 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. */ ******************************************************** 正確的答案是:D和E! 根據程序流程和線程(同優先級)調用的不確定性,這個程序有可能會輸出的是A和B.但是你應該注重到兩個線程1和2鎖定對象的時候的加鎖順序不一致,也就是說可能會導致死鎖。 假如你實際去運行上面的程序,你會發現輸出的結果可能總是"ABBCAD",實際上還可能輸出"CDDACB"!這和你當前的JAVA虛擬機的運行環境有關的!你不能很好的加其他的Thread進來,所以看到的結果好象只有A答案!但是我的運行結果是--多半是A情況,B情況出現的幾率少,呵呵!你,試試看? 這道題我兩次考試都碰到了,你肯定也能碰到的!不信?我和你打賭,賭什么?當然是請我吃飯了,呵呵! 好象SUN的SCJP題庫中關于Thread就沒有其他的題型似的!當你碰到這個題時,答案都不用看,直接選D和E好了!
9. class a{ Integer u(){return new Integer(4);} } class b extends a{ Long u(){return new Long(8);} public static void main(String[] args){ ... } } 問結果,結果是編譯不通,override方法的返回值必須一樣! 補充:override的三個方面要完全一致!而overloading是方法進口的參數必須不一樣,它的返回值可以不同的!這類題型肯定要考到的!方式可能不一樣,但抓住上面的要點就不會錯了!
10.如何定義一個方法使它不能被繼續? 給你幾個選項,要你選兩個 其中有是 static void xx(){} final static void xx(){} final void xx(){} 我那道題在lang fund上面錯的,不會是這道吧? 我選的后兩個,也是就說static void xx(){}沒選 其實static方法到底可不可以被繼續,眾說紛紛. 這個方面我滔滔不絕可以給你說很多了, 大家假如不清楚還是自己看書吧?;旧隙加小?br /> 11. 這讓我想到了 static inner class 的問題 inner class 到底可不可以用static修飾 就是說static inner class 這種說法到底正不正規 也是眾說紛紛。 其實大家都明白static inner class是什么,而且這么說 大家都懂,我覺得那種死扣字眼的人有點無聊。
寫sun考題的人認為是可以的 其中有一題是單選 innter class can be static anonymous inner class can be public ............................ static ............................ privated ............................ protected 這題為A,因為這題前一題的題目(不是選項)中就出現了static inner class 的字樣,而且sun給出的考點中也出現了static inner class 補充:這個題出現的幾率比較多!一定要將inner class的特性搞清楚,非凡是anonymous inner class 的相關特性,非常重要!還有Abstract class和Interface class的主要特性!以及static、final等高級類的屬性!??!將其基本思想搞清楚!SUN經常考到的,不信,你等著瞧好了。這部分可以仔細看my_notes里的相關部分!多看幾便,最好背下來!
14. class a{ public String toString(){ return "4" } } class b extends a{ public String toString(){ return super.toString()+"3";//此處是調用父類中的方法!275書上有類似的程序。 } public static void main(String[] args){ System.out.println(new b()); } } 問輸出,為"43"
15. sun的題目很扣考點的 java Test a b c class Test{ pubic static void main(String[] args){ String k1 = args[0]; String k2 = args[1]; String k3 = args[2]; } } 問你k3是多少?我當時好好看了一下題目,確定就是這么簡單
16. class a implements Runnable{ public void run(){ System.out.println("abc"); } } 問你如何在一個new Thread 中打印出abc 給你一些一眼都看得出來的錯誤選項,不過我還是好好看了一下 補充:使Thread的實例啟動變成可運行狀態是調用其start()方法。
17. 考RandomaccessFile的構造器,問你如何寫一個文件云云 a. ...RandomAccessFile(xxx,"r") b. .......................,"w") c. .......................,"rw") d. .......................,"x") 選c. 真實的考題如下: ********************************************************* File f=new File("aa.txt"); Suppose this file exists in your Directory. Which of the following can be used to write a line of text to the end of this file? A. RandomAccessFile f1=new RandomAccessFile(f,"r"); B. RandomAccessFile f1=new RandomAccessFile(f,"a"); C. RandomAccessFile f1=new RandomAccessFile(f,"rw"); D. RandomAccessFile f1=new RandomAccessFile(f,"w"); E. RandomAccessFile f1=new RandomAccessFile(f,"wr"); *********************************************************
18. 一個考布局的 一個Frame, 程序里面用了setLayout(new BorderLayout());//似乎sun出題的人怕你忘了 Panel p = new Panel(); Button b1 = new Button(); p.add(b1); add(p,北邊); Button b2 = new Button(); add(b2,南邊); .... 問你北邊,南邊Button的多大,是不是一樣大,Frame resize的時候如何...等 我的補充:可運行的源程序如下: ****************************************************** import java.awt.*;
public class FrameExample { private Frame f; private Panel p; private Button b1; private Button b2;
public FrameExample() { f = new Frame("Hello Out There!"); p=new Panel(); b1=new Button("Button One"); b2=new Button("Button Two"); }
19. java.io.PrintStream p = new java.io.PrintStream( new java.io.InputStreamReader(System.out) ) 要你選import xxx 或者不import 下面是類似的一道題,你看選哪個? ********************************************** //code class Happy { public static void main(String args[]) {
PrintWriter p=new PrintWriter(new java.io.OutputStreamWriter(System.out)); } } Which statement can be placed in //code to make this program work? a) import java.io.PrintWriter b) import java.io.OutputStreamWriter c) include java.io.PrintWriter d) include java.io.OutputStreamWriter e) import java.io.PrintWriter import java.io.OutputStream f) no need to do anything. **********************************************
20.關于異常! catch可以有多個,但是必須保證“逆向” 即先有異常子類,再有父類 假如反過來的話,編譯將通不過。 1.在方法體內假如拋出了異常而又不想在該方法體內處理的化,必須再次拋出。 public static void methodA() throws Exception { throw new IOException(); } 2.假如catch塊根本不可能捕捉到異常的化,編譯會出錯。 3.假如try對應了多個catch塊,程序會尋找第一個匹配的塊,然后直接跳到finally(假如有的話)。對于其他塊將不作處理。 ********************************************** import java.io.IOException; public class A{ public static void main(String[] args){ try{ methodA(); } catch(IOException e){ //去掉這個catch程序能正常運行出結果! System.out.println("Caught IOException"); }
catch(Exception e){ //去掉這個catch程序卻不能正常運行出結果!因為catch中捕捉的異常必須和方法聲明 //處的異常一致!盡管方法體內拋出的是其子異常,假如僅保持和這個子異常一致, //編譯卻出錯!TRY IT OUT! System.out.println("Caught Exception"); }
} public static void methodA() throws Exception{ //方法體內拋出了異常,但是方法聲明處仍需再次拋出! //此處的throws Exception千萬不能漏掉!!! throw new IOException(); } } ********************************************** 你看看下面的題該選哪個呢?運行一下檢驗每個答案選項,想想為什么? import java.io.*; class Excep{ static void method() throws Exception{ throw new EOFException(); } public static void main(String args[]){ try{ method(); }catch(////){} } } Which of the following should be placed at //// so that the code will compile without errors? A. IOException e B. EOFException e C. MalformedURLException e D. NullPointerException e E. Exception e F. FileNotFoundException
以下完全是偶自己總結的東東!希望大家重視! 1. 看下面的程序!想想輸出的結果是?或編譯錯誤? 這是我考題中的一道,當時我想得太多,結果做錯了!但實際上它能正常編譯并且輸出結果是:1。 class A { static void method(int [] a){ int j=1; a[j]++; } public static void main(String args[]) { int [] b=new int[5]; method(b); System.out.println(b[1]); } }
2.下面的也出現在我的考題中,但到現在為止我還不知道其正確答案,并且題目具體細節也忘了。 程序大概如下,似乎是問,A.該程序結果能正確的繪一個圓。B.該圓的直徑永遠是半徑的2倍。 C.method(double radius)處應加上synchronized才能保證圓的直徑永遠是半徑的2倍。 D.該程序能返回正確的半徑值。大概是這樣的。。。。,你若碰到了告訴我正確的答案,好嗎? class Circle { private double radius; private double diameter; void method(double radius){ this.radius=radius; this.diameter=radius*2; } double getRadius(){ return radius; } public static void main(String args[]) { Circle cir=new Circle(); cir.getRadius(); } }
4.cause a thread to stop的條件如下: sleep();stop();yield();wait();Synchronized();exits Synchronized code;InputStream access No stop a thread的條件如下: notify();notifyAll();setPriority;getPriority.
7.考試中一定要清醒的辨別JAVA的一個重要特點:Pass-by-value!!!用值來傳遞參數,什么情況下參數的值會被改變呢?這個知識點考的很多的!!!看下面的題,運行一下看該選哪個? What will be printed when following code runs? 1. class Foo{ 2. static void change(String s){ 3. s=s.replace('j','l'); 4. } 5. 6. public static void main(String args[]){ 7. String s="java"; 8. change(s); 9. System.out.println(s); 10. } 11. } A. Compiler error B. Will print lava C. Runtime exception D. Will print java
8. JAVA程序的執行順序??? 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. 任何JAVA對象實例化時,第一步:先給實例變量即類級變量賦其缺省值,以及static變量的初始化賦值和static塊代碼的運行,然后進入對象構造器的代碼塊中。第二步:進入構造器的代碼塊后,先缺省調用或顯性調用父類的構造器,在執行父類的構造器的時候,也是按照當前的步驟運行的,既先給父類的實例變量賦其缺省值,以及父類的static變量的初始化賦值和父類的static塊代碼的運行,然后進入父類的對象構造器的代碼塊中,執行隨后的代碼行;假如父類還需調用其上一級的構造器,則先去調用父類的父類構造器,如此類推,直至調用到Object的構造器為止。第三步:執行完父類的構造器后,回來后再給本地的實例變量賦其初始值,然后再次進入到本地的構造器代碼塊中,接著執行隨后的構造器中的代碼行。至此,一個對象實例化結束!在父類構造器執行的過程中,假如要調用和子類同名重寫的方法時,還應該注重到JAVA程序的動態綁定,此時父類調用的是子類中重寫父類的方法,而不是父類本地的方法!
10.下面這道題能幫助你很好的理解線程的運行機制! 我考試時碰到過的。問你,結果輸出i的值是什么?是10還是999? 答案是:可能是10也可能是999,并不一定確定!依靠于其執行機的環境。 你可以試著多運行N次。 class Xyz implements Runnable { static int i=10; public void run() { i = 999; } public static void main(String args[]) { Xyz r = new Xyz(); Thread t = new Thread(r); t.start(); System.out.println("i= " + i); } }
11.以下列出的是SUN公司的SCJP的考試軟件中歸納的Tips,我想有點用! Quick Revision Tips 1. An identifier in java must begin with a letter , a dollar sign($), or an underscore (-); subsequent characters may be letters, dollar signs, underscores, or digits.
2. There are three top-level elements that may appear in a file. None of these elements is required. If they are present, then they must appear in the following order: -package declaration?? ?????? -import statements?? ????? -class definitions?
3. A static method can't be overridden to non-static and vice versa.
4.The variables in an interface are implicitly final and static.If the interface , itself, is declared as public the methods and variables are implicitly public.
5.A final class cannot have abstract methods.
6.All methods of a final class are automatically final.
7. While casting one class to another subclass to superclass is allowed without any type casting. e.g.. A extends B , B b = new A(); is valid but not the reverse.
8. The String class in java is immutable. Once an instance is created, the string it contains cannot be changed. e.g. String s1 = new String("test"); s1.concat("test1"); Even after calling concat() method on s1, the value of s1 will remain to be "test". What actually happens is a new instance is created. But the StringBuffer class is mutable.
9. The short circuit logical Operators && and provide logical AND and OR operations on boolean types and unlike & and , these are not applicable to integral types. The valuable additional feature provided by these operators is the right operand is not evaluated if the result of the operation can be determined after evaluating only the left operand.
10. The difference between x = ++y; and x = y++; In the first case y will be incremented first and then assigned to x. In second case first y will be assigned to x then it will be incremented. The initialization values for different data types in java is as follows ? byte = 0, int = 0, short = 0, char = 'u0000', long = 0L, float = 0.0f, double = 0.0d, boolean = false, ?object referenece(of any object) = null.
11. An overriding method may not throw a checked exception unless the overridden method also throws that exception or a superclass of that exception.
12. Interface methods can't be native, static, synchronized, final, private, protected or abstract.
13. The String class is a final class, it can't be subclassed.
14. The Math class has a private constructor, it can't be instantiated.
15. The two kinds of exceptions in java are : Compile time (Checked ) and Run time (Unchecked) exceptions. All subclasses of Exception except the RunTimeException and its subclasses are checked exceptions. Examples of Checked exception : IOException, ClassNotFoundException.? Examples of Runtime exception :ArrayIndexOutOfBoundsException,NullPointerException, ClassCastException, ArithmeticException, NumberFormatException.
16. The various methods of Java.lang.Object are clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString and wait.?
17. Garbage collection in java cannot be forced. The methods used to call garbage collection thread are System.gc() and Runtime.gc()
18. Inner class may be private, protected, final, abstract or static.
19. An example of creation of instance of an inner class from some other class: class Outer { ??? public class Inner{} } class Another { ??? public void amethod() ??? { ??????? Outer.Inner i = new Outer().new Inner(); ??? } }
20. The range of Thread priority in java is 1-10. The minimum priority is 1 and the maximum is 10. The default priority of any thread in java is 5.
21. There are two ways to mark code as synchronized: a.) Synchronize an entire method by putting the synchronized modifier in the method's declaration. b.) Synchronize a subset of a method by surrounding the desired lines of code with curly brackets ({}).
22. The argument to switch can be either byte, short , char or int.
23. Breaking to a label (using break ;) means that the loop at the label will be terminated and any outer loop will keep iterating. While a continue to a label (using continue ;) continues execution with the next iteration of the labeled loop.
24. A static method can only call static variables or other static methods, without using the instance of the class. e.g. main() method can't directly access any non static method or variable, but using the instance of the class it can.
25. The if() statement in java takes only boolean as an argument. Please note that if (a=true){}, provided a is of type boolean is a valid statement and the code inside the if block will be executed.?
26. The (-0.0 == 0.0) will return true, while (5.0==-5.0) will return false.
27. An abstract class may not have even a single abstract method but if a class has an abstract method it has to be declared as abstract.
28. The default Layout Manager for Panel and Applet is Flow. For Frame and Window its BorderLayout.
29. The FlowLayout always honors the a component's preferred size.
30. The statement float f = 5.0; will give compilation error as default type for floating values is double and double can't be directly assigned to float without casting.
31. The equals() method in String class compares the values of two Strings while == compares the memory address of the objects being compared. e.g. String s = new String("test"); String s1 = new String("test"); s.equals(s1) will return true while s==s1 will return false.
32. The example of array declaration along with initialization - int k[] = new int[]{1,2,3,4,9}; The octal number in java is preceded by 0 while the hexadecimal by 0x (x may be in small case or upper case) e.g. octal :022 hexadecimal :0x12
33. A constructor cannot be native, abstract, static, synchronized or?final.