Monday, March 28, 2011

Object Ordering

A List l may be sorted as follows.Collections.sort(l);If the List consists of String elements, it will be sorted into alphabetical order. If it consists of Date elements, it will be sorted into chronological order. How does this happen? String and Date both implement the Comparable interface. Comparable implementations provide a natural ordering for a class, which allows objects of that class to be sorted automatically. The following table summarizes some of the more important Java platform classes that implement Comparable.Classes Implementing ComparableClass Natural OrderingByte Signed numericalCharacter Unsigned numericalLong Signed numericalInteger Signed numericalShort Signed numericalDouble Signed numericalFloat Signed numericalBigInteger Signed numericalBigDecimal Signed numericalBoolean Boolean.FALSE < Boolean.TRUEFile System-dependent lexicographic on path nameString LexicographicDate ChronologicalCollationKey Locale-specific lexicographicIf you try to sort a list, the elements of which do not implement Comparable, Collections.sort(list) will throw a ClassCastException. Similarly, Collections.sort(list, comparator) will throw a ClassCastException if you try to sort a list whose elements cannot be compared to one another using the comparator. Elements that can be compared to one another are called mutually comparable. Although elements of different types may be mutually comparable, none of the classes listed here permit interclass comparison. This is all you really need to know about the Comparable interface if you just want to sort lists of comparable elements or to create sorted collections of them. The next section will be of interest to you if you want to implement your own Comparable type. Writing Your Own Comparable Types The Comparable interface consists of the following method.public interface Comparable { public int compareTo(T o);}The compareTo method compares the receiving object with the specified object and returns a negative integer, 0, or a positive integer depending on whether the receiving object is less than, equal to, or greater than the specified object. If the specified object cannot be compared to the receiving object, the method throws a ClassCastException.The following class representing a person's name implements Comparable. import java.util.*; public class Name implements Comparable { private final String firstName, lastName; public Name(String firstName, String lastName) { if (firstName == null lastName == null) throw new NullPointerException(); this.firstName = firstName; this.lastName = lastName; } public String firstName() { return firstName; } public String lastName() { return lastName; } public boolean equals(Object o) { if (!(o instanceof Name)) return false; Name n = (Name)o; return n.firstName.equals(firstName) && n.lastName.equals(lastName); } public int hashCode() { return 31*firstName.hashCode() + lastName.hashCode(); } public String toString() { return firstName + " " + lastName; } public int compareTo(Name n) { int lastCmp = lastName.compareTo(n.lastName); return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName)); }}To keep the preceding example short, the class is somewhat limited: It doesn't support middle names, it demands both a first and a last name, and it is not internationalized in any way. Nonetheless, it illustrates the following important points:Name objects are immutable. All other things being equal, immutable types are the way to go, especially for objects that will be used as elements in Sets or as keys in Maps. These collections will break if you modify their elements or keys while they're in the collection.The constructor checks its arguments for null. This ensures that all Name objects are well formed so that none of the other methods will ever throw a NullPointerException.The hashCode method is redefined. This is essential for any class that redefines the equals method. (Equal objects must have equal hash codes.)The equals method returns false if the specified object is null or of an inappropriate type. The compareTo method throws a runtime exception under these circumstances. Both of these behaviors are required by the general contracts of the respective methods.The toString method has been redefined so it prints the Name in human-readable form. This is always a good idea, especially for objects that are going to get put into collections. The various collection types' toString methods depend on the toString methods of their elements, keys, and values.Since this section is about element ordering, let's talk a bit more about Name's compareTo method. It implements the standard name-ordering algorithm, where last names take precedence over first names. This is exactly what you want in a natural ordering. It would be very confusing indeed if the natural ordering were unnatural!Take a look at how compareTo is implemented, because it's quite typical. First, you compare the most significant part of the object (in this case, the last name). Often, you can just use the natural ordering of the part's type. In this case, the part is a String and the natural (lexicographic) ordering is exactly what's called for. If the comparison results in anything other than zero, which represents equality, you're done: You just return the result. If the most significant parts are equal, you go on to compare the next most-significant parts. In this case, there are only two parts — first name and last name. If there were more parts, you'd proceed in the obvious fashion, comparing parts until you found two that weren't equal or you were comparing the least-significant parts, at which point you'd return the result of the comparison. Just to show that it all works, here's a program that builds a list of names and sorts them. import java.util.*; public class NameSort { public static void main(String[] args) { Name nameArray[] = { new Name("John", "Lennon"), new Name("Karl", "Marx"), new Name("Groucho", "Marx"), new Name("Oscar", "Grouch") }; List names = Arrays.asList(nameArray); Collections.sort(names); System.out.println(names); }}If you run this program, here's what it prints.[Oscar Grouch, John Lennon, Groucho Marx, Karl Marx]There are four restrictions on the behavior of the compareTo method, which we won't go into now because they're fairly technical and boring and are better left in the API documentation. It's really important that all classes that implement Comparable obey these restrictions, so read the documentation for Comparable if you're writing a class that implements it. Attempting to sort a list of objects that violate the restrictions has undefined behavior. Technically speaking, these restrictions ensure that the natural ordering is a total order on the objects of a class that implements it; this is necessary to ensure that sorting is well defined.Comparators What if you want to sort some objects in an order other than their natural ordering? Or what if you want to sort some objects that don't implement Comparable? To do either of these things, you'll need to provide a Comparator — an object that encapsulates an ordering. Like the Comparable interface, the Comparator interface consists of a single method.public interface Comparator { int compare(T o1, T o2);}The compare method compares its two arguments, returning a negative integer, 0, or a positive integer depending on whether the first argument is less than, equal to, or greater than the second. If either of the arguments has an inappropriate type for the Comparator, the compare method throws a ClassCastException.Much of what was said about Comparable applies to Comparator as well. Writing a compare method is nearly identical to writing a compareTo method, except that the former gets both objects passed in as arguments. The compare method has to obey the same four technical restrictions as Comparable's compareTo method for the same reason — a Comparator must induce a total order on the objects it compares. Suppose you have a class called Employee, as follows. public class Employee implements Comparable { public Name name() { ... } public int number() { ... } public Date hireDate() { ... } ...}Let's assume that the natural ordering of Employee instances is Name ordering (as defined in the previous example) on employee name. Unfortunately, the boss has asked for a list of employees in order of seniority. This means we have to do some work, but not much. The following program will produce the required list.import java.util.*;public class EmpSort { static final Comparator SENIORITY_ORDER = new Comparator() { public int compare(Employee e1, Employee e2) { return e2.hireDate().compareTo(e1.hireDate()); } }; // Employee database static final Collection employees = ... ; public static void main(String[] args) { Liste = new ArrayList(employees); Collections.sort(e, SENIORITY_ORDER); System.out.println(e); }}The Comparator in the program is reasonably straightforward. It relies on the natural ordering of Date applied to the values returned by the hireDate accessor method. Note that the Comparator passes the hire date of its second argument to its first rather than vice versa. The reason is that the employee who was hired most recently is the least senior; sorting in the order of hire date would put the list in reverse seniority order. Another technique people sometimes use to achieve this effect is to maintain the argument order but to negate the result of the comparison.// Don't do this!!return -r1.hireDate().compareTo(r2.hireDate());You should always use the former technique in favor of the latter because the latter is not guaranteed to work. The reason for this is that the compareTo method can return any negative int if its argument is less than the object on which it is invoked. There is one negative int that remains negative when negated, strange as it may seem.-Integer.MIN_VALUE == Integer.MIN_VALUEThe Comparator in the preceding program works fine for sorting a List, but it does have one deficiency: It cannot be used to order a sorted collection, such as TreeSet, because it generates an ordering that is not compatible with equals. This means that this Comparator equates objects that the equals method does not. In particular, any two employees who were hired on the same date will compare as equal. When you're sorting a List, this doesn't matter; but when you're using the Comparator to order a sorted collection, it's fatal. If you use this Comparator to insert multiple employees hired on the same date into a TreeSet, only the first one will be added to the set; the second will be seen as a duplicate element and will be ignored.To fix this problem, simply tweak the Comparator so that it produces an ordering that is compatible with equals. In other words, tweak it so that the only elements seen as equal when using compare are those that are also seen as equal when compared using equals. The way to do this is to perform a two-part comparison (as for Name), where the first part is the one we're interested in — in this case, the hire date — and the second part is an attribute that uniquely identifies the object. Here the employee number is the obvious attribute. This is the Comparator that results. static final Comparator SENIORITY_ORDER = new Comparator() { public int compare(Employee e1, Employee e2) { int dateCmp = e2.hireDate().compareTo(e1.hireDate()); if (dateCmp != 0) return dateCmp; return (e1.number() < e2.number() ? -1 : (e1.number() == e2.number() ? 0 : 1)); }};One last note: You might be tempted to replace the final return statement in the Comparator with the simpler:return e1.number() - e2.number();Don't do it unless you're absolutely sure no one will ever have a negative employee number! This trick does not work in general because the signed integer type is not big enough to represent the difference of two arbitrary signed integers. If i is a large positive integer and j is a large negative integer, i - j will overflow and will return a negative integer. The resulting comparator violates one of the four technical restrictions we keep talking about (transitivity) and produces horrible, subtle bugs. This is not a purely theoretical concern; people get burned by it.

Trail: Collections

This chapter describes the Java Collections Framework. Here you will learn what collections are and how they can make your job easier and programs better. You'll learn about the core elements — interfaces, implementations, and algorithms — that comprise the Java Collections Framework. Introduction tells you what collections are, and how they'll make your job easier and your programs better. You'll learn about the core elements that comprise the Collections Framework: interfaces, implementations and algorithms. Interfaces describes the core collection interfaces, which are the heart and soul of the Java Collections Framework. You'll learn general guidelines for effective use of these interfaces, including when to use which interface. You'll also learn idioms for each interface that will help you get the most out of the interfaces. Implementations describes the JDK's general-purpose collection implementations and tells you when to use which implementation. You'll also learn about the wrapper implementations, which add functionality to general-purpose implementations. Algorithms describes the polymorphic algorithms provided by the JDK to operate on collections. With any luck you'll never have to write your own sort routine again! Custom Implementations tells you why you might want to write your own collection implementation (instead of using one of the general-purpose implementations provided by the JDK), and how you'd go about it. It's easy with the JDK's abstract collection implementations! Interoperability tells you how the Collections Framework interoperates with older APIs that predate the addition of Collections to Java. Also, it tells you how to design new APIs so that they'll interoperate seamlessly with other new APIs. Lesson: Introduction to Collections A collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. Typically, they represent data items that form a natural group, such as a poker hand (a collection of cards), a mail folder (a collection of letters), or a telephone directory (a mapping of names to phone numbers).If you've used the Java programming language — or just about any other programming language — you're already familiar with collections. Collection implementations in earlier (pre-1.2) versions of the Java platform included Vector, Hashtable, and array. However, those earlier versions did not contain a collections framework. What Is a Collections Framework? A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following:Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.Implementations: These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality.Apart from the Java Collections Framework, the best-known examples of collections frameworks are the C++ Standard Template Library (STL) and Smalltalk's collection hierarchy. Historically, collections frameworks have been quite complex, which gave them a reputation for having a steep learning curve. We believe that the Java Collections Framework breaks with this tradition, as you will learn for yourself in this chapter. Benefits of the Java Collections Framework The Java Collections Framework provides the following benefits:Reduces programming effort: By providing useful data structures and algorithms, the Collections Framework frees you to concentrate on the important parts of your program rather than on the low-level "plumbing" required to make it work. By facilitating interoperability among unrelated APIs, the Java Collections Framework frees you from writing adapter objects or conversion code to connect APIs.Increases program speed and quality: This Collections Framework provides high-performance, high-quality implementations of useful data structures and algorithms. The various implementations of each interface are interchangeable, so programs can be easily tuned by switching collection implementations. Because you're freed from the drudgery of writing your own data structures, you'll have more time to devote to improving programs' quality and performance.Allows interoperability among unrelated APIs: The collection interfaces are the vernacular by which APIs pass collections back and forth. If my network administration API furnishes a collection of node names and if your GUI toolkit expects a collection of column headings, our APIs will interoperate seamlessly, even though they were written independently.Reduces effort to learn and to use new APIs: Many APIs naturally take collections on input and furnish them as output. In the past, each such API had a small sub-API devoted to manipulating its collections. There was little consistency among these ad hoc collections sub-APIs, so you had to learn each one from scratch, and it was easy to make mistakes when using them. With the advent of standard collection interfaces, the problem went away.Reduces effort to design new APIs: This is the flip side of the previous advantage. Designers and implementers don't have to reinvent the wheel each time they create an API that relies on collections; instead, they can use standard collection interfaces.Fosters software reuse: New data structures that conform to the standard collection interfaces are by nature reusable. The same goes for new algorithms that operate on objects that implement these interfaces.

Get started with the Java Collections

JDK 1.2 introduces a new framework for collections of objects, called the Java Collections Framework. "Oh no," you groan, "not another API, not another framework to learn!" But wait, before you turn away, hear me out: the Collections framework is worth your effort and will benefit your programming in many ways. Three big benefits come immediately to mind: It dramatically increases the readability of your collections by providing a standard set of interfaces to be used by many programmers in many applications.It makes your code more flexible by allowing you to pass and return interfaces instead of concrete classes, generalizing your code rather than locking it down.It offers many specific implementations of the interfaces, allowing you to choose the collection that is most fitting and offers the highest performance for your needs. And that's just for starters. Our tour of the framework will begin with an overview of the advantages it provides for storing sets of objects. As you'll soon discover, because your old workhorse friends Hashtable and Vector support the new API, your programs will be uniform and concise -- something you and the developers accessing your code will certainly cheer about. After our preliminary discussion, we'll dig deeper into the details. The Java Collections advantage: An overviewBefore Collections made its most welcome debut, the standard methods for grouping Java objects were via the array, the Vector, and the Hashtable. All three of these collections have different methods and syntax for accessing members: arrays use the square bracket ([]) symbols, Vector uses the elementAt method, and Hashtable uses get and put methods. These differences have long led programmers down the path to inconsistency in implementing their own collections -- some emulate the Vector access methods and some emulate the Enumeration interface. To further complicate matters, most of the Vector methods are marked as final; that is, you cannot extend the Vector class to implement a similar sort of collection. We could create a collection class that looked like a Vector and acted like a Vector, but it couldn't be passed to a method that takes a Vector as a parameter. Finally, none of the collections (array, Vector or Hashtable) implements a standard member access interface. As programmers developed algorithms (like sorts) to manipulate collections, a heated discourse erupted on what object to pass to the algorithm. Should you pass an array or a Vector? Should you implement both interfaces? Talk about duplication and confusion. Thankfully, the Java Collections Framework remedies these problems and offers a number of advantages over using no framework or using the Vector and Hashtable: A usable set of collection interfaces By implementing one of the basic interfaces -- Collection, Set, List, or Map -- you ensure your class conforms to a common API and becomes more regular and easily understood. So, whether you are implementing an SQL database, a color swatch matcher, or a remote chat application, if you implement the Collection interface, the operations on your collection of objects are well-known to your users. The standard interfaces also simplify the passing and returning of collections to and from class methods and allow the methods to work on a wider variety of collections

Java Collection Framework

We have tried you to make a walk through the Collection Framework. The Collection Framework provides a well-designed set if interface and classes for sorting and manipulating groups of data as a single unit, a collection. The Collection Framework provides a standard programming interface to many of the most common abstractions, without burdening the programmer with too many procedures and interfaces. The Collection Framework is made up of a set of interfaces for working with the groups of objects. The different interfaces describe the different types of groups. For the most part, once you understand the interfaces, you understand the framework. While you always need to create specific, implementations of the interfaces, access to the actual collection should be restricted to the use of the interface methods, thus allowing you to change the underlying data structure, without altering the rest of your code. In the Collections Framework, the interfaces Map and Collection are distinct with no lineage in the hierarchy. The typical application of map is to provide access to values stored by keys. When designing software with the Collection Framework, it is useful to remember the following hierarchical relationship of the four basic interfaces of the framework. The Collection interface is a group of objects, with duplicates allowed. Set extends Collection but forbids duplicates. List extends Collection also, allows duplicates and introduces positional indexing. Map extends neither Set nor Collection Interface Implementation Historical Set HashSet TreeSet List ArrayList LinkedList VectorStack Map HashMap Treemap HashtableProperties The historical collection classes are called such because they have been around since 1.0 release of the java class libraries. If you are moving from historical collection to the new framework classes, one of the primary differences is that all operations are synchronized with the new classes. While you can add synchronization to the new classes, you cannot remove from the old.Explore the Interface and Classes of Java Collection Framework

Java Collections Tutorial

The Java Collections API's provide Java developers with a set of classes and interfaces that makes it easier to handle collections of objects. In a sense Collection's works a bit like arrays, except their size can change dynamically, and they have more advanced behaviour than arrays. Rather than having to write your own collection classes, Java provides these ready-to-use collection classes for you. This tutorial will look closer at the Java Collection's, as they are also sometimes referred to, and more specifically the Java Collections available in Java 6. The purpose of this tutorial is to give you an overview of the Java Collection classes. Thus it will not describe each and every little detail of the Java Collection classes. But, once you have an overview of what is there, it is much easier to read the rest in the JavaDoc's afterwards. Most of the Java collections are located in the java.util package. Java also has a set of concurrent collections in the java.util.concurrent package. This tutorial will not describe the concurrent collections. These will be described in their own tutorial some time in the future. Here is a list of the texts in this trail: Java Collections Java Collections Introduction Overview of Interfaces Iterable Collection Generic Collections List Set SortedSet NavigableSet Map SortedMap NavigableMap Queue Deque Stack hashCode() and equals() Sorting Overview of Java Collections To help you get an overview of the Java Collections classes and interfaces, the first text in this Java Collections tutorial is the Overview of Interfaces text. The Central Java Collection Interfaces The third and fourth text explains the two central interfaces: and Additionally, the is central too. Java Collections and Generics The fifth text in this Java Collections tutorial covers how to use Generics in Java Collections. Generics is very useful when working with Java's Collection classes. Java Collections and the equals() and hashCode() Methods The last two texts in this Java Collections tutorial explains the central role the two java.lang.Object methods equals() and hashCode() play when using Java Collections. You should read this, if you plan to use Java Collections with your own classes, and thus need to implement equals() and hashCode().

Sunday, March 6, 2011

What Is an Object?

Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your bicycle.

Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.

Take a minute right now to observe the real-world objects that are in your immediate area. For each object that you see, ask yourself two questions: "What possible states can this object be in?" and "What possible behavior can this object perform?". Make sure to write down your observations. As you do, you'll notice that real-world objects vary in complexity; your desktop lamp may have only two possible states (on and off) and two possible behaviors (turn on, turn off), but your desktop radio might have additional states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in turn, will also contain other objects. These real-world observations all translate into the world of object-oriented programming.

A circle with an inner circle filled with items, surrounded by gray wedges representing methods that allow access to the inner circle.

A software object.

Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.

Consider a bicycle, for example:

A picture of an object, with bibycle methods and instance variables.

A bicycle modeled as a software object.

By attributing state (current speed, current pedal cadence, and current gear) and providing methods for changing that state, the object remains in control of how the outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than 6.

Bundling code into individual software objects provides a number of benefits, including:

  1. Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.

  2. Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.

  3. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.

  4. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.

Object-Oriented Programming Concepts

If you've never used an object-oriented programming language before, you'll need to learn a few basic concepts before you can begin writing any code. This lesson will introduce you to objects, classes, inheritance, interfaces, and packages. Each discussion focuses on how these concepts relate to the real world, while simultaneously providing an introduction to the syntax of the Java programming language.
What Is an Object?

An object is a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life. This lesson explains how state and behavior are represented within an object, introduces the concept of data encapsulation, and explains the benefits of designing your software in this manner.

What Is a Class?

A class is a blueprint or prototype from which objects are created. This section defines a class that models the state and behavior of a real-world object. It intentionally focuses on the basics, showing how even a simple class can cleanly model state and behavior.

What Is Inheritance?

Inheritance provides a powerful and natural mechanism for organizing and structuring your software. This section explains how classes inherit state and behavior from their superclasses, and explains how to derive one class from another using the simple syntax provided by the Java programming language.

What Is an Interface?

An interface is a contract between a class and the outside world. When a class implements an interface, it promises to provide the behavior published by that interface. This section defines a simple interface and explains the necessary changes for any class that implements it.

What Is a Package?

A package is a namespace for organizing classes and interfaces in a logical manner. Placing your code into packages makes large software projects easier to manage. This section explains why this is useful, and introduces you to the Application Programming Interface (API) provided by the Java platform.

Questions and Exercises: Object-Oriented Programming Concepts

Use the questions and exercises presented in this section to test your understanding of objects, classes, inheritance, interfaces, and packages.

Designing Java applications using Object Orientation

Now we will consider a java example under object-oriented definitions by building up the HelloWorld2 application.
Architecture & code of HelloWorld3

Following is the class diagram of the HelloWorld3 application:

The GreetingFactory class is designed to generate a new greeting object base on input type. The HelloWorld3 class then gets a greeting interface referencing to a corresponding concrete class by using the factory class. This means it invokes methods of the interface only and does not need to know what greeting concrete classes are and how they are implemented.

With this architecture,you also can add a new different greeting class implementing IGreeting interface such as ItalianGreeting but do not need to update the HelloWorld3 again.

Followings are screenshots of class details and running results:
• Define the interface below for Greeting object,this interface has only one method

• Create two greeting classes to implement the interface above,one for French greeting,another for English greeting

• Define the factory,GreetingFactory,to produce greeting

• Create the entry point of this application,it checks input params and call GreetingFactory to produce the corresponding greeting

Run HelloWorld3
Followings are steps help you to compile and run the HelloWorld3 application:

• Go to the source code folder of HelloWorld3 and type command javac *.java to compile all source code files,as following:

• The console below show the way to run HelloWorld3 with value of input parameter passed as french to receive a French greeting:

• By passing input parameter with value different to french you will receive a English greeting as following:

What is Java? & Java Environment Setup:

Java is:

  • Object Oriented
  • Platform independent:
  • Simple
  • Secure
  • Architectural- neutral
  • Portable
  • Robust
  • Multi-threaded
  • Interpreted
  • High Performance
  • Distributed
  • Dynamic

Java Environment Setup:

Java SE is freely available from the link Download Java. So you download a version based on your operating system.

You can refere to installation guide for a complete detail.

Java Basic Syntax:

  • Object - Objects have states and behaviors. Example: A dog has states-color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.

  • Class - A class can be defined as a template/ blue print that describe the behaviors/states that object of its type support.

  • Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.

  • Instant Variables - Each object has its unique set of instant variables. An object.s state is created by the values assigned to these instant variables.

First Java Program:

Let us look at a simple code that would print the words Hello World.

public class MyFirstJavaProgram{

/* This is my first java program.
* This will print 'Hello World' as the output

public static void main(String []args){
System.out.println("Hello World"); // prints Hello World

About Java programs, it is very important to keep in mind the following points.

  • Case Sensitivity - Java is case sensitive which means identifier Hello and hello would have different meaning in Java.

  • Class Names - For all class names the first letter should be in Upper Case.

    If several words are used to form a name of the class each inner words first letter should be in Upper Case.

    Example class MyFirstJavaClass

  • Method Names - All method names should start with a Lower Case letter.

    If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.

    Example public void myMethodName()

  • Program File Name - Name of the program file should exactly match the class name.

    When saving the file you should save it using the class name (Remember java is case sensitive) and append '.java' to the end of the name. (if the file name and the class name do not match your program will not compile).

    Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as ''

  • public static void main(String args[]) - java program processing starts from the main() method which is a mandatory part of every java program..

Java Identifiers:

All java components require names. Names used for classes, variables and methods are called identifiers.

In java there are several points to remember about identifiers. They are as follows:

  • All identifiers should begin with a letter (A to Z or a to z ), currency character ($) or an underscore (-).

  • After the first character identifiers can have any combination of characters.

  • A key word cannot be used as an identifier.

  • Most importantly identifiers are case sensitive.

  • Examples of legal identifiers:age, $salary, _value, __1_value

  • Examples of illegal identifiers : 123abc, -salary

Java Modifiers:

Like other languages it is possible to modify classes, methods etc by using modifiers. There are two categories of modifiers.

  • Access Modifiers : defualt, public , protected, private

  • Non-access Modifiers : final, abstract, strictfp

We will be looking into more details about modifiers in the next section.

Java Variables:

We would see following type of variables in Java:

  • Local Variables
  • Class Variables (Static Variables)
  • Instance Variables (Non static variables)

Java Arrays:

Arrays are objects that store multiple variables of the same type. However an Array itself is an object on the heap. We will look into how to declare, construct and initialize in the upcoming chapters.

Java Enums:

Enums were introduced in java 5.0. Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums.

With the use of enums it is possible to reduce the number of bugs in your code.

For example if we consider an application for a fresh juice shop it would be possible to restrict the glass size to small, medium and Large. This would make sure that it would not allow anyone to order any size other than the small, medium or large.


class  FreshJuice{

enum FreshJuiceSize{ SIZE, MEDUIM, LARGE }
FreshJuiceSize size;

public class FreshJuiceTest{
public static void main(String args[]){
FreshJuice juice = new FreshJuice();
juice.size = FreshJuice. FreshJuiceSize.MEDUIM ;

Note: enums can be declared as their own or inside a class. Methods, variables, constructors can be defined inside enums as well.

Java Keywords:

The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names.


Comments in Java

Java supports single line and multi-line comments very similar to c and c++. All characters available inside any comment are ignored by Java compiler.

public class MyFirstJavaProgram{

/* This is my first java program.
* This will print 'Hello World' as the output
* This is an example of multi-line comments.

public static void main(String []args){
// This is an example of single line comment
/* This is also an example of single line comment. */
System.out.println("Hello World");

Data Types in Java

There are two data types available in Java:

  1. Primitive Data Types

  2. Reference/Object Data Types

Primitive Data Types:

There are eight primitive data types supported by Java. Primitive data types are predefined by the language and named by a key word. Let us now look into detail about the eight primitive data types.

  • byte
  • short
  • int
  • long
  • float
  • double
  • boolean
  • char

Reference Data Types:

  • Reference variables are created using defined constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Puppy etc.

  • Class objects, and various type of array variables come under reference data type.

  • Default value of any reference variable is null.

  • A reference variable can be used to refer to any object of the declared type or any compatible type.

  • Example : Animal animal = new Animal("giraffe");

Java Literals:

A literal is a source code representation of a fixed value. They are represented directly in the code without any computation.

Literals can be assigned to any primitive type variable. For example:

byte a = 68;

char a = 'A'

String literals in Java are specified like they are in most other languages by enclosing a sequence of characters between a pair of double quotes. Examples of string literals are:

"Hello World"

"\"This is in quotes\""

Java language supports few special escape sequences for String and char literals as well. They are:

NotationCharacter represented
\nNewline (0x0a)
\rCarriage return (0x0d)
\fFormfeed (0x0c)
\bBackspace (0x08)
\sSpace (0x20)
\" Double quote
\'Single quote
\dddOctal character (ddd)
\uxxxxHexadecimal UNICODE character (xxxx)

Java Access Modifiers:

Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:

  1. Visible to the package. the default. No modifiers are needed.

  2. Visible to the class only (private).

  3. Visible to the world (public).

  4. Visible to the package and all subclasses (protected).

Java Basic Operators:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

The Arithmetic Operators:

+Addition - Adds values on either side of the operator A + B will give 30
-Subtraction - Subtracts right hand operand from left hand operand A - B will give -10
*Multiplication - Multiplies values on either side of the operator A * B will give 200
/Division - Divides left hand operand by right hand operand B / A will give 2
%Modulus - Divides left hand operand by right hand operand and returns remainder B % A will give 0
++Increment - Increase the value of operand by 1 B++ gives 21
--Decrement - Decrease the value of operand by 1 B-- gives 19

The Relational Operators:

== Checks if the value of two operands are equal or not, if yes then condition becomes true. (A == B) is not true.
!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A <>
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true.

The Bitwise Operators:

& Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12 which is 0000 1100
| Binary OR Operator copies a bit if it exists in eather operand. (A | B) will give 61 which is 0011 1101
^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49 which is 0011 0001
~ Binary Ones Complement Operator is unary and has the efect of 'flipping' bits. (~A ) will give -60 which is 1100 0011
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A <<>
>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15 which is 1111
>>> Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. A >>>2 will give 15 which is 0000 1111

The Logical Operators:

&& Called Logical AND operator. If both the operands are non zero then then condition becomes true. (A && B) is false.
||Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. (A || B) is true.
!Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is true.

The Assignment Operators:

=Simple assignment operator, Assigns values from right side operands to left side operand C = A + B will assigne value of A + B into C
+=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand C += A is equivalent to C = C + A
-=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand C -= A is equivalent to C = C - A
*=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand C *= A is equivalent to C = C * A
/=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand C /= A is equivalent to C = C / A
%=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand C %= A is equivalent to C = C % A
<<=Left shift AND assignment operator C <<= 2 is same as C = C <<>
>>=Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&=Bitwise AND assignment operator C &= 2 is same as C = C & 2
^=bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
|=bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

Misc Operators

There are few other operators supported by Java Language.

Conditional Operator ( ? : ):

Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as :

variable x = (expression) ? value if true : value if false

instanceOf Operator:

This operator is used only for object reference variables. The operator checks whether the object is of a particular type(class type or interface type). instanceOf operator is wriiten as:

( Object reference variable ) instanceOf  (class/interface type)

Precedence of Java Operators:

Category Operator Associativity
Postfix () [] . (dot operator) Left to right
Unary ++ - - ! ~ Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right

What Is a Servlet?

What Is a Servlet?

A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed via a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.

The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods.

When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.

This chapter focuses on writing servlets that generate responses to HTTP
requests. Some knowledge of the HTTP protocol is assumed; if you are unfamiliar with this protocol, you can get a brief introduction to HTTP in Appendix A.

The Example Servlets

This chapter uses the Duke's Bookstore application to illustrate the tasks involved in programming servlets. Table 10-1 lists the servlets that handle each bookstore function. Each programming task is illustrated by one or more servlets. For example, BookDetailsServlet illustrates how to handle HTTP GET requests, BookDetailsServlet and CatalogServlet show how to construct responses, and CatalogServlet illustrates how to track session information.

Table 10-1 Duke's Bookstore Example Servlets Function
Enter the bookstore
Create the bookstore banner
Browse the bookstore catalog
Put a book in a shopping cart
Get detailed information on a specific book
Display the shopping cart
Remove one or more books from the shopping cart
Buy the books in the shopping cart
Receive an acknowledgement for the purchase

The data for the bookstore application is maintained in a database and accessed through the helper class database.BookDB. The database package also contains the class BookDetails, which represents a book. The shopping cart and shopping cart items are represented by the classes cart.ShoppingCart and cart.ShoppingCartItem, respectively.

The source code for the bookstore application is located in the j2eetutorial/examples/src/web/bookstore1 directory created when you unzip the tutorial bundle (see Downloading the Examples). To build, deploy, and run the example, follow these steps.

1. Go to j2eetutorial/examples and build the example by running ant bookstore1 (see How to Build and Run the Examples).
2. Start the j2ee server.
3. Start deploytool.
4. Start the Cloudscape database server by running cloudscape -start.
5. Load the bookstore data into the database by running ant create-web-db.
6. Create a J2EE application called Bookstore1App.
1. Select FileNewApplication.
2. In the file chooser, navigate to j2eetutorial/examples/src/web/bookstore1.
3. In the File Name field, enter Bookstore1App.
4. Click New Application.
5. Click OK.
7. Create the WAR and add the BannerServlet Web component and all of the Duke's Bookstore content to the Bookstore1App application.
1. Select FileNewWeb Component.
2. Click the Create New WAR File In Application radio button and select Bookstore1App from the combo box. Enter Bookstore1WAR in the field labeled WAR Display Name.
3. Click Edit to add the content files.
4. In the Edit Archive Contents dialog box, navigate to j2eetutorial/examples/build/web/bookstore1. Select BannerServlet.class, BookStoreServlet.class, BookDetailsServlet.class, CatalogServlet.class, ShowCartServlet.class, CashierServlet.class, and ReceiptServlet.class. Click Add. Add errorpage.html and duke.books.gif. Add the cart, database, exception, filters, listeners, messages, and util packages. Click OK.
5. Click Next.
6. Select the Servlet radio button.
7. Click Next.
8. Select BannerServlet from the Servlet Class combo box.
9. Click Next twice.
10. In the Component Aliases pane, click Add and then type /banner in the Alias field.
11. Click Finish.
8. Add each of the Web components listed in Table 10-2. For each servlet, click the Add to Existing WAR File radio button and select Bookstore1WAR from the combo box. Since the WAR contains all of the servlet classes, you do not have to add any more content.

Table 10-2 Duke's Bookstore Web Components Web Component Name
Servlet Class
Component Alias
9. Add a resource reference for the Cloudscape database.
1. Select Bookstore1WAR.
2. Select the Resource Refs tab.
3. Click Add.
4. Select javax.sql.DataSource from the Type column
5. Enter jdbc/BookDB in the Coded Name field.
6. Enter jdbc/Cloudscape in the JNDI Name field.
10. Add the listener class listeners.ContextListener (described in Handling Servlet Life-Cycle Events).
1. Select the Event Listeners tab.
2. Click Add.
3. Select the listeners.ContextListener class from the drop-down field in the Event Listener Classes pane.
11. Add an error page (described in Handling Errors).
1. Select the File Refs tab.
2. In the Error Mapping panel, click Add.
3. Enter exception.BookNotFoundException in the Error/Exception field.
4. Enter /errorpage.html in the Resource To Be Called field.
5. Repeat for exception.BooksNotFoundException and javax.servlet.UnavailableException.
12. Add the filters filters.HitCounterFilter and filters.OrderFilter (described in Filtering Requests and Responses).
1. Select the Filter Mapping tab.
2. Click Edit Filter List.
3. Click Add.
4. Select filters.HitCounterFilter from the Filter Class column. The deploytool utility will automatically enter HitCounterFilter in the Display Name column.
5. Click Add.
6. Select filters.OrderFilter from the Filter Class column. The deploytool utility will automatically enter OrderFilter in the Display Name column.
7. Click OK.
8. Click Add.
9. Select HitCounterFilter from the Filter Name column.
10. Select Servlet from the Target Type column.
11. Select BookStoreServlet from the Target column.
12. Repeat for OrderFilter. The target type is Servlet and the target is ReceiptServlet.
13. Enter the context root.
1. Select Bookstore1App.
2. Select the Web Context tab.
3. Enter bookstore1.
14. Deploy the application.
1. Select ToolsDeploy.
2. Click Finish.
15. Open the bookstore URL http://:8000/bookstore1/enter.


The section Common Problems and Their Solutions (in particular, Web Client Runtime Errors) lists some reasons why a Web client can fail. In addition, Duke's Bookstore returns the following exceptions:

* BookNotFoundException: Returned if a book can't be located in the bookstore database. This will occur if you haven't loaded the bookstore database with data by running ant create-web-db or if the Cloudscape server hasn't been started or it has crashed.
* BooksNotFoundException: Returned if the bookstore data can't be retrieved. This will occur if you haven't loaded the bookstore database with data by running ant create-web-db or if the Cloudscape server hasn't been started or has crashed.
* UnavailableException: Returned if a servlet can't retrieve the Web context attribute representing the bookstore. This will occur if you haven't added the listener class to the application.

Since we have specified an error page, you will see the message The application is unavailable. Please try later. If you don't specify an error page, the Web container generates a default page containing the message A Servlet Exception Has Occurred and a stack trace that can help diagnose the cause of the exception. If you use errorpage.html, you will have to look in the Web container's log to determine the cause of the exception. Web log files reside in the directory


and are named catalina..log.

The element is the directory specified by the entry in the file. The default value is logs. The element is the name of the computer. See the Configuration Guide provided with the J2EE SDK for more information about J2EE SDK log files.

Free Java tutorials & programming source code

Learn the fundamentals of Java programming language through a variety of online tutorials. These tutorials teach the essential concepts behind building applications using various programming concepts and modules. This site can be used as a practical, example based guide for beginning programmers or those without much Object Oriented programming experience.

Free Java Guide: This site lists General Java tutorials and specific Java programming topics for serious programming. In the case of sql tutorial, for each command, the SQL syntax will first be presented and explained, followed by an example. This site aims to teach beginners the building blocks of SQL. Well organized, easy to understand SQL guide with lots of examples that helps you need to get started using SQL. If you are also looking for a PL/SQL tutorial, this is the site. Our PL/SQL tutorial provides the help you need to get started using SQL and PL/SQL.

Master Java, find popular listings for various Java technologies ranging from Core Java, PL/SQL, HTML, XML and SQL


Learn the Core Java basics. This topic is for those learning Java programming or having general Java programming questions. It is a fundamental guide, aimed at beginners to java programming.


If you are looking to learn PL/SQL, this is the site. It provides the help you need to get started using SQL and PL/SQL. It gives an introduction to Procedural Structured Query Language (pl/sql). PL/SQL help, examples and references needed to start programming in plsql.


This covers the basics of SQL Language. This lists the commonly used SQL commands, and is divided into the various sections organized by sql topics. By the end of this sql guide, you should have a good general understanding of the SQL syntax. In addition, you should be able to write SQL queries using the correct syntax.

ORACLE Question Bank

It contains more than 500 Questions (in 10 pages) of oracle and SQL + PL/SQL which can be used for facing interviews and for personal evaluation of oracle knowledge organized by topic. This question bank helps by asking you questions and explaining which answer is correct and why.

HTML Tutorial for beginners HTML Tutorial - advanced

This is a terrific resource for beginners and students. It includes many copy & paste HTML scripts with detailed explanations that you can put right into an existing web page. It's also a good reference to find that tag that you just can't remember but need for your web page.

The following material is a part of 'IBM's resource for developers' website.

1. SCJP, Part 1

This SCJP guide is to help you become a Sun certified Java programmer. It is organized in the same way as the Sun Certified Java Programmer (SCJP) 1.4 exam and provides a detailed overview of all of the exam's main objectives. Throughout the java pdf, simple examples are provided to illustrate the important concepts covered in the exam.

2. Introduction to Core java I/O

This java I/O pdf is an overview of Java I/O and all the classes in the package. This guide assumes you have a basic knowledge of I/O, including Input Stream and Output Stream.

3. Enterprise Beans Fundamentals

This ejb pdf provides an introduction to Enterprise JavaBeans technology with particular attention to the role of Enterprise JavaBean components in distributed computing scenarios, the architecture, the extension APIs, and the fundamentals of working with EJB technologies

4. The Class Loader

The Java ClassLoader is a crucial, but often overlooked, component of the Java runtime system. It is the class responsible for finding and loading class files at run time. Creating your own ClassLoader lets you customize the JVM in useful and interesting ways, allowing you to completely redefine how class files are brought into the system.

5. Design Patterns 101

This lesson is for Java programmers who want to learn about java design patterns as a means of improving their object oriented design and development skills. After reading this pdf you will:
* Understand what design patterns are and how they are described and categorized in several well known catalogs
* Be able to use design patterns as a vocabulary for understanding and discussing object oriented software design
* Understand a few of the most common design patterns and know when and how they should be used

4. Introduction to Threads

This tutorial explores the basics of threads -- what they are, why they are useful, and how to get started writing simple programs that use them. It also explains the basic building blocks of more sophisticated threading applications, how to exchange data between threads, how to control threads, and how threads can communicate with each other.

XML Tutorials

Introduction: Learn what XML is all about and discover how it differs from HTML. Explore XML syntax rules, learn how to write well formed XML documents, adjust XML attributes, validate XML documents and XML programming with java. In these tutorials you will learn what XML is about. You'll understand the basic XML syntax. Know what's needed to make XML usable along with java programming. You'll be able to understand XML Documents and most of XML DTD's.

6. XML programming in Java technology, Part 1

This xml tutorial covers the basics of manipulating XML documents using Java technology and looks at the common APIs for XML and discusses how to parse, create, manipulate, and transform XML documents. Covers basics of XML parsing in the Java language.

7. XML programming in Java technology, Part 2

This looks at working with namespaces, validating XML documents, building XML structures without a typical XML document, converting between one API and another, and manipulating tree structures.

8. XML programming in Java technology, Part 3

Covers more sophisticated topics for manipulating XML documents with Java technology. It shows you how to do tasks such as generate XML data structures, manipulate those structures, and interface XML parsers with non XML data sources.

8. Understanding DOM

This is designed for developers who understand the basic concept of XML and are ready to move on to coding applications to manipulate XML using the Document Object Model (DOM). It assumes that you are familiar with concepts such as well formed ness and the tag like nature of an XML document

Java Beginner Tutorial is a beginner Java tutorial site that attempts to teach basics of Java programming Language in plain English using huge number of java source code examples spread across various topics. This site is for absolute starters to learn java who do not require any prerequisite Java knowledge. This site can also be used by advanced java developers. This site has links to some of my other sites that will help you in learning advanced Java topics and other technical subjects.

Java has evolved to be the most predominant and popular general purpose programming language of the current age. Java is a simple, portable, distributed, robust, secure, dynamic, architecture neutral, object orientedprogramming language. It was developed by Sun Microsystems. This technology allows the software designed and developed once for an idealized ‘virtual machine’ and run on various computing platforms.

Java plays a significant role in the corporate world. Companies of all sizes are using Java as the main programming language to develop various applications/projects world wide. It has found its use in various sectors including banking, insurance, retail, media, education, manufacturing and so on. E-commerce, Gaming, Mobile, Embedded, Media and many more types of applications are being developed using Java. Organizations are developing mission critical applications using Java technologies. This necessitates the corporations to hire highly skilled java developers. On the other hand it opens the doors for many opportunities for java developers. There is significant demand for java developers with sound technical skills. Now Colleges and Universities all over the world are using it in their introduction courses as well as their junior and senior software engineering courses.

This site was developed considering the importance of this language and the benefits that it provides to corporations, developers, students, education institutions and more. is free online Java tutorial site with a huge number of java programs for java development. This site is evolving with more content, features, links and useful information. If you have any suggestions, feedback, concerns, corrections or questions please communicate through Feedback section.