Monday, January 9, 2012

Collections API

The Collections API is a set of classes and interfaces that support operations on collections of objects.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

 The Collection interface is the root of all collections except maps.
List
The List interface provides support for ordered collections of objects but may contain duplicate elements.Lists
implement the List interface. 
 Set 
A Set stores elements in an unordered way and does not contain duplicate elements.Sets implement the Set
interface.
Queues 
A queue is a collection that orders its elements in a specifi c order for processing.
A typical queue processes its elements in a fi rst - in, fi rst - out (FIFO) fashion, but other
ordering is possible. Queues implement the Queue interface.
Map 
A map is a collection that maps keys to values, with no duplicate keys allowed.
The elements in a map are key - value pairs. Maps implement the Map interface, which is
unique because the Map interface is not a sub interface of Collection like the other types of
collections.
 

Wrapper Classes

Data in a Java application is either an object or a primitive data type. There are situations
in Java where only an object can be used and primitive types do not work. For example, the
classes in the Collections API can only hold Object references. The wrapper classes provide
the ability to treat primitive types as objects by wrapping the primitive in an Object . This
section discusses how to wrap a primitive type into its corresponding wrapper class.The wrapper classes are defined in the java.lang package and are used in
situations where an object is required but the data is a primitive type. The primitive type is
“ wrapped ” into an object and can be “ unwrapped ” whenever the primitive value is needed.
There is a wrapper class in the java.lang package for each of the eight primitive types:
 
Byte This type wraps a byte .
Short This type wraps a short .
Integer This type wraps an int .
Long This type wraps a long .
Float This type wraps a float .
Double This type wraps a double .
Character This type wraps a char .
Boolean This type wraps a boolean .


Wrapper classes have the following properties:

#Each of the wrapper classes contains a single field that holds the value it is wrapping.
#The value of the wrapped primitive type cannot be changed.
#Each class has a constructor that takes in the data type it wraps.
#Except for Character , each class has a constructor that takes in a String that is
#automatically parsed into the corresponding primitive type.

#Each wrapper class has a “ value ” method that unwraps the primitive type. For
example, the Float class has a floatValue method that returns the float .
Let ’ s look at an example. The following code wraps an int into an Integer object:
int x = 357;
Integer w = new Integer(x);
The Integer class has a method named intValue that unwraps the int :
int y = w.intValue();

Design Patterns types


Design Patterns types
Creational Patterns
Factory Pattern

Abstract Factory Pattern

Singleton Pattern

Builder Pattern

Prototype Pattern
Structural Patterns
Adapter Pattern

Bridge Pattern

Composite Pattern

Decorator Pattern

Facade Pattern

Flyweight Pattern

Proxy Pattern
Behavioral Patterns
Chain of Responsibility Pattern

Command Pattern

Interpreter Pattern

Iterator Pattern

Mediator Pattern

Momento Pattern

Observer Pattern

State Pattern

Strategy Pattern

Template Pattern

Visitor Pattern


Design Patterns

The design patterns are language-independent strategies used to solve common object-oriented design issues (problems). When you design a problem, you should know some common solutions. It makes communication between team players easier, effective and result oriented.
A good software-developer should know at least some popular solutions to the coding problems. These solutions prove efficient and effective to the new breed of developers as they are gradually developed by the experienced developers. Such solutions are described as so-called design patterns

Sunday, January 8, 2012

Autoboxing and Unboxing

As of Java 5.0, you no longer need to write the code to wrap primitive types into their corresponding
wrapper class; the compiler now does this for you behind the scenes. The term      autoboxing refers to the compiler automatically converting a primitive type into its corresponding
wrapper class. The term unboxing refers to the compiler automatically unwrapping
a primitive type from its wrapper object. Autoboxing and unboxing do not require
any special syntax. The compiler realizes situations where primitives need to be boxed or
unboxed. For example, if an int needs to be treated as an object, it automatically becomes
an Integer . Similarly, an Integer automatically becomes an int whenever necessary.
Before autoboxing, you would wrap a primitive by instantiating a new wrapper object:
Integer w = new Integer(10);
With autoboxing, you simply assign a wrapper class reference to a primitive type:
Integer w = 10;
Behind the scenes, the compiler instantiates a new Integer object for the int 10 .
Similarly, the compiler unboxes a wrapped primitive whenever necessary. The following
statements are valid:
5. Double pi = 3.14159;
6. double radius = 10.0;
7. double area = pi * radius * radius;
The Double object on line 5 is automatically instantiated and wraps the value 3.14159 .
On line 7, pi is automatically unwrapped into a double before the multiplication occurs.
Before unboxing, we would have used the doubleValue method:
double area = pi.doubleValue() * radius * radius;
The autoboxing occurs whenever the compiler realizes that a primitive needs to be
wrapped in its corresponding wrapper class. For example, the ScoreKeeper class from the
previous section contains the following method:
public void addScore(Object score) {
scores.add(score);
}
The following statements are valid method invocations of addScore :
keeper.addScore(50);
keeper.addScore(23.4);
keeper.addScore(18.5F);
Behind the scenes, the 50 is converted to an Integer , 23.4 is converted to a Double , and
18.5F is converted to a Float .

Object DeSerialization with The ObjectInputStream Class

An ObjectInputStream deserializes objects from an input stream. It is a high - level stream
that needs to be chained to a low - level stream that represents the source of the serialized
objects. You should know how to use FileInputStream with ObjectInputStream , and I
discuss an example of using these two classes as we deserialize the two Contact2 objects
from the SerializeDemo program in the previous sectionThe ObjectInputStream class contains read methods that correspond to the write methods
of ObjectOutputStream , including public Object readObject() throws IOException,
ClassNotFoundException .
The readObject method deserializes the next object in the stream. Note the reference
type of the return value is Object . Typically we need to cast the reference to its appropriate
class type.
The following DeserializeDemo program deserializes two objects from the mycontacts.
ser fi le created in SerializeDemo .

1. package com.sybex.io;
2.
3. import java.io.*;
4. import java.util.GregorianCalendar;
5.
6. public class DeserializeDemo {
7. public static void main(String [] args) {
8. try {
9. File contactsFile = new File(“mycontacts.ser”);
10. FileInputStream fis =
11. new FileInputStream(contactsFile);
12. ObjectInputStream in = new ObjectInputStream(fis);
13.
14. while(fis.available() > 0) {
15. Object obj = in.readObject();
16. if(obj instanceof Contact2) {
17. Contact2 contact = (Contact2) obj;
18. System.out.println(contact);
19. System.out.println(“city = “
20. + contact.getCity());
21. }
22. }
23.
24. in.close();
25. fis.close();
26. }catch(IOException e) {
27. e.printStackTrace();
28. }catch(ClassNotFoundException c) {
29. c.printStackTrace();
30. }
31. }
32. }
The while loop on line 14 reads in objects from the mycontacts.ser fi le until the stream
is empty. Two objects are in the fi le, so the while loop executes twice. The instanceof
comparison on line 16 is true for both objects and line 18 prints the Contact2 object,
outputting the result of its toString method. I added line 19 to explicitly illustrate that
the city fi eld did not get serialized because it was declared transient . Transient fi elds are
ignored during serialization and initialized to their “ zero ” value during deserialization,
which for references is null . The output of the DeserializeDemo program is Bugs Bunny 22 2025551212
city = null
Daffy Duck 33 3035551212
city = null
By the way, the GregorianCalendar objects were also serialized, but the toString
method for GregorianCalendar prints out a lot of information, so I purposely left it out of
the toString method of Contact2 . (We discuss formatting dates in detail later in this chapter.)
If you open mycontacts.ser in a text editor, you will clearly see the two Gregorian-
Calendar objects serialized in the fi le.


Object Serialization with The ObjectOutputStream Class

An ObjectOutputStream writes Serializable objects to an output stream. It is a high - level
stream that needs to be chained to a low - level stream that represents the destination of the
serialized objects. The upcoming SerializeDemo program demonstrates using FileOutput-
Stream with ObjectOutputStream .
1. package com.sybex.io;
2.
3. import java.io.*;
4. import java.util.GregorianCalendar;
5.
6. public class SerializeDemo {
7. public static void main(String [] args) {
8. try {
9. GregorianCalendar bday1 =
10. new GregorianCalendar(1950, 3, 21);
11. GregorianCalendar bday2 =
12. new GregorianCalendar(1956, 5, 30);
13. Contact2 one = new Contact2(“Bugs Bunny”, 2214. 2025551212L, bday1, “Toontown”);
15. Contact2 two = new Contact2(“Daffy Duck”, 33,
16. 3035551212L, bday2, “Toontown”);
17.
18. File contactsFile = new File(“mycontacts.ser”);
19. FileOutputStream fos =
20. new FileOutputStream(contactsFile);
21. ObjectOutputStream out = new ObjectOutputStream(fos);
22.
23. out.writeObject(one);
24. out.writeObject(two);
25.
26. out.close();
27. fos.close();
28. }catch(IOException e) {
29. e.printStackTrace();
30. }
31. }
32. }
There is no output, but the SerializeDemo program does create a new fi le named my
contacts.ser that contains two serialized objects of type Contact2 . The lines of code
to focus on in this program are lines 23 and 24. Calling writeObject and passing in a
Contact2 reference serializes the object and writes it to the mycontacts.ser fi le.

The Serializable Interface

The Serializable interface is a tagging interface, which means it does not have any methods
in it. A class implements Serializable to let the JVM know that instances of the class
can be serialized. There is no extra work on your part to make a class serializable because
there are no methods in the interface. Your main concern with implementing Serializable
is ensuring that all the fi elds in your class are also Serializable . If an attempt is
made to serialize an object and a fi eld is reached during the serialization process that is not
serializable, the JVM throws a NotSerializableException and the serialization fails. The
compiler does not verify whether or not your fi elds are Serializable . Denote a fi eld as
transient (using the transient keyword) to tell the JVM to ignore the fi eld during the serialization
and deserialization process.

Object Serialization

Object serialization refers to taking the state of an object and writing it to a stream.
You can use serialization to persistently store your objects in fi les. You can also serialize
an object and send it across the network to another Java program or save it in a database.
Deserialization refers to the process of reading the data from an object stream and
reconstituting the object in memory. Not all objects can be serialized; only objects whose
classes implement the java.io.Serializable interface . Let ’ s take a look at this interface
and what it means to implement it.

Thursday, January 5, 2012

Final Methods

A method in Java can be declared final using the final keyword. A final method cannot be
overridden. You might make a method fi nal if it has a critical implementation that should
not be changed, or you might just want a child class not to have the option of overriding
a particular method. Whatever the motivation, an attempt to override a final method
generates a compiler error.
The following Lion class has a final method named breathe :
1. public class Lion {
2. public void eat(String something) {
3. System.out.println(“Lion is eating”);
4. }
Declaring Methods 137
5.
6. public final void breathe() {
7. System.out.println(“Lion is breathing”);
8. }
9. }
No subclass of Lion can override the breathe method, but let ’ s try it anyway and see
what happens. The following MountainLion class extends Lion and declares a breathe
method:
1. public class MountainLion extends Lion {
2. public void breathe() {
3. System.out.println(“MountainLion is breathing”);
4. }
5. }
As expected, this does not compile. Here is the compiler error that it generates:
MountainLion.java:2: breathe() in MountainLion cannot override breathe() in
Lion; overridden method is final
public void breathe() { }

JDBC DRIVERS

4 types of JDBC drivers
Type 1 : JDBC-ODBC bridge
It is used for local connection.
ex) 32bit ODBC in windows
Type 2 : Native API connection driver
It is connected by the Native Module of dependent form of h/w like .dll or .so.
ex) OCI driver for local connection to Oracle
Type 3 : Network connection driver
Type 4 : Database Protocol driver
It is independent from h/w because this driver is in Java.
ex) thin driver for local/global connection to Oracle
*** Type1, type 2, and type 3 are usually used.

THREAD STATES

A thread takes on various states from the time that it starts to the point when its run
method completes execution. You should be able to recognize the various thread states and
how a thread transitions from one state to another. This section discusses the details of
these various states.
The Thread class defines the following method for obtaining the current state of a
thread:
public Thread.State getState()
Thread.State is an enumeration defined in the Thread class that represents all the
possible states of threads. The Thread.State enumeration has the following values:
NEW The thread has been instantiated but not started yet.
RUNNABLE The thread is either currently running on the CPU or waiting to be scheduled by
the JVM for execution.
BLOCKED The thread is waiting for a monitor lock to become available. A thread becomes
blocked when attempting to enter a block of synchronized code.
WAITING The thread is waiting for another thread to perform a particular action. For
example, the thread might be waiting for another thread to call Object.notify on a specifi
c object or waiting for another thread to terminate due to a call to Thread.join .
TIMED_WAITING This state is similar to WAITING except the thread only waits until a specifi
ed time elapses. A thread enters this state with a call to Thread.join or Object.notify
with a timeout, or Thread.sleep .
TERMINATED The thread has run to completion. A terminated thread cannot be started
again.

THREAD_CREATION IN JAVA

 A thread has two components:
A thread object that gets started and has a priority and state, and is scheduled to run
by the JVM
A runnable target that contains the code that executes when the thread object finally
gets to the CPU
The Thread class represents a thread object in Java, and the Runnable interface is used to
defi ne a runnable target. You can write a thread two ways in Java:
Write a class that implements Runnable and then pass an instance of your Runnable
class into the constructor of a new Thread object. When the Thread object is started
and reaches the CPU, the run method of the Runnable object is invoked.
Write a class that subclasses the Thread class and overrides the run method. (The
Thread class implements Runnable .) When your Thread object is started and reaches
the CPU, the overridden run method is invoked.
In either option, you implement the run method defined in the Runnable interface and
instantiate a new Thread object. The run method has the following signature:
public void run()
The run method represents the code that executes when the Thread object gets scheduled
to run. Before a thread can run, it needs to be started. Once started, a thread is alive
until the run method finishes executing, either by running to completion or throwing an
exception.

STRINGBUILDER AND STRINGBUFFER

The java.lang package contains two classes for representing strings as a mutable sequence
of characters: StringBuilder and StringBuffer . The StringBuffer class has been around
since the fi rst version of Java, while StringBuilder was added in J2SE 5.0. The two classes
have the exact same method signatures and constructor parameters. The only difference
between them is that StringBuffer is thread - safe and StringBuilder is not. If you are
working with arrays of characters in a multithreaded application, use the StringBuffer
class. Otherwise, if threads are not an issue for your particular situation, use the String-
Builder class.

JAVA STRING

The new keyword is not required for creating the String object “How are you?” because
it is a string literal. String literals get special treatment by the JVM. Behind the scenes,
the JVM instantiates a String object for “How are you?” and stores it in the string pool.
The greeting reference refers to this String object in the pool. Because String objects
in Java are immutable (which means they cannot be changed), the JVM can optimize the
use of string literals by allowing only one instance of a string in the pool. For example,
the following two String references actually point to the same string in the pool,