Friday, September 10, 2010

Enhancements in JAVA 5

Please refer to http://download.oracle.com/javase/1.5.0/docs/guide/language/


JAVA Variable Arguments


Variable Arguments (Varargs)

Varargs can be used only in the final argument position.

So when should you use varargs? As a client, you should take advantage of them whenever the API offers them. Important uses in core APIs include reflection, message formatting, and the new printf facility. As an API designer, you should use them sparingly, only when the benefit is truly compelling. Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called.


(*^__^*)

Wednesday, September 8, 2010

String, StringBuffer, StringBuilder



String is immutable whereas StringBuffer and StringBuilder can change their values.

What is the difference between StringBuffer and StringBuilder?

The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.

Criteria to choose among String, StringBuffer and StringBuilder

1. If your text is not going to change use a String Class because a String object is immutable.
2. If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.
3. If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.

StringBuilder was introduced in JDK 1.5. According to javadoc, StringBuilder is designed as a replacement for StringBuffer in single-threaded usage. Their key differences in simple term:

* StringBuffer is designed to be thread-safe and all public methods in StringBuffer are synchronized. StringBuilder does not handle thread-safety issue and none of its methods is synchronized.

* StringBuilder has better performance than StringBuffer under most circumstances.

* Use the new StringBuilder wherever possible.

Other than that, the two classes are remarkably similar with compatible API.


(^_ end _^)

About

My photo
Petaling Jaya, Selangor, Malaysia