2010年9月12日 星期日

JAVA-CORE 面試題

Question: How could Java classes direct program messages to the system console, but error messages, say to a file?

Answer: The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:

Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);

Question: Why would you use a synchronized block vs. synchronized method?

Answer: Synchronized blocks place locks for shorter periods than synchronized methods.

Question: Explain the usage of the keyword transient?

Answer: This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

Question: How can you force garbage collection?

Answer: You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.

Question: What's the difference between the methods sleep() and wait()

Answer: The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

Question: Can you call one constructor from another if a class has multiple constructors

Answer: Yes. Use this() syntax.

Question: How would you make a copy of an entire Java object with its state?

Answer: Have this class implement Cloneable interface and call its method clone().

clone() 預設是 重新配置一塊記憶體,並予以 copy ,
所以內容與原來的是一模一樣, 但是分屬不同的空間
所以 x.clone() 當然不等於 x


Inner Class 和 Nested Class

  1. What is nested class? - If all the methods of a inner class is static then it is a nested class.
  2. What is inner class? - If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class.

Inner Classes 與 Nested Classes
[class-modifiers] class OuterClassName {
  ‥‥
  [inner-class-modifiers] class InnerClassName {
    ‥‥
  }
  [nested-class-modifiers] static class StaticClassName {
    ‥‥
  }
  ‥‥
}


Inner Class
Java 將 Inner Class 分為下列 3 類
‧ 一般的 Inner Class
指的是將 class 宣告在 class 內
[語法]
[class-modifiers] class EnclosingClass {
  [inner-class-modifiers] class InnerClass {
    // Write Codes Here
  }
}
 inner-class-modifiers 可以是 public、protected、private、final、strictfp、abstract、static(會變成static nested class)

1. 若在 enclosing class 之外建立 inner class 的 instance,必須先建立 enclosing class 的 instance。
 [範例]
 EnclosingClass.InnerClass obj = new EnclosingClass( ).new InnerClass( );
 或是
 EnclosingClass objX = new EnclosingClass( );
 EnclosingClass.InnerClass objY = objX.new InnerClass( );

2. 所有的 inner class 會隱性參考(reference) 其 enclosing class,其型式為 "EnclosingClass.this"
 [範例]
 public class MyEnclosingClass {
   private String someMember = "Some Member";
   private class MyInnerClass {
     private String someMember = "Inner Member";
     public void doIt( ) {
       System.out.println(someMember);  // 印出 Inner Member
       System.out.println( MyEnclosingClass.this.someMember );  // 印出 Some Member
     }
   }

   public static void main(String[ ] args) {
     new MyEnclosingClass( ).new MyInnerClass( ).doIt( );
   }
 }

3. non-static inner class 可存取包含該 inner class 的所有的 members。
4. inner class 內不能宣告 static members,inner class 內所有 members 必須是 instance members,但是 inner classes 可
 存取 enclosing class 的 static members。
 唯一的例外是,inner classes 內可宣告 static 和 final 的 fields(compile-time constant)。

[範例]
class HasStatic {
static int j = 100;
}
class Outer {
class Inner extends HasStatic {
static final int x = 3; // ok - compile-time constant
static int y = 4; // compile-time error, an inner class
}
static class NestedButNotInner {
static int z = 5; // ok, not an inner class
}
interface NeverInner { } // interfaces are never inner
}


‧ Method local Inner Class
1. local class 為定義在 method 內的 class,其 scope 在該 method 內
2. 當 inner class 定義在 method 內,則該 class 只可以存取 enclosing class 宣告為 final 的 variables(或稱為 automatic 或 local variables)

[範例]
public class MyInnerClass {
static String msg = "Hello";

public static void main(String[ ] av) {
class Inner {
public void doSomeWork( ) { // print member of enclosing class
System.out.println(msg);
}
}
Inner p = new Inner( );
p.doSomeWork( );
}
}


‧ Anonymous Inner Class
1. anonymous nested class 必須實作某個 interface 或是繼承某個 class,但是不使用 implements 或 extends 關鍵字做宣告。
2. anonymous class 內不能宣告 constructor,可宣告 instance initializer 做初值設定
[註] anonymous class 的類別名稱可用 this.getClass( ).getName( ) 觀察

[範例]
return new SomeClass( ) {  /*body of the anonymous class goes here*/  };

[範例]
someMethod(new SomeClass( ) {  /*body of the anonymous class goes here*/  } );

Nested Class
Nested Classes 也是 inner class 的一種型式,但是 Java 將宣告為 static 的 inner class 稱為 Nested Class
‧ Static Nested Classes
1. nested classes 即為所謂的 static inner classes
 nested classes 有點像似 top-level classes,enclosing class 提供這種類型的 class 一個 package-like 的架構,nested classes 可
 存取 enclosing class 所有的 members。但是 nested class 比 inner class 有更多的限制。
2. static nested class 可以合用修飾字 abstract。
 [註] 注意,一般而言,在 class 內你不能宣告 static methods 為 abstract。
3. 可直接建立 nested class 的 instance,不需先建立 enclosing class 的 instance。
 EnclosingClass.NestedClass obj = new EnclosingClass.NestedClass( );
4. nested class 只能存取 enclosing class 的 static members(private 權限的 members 亦可)
 
[範例]
public class MyEnclosingClass {
  private static String staticMember = "Static Member";
  private String someMember = "Some Member";
  static class MyNestedClass {
    public void doIt( ) {
      System.out.println(staticMember);
    }
  }

  public static void main(String[ ] args) {
    new MyNestedClass( ).doIt( );
    // new MyInnerClass( ); // ERROR
  }

  class MyInnerClass {
    // static String InnerStaticMember = "Inner Static Member"; // Error:inner classes cannot have static declarations
    public void doIt( ) {
      System.out.println(staticMember + ", " +myStaticFinalConstant);
    }
    static final int myStaticFinalConstant = 0; // OK
  }
}


※ inner interface 與 inner class 混用
1. interface 內的 inner interface 預設為 public static,class 內的 inner interface 預設為 static,存取權限可以為 private/protected/public/default
2. class 的 inner class 內不能再有 inner interface,否則會出現編譯錯誤:inner classes cannot have static declarations
3. Interface 的 Inner Class 內可以有 Inner Interface
4. Interface 內可以有 Inner class
5. Inner Interface 可以繼承 Outer Intreface
6. Inner Class 可以繼承 Outer Class 或 implments Outer Interface

[範例]
public class X {
  class Y {
    private void f( ) { }
  }
  class Z extends Y {
    { // initializer
      f( );    // 編譯錯誤
      this.f( );  // 編譯錯誤
      ((Y)this).f( ); // 可過編譯
      super.f( ); // 可過編譯
    } //end initializer
  }
} // end class X

2010年9月11日 星期六

java 面試題 (2) English

Q:

What is the difference between an Interface and an Abstract class?

A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

Q:

What is the purpose of garbage collection in Java, and when is it used?

A: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

Q:

Describe synchronization in respect to multithreading.

A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.

Q:

Explain different way of using thread?

A: The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.

Q:

What are pass by reference and passby value?

A: Interface Pass By Reference means the passing the address itself rather than passing the value. Pass By Value means passing a copy of the value to be passed.

Q:

What is HashMap and Map?

A: Map is Interface and Hashmap is class that implements that.

Q:

Difference between HashMap and HashTable?

A: The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.

Q:

Difference between Vector and ArrayList?

A: Vector is synchronized whereas arraylist is not.

Q:

Difference between Swing and Awt?

A: AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.

Q:

What is the difference between a constructor and a method?

A: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.
Q:

What is an Iterator?

A: Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.

Q:

State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.

A: public : Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package
.

Q:

What is an abstract class?

A: Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.

Q:

What is static in java?

A: Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

例子:
底下程式看起來像是可以用一般的override來看待,其實不然
如果overridemethodstatic,實際執行的method會是宣告型別的method而不是實際型別的method

程式:

class Question30Super{

public static void printSomething(){

System.out.println("In Question30Super");

}

}

public class Question30 extends Question30Super {

public static void main(String[] args){

Question30Super q30 = new Question30();

q30.printSomething();

}

public static void printSomething(){

System.out.println("In Question30");

}

}

執行結果:

In Question30Super

Q:

What is final? (Immutable?)

A: A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).


Servlet Life Cycle and TOMCAT (multi-threaded server)

http://www.iam.ubc.ca/guides/javatut99/servlets/lifecycle/index.html

Each servlet has the same life cycle:

  • A server loads and initializes the servlet
  • The servlet handles zero or more client requests
  • The server removes the servlet
    (some servers do this step only when they shut down)



Initializing a Servlet:

When a server loads a servlet, the server runs the servlet's init method. Initialization completes before client requests are handled and before the servlet is destroyed.

Even though most servlets are run in multi-threaded servers, servlets have no concurrency issues during servlet initialization. The server calls the init method once, when the server loads the servlet, and will not call the init method again unless the server is reloading the servlet. The server can not reload a servlet until after the server has destroyed the servlet by calling the destroy method.


Interacting with Clients:

After initialization, the servlet is able to handle client requests.

Destroying a Servlet:

Servlets run until the server are destroys them, for example, at the request of a system administrator. When a server destroys a servlet, the server runs the servlet's destroy method. The method is run once; the server will not run that servlet again until after the server reloads and reinitializes the servlet.

=================

Tomcat is a multi-threaded servlet container

this means that each request needs to be executed by some thread. Prior to Tomcat 3.2, the default was to create a new thread to serve each request that arrives. This behavior is problematic for loaded sites because:

  • Starting and stopping a thread for every request puts a needless burden on the operating system and the JVM.
  • It is hard to limit the resource consumption. If 300 requests arrive concurrently Tomcat will open 300 threads to serve them and allocate all the resources needed to serve all the 300 requests at the same time. This causes Tomcat to allocate much more resources (CPU, Memory, Descriptors...) than it should and it can lead to low performance and even crashes if resources are exhausted.

The solution for these problems is to use a thread pool, which is the default for Tomcat 3.2. Servlet containers that are using a thread pool relieve themselves from directly managing their threads. Instead of allocating new threads; whenever they need a thread they ask for it from the pool, and when they are done, the thread is returned to the pool. The thread pool can now be used to implement sophisticated thread management techniques, such as:

  1. Keeping threads "open" and reusing them over and over again. This saves the trouble associated with creating and destroying threads continuously.
    • Usually the administrator can instruct the pool not to keep too many idle threads, freeing them if needed.
  2. Setting an upper bound on the number of threads used concurrently. This prevents the resources allocation problem associated with unlimited thread allocation.
    • If the container maxed out to the threads upper limit, and a new request arrives, the new request will have to wait for some other (previous) request to finish and free the thread used to service it.

You can refine the techniques described above in various ways, but these are only refinements. The main contribution of thread pools is thread-reuse and having a concurrency upper bound that limits resource usage.

Using a thread pool in Tomcat is a simple move; all you need to do is to use a PoolTcpConnector in your configuration. For example the following server.xml fragment defines ajpv12, pooled Connector:


2010年9月10日 星期五

Cygwin bash_profile 的 path

方法 1:
=====================
export ALT_BOOTDIR=`cygpath -s -m "F:/Program Files/Java/jdk1.5.0_14"`
export ALT_BINARY_PLUGS_PATH=F:/JDKSource/jdk-6-ea-plug-b08-windows-i586-26_mar_2008/openjdk-binary-plugs
export ALT_MSVCRT_DLL_PATH=`cygpath -s -m "C:/WINDOWS/system32"`
export ALT_MSVCR71_DLL_PATH=C:/WINDOWS/system32

export DXSDK_DIR=`cygpath -s -m "H:/Program Files/Microsoft DirectX SDK (February 2007)"`
export ALT_COMPILER_PATH=`cygpath -s -m "H:\Program Files\Microsoft Visual Studio 8\VC\bin"`


方法 2:
====================

It seems to be a quoting problem. This is what I was doing:

$ ttt="$(cygpath -u "$JAVA_HOME")"

$ echo $ttt
/cygdrive/c/Program Files/Java/jdk1.5.0_10

$ cd $ttt
bash: cd: /cygdrive/c/Program: No such file or directory

$ cd "$ttt"

$pwd
/cygdrive/c/Program Files/Java/jdk1.5.0_10

Is is possible to setup the variable to not require the double quotes?
Since my other method doesn't require the double quotes, it would
make the scripting much easier. I wouldn't need to keep track of which
variables I had to double quote.

$ tttt="$(cygpath -u "$(cygpath -m -s "$JAVA_HOME")")"

$ echo $tttt
/cygdrive/c/PROGRA~1/Java

$ cd $tttt

$ pwd
/cygdrive/c/PROGRA~1/Java

Notice that I can use $tttt directly without have to use the double quote.

int 和 Integer 的差別

所謂的 int 是像上位前輩所說的~
int 是所謂的 premitive type 就是所謂的原紿資料型態~
而 Integer 是 Java 的內建類別型態~

int a = 5; == int a;
a =5;

只是說有個變數名稱是 a ,定義為 int 的型態~有給值 5 給到a~

Integer a=new Integer(5);
裡面的 Integer 是個類別名稱~
而 new Integer(5) 是說建立一個 Integer 類別的實體 a ~
而實體內是個 int 型態的值 5~

所以意思就是說~一個是定義變數的原紿資料型態~
而另一個是建立了一個 Java 的內建類別的實體~
如果你使用了 Integer 類別的話~
()<=裡面的值就”必需”是要為 int or String 的資料型態~如果想看詳細一點~
可以查看 Java 官方網站的 Doucumaentaion ~裡面有很詳細的介紹~
不知道我這樣講會不會讓你更不了解了~^^"

2010年8月2日 星期一

Framework: Hibernate

Java Hibernate程式的過程中,我們可以粗分四大步驟(1~4) 與二大檔案(5、6),依序是 :

1. Configuration

1.1. 透過 Configuration File (hibernate.cfg.xml) 設定與 Database 連線的方式與設定要匯入哪些 Mapping File。

1.2 (JavaEE 環境) 透過 JNDI Service 來註冊 org.hibernate.SessionFactory 成為 Global 物件。

1.3 (JavaEE 環境) 設定 AP Server 所提供的 Transaction 的功能。

1.4. 透過 org.hibernate.cfg.Configuration 的 configure() mathod 來讀取 Configuration File。

1.5 透過 org.hibernate.cfg.Configuration 的 buildSessionFactory() 來產生 下一步驟要用到的 org.hibernate.SessionFactory

2. SessionFactory

2.1 一個 org.hibernate.SessionFactory 只對應到一個 Database

2.2 必須在程式要使用之前就必須建立好 SessionFactory,因為需要一點時間才能建立,所以最好是在網站或程式初始化時就去建立,至少必須在程式開始接觸 Database 之前就要建立。

2.3 必須放在所有程式都可以取用到地方 ( 有 JNDI 就註冊到 JNDI 中, 如果沒有 JNDI, 且是Web Apps, 也可以註冊在 ServletContext)。

2.4 org.hibernate.SessionFactory 會 catch 執行 Hibernate 所產生的 SQL statement 和 Database 的 metadata。

2.5 org.hibernate.SessionFactory 是 thread-safe 物件,會自己處理 multi-thread。

2.6 透過 org.hibernate.SessionFactoryopenSession() 或是 getSession() 來 產生/取得 下一步驟要用到的 org.hibernate.Session

3. Session:

3.1 org.hibernate.Session 包含了 JDBC 的 Connection object。

3.2 所以可以視為 Hibernate 與 Database 之間溝通的橋樑、過程。

3.3 org.hibernate.Session 可以提供 org.hibernate.Transaction object

3.4 所以存取 Persistent Class 都需要透過 org.hibernate.Session

4. Transaction:

4.1 org.hibernate.Transaction 將真正在底層執行 Transaction service包裝起來,

在 J2EE 中使用 JTA 的 UserTransaction 服務多個 Database (ex: 轉帳);或利用 J2SE 中 JDBC 的 Transaction 來服務一個 Databae。

4.2 在 Hibernate 3.x 中,存取 Persistent Class 的動作一定要包在 org.hibernate.Transaction 的可視範圍之中。

例如:

Transaction transaction = session.beginTransaction();

存取 Persistent Class ...
......

transaction.commit();

5. Persistance Class:

5.1 最好是 JavaBeans 的架構。

5.2 使用 Hibernate 來處理的 Table 一定要有 primary key,且對應到 Java Class 中的 欄位與 setter,為了避免誤改,所以都應該宣告為 private 屬性。primary key 是獨一無二的 id,所以在選定時最好避免與目前專案相關性太高的欄位,應儘量使用流水號。

5.3 不要使用 final。Hibernte 會自動為每個 Persistent Class 產生各自的 proxy,但 proxy 會繼承 Persistent Class,所以一旦設為 final,將會限制 proxy 所提供的功能。

5.4 要小心處理 Persistent Class 的三種狀態:
transient : 尚未跟 Persistent Context 接觸。( 與 Session 沒有關係的狀態 )
persistent : 正在跟 Persistent Context 接觸。
detached : 以前曾經跟 Persistent Context 接觸,但現在分開了。

6. Hibernate Mapping File:

6.1 每一個 Persistent Class 都會有自己的 Mapping File,以維護 Table 與 Persistent Class 的對應關係。

6.2 Mapping File 的副檔名為 .hbm.xml

6.3 Mapping File 的存放位置必須跟所對應的 Persistent Class 的目錄相同。

6.4 在使用 Mapping File 之前必須註冊到 Configuration file 中,通常使用靜態的方法,直接寫入 hibernate.cfg.xml 中。