SCJP Sun Certified Programmer for Java 5 Study Guide (Exam 310-055)

1.需要仔细看一下scjp的chapter3的Certification Objective —Garbage Collection (Exam Objective 7.4)

1、 Chapter 1:
Volatile Variables
The volatile modifier tells the JVM that a thread accessing the variable must always reconcile its own private copy of the variable with the master copy in memory. Say what? Don't worry about it. For the exam, all you need to know about volatile is that, as with transient, it can be applied only to instance variables. Make no mistake, the idea of multiple threads accessing an instance variable is scary stuff, and very important for any Java programmer to understand. But as you'll see in Chapter 11, you'll probably use synchronization, rather than the volatile modifier, to make your data thread-safe.
 On the Job  The volatile modifier may also be applied to project managers :)

 

Chapter1:
1。Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). Identifiers cannot start with a number! 标志符必须以字母,$和下划线开始
2。After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers.所以不能是#,?之类的。只能是字母,$和_或者数字的组合。
3。Inteface constants in interface are public ,final,static,So it can not be assigned in its sub class.
4。a Class can use two access control level,(default or public).members can use all four:public protected default and private.default就是包内可见。Protected就是继承可见和包内可见,对于非继承的情况一律不可见(比如一个Base中的变量i是protected,如果是继承SubCalss中可以使用变量i。但是通过在Base中定义变量,Base b;b.i 出错)
For a subclass outside the package, the protected member can be accessed only through inheritance.

Final字段

Int… t必须是方法参数列表中的最后一个。只能一个

Files with no public classes have no naming restrictions.
"   It must not declare any new checked exceptions for an implementation method.
"   It must not declare any checked exceptions that are broader than the exceptions declared in the interface method.
"   It may declare runtime exceptions on any interface method implementation regardless of the interface declaration.
"   It must maintain the exact signature (allowing for covariant returns) and return type of the methods it implements (but does not have to declare the exceptions of the interface).

"   final variables have the following properties:
"   final variables cannot be reinitialized once assigned a value.
"   final reference variables cannot refer to a different object once the object has been assigned to the final variable.
"   final reference variables must be initialized before the constructor completes.

"   There is no such thing as a final object. An object reference marked final does not mean the object itself is immutable.

   An enum can be declared outside or inside a class, but NOT in a method.
   An enum declared outside a class must NOT be marked static, final, abstract, protected, or private.


表达不错。用于面试
If you find a topic that you are weak in, spend more time reviewing and studying. Many programmers need two or three serious passes through a chapter (or an individual objective) before they can answer the questions confidently.
The following questions will help you measure your understanding of the material presented in this chapter. Read all of the choices carefully, as there may be more than one correct answer. Choose all correct answers for each question. Stay focused.
If you have a rough time with these at first, don't beat yourself up. Be positive. Repeat nice affirmations to yourself like, "I am smart enough to understand enums" and "OK, so that other guy knows enums better than I do, but I bet he can't like me."
出错题:
6.   Given:
1. class Voop {
2.   public static void main(String [] args) {
3.     doStuff(1);
4.     doStuff(1, 2);
5.   }
6.   // insert code here
7. }
Which, inserted independently at line 6, will compile? (Choose all that apply.)
A. static void doStuff(int... doArgs) { }
B. static void doStuff (int [] doArgs) { }
C. static void doStuff(int doArgs...) { }
D. static void doStuff(int... doArgs, int y) { }
E. static void doStuff(int x, int... doArgs) { }

答案是A和E

 


9.   Given:
1. enum A { A }
2. class E2 {
3.   enum B { B }
4.   void C() {
5.     enum D { D }
6.   }
7. }
Which statements are true? (Choose all that apply.)
A. The code compiles.
B. If only line 1 is removed the code compiles.
C. If only line 3 is removed the code compiles.
D. If only line 5 is removed the code compiles.
E. If lines 1 and 3 are removed the code compiles
F. If lines 1, 3 and 5 are removed the code compiles.
答案是D and F 。enum can't be local to a method.

 

2、 Chapter 2
 public class Animal {
   public void eat () { }
}
重载方法:public String eat()。错误的. 因为不是重载.返回类型不一致。

class Animal { }
class Horse extends Animal { }
class UseAnimals {
   public void doStuff(Animal a) {
      System.out.println("In the Animal version");
   }
   public void doStuff(Horse h) {
      System.out.println("In the Horse version");
   }
   public static void main (String [] args) {
      UseAnimals ua = new UseAnimals();
      Animal animalobj = new Horse();
      ua.doStuff(animalobj);
   }
}
输出:
In the Animal version
Even though the actual object at runtime is a Horse and not an Animal, the choice of which overloaded method to call (in other words, the signature of the method) is NOT dynamically decided at runtime
Just remember, the reference type (not the object type) determines which overloaded method is invoked! To summarize, which overridden version of the method to call (in other words, from which class in the inheritance tree) is decided at runtime based on object type, but which overloaded version of the method to call is based on the reference type of the argument passed at compile time

Finally, remember that static methods can't be overridden! This doesn't mean they can't be redefined in a subclass, but redefining and overriding aren't the same thing. Let's take a look at an example of a redefined (remember, not overridden), static method:
class Animal {
  static void dostuff() {
    System.out.print("a ");
  }
}
class Dog extends Animal {
  static void dostuff() {         // it's a redefinition,
                                   // not an override
    System.out.print("d ");
  }
  public static void main (String [] args) {
    Animal [] a = {new Animal(), new Dog(), new Animal()};
    for (int x = 0; x < a.length; x++)
      a[x].doStuff();                // invoke the static method
  }
}
Running this code produces the output:
a a a

1.   Which statement(s) are true? (Choose all that apply.)
A. Has-a relationships always rely on inheritance.
B. Has-a relationships always rely on instance variables.
C. Has-a relationships always require at least two class types.
D. Has-a relationships always rely on polymorphism.
E. Has-a relationships are always tightly coupled
答案是
  B is correct.
    A and D describe other OO topics, C is incorrect because a class can have an instance of , itself. E is incorrect because while has-a relationships can lead to tight coupling, it is by no means always the case.
(Objective 5.5).


2.   Given:
class Clidders {
  public final void flipper() { System.out.println("Clidder"); }
}
public class Clidlets extends Clidders {
  public void flipper() {
    System.out.println("Flip a Clidlet");
    super.flipper();
  }
  public static void main(String [] args) {
    new Clidlets().flipper();
  }
}
What is the result?
A. Flip a Clidlet
B. Flip a Clidder
C. Flip a Clidder
Flip a Clidlet
D. Flip a Clidlet
Flip a Clidder
E. Compilation fails.
答案:
    E is correct. final methods cannot be overridden.
    A, B, C, and D are incorrect based on the above. (Objective 5.3)


5.   Select the two statements that best indicate a situation with low coupling. (Choose two.)
A. The attributes of the class are all private.
B. The class refers to a small number of other objects.
C. The object contains only a small number of variables.
D. The object is referred to using an anonymous variable, not directly.
E. The reference variable is declared for an interface type, not a class. The interface provides a small number of methods.
F. It is unlikely that changes made to one class will require any changes in another.
  E and F are correct. Only having access to a small number of methods implies limited coupling. If the access is via a reference of interface type, it may be argued that there is even less, opportunity for coupling as the class type itself is not visible. Stating that changes in one part of a program are unlikely to cause consequences in another part is really the essence of low coupling. There is no such thing as an anonymous variable. Referring to only a small number of other objects might imply low coupling, but if each object has many methods, and all are used, then coupling is high. Variables (attributes) in a class should usually be private, but this describes encapsulation, rather than low coupling. Of course, good encapsulation tends to reduce coupling as a consequence.
    A, B, C and D are incorrect based on the preceding treatise.
(Objective 5.1)


Given:
 1. class Dog { }
 2. class Beagle extends Dog { }
 3.
 4. class Kennel {
 5.   public static void main(String [] arfs) {
 6.     Beagle bl = new Beagle();
 7.     Dog dogl = new Dog();
 8.     Dog dog2 = bl;
 9.     // insert code here
10. } }
Which, inserted at line 9, will compile? (Choose all that apply.)
A. Beagle b2 = (Beagle) dog1;
B. Beagle b3 = (Beagle) dog2;
C. Beagle b4 = dog2;
D. None of the above statements will compile.
答案是:
    A and B are,correct. However, at runtime, A will throw a claasCastExcepfcion, because dog1 refers to a Dog object, which can't necessarily do Beagle stuff.
    C and D are incorrect based on the preceding.
(Objective 5.2).

 


  表达不错.用于面试
 5.1 Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits. 松耦合.高内聚
This scenario highlights two of the promises/benefits of Object Orientation: flexibility and maintainability
But those benefits don't come automatically. You have to do something. You have to write your classes and code in a way that supports flexibility and maintainability.
 explore this topic
 figure out 估算
It's also important to understand that the two most common reasons to use inheritance are
" To promote code reuse
" To use polymorphism
The software industry has evolved to aid the designer
it was useful to apply the same designs because it reduced the potential to introduce new design errors
Object-oriented designers then started to share these designs with each other. Now, there are many catalogs of these design patterns both on the Internet and in book form.
you have no choice

good OO design calls for loose coupling and shuns tight coupling, and good OO design calls for high cohesion, and shuns low cohesion. As with most OO design discussions, the goals for an application are
" Ease of creation
" Ease of maintenance
" Ease of enhancement
We looked at the difference between overridden and overloaded methods

3、 Chap3
 we're going to worry about only three types of things: instance variables, local variables, and objects:
" Instance variables and objects live on the heap.
" Local variables live on the stack.

class Casting {
  public static void main(String [] args) {
    long 1 = 130L;
    byte b = (byte)1;
    System.out.println("The byte is " + b) ;
  }
}
The code compiles fine, and when we run it we get the following:
%java Casting
The byte is -126
You don't get a runtime error, even when the value being narrowed is too large for the type. The bits to the left of the lower 8 just…go away. If the leftmost bit (the sign bit) in the byte (or any integer primitive) now happens to be a 1, the primitive will have a negative value.
byte b = 3;
b += 7;         // No problem - adds 7 to b (result is 10)
and is equivalent to
byte b = 3;
b = (byte) (b + 7);   // Won't compile without the
                      // cast, since b + 7 results in an int

Int[] ints = new int[5]{};其中的5不能指定长度

 

Integer i1 = 1000;
Integer i2 = 1000;
if(il != i2) System.out.println("different objects");
if(i1.equals(i2)) System.out.println("meaningfully equal");
Produces the output:
different objects
meaningfully equal

It's just two wrapper objects that happen to have the same value. Because they have the same int value, the equals() method considers them to be "meaningfully equivalent", and therefore returns true. How about this one:
Integer i3 = 10;
Integer i4 = 10;
if(i3 == i4) System.out.println("same object");
if(i3.equals(i4)) System.out.println("meaningfully equal");
This example produces the output:
same object
meaningfully equal
Yikes! The equals() method seems to be working, but what happened with = = and != ? Why is != telling us that i1 and i2 are different objects, when = = is saying that i3 and i4 are the same object? In order to save memory, two instances of the following wrapper objects will always be = = when their primitive values are the same:
" Boolean
" Byte
" Character from /u0000 to /u007f (7f is 127 in decimal)
" Short and Integer from -128 to 127

class Boxing2 {
  static Integer x;
  public static void main(String [] args) {
    doStuff(x);
  }
  static void doStuff(int z) {
    int z2 = 5;
    System.out.println(z2 + z);
} }
This code compiles fine, but the JVM throws a NullpointerException when it attempts to invoke doStuff(x), because x doesn't refer to an Integer object, so there's no value to unbox.


class AddBoxing {
  static void go(Integer x) { System.out.println("Integer"); }
  static void go(long x) { System.out.println("long"); }

  public static void main(String [] args) {
    int i = 5;
    go(i);           // which go() will be invoked?
  }
}
答案是 long
the compiler will choose widening over boxing, so the output will be
long


class BoxOrVararg {
  static void go(Byte x, Byte y)
                { System.out.println("Byte, Byte"); }
  static void go(byte... x) { System.out.println("byte... "); }

  public static void main(String [] args) {
    byte b = 5;
    go(b,b);         // which go() will be invoked?
  }
}

As it turns out, the output is   Byte, Byte
可以从Integer 拓宽为long。但不能是Long外覆类


1.   Given:
class Scoop {
  static int thrower() throws Exception { return 42; }
  public static void main(String [] args) {
    try {
      int x = thrower();
    } catch (Exception e) {
      X++;
    } finally {
      System.out.printIn("x = " + ++x);
} } }
What is the result?
A. x = 42
B. x = 43
C. x = 44
D. Compilation fails.
E. The code runs with no output
1.
    D is correct, the variable x is only in scope within the try code block, it's not in scope in the catch or finally blocks. (For the exam, get used to those horrible closing } } } .)
    A, B, C, and E are incorrect based on the above. (Objective 1.3)


2.   Given:
class CardBoard {
  Short story = 5;
  CardBoard go(CardBoard cb) {
    cb = null;
    return cb;
  }
  public static void main(String[] args) {
    CardBoard c1 = new CardBoard();
    CardBoard c2 = new CardBoard();
    CardBoard c3 = c1.go(c2);
    c1 = null;
    // do Stuff
} }
When // doStuff is reached, how many objects are eligible for GC?
A. 0
B. 1
C. 2
D. Compilation fails.
E. It is not possible to know.
F. An exception is thrown at runtime
2.
    C is correct. Only one CardBoard object (c1) is eligible, but it has an associated Short wrapper object that is also eligible.
    A, B, D, E, and F are incorrect based on the above. (Objective 7-4)

3.   Given:
class Alien {
  String invade(short ships) { return "a few"; }
  String invade(short... ships) { return "many"; }
}
class Defender {
  public static void main(String [] args) {
    System.out.println(new Alien().invade(7));
  }
}
What is the result?
A. many
B. a few
C. Compilation fails.
D. The output is not predictable.
E. An exception is thrown at runtime
3.
    C is correct, compilation fails. The var-args declaration is fine, but invade takes a short, so the argument 7 needs to be cast to a short. With the cast, the answer is B, 'a few'.
    A, B, D, and E are incorrect based on the above. (Objective 1.3)

4.   Given:
1. class Dims {
2.   public static void main(String[] args) {
3.     int[] [] a = {{1,2,}, {3,4}};
4.     int [] b = (int [] ) a [1] ;
5.     Object o1 = a;
6.     int [] [] a2 = (int[] [] )   o1;
7.     int [] b2 = (int []) o1;
8.     System.out.println(b[1]);
9. } }
What is the result?
A. 2
B. 4
C. An exception is thrown at runtime.
D. Compilation fails due to an error on line 4.
E. Compilation fails due to an error on line 5.
F. Compilation fails due to an error on line 6.
G. Compilation fails due to an error on line 7.
4.
    C is correct. A ClassCastException is thrown at line 7 because o1 refers to an int [] [] not an int []. If line 7 was removed, the output would be 4.
    A, B, D, E, F, and G are incorrect based on the above. (Objective 1.3)

5.   Given:
class Eggs {
  int doX(Long x, Long y) { return 1; }
  int doX(long... x) { return 2; }
  int doX(Integer x, Integer y) { return 3; }
  int doX(Number n, Number m) { return 4; }
  public static void main(String[] args) {
    new Eggs().go();
  }
  void go () {
    short s = 7;
    System.out.print(doX(s,s) + " ");
    System.out.println(doX(7,7));
} }
What is the result?
A. 1 1
B. 2 1
C. 3 1
D. 4 1
E. 2 3
F. 3 3
G. 4 3
5.
    G is correct. Two rules apply to the first invocation of dox(). You can't widen and then box in one step, and var-args are always chosen last. Therefore you can't widen shorts to either ints or longs, and then box them to Integers.or Longs. But you can box shorts to Shorts and then widen them to Numbers, and this takes priority over using a var-args method. The second invocation uses a simple box from int to Integer.
    A, B, C, D, E, and F are incorrect based on the above, (Objective 3.1)

10.   Which is true? (Choose all that apply.)
A. The invocation of an object's finalize() method is always the last thing that happens before an object is garbage collected (GCed).
B. When a stack variable goes out of scope it is eligible for GC.
C. Some reference variables live on the stack, and some live on the heap.
D. Only objects that have no reference variables referring to them can be eligible for GC.
E. It's possible to request the GC via methods in either java. lang. Runtime or java.lang.System classes.
10.
    C and E are correct. When an object has a reference variable, the reference variable lives inside the object, on the heap.
    A is incorrect, because if, the first time an object's finalize() method runs, the object is saved from the GC, then the second time that object is about to be GCed, finalize() will not run. B is incorrect-stack variables are not dealt with by the GC. D is incorrect because objects can live in "islands of isolation" and be GC eligible. (Objective 7.4)


4、 Chap5
 A switch's expression must evaluate to a char, byte, short, int, or, as of Java 5, an enum. That means if you're not using an enum, only variables and values that can be automatically promoted (in other words, implicitly cast) to an int are acceptable. You won't be able to compile if you use anything else, including the remaining numeric types of long, float, and double.
It's okay for an overriding method to throw the same exceptions, narrower exceptions, or no exceptions. And it's okay for the overriding method to throw any runtime exceptions.

3.   Given:
import java.io.*;
class Master {
  String doFileStuff() throws FileNotFoundException { return "a"; }
}
class Slave extends Master {
  public static void main(String[] args) {
    String s = null;
    try { s = new Slave().doFileStuff();
    } catch ( Exception x) {
      s = "b"; }
    System.out.println(s);
  }
  // insert code here
}
Which, inserted independently at // insert code here, will compile, and produce the output b? (Choose all that apply.)
A. String doFileStuff() { return "b"; }
B. String doFileStuff() throws IOException ( return "b"; }
C. String doFileStuff(int. x) throws IOException ( return "b"; }
D. String doFileStuff() throws FileNotFoundException { return "b"; }
E. String doFileStuff() throws NumberFormatException { return "b"; }
F. String doFileStuff() throws NumberFormatException, FileNotFoundException { return "b"; }
3.
    A, D, E, and F are correct. It's okay for an overriding method to throw the same exceptions, narrower exceptions, or no exceptions. And it's okay for the overriding method to throw any runtime exceptions.
    B is incorrect, because the overriding method is trying to throw a broader exception. C is incorrect. This method doesn't override, so the output is a. (Objective 2.4)

 

5.   Given:
1. class Crivitch {
2.   public static void main(String [] args) {
3.     int x = 0;
4.     // insert code here
5.     do { } while (x++ < y);
6.     System.out.println(x);
7.   }
8. }

Which, inserted at line 4, produces the output 12?
A. int y = x;
B. int y = 10;
C. int y = 11;
D. int y = 12;
E. int y = 13;
F. None of the above will allow compilation to succeed.
5.
    C is correct. x reaches the value of 11, at which point the while test fails. x is then incremented (after the comparison test!), and the println() method runs.
    A, B, D, E, and F are incorrect based on the above. (Objective 2.2)

 

13.   Given:
 1. class Ring {
 2.   final static int x2 = 7;
 3.   final static Integer x4 = 8;
 4.   public static void main(String[] args) {
 5.     Integer x1 = 5;
 6.     String s = "a";
 7.     if(xl < 9) s += "b";
 8.     switch(x1) {
 9.       case 5:  s += "c";
10.       case x2: s += "d";
11.       case x4: s += "e";
12.     }
13.     System.out.println(s);
14.   }
15. }
What is the result?
A. abc
B. abcde
C. Compilation fails due only to an error on line 7.
D. Compilation fails due only to an error on line 8.
E. Compilation fails due only to an error on line 10.
F. Compilation fails due only to an error on line 11.
G. Compilation fails due to errors on multiple lines.
    F is correct. A switch statement requires its case expressions to be constants, and wrapper variables (even final static ones) aren't considered constants, The rest of the code is correct.
    A, B, C, D, E, and G are incorrect based on the above. (Objective 2.1)
s

14 class StringTest{

 public static void main(String[] args){

final String ing="ing";

String s0="string";

String s1="string";

String s2="str"+"ing";

String s3="str"+new String("ing");

String s5="str"+ing;

System.out.println(s0==s1);

System.out.println(s0==s2);

System.out.println(s0==s3);

System.out.println(s0==s3.intern());

System.out.println(s0==s5);

答案:true,true,false,true,true

}

}

15.
class Base
{
String str = "Base";
private void Init(String str){
str = "Base Created!";
print();
System.out.println(this.str);
}
void print(){
System.out.println(str);
}
public Base(){
Init(str);
}
}

class Ext extends Base
{
String str = "Ext";
void print(){
System.out.println(str);
}
public Ext(){
print();
}
}

public class MyMain
{
public static void main(String[] argv){
new Ext();
}
}
参考答案:
null  Base  Ext

16.
public class Test {
 public static void main(String[] as) {
  final StringBuffer s1 = new StringBuffer();
  final StringBuffer s2 = new StringBuffer();

  new Thread() {
   public void run() {
    synchronized (s1) {
     s2.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();
 }
}
答案:
ABABCD

17 

import java.util.regex.*;
class RegexSmall {
    public static void main(String[] args) {
        Pattern p = Pattern.compile("//d+");
        Matcher m = p.matcher("1 a12 234b");
        boolean b = false;
        while(b = m.find()) {
            System.out.print(m.start() + " ");
        }
    }
}
答案:0 3 6
18
 
public class test {
    public static void main(String[] args) {
        try{
           unsafe();
           System.out.println(“Test1”);
           return;
        }catch(SafeException e){
           System.out.println(“Test 2”);
        }finally{
           System.out.println(“Test 3”);
        }
        System.out.println(“Test 4”);
    }
}
如果正常:test1,test3
如果不正常:test2,test3,test4

19.请简要的说明一下transient fields, volatile fields有什么特点?
Java Virtual Machine是怎么处理Boolean类型的?
请简要的说明一下JVM的Constant Pool?
java.util.Timer与javax.swing.Timer的区别?
请结合MVC设计模式,简要描述swing中与表格相关的各个组成部分。

你可能感兴趣的:(读书笔记,java,sun,variables,string,class,integer)