🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: cn.bbs.comp.lang.java
Article #19215

[ת��]20��Java��Tips

#19215
From: ����
Date: Fri, 09 Jan 2004 02:49
696 lines
25259 bytes
ע��*��ʾ0����������ʾ1������
Object-Oriented Programming
1��Constructor 
û�з���ֵ
���ֻ����һ��������constructor����loseȱʡ���޲����constructor,new xx()���
�?
 
2��Source file layout��
����˳��Package �C >import �C> class declaration
һ���ļ�����Ӧ����һ��class,ֻ����һ��public 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 �C 1)
Short160-215 215 - 1
Char16��\u0000����\u0000�� (0)��\uFFFF�� (216 �C 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. �������IJ����Ƕ��������ʱ�������ֵ�Ƕ���ĵ�ַ������
�ǿ����ڲ������ʱ�ı�ġ�
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;��Ϊ����ĵ�ַ�Dz���ġ� 

10.Java Coding Convention(�������)
Package �C �����Сд
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:null 

2��Bitwise logic Operators
λ�߼���������������Ρ�(byte,char,short,int,long) 

3��>>
�����ǰѵ�һ��������/2�ĵڶ���������η�
e.g
128>>4 returns 128/(2��4�η�) 

4�����ȼ�
��Ǵ� ��������� �����
UlcerUnary+ - ++ �C [[ 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) 

4��>>>
11000>>2 returns 11110
11000>>>2 returns 00110 
Note��
>>>ֻ��int,long��Ч��������byte��short,��>>>֮ǰ��promote��int,���������ۻ�b
yte��short������ͨ��unsigned shift becomes signed shift 

5.<<
128<<4 returns 128*(2���Ĵη�) 

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.(�����ˣ�����ǻ����͵����飬��ar
raycopy���޸�����һ�������ֵ����һ�������Dz���ģ�����Ƕ�������飬��ֵ���
��) 

Inheritance
1.Constructors Are not Inherited 
2.instance of ����������ͣ��࣬�ӿڣ����飩 
3.cast
Up Cast(parent class = subclass) :ֱ����=ת��
Downward(subclass = parent class):���ö�����Ҫת�����Ǹ����������Runtim
e��ʱ����? 
4.OverLoading Method
�����в�ͬ�IJ�������в�ͬ�ķ������� 
5.Overriding Method
����ͬ�ĺ�����������ͣ��ͷ���ֵ��ʵ�ֿ��Բ�һ��������ķ������ܱȸ����
����ķ���Ȩ��С�� 
6.Super
��Constructor�����Ҫ����Super�Ļ�Ӧ��д�ڵ�һ��
Super��ָ��������ø����Constructor
�����Constructor��û�е���Super����Compiler���������ø���ġ�default����Const
ructor
�����û�ж����˽�еġ�default����Constructor����Compile Error 
7�����캯���ʼ��
1���������Ŀռ䣬��instance variable����default value(Boolean->false,Integer
,float->0,reference->null)
2��
2.1��Constructor�IJ���
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��get
Detail�� 
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, null);
 } 
 private String getDetails() {
   return "Name: " + name + "\nSalary: " + salary
       + "\nBirth 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 "\nDept: " + department;
 } 
} 
8���������equals,�������hasCode() 

9.toString
�����Ͷ���Ӧһ����װ���࣬�ڳ�ʼ��ʱ���Դ���String,������Ͳ��ԣ����׳�Numbe
rFormatException 
String->����
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 Lo
cal Variable�ں����и�ֵ�� 
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������I
nner�Ͳ��ܷ���Outer��)��
o.Inner.doSomething() 
5.2 Inner Class ������һ��Outer Class Method�ж��壬�����ܷ���method�е�variab
le(final
Variable����)��Ϊ���method�н���һ��Inner Class���󲢷���Instance,�ⲿ�ô�Ins
tance���ʷ����е�variable������variable���ٴ��ڣ��ͻ���? 
5��3
��Ƕ�������final,abstract,static��,���Դ�public,private��modifier
�����ڵ���Ƕ�಻��Ϊstatic��Ҳ���ܴ��κ�modifier
�����಻���й�������������abstract(���abstract����ʲô�ã�һ�������඼�����¼�
������ʹ��),������static 
5.4 modifier
�����default,����ֻ��ͬ�������
�����protected����ͬһ������û���⣻
����ͬ�������뱻���ʣ�(�ٶ��� B ��Ҫ������ A �е�protected��Ա)
a. B ����̳� A
b. �� B ��, ������ B �� B �� sub-class ��ʵ��������.��Ȼ, Ҳ�����ùؼ���super
�������ԭ��, �ٿ������source, ��֪��, ClassOne�е�getVar()����, �����(defau
lt)
��, ��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 ar
e 
missing too. These keywords aren't allowed because we create anonymous inner 
class through another extension to the new operator syntax. That means the com
plete
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 defi
nition.
It's that simple.
The lack of a class name has a number of implications for the definition and u
se of
inner classes.You can't define contructors for an anonymous inner class becaus
e 
you can't name them. They must always (implicitly) extend a superclass or impl
ements 
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 t
he inheritance tree:
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, null);
}
}
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�Dz����׳��쳣��(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(null)
Ȼ���ڵ��������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 param
eter or be left to use the platform default encoding
InputStreamReader(InputStream in)
InputStreamReader(InputStream in, String encoding);// English :��ISO8859_1",Ch
inese:"GB2312" 
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 
specify the append mode in the second argument. 

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 maintai
ns the pool of Java strings and when a new string is created, it first checks 
if it already exists in memory
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 Ob
ject 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 mem
ory area
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) a
nd will thus cause an Exception at runtime
ÿ��������һ������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 ope
rand is negative negate the result, the sign of right-hand side operand doesn'
t matter.
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 ex
ecution
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 there
 is a matching case like in the above code
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 o
f 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 ex
ecuted. So when new Z() is executed , the object of class X will be constructe
d, which means Y b = new Y() will be executed and "Y" will be printed as a res
ult. After that constructor of X will be called which implies "X" will be prin
ted. Now the object of Z will be constructed and thus Y y = new Y() will be ex
ecuted and Y will be printed and finally the constructor Z() will be called an
d 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, foregroun
d color, background color, etc) are explicitly defined, they are inherited fro
m 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' wil
l 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 ch
eck.
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 <<< operator.

--
No problem???

�� ��Դ:��Ʈ��ˮ�Ƽ� freecity.cnzju.net��[FROM: matianyi]
Technical Details
Message-ID: <4ABh63$A4N@freecity.cnzju.net>
Path: arc1-ca.pugleaf.net!archiver1.google.com!news2.google.com!news.maxwell.syr.edu!elnk-pas-nf1!elnk-nf2-pas!newsfeed.earthlink.net!sjc70.webusenet.com!news.webusenet.com!maily.cic.tsinghua.edu.cn!news.ccie.net.cn!Freecity

Show Full Headers
Complete Article Headers
X-Google-Language: Chinese,GB
X-Google-Thread: f6cb0,503cdf328c9696cd,start
X-Google-Attributes: gidf6cb0,public
X-Google-ArrivalTime: 2004-01-08 18:50:44 PST
Path: arc1-ca.pugleaf.net!archiver1.google.com!news2.google.com!news.maxwell.syr.edu!elnk-pas-nf1!elnk-nf2-pas!newsfeed.earthlink.net!sjc70.webusenet.com!news.webusenet.com!maily.cic.tsinghua.edu.cn!news.ccie.net.cn!Freecity
From: matianyi.bbs@freecity.cnzju.net (����)
Newsgroups: cn.bbs.comp.lang.java
Subject: [ת��]20��Java��Tips
Date: 09 Jan 2004 02:49:24 GMT
Organization: Ʈ��ˮ�Ƽ�
Message-ID: <4ABh63$A4N@freecity.cnzju.net>
Mime-Version: 1.0
Content-Type: text/plain; charset="gb2312"
Content-Transfer-Encoding: 8bit
X-Filename: Java/M.1073615907.A