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题库会经常出现的,祝你好运!) 大家可以把下面我提供的完整程序去认真的编译运行验证一下! //大家将注释掉的和未注释的程序分别运行! ******************************************************** 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是方法进口的参数必须不一样,它的返回值可以不同的!这类题型肯定要考到的!方式可能不一样,但抓住上面的要点就不会错了!
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.