Thursday, May 05, 2005

SCJP reading 2

注:*表示0或多个;+表示1个或多个
  Object-Oriented Programming
  1.Constructor
  没有返回值
  如果只定义一个带参数的constructor,则lose缺省的无参数的constructor,new xx()会
  2.Source file layout:   定义顺序:Package ? >import ?> class declaration
  一个文件至少应该有一个class,只能有一个public class,文件名必须要和public class
  3.Package:
  如果文件中没声明Package,则class属于缺省包,即没有名字的包
  Identifiers,Keywords,and Type
  1.Identifiers:
  开头以Unicode letter,”_”和”$”。后面可以跟数字;(中文变量,方法名居然都可
  大小写敏感;
  没有长度限制。
  Warning:
  类名必须是ASCII的字母。因为很多文件系统不支持UNICODE.(不过我试了一下,类名是
中文的,Compile的时候是可以通过,Runtime时throw java.lang.NoClassDefFoundError)
  2.Keywords:
  几个 很生僻的Keywords:
  transient,strictfp,volatile
  没有goto和const;没有sizeof()。
  4.Basic Java Type:
  共8种。
  Boolean和integer Type之间不能转化。
  5.Integral:
  Byte:8bit -2的7次方~2的7次方-1
  short:16bit
  int:32bit
  long:64bit
  6.Floating point
  float:32bit
  double:64bit
  浮点形默认是double.
  float a = 1.02 //compile error
  float a = 1.02f or float a = 1.02F //correct
  7.类型的取值范围
  Data TypeSize (bits)Initial ValueMin ValueMax Value
  boolean1false falsetrue
  Byte80-128 (-27)127 (27 ? 1)
  Short160-215 215 - 1
  Char16‘u0000’‘u0000’ (0)‘uFFFF’ (216 ? 1)
  Int320-231 231 - 1
  Long640L-263 263 - 1
  Float320.0F1.4E-453.4028235E38
  Double640.04.9E-3241.7976931348623157E308

  8.Assignment of Reference Type
  基本类型的赋值是值的赋值;int x =6; int y = x;相当于复制x的内容到y上。
  对象的赋值不会赋值内容,两个对象的指针都是指向同一个object..
  9.Pass by Value
  Pass argument by Value. 当方法的参数是对象的引用时,参数的值是对象的地址,对象
  Public class test{
  Public static void changeObject(MyDate ref){
  Ref = new MyDate(1,2,2002);
  }
  public static void main(String[] arv){
  MyDate d = new MyDate(3,3,1988);
  ChangeObject(d);
  }
  }
  结果是d还是为1988,3,3;因为对象的地址是不变的。
  10.Java Coding Convention(编码惯例)
  Package ? 名词且小写
  Class--名词且第一个字母大写
  Interface?同Class
  Methods-动词且第一个字母小写,分隔词第一个字母大写,不用”-“
  Variable?第一个字母小写,不用”_”,”$”(对于inner class有意义)
  Constants?大写并用”_”
  Expression and Flow Control
  1.
  Local variables?Variable defined in method

  Instance variables?Variable defined outside method
  Instance variable initialize:
  byte,short,int,long,float,double:0
  boolean:false
  char:’u0000’
  all reference type:
  2.Bitwise logic Operators
  位逻辑运算符作用于整形。(byte,char,short,int,long)
  3.>>
  右移是把第一个操作数/2的第二个操作数次方
  e.g   128>>4 returns 128/(2的4次方)
  4.优先级
  助记词 运算符类型 运算符
  UlcerUnary+ - ++ ? [[ rest...]],()cast   AddictsArithmetic (and shift)* / % + - << >>
  ReallyRelational> < >= <= == !=
  LikeLogical (and bitwise)&& || & | ^   CConditional (ternary)A > B ? X : Y
  A LotAssignment= (and compound assignment like *=)
  Note:
  对于int,其实是右移右操作数的求32的模;对于long,其实是右移右操作数的求64的模
  int y = x >> 32 ,y没有改变,而不是0.(我试了一下,byte和short分别右移8和16,结果都为0)
  Note:
  >>>只对int,long有效。如果对于byte和short,在>>>之前先promote成int,右移完再折
回byte或short,这样,通常unsigned shift becomes signed shift

  6.+
  short x =5;
  short y=6;
  short z=x+y;//compile error
  因为+的结果最小起码是int
  7.cast
  7.if()要求的是一个boolean表达式
  if(x) //int x cause error
  use if(x!=0)
  8.switch(exp1)
  exp1必须是和int兼容,(byte,short,int,char)
  float,long,和类指针(String)都不允许。
  9.label:statement
  statement必须是循环(break 还可以是switch)
  Array:
  1.初始化
  s = new char[5] //initialize for ‘u0000’
  2.多维数组的定义
  int [][] a = new int [2][];
  a[0] = new int[4];
  a[1] = new int[6];
  System.out.println(a.length);
  System.out.println(a[0].length);
  Result:
  2
  4
  3.数组的复制
   int a[]={1,2,3};
   int b[]={4,5,6,7,8,9};
   System.arraycopy(a,0,b,0,a.length);
  Result:
  b[]={1,2,3,7,8,9}
  Note:
  System.arraycopy拷贝的是引用,而不是Object.(我试了,如果是基本类型的数组,用
arraycopy后,修改其中一个数组的值,另一个数组是不变的;如果是对象的数组,则值会改
  Inheritance
  1.Constructors Are not Inherited
  2.instance of 检查对象的类型(类,接口,数组)
  3.cast
  Up Cast(parent class = subclass) :直接用=转化
  Downward(subclass = parent class):如果该对象不是要转化的那个对象,则会在
  4.OverLoading Method
  必须有不同的参数,可以有不同的返回类型
  5.Overriding Method
  有相同的函数名,参数类型,和返回值,实现可以不一样。并且子类的方法不能比父类的
  6.Super
  在Constructor中如果要调用Super的话应该写在第一行
  Super能指定参数调用父类的Constructor
  如果在Constructor中没有调用Super,则Compiler会隐含调用父类的”default”的
  如果父类没有定义非私有的“default”的Constructor,则Compile Error
   7.构造函数初始化   1.分配对象的空间,把instance variable设置default value(Boolean->false,Integer,float->0,reference->)
  2.
  2.1绑定Constructor的参数
  2.2如果有this(),跳到2.5
  2.3递归调用implicit 或explicit的super
  2.4执行instance variable的explict的赋值
  2.5执行当前的Constructor.
  7.Constructor的Rule
  在Constructor中调用的函数应为私有函数。
  因为如果超类Employee的Constructor中有公有函数getDetail,类Manager继承Employee,
而manager中override此函数getDetail,声明一个manager的对象时会递归调用Employee的
Constructor,而因为是runtime check,实际上Emplyee中调用的getDetail是Manager的
  public class Emploee extends Object {
   private String name;
   private double salary = 15000.00;
   private Date birthDate;
   private String summary;
   public Emploee(String n, Date DoB) {
   name = n;
   birthDate = DoB;
   summary = getDetails();
   }
   public Emploee(String n) {
   this(n, );
   }
   private String getDetails() {
   return "Name: " + name + " Salary: " + salary
   + " Birth Date: " + birthDate;
   }
   public static void main(String[] arg)
   {
   Manager m = new Manager("2","gl");
   }
  }
  class Manager extends Emploee {
   private String department;
   public Manager(String n, String d) {
   super(n);
   department = d;
   }
   public String getDetails() {
   return " Dept: " + department;
   }
  }
  8.如果重载equals,最好重载hasCode()
  9.toString
  基本类型都对应一个封装的类,在初始化时可以传入String,如果类型不对,会抛出
NumberFormatException

  int x = Integer.valueof(str).intValue();

  int x = Integer.parseInt(str);
  Advanced Class Features
  1.Static的方法不能被override
  2.Final Method
  2.1.Final方法不能被override
  2.2.Static和private的方法都被默认为Final方法。
  3.Final Variable
  3.1.Final Reference:指向对象的内容可以改变,但不能改变指向的对象。
  3.2.A Blank Final Instance Variable:在Constructor中赋值,而A Blank Final
  4.Abstract
  如果子类没有实现父类(抽象类)的Abstract方法,则该方法继续声明为Abstract
  5.Inner Class
  5.1 new Inner Class
  Outer o = new Outer();
  Outer.Inner i = o.new Inner();
  i.doSomething();
  如果Inner类定义为static(Inner的函数定义为static则Inner也要定义为 static,这样
  o.Inner.doSomething()
  5.2 Inner Class 可以在一个Outer Class Method中定义,但不能访问method中的
  Variable除外)因为如果method中建立一个Inner Class对象并返回Instance,外部用此
Instance访问方法中的variable,如果该variable不再存在,就会出错。
  5.3
  内嵌类可以是final,abstract,static的,可以带public,private等modifier
  方法内的内嵌类不能为static,也不能带任何modifier
  匿名类不能有构造器,不能是abstract(如果abstract还有什么用,一般匿名类都是在事
  5.4 modifier
  如果是default,就是只能同包里访问
  如果是protected,在同一个包内没问题;
  若不同包里,如果想被访问,(假定类 B 中要访问类 A 中的protected成员)
  a. B 必须继承 A
  b. 在 B 中, 必须用 B 或 B 的 sub-class 的实例来访问.当然, 也可以用关键字super
  根据以上原则, 再看上面的source, 会知道, ClassOne中的getVar()方法, 如果是
  的, 在ClassTest中, 始终找不到这个方法.---compile-error
  如果是 protected 的, 则必须用ClassTest的实例来调用.
  char a = new ClassOne().getVar(); --- compile-error
  // char a = new ClassTest().getVar(); ----OK

  // char a = super.getVar(); --- OK
  // char a = getVar(); --- OK
  5.5外面一层的类不能声明成protect和pravite的
  5.6 Interface
  Interface的method默认为public,abstract,no-static
  变量默认为public,final,static
  5.7关于匿名类的描述。
  Anonymous inner class are local inner classes that don't have a class name.
  You use an anonymous class when you want to create and use a class but don't
  want to bother with giving it a name or using it again.
  When use an anonymous inner class ,the keyword class is missing,and there are
  no modifers(public,protected,and so on). The kewords extends and implements
  missing too. These keywords aren't allowed because we create anonymous inner
  class through another extension to the new operator syntax. That means the
  class definition is actually part of a java expression. Right after the
  new someClass() syntax,you write a curly brace and start to write a class
  It's that simple.
  The lack of a class name has a number of implications for the definition and
  inner classes.You can't define contructors for an anonymous inner class
  you can't name them. They must always (implicitly) extend a superclass or
  some interface,even though you never use the extends or implements keywords.
  5.8 Interface
  interface can extend several interfaces
  e.g
  interface q
  {
  }
  interface p
  {
  }
  interface qq extends q,p
  {
   String s = "interface";
  }
  is OK
  5.9 构造顺序
  First.
  the memory for the complete object is allocated and the default values for
the instance variables are assigned.(或static变量的赋值)
  Second,
  the top-level constructor is called and follows these steps recursively down
  1. Bind constructor parameters.
  2. If explicit this(), call recursively and then skip to step 5.
  3. Call recursively the implicit or explicit super(...), except for
  Object because Object has no parent class.
  4. Execute explicit instance variable initializers.({ }也在这时候执行)
  5.Execute body of current constructor.
  e.g 1.
  class Employee extends Object {
  private String name;
  private double salary = 15000.00;
  private Date birthDate;
  public Employee(String n, Date DoB) {
  // implicit super();
  name = n;
  birthDate = DoB;
  }
  public Employee(String n) {
  this(n, );
  }
  }
  public class testchild extends Employee {

  private String department;
  public testchild(String n, String d) {
  super(n);
  department = d;
  }
  public static void main(String[] args)
  {
   testchild t = new testchild("x","d");
   }
  }
  e.g 2
  class X1
  {
   Y b = new Y();
   X1()
   {
   System.out.print("X");
   }
  }
  class Y
  {
   Y()
   {
   System.out.print("Y");
   }
  }
  public class test extends X1
  {
   static int x=10;
   Y y = new Y();
   {
   int i=20;
   }
   static
   {
   int xx=10;
   }
   test()
   {
   System.out.print("Z");
   }
   public static void main(String[] args)

   {
   test t = new test();
   }
  }
  Exception
  1.try/catch/finally
  不执行finally的唯一情况:System.exit()
  2.ArithmeticException
  浮点数除0是不会抛出异常的(ArithmeticException)
  如float x = (float)5.0/0
  0.0/0 = NAN(not a number)
  FPN/0 =POSITIVE_INFINITE
  -FPN/0 =NEGATIVE_INFINITE
  3.函数可以throw多个exception
  4.函数override如果抛出异常必须是父类函数异常或异常的子集(p322)
  5.继承图
  àError
  Throwable--|
  àException
  Text Based Application
  1.command line???(p335)
  2.p345??
  3.Collection/List/Set
  Collection:无序元素可重复
  List:有序元素可重复
  (ArrayList:this implementation is not synchronized)
  Set:无序元素不可重复。
  (StoreSet,TreeSet:排序,TreeSet: this implementation is not synchronized)
  4.ListIterator
  Add是把元素插入到指针当前位置之前,所以在Add后调用Previous是指向新元素。
  AWT
  1.Component/Container
  GUI component 是Component或MenuComponent的子类
  Container是Component的子类
  Panel是Container的子类
  Component
  |
  Container
  |
  ------------------------------
  ||
  Panel Window
  ||
  Applet-----------------------------------------
  ||
  Frame(title and resize) Dialog(can’t resize)

  Panel必须放到Window中去显示
  3.Layout manager
  Layout manager负责组件在容器中的位置和大小。(不基于平台)
  如果你必须要改动组件的位置和大小。
  Container.setLayout()
  然后在调用组件的SetLocation,SetSize,SetBounds
  4.Frame
  Frame必须可见(setVisible(true))和设定大小(setSize)
  5.Default Layout Mannager
  Window/Frame/Dialog---BorderLayout
  Panel/Applet---FlowLayout
  6.
  Applet
  IO
  1.InputStreamReader/OutputStreamWriter
  Converting between Bytes and Characters
  The StreamReader and Writer classes can take either a character encoding
parameter or be left to use the platform default encoding
  InputStreamReader(InputStream in)
  InputStreamReader(InputStream in, String encoding);// English :“
  2.Streams operate on bytes while Readers/Writers operate on chars.
  FileReader/FileWriter---FileInputStream/FileOutputStream
  构造函数直接对(String)文件名或File操作
  New FileWriter(“filename”) or FileOutputStream(“filename”) will overwrite
if “filename” is existing or create a new file, if not existing. But we can
  Others
  1.String
  substring(int,int),the second arg is exclusive.= [ )
  还有一些是做模题的笔记:
  1.==
  Comparing two strings with == operator checks for memory address to which the
object reference is referring to. Java uses the concept of pooling. It maintains
the pool of Java strings and when a new string is created, it first checks if it
  Eg
   String s3 = "arit";
   String s4 = "arit";
   String s2 = s1.replace('m','r');
   System.out.println(s2 == s3);
   System.out.println(s3 == s4);
  Output:
  False
  True
  (pratice 1:1)
  2.equals()
  if equals() method is not defined in 自定义的class, the equals() method of
Object class, the parent class will be used. The equals() method of Object class
returns true when two object references being compared, point to the same memory
  e.g
  class MyClass
  {
  int x;
  MyClass(int i){x = i;}
  public static void main(String args[])
  {
  MyClass m1 = new MyClass(100);
  MyClass m2 = new MyClass(100);
  System.out.println(m1.equals(m2))
  }
  }
  output:
  false
  (pratice 1:4)
  3. wait/notify
  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)
  每个对象含有一个机锁(lock,monitor),当你调用任何一个synchronized函数时,对象
被锁定,该对象其他synchronized函数无法被调用,直到第一个函数执行完毕并解锁。
  Wait/notify属于Object一部分;wait和sleep区别是wait会将机锁释放掉。
  (pratice 1:6)
  4.Logical /Bitwise operators
  Logical: AND(&&), OR(||) , NOT(!)用于boolean,(短路short-circuiting)
  Bitwise:
  AND(&),OR(|),XOR(^)?用于基本类型的Bits,boolean
  NOT(~) 只用于基本类型的Bits
  (pratice 1:15)
  5. there can't be more than one public class/interface
  6.%
  To calculate a % b(a modulus b), the simplest way is, drop any negative signs
from both the operands and calculate the result. Now if the left-hand side
operand is negative negate the result, the sign of right-hand side operand
  e.g
   int a = -5; int b = -2;
   System.out.println(a % b);
   a = -5;b = 2;
   System.out.println(a % b);
   a = 5;b = -2;
   System.out.println(a % b);
  Output:
  -1
  -1
  1
   7.yield()
  The yield() method simply returns control back to the JVM, and unless there
is a higher priority thread ready to run, this thread will continue or resume
  e.g
  public class ThreadTest extends Thread
  {
  public void run()
  {
  System.out.println("In run");
  yield();
  System.out.println("Leaving run");
  }
  public static void main(String args [])
  {
  (new ThreadTest()).start();
  }
  }
  output:
  The text "In run" followed by "Leaving run" will be displayed.
  8.swtich
  The default statement need not be at the end and will not be executed if
  e.g
   switch(k)
  {
   default:
   System.out.println("This is the default output");
   break;
   case 10:
   System.out.println("ten");
   case 20:
   System.out.println("twenty");
   break;
   }
  output:
  ten
  twenty
  9.
  Prefixing a number with a zero indicates that it is in Octal format
  e.g
   int i = 012;
   System.out.println(i);
  Output:
  10.
  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.
  class X1
  {
   Y b = new Y();
   X1()
   {
   System.out.print("X");
   }
  }
  class Y
  {
   Y()
   {
   System.out.print("Y");
   }
  }
  public class test extends X1
  {
   Y y = new Y();
   test()
   {
   System.out.print("Z");
   }
   public static void main(String[] args)
   {
   test t = new test();
   }
  }
  11. instanceof
  instanceof后面可以跟类名,接口名,居然还可以跟数组!(Object)
  e.g compile succeed
   x instanceof int[]
  x instanceof String[]
  12.AWT
  In all cases, unless a component's attributes (font type, font size,
foreground color, background color, etc) are explicitly defined, they are
inherited from the surrounding container
  13. ThreadGroup
  14.sleep
  sleep会 throws InterruptedException,一定注意要加上try/catch
  15.
  int i = 10, j = 3, k = 7;
   int p = 30;    p += k -= j <<= i %= 4;
   System.out.println("i = " + i);
   System.out.println("j = " + j);
   System.out.println("k = " + k);
   System.out.println("p = " + p);
  Output:
  i = 2
  j = 12
  k = -5
  p = 25
  16.byte溢出
  void infiniteLoop()
  {
  byte b = 1;   while ( ++b > 0 );
  System.out.println("Welcome to My World!");

  }
  output:
  the variable 'b' will go up to 127. After that overflow will occur and 'b'
will be set to -ve value, the loop ends and prints "Welcome to My World!".
  17.Integer/Long/Float/Double/String/StringBuffer is final
  18. only the casting of object references may potentially require a runtime
  e.g
   int n=25600;
   byte b=(byte)n;
  都溢出了,居然没错!没天理,b=0;
  19.native
  native
  e.g. generally use static intitializer
  static {
  System.loadLibrary("NativeLib");
  }
  native void nativeMethod();
  20. not a <<<>

No comments: