Wednesday, October 31, 2007

Java 2 Enterprise Edition Bible

Java 2 Enterprise Edition Bible

Justin Couch,«Java 2 Enterprise Edition Bible»John Wiley ISBN 0764508822 PDF 2,91 Mb 960 Pages 2002 Year
Sun Microsystems’ Java 2 Platform, Enterprise Edition (J2EE) defines the standard for developing multitier enterprise applications — and the Java 2 Enterprise Edition Bible defines the standard for comprehensive coverage of this exciting development tool! This book covers all the primary technologies of J2EE, including: Enterprise JavaBeans, Java Server Pages, servlets, the Java Naming and Directory Interface (JNDI), the Java Transaction API (JTA), CORBA, and the JDBC data access API. It also explains how XML works with Java. Developers can rely on this book to provide detail on developing and deploying a complete, stable, secure, fast Java platform to the enterprise level.

Generics in Java Programming.

Generics

Generics were added to the Java language syntax in version 1.5. This means that code using Generics will not compile with Java 1.4 and less.

Java was long criticized for the need to explicitly type-cast an element when it was taken out of a "container/collection" class. There was no way to enforce that a "collection" class contains only one type of object. This is now possible since Java 1.5.

In the first couple of years of Java evolution, Java did not have a real competitor. This has changed by the appearance of Microsoft C#. With Generics Java is better suited to compete against C#.

What are Generics?

Generics are so called because this language feature allows methods to be written generically, with no foreknowledge of the type on which they will eventually be called upon to carry out their behaviors. A better name might have been type parameter argument. Because, it is basically that, to pass a Type as a parameter to a class at creation time.

When an object is created, parameters can be passed to the created object, through the constructor. Now with Generics, we can also pass in Types. The type-place-holders will be replaced with the specified type, before the object is created.

Type parameter arguments can be set:
for a class
When an object is created from that class the type-parameter-argument will be replaced with the actual Type.
public class Person
{
private Person person;
...
}...// --- Create an Employee person ---
Person emplPerson = new Person();
...
// --- Create a Customer person ---
Person custPerson = new Person();

for a method

Just like class declarations, method declarations can be generic--that is, parameterized by one or more type parameters.
static public void assign( Person person, T obj )
{
person.setPerson( obj );
}
use of generics is optional


For backwards compatibility with pre-Generics code, it is okay to use generic classes without the generics type specification thing (). In such a case, when you retrieve an object reference from a generic object, you will have to manually typecast it from type Object to the correct type. The compiler should also warn about unsafe operations.

Introduction

Java is a "strongly" typed language. That's why it is so easy to use. Many potential problems are caught by the compiler. One area where Java was criticized was regarding the "Container/Collection" objects. Container objects are objects that contain other objects. Before Generics were introduced there was no way to ensure that a container object contains only one type of objects. When an object was added to a container, it was automatically cast to Java Object. When it was taken out an explicit cast was needed. Normally an explicit cast is checked by the compiler.

String st = "This is a String";
...
Integer integer = (Integer) st; // --- Compilation Error --

But in the case of container classes, the compiler was not able to catch an invalid type casting.

1 Collection collString = new ArrayList();
2 collString.add( "This is a String" );
...
3 Integer integer = (Integer) collString.get(0); // --- No Compilation Error; RunTime CastException

Just looking at line 3, we do not know what type of objects collString contains. If that contains Integers then the code is fine.

The above code using Generic:
Collection<String> collString = new ArrayList<String>();
collString.add( "This is a String" );
...
Integer integer = (Integer) collString.get(0); // --- Compilation Error

collString is a container object, that can contain only String objects, nothing else, so when we get out an element it can be casted only to class that normally a String can be casted.

With Generics, Java strict type checking can be extended to container objects. Using Generics with container classes, gives an impression that a new container type is created, with each different type parameter. Before Generics:

Collection collCustomer = new ArrayList();
collCustomer.add( new Customer() );
...
Collection collObject = collCustomer; // --- No problem, both collObject and collCustomer have the same type

With generics:
Collection collCustomer = new ArrayList();
collCustomer.add( new Customer() );
...
Collection(object) collObject = collCustomer; // --- Compilation Error

Both collObject and collCustomer have the same type, BUT it is against the Generic rule, that is collCustomer can contain only Customer objects, and collObject can contain only Object object. So there is an additional check to the normal type checking, the type of the parameter type has to be matched too.

Note for C++ programmers

Java Generics are similar to C++ Templates in that both were added for the same reason. The syntax of Java Generic and C++ Template are also similar.

There are some differences however. The C++ template can be seen as a kind of macro, that generates code before compilation. The generated code depends on how the Template class is referenced. The amount of code generated depends on how many different types of classes are created from the Template. C++ Templates do not have any run-time mechanisms. The compiler creates normal code to substitute the template, similar to any 'hand-written' code.

In contrast, Java Generics are built into the language. The same Class object handles all the Generic type variations. No additional code is generated, no matter how many Generic objects are created with different type parameters. For example.

Collection collString = new ArrayList<String>();
Collection collInteger = new ArrayList();

There is only one Class object created. In fact, at runtime, both these objects appear as the same type (both ArrayList's). The generics type information is erased during compilation (type erasure). This means, for example, that if you had function that takes Collection as an argument, and that collection happened to be empty, your function would have no way of instantiating another T object, because it doesn't know what T was.

The Class
class itself is generic since Java 1.5.

public final class Class extends Object implements Serializable, GenericDeclaration, Type, AnnotatedElement{
...
}

The T type here represents the type that is handed to the Class object. The T type will be substituted with the class being loaded.

Class

Since Java 1.5, the class java.lang.Class is generic. It is an interesting example of using genericness for something other than a container class.

For example, the type of String.class is Class, and the type of Serializable.class is Class. This can be used to improve the type safety of your reflection code.

In particular, since the newInstance() method in Class now returns a T, you can get more precise types when creating objects reflectively.

Now we can use the newInstance() method to return a new object with exact type, without casting.

Customer cust = Utility.createAnyObject(Customer.class); // - No casting
...
public static T createAnyObject(Class cls) {
T ret = null;
try
{
ret = cls.newInstance();
}
catch (Exception e) {
// --- Exception Handling
}
return ret;
}

And the above code without Generics:

Customer cust = (Customer) Utility.createAnyObject(Customer.class); // - Casting is needed
...
public static Object createAnyObject(Class cls)
{
Object ret = null;
try
{
ret = cls.newInstance();
}
catch (Exception e)
{ // --- Exception Handling }
return ret;
}

Get exact type when getting JavaBean property, using reflection

See the following code where the method will return the exact type of the Java Bean property, based on how it will be called.
// --- Using reflection, get a Java Bean property by its name ---

public static T getProperty(Object bean, String propertyName)
{
if (bean == null propertyName == null propertyName.length() == 0)
{
return null;
} // --- Based on the property name build the getter method name ---
String methodName = "get" +propertyName.substring(0,1).toUpperCase() + propertyName.substring(1);
T property = null;
try
{
java.lang.Class c = bean.getClass();
java.lang.reflect.Method m = c.getMethod(methodName, null);
property = (T) m.invoke(bean, null);
}
catch (Exception e)
{ // --- Handle exception -- }
return property;
}

Variable Argument

With Generic it is very easy to define a method with variable argument. Before generic usually passing in array was close to the variable argument. The only requirement is that the arguments in the list must have the same type.

The following code illustrates the method that can be called with variable arguments:
/**
* Method using variable argument list
* @param
* @param args
*/
public static List makeAList(T... args)
{
List argList = new ArrayList();
for (int i = 0; i <>
{
argList.add(args[i]);
}
return argList;
}

And the above method can be called with variable argument, see below:

List<String> list1 = makeAList("One", "Two", "Three");
List<String> list2 = makeAList("One", "Two", "Three", "Four");

In the above calls the arguments must be String. If we for the T, then we can pass in any kind of objects regardles of their type. See below:

List list3 = makeAList("One", 10);

Note: the number 10 in the above code will be converted (autoboxed) to Integer.

See also: java.util.Arrays.asList(T... a)

Wildcard Types

As we have seen above, generics give the impression that a new container type is created with each different type parameter. We have also seen that in addition to the normal type checking, the type parameter has to match as well when we assign generics variables.

In some cases this is too restrictive. What if we would like to relax this additional checking? What if we would like to define a collection variable that can hold any generic collection, regardless of the parameter type it holds?

Wildcard

The wildcard type is represented by the character , and pronounced Unknown, or Any-Type. This Unknown type matches anything, if it is used only by itself. Any-Type can be express also by . Any-Type includes Interfaces, not only Classes.

Tuesday, October 30, 2007

Core Java FAQs or Interview Questions--2

Core Java FAQs or Interview Questions:--2

1)What is the difference between an Abstract class and Interface?
Abstract classes may have some executable methods and methods left unimplemented. Interfaces contain no implementation code.
-- An class can implement any number of interfaces, but subclass at most one abstract class.
--An abstract class can have nonabstract methods. All methods of an interface are abstract.
--An abstract class can have instance variables. An interface cannot.
--An abstract class can define constructor. An interface cannot.
--An abstract class can have any visibility: public, protected, private or none (package). An interface's visibility must be public or none (package).
--An abstract class inherits from Object and includes methods such as clone() and equals().

2)What are checked and unchecked exceptions?
Java defines two kinds of exceptions :

-->Checked exceptions: Exceptions that inherit from the Exception class are checked exceptions. Client code has to handle the checked exceptions thrown by the API, either in a catch clause or by forwarding it outward with the throws clause. Examples - SQLException, IOxception

-->Unchecked exceptions: RuntimeException also extends from Exception. However, all of the exceptions that inherit from RuntimeException get special treatment. There is no requirement for the client code to deal with them, and hence they are called unchecked exceptions. Example Unchecked exceptions are NullPointerException, OutOfMemoryError, DivideByZeroException typically, programming errors.

3)What is a user defined exception?
User-defined exceptions may be implemented by

* defining a class to respond to the exception and

* embedding a throw statement in the try block where the exception can occur or declaring that the method throws the exception (to another method where it is handled).

The developer can define a new exception by deriving it from the Exception class as follows:

public class MyException extends Exception {
/* class definition of constructors (but NOT the exception handling code) goes here */
public MyException() {
super();
}
public MyException( String errorMessage ) {
super( errorMessage );
}
}

The throw statement is used to signal the occurance of the exception within a try block. Often, exceptions are instantiated in the same statement in which they are thrown using the syntax.
throw new MyException("I threw my own exception.")
To handle the exception within the method where it is thrown, a catch statement that handles MyException, must follow the try block. If the developer does not want to handle the exception in the method itself, the method must pass the exception using the syntax:
public myMethodName() throws MyException


4)What is the difference between C++ & Java?
Well as Bjarne Stroustrup says "..despite the syntactic similarities, C++ and Java are very different languages. In many ways, Java seems closer to Smalltalk than to C++..".

:* Java is multithreaded

* Java has no pointers

* Java has automatic memory management (garbage collection)

* Java is platform independent (Stroustrup may differ by saying "Java is a platform"

* Java has built-in support for comment documentation

* Java has no operator overloading

* Java doesn’t provide multiple inheritance* There are no destructors in Java


5)What are statements in JAVA ?
Statements are equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon

* Assignment expressions

* Any use of ++ or --

* Method calls

* Object creation expressions

These kinds of statements are called expression statements. In addition to these kinds of expression statements, there are two other kinds of statements. A declaration statement declares a variable. A control flow statement regulates the order in which statements get executed. The for loop and the if statement are both examples of control flow statements.

6)What is JAR file ?
JavaARchive files are a big glob of Java classes, images, audio, etc., compressed to make one simple, smaller file to ease Applet downloading. Normally when a browser encounters an applet, it goes and downloads all the files, images, audio, used by the Applet separately. This can lead to slower downloads.

7)What is JNI ?
JNI is an acronym of Java Native Interface. Using JNI we can call functions which are written in other languages from Java. Following are its advantages and disadvantages.

Advantages:

* You want to use your existing library which was previously written in other language.

* You want to call Windows API function.

* For the sake of execution speed.

* You want to call API function of some server product which is in c or c++ from java client.

Disadvantages:

* You can’t say write once run anywhere.

* Difficult to debug runtime error in native code.

* Potential security risk.

* You can’t call it from Applet.

8)What is serialization ?
Quite simply, object serialization provides a program the ability to read or write a whole object to and from a raw byte stream. It allows Java objects and primitives to be encoded into a byte stream suitable for streaming to some type of network or to a file-system, or more generally, to a transmission medium or storage facility. A seralizable object must implement the Serilizable interface. We use ObjectOutputStream to write this object to a stream and ObjectInputStream to read it from the stream.

9)Why there are some null interface in java ? What does it mean ? Give me some null interfaces in JAVA ?
Null interfaces act as markers..they just tell the compiler that the objects of this class need to be treated differently..some marker interfaces are : Serializable, Remote, Cloneable

10)Is synchronised a modifier?indentifier??what is it??
It's a modifier. Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

Core Java FAQs or Interview Questions

Core Java FAQs or Interview Questions

1)What is singleton class?where is it used?

Singleton is a design pattern meant to provide one and only one instance of an object. Other objects can get a reference to this instance through a static method (class constructor is kept private). Why do we need one? Sometimes it is necessary, and often sufficient, to create a single instance of a given class. This has advantages in memory management, and for Java, in garbage collection. Moreover, restricting the number of instances may be necessary or desirable for technological or business reasons--for example, we may only want a single instance of a pool of database connections.

2)What is a compilation unit?

The smallest unit of source code that can be compiled, i.e. a .java file.

3)Is string a wrapper class?

String is a class, but not a wrapper class. Wrapper classes like (Integer) exist for each primitive type. They can be used to convert a primitive data value into an object, and vice-versa.

4)Why java does not have multiple inheritance?

The Java design team strove to make Java:
Simple, object oriented, and familiar
Robust and secure
Architecture neutral and portable
High performance
Interpreted, threaded, and dynamic

The reasons for omitting multiple inheritance from the Java language mostly stem from the "simple, object oriented, and familiar" goal. As a simple language, Java's creators wanted a language that most developers could grasp without extensive training. To that end, they worked to make the language as similar to C++ as possible (familiar) without carrying over C++'s unnecessary complexity (simple).

In the designers' opinion, multiple inheritance causes more problems and confusion than it solves. So they cut multiple inheritance from the language (just as they cut operator overloading). The designers' extensive C++ experience taught them that multiple inheritance just wasn't worth the headache.

5)Why java is not a 100% oops?

Many people say this because Java uses primitive types such as int, char, double. But then all the rest are objects. Confusing question..

6)What is a resource bundle?


In its simplest form, a resource bundle is represented by a text file containing keys and a text value for each key.

7)What is transient variable?

Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.

8)What is Collection API?

The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.Example of interfaces: Collection, Set, List and Map.

9)Is Iterator a Class or Interface? What is its use?

Iterator is an interface which is used to step through the elements of a Collection.

10)What is similarities/difference between an Abstract class and Interface?

Differences are as follows:
* Interfaces provide a form of multiple inheritance. A class can extend only one other class.
* Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
* A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
* Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.

Similarities:
* Neither Abstract classes or Interface can be instantiated.

J2EE FAQs or Interview Questions

J2EE FAQs or Interview Questions.

1.What is J2EE?
J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multi tiered, and web-based applications.


2. What is the J2EE module?
A J2EE module consists of one or more J2EE components for the same container type and one component deployment descriptor of that type.

3.What are the components of J2EE application?
A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:
o Application clients and applets are client components.
o Java Servlets and Java Server Pages TM (JSPTM) technology components are web components.
o Enterprise JavaBeansTM (EJBTM) components (enterprise beans) are business components.
o Resource adapter components provided by EIS and tool vendors.

4. What are the four types of J2EE modules?
1. Application client module
2. Web module
3. Enterprise JavaBeans module
4. Resource adapter module
5. What does application client module contain?

The application client module contains:
o class files,
o an application client deployment descriptor.
Application client modules are packaged as JAR files with a .jar extension.

6. What does Enterprise JavaBeans module contain?
The Enterprise JavaBeans module contains:
o class files for enterprise beans
o An EJB deployment descriptor.
EJB modules are packaged as JAR files with a .jar extension
.

7.What does resource adapt module contain?
The resource adapt module contains:
o all Java interfaces,
o classes,
o native libraries,
o other documentation,
o A resource adapter deployment descriptor.
Resource adapter modules are packages as JAR files with a .rar (Resource adapter Archive) extension.

8.How many development roles are involved in J2EE application?
There are at least 5 roles involved:

1. Enterprise Bean Developer
* Writes and compiles the source code
* Specifies the deployment descriptor
* Bundles the .class files and deployment descriptor into an EJB JAR file
2. Web Component Developer
* Writes and compiles Servlets source code
* Writes JSP and HTML files
* Specifies the deployment descriptor for the Web component
* Bundles the .class, .jsp, .html, and deployment descriptor files in the WAR file
3. J2EE Application Client Developer
* Writes and compiles the source code
* Specifies the deployment descriptor for the client
* Bundles the .class files and deployment descriptor into the JAR file
4. Application Assembler : The application assembler is the company or person who receives application component JAR files from component providers and assembles them into a J2EE application EAR file. The assembler or deployer can edit the deployment descriptor directly or use tools that correctly add XML tags according to interactive selections. A software developer performs the following tasks to deliver an EAR file containing the J2EE application:
* Assembles EJB JAR and WAR files created in the previous phases into a J2EE application (EAR) file
* Specifies the deployment descriptor for the J2EE application
* Verifies that the contents of the EAR file are well formed and comply with the J2EE specification
5. Application Deployer and Administrator
* Configures and deploys the J2EE application
* Resolves external dependencies
* Specifies security settings & attributes
* Assigns transaction attributes and sets transaction controls
* Specifies connections to databases
* Deploys or installs the J2EE application EAR file into the J2EE server
* Administers the computing and networking infrastructure where J2EE applications run
* Oversees the runtime environment
But a developer role depends on the job assignment. For a small company, one developer may take these 5 roles altogether.

9. What is difference between J2EE 1.3 and J2EE 1.4?
J2EE 1.4 is an enhancement version of J2EE 1.3. It is the most complete Web services platform ever.
J2EE 1.4 includes:
o Java API for XML-Based RPC (JAX-RPC 1.1)
o SOAP with Attachments API for Java (SAAJ),
o Web Services for J2EE(JSR 921)
o J2EE Management Model(1.0)
o J2EE Deployment API(1.1)
o Java Management Extensions (JMX),
o Java Authorization Contract for Containers(JavaACC)
o Java API for XML Registries (JAXR)
o Servlet 2.4
o JSP 2.0
o EJB 2.1
o JMS 1.1
o 2EE Connector 1.5

The J2EE 1.4 features complete Web services support through the new JAX-RPC 1.1 API, which supports service endpoints based on Servlets and enterprise beans. JAX-RPC 1.1 provides interoperability with Web services based on the WSDL and SOAP protocols.

The J2EE 1.4 platform also supports the Web Services for J2EE specification (JSR 921), which defines deployment requirements for Web services and utilizes the JAX-RPC programming model.

In addition to numerous Web services APIs, J2EE 1.4 platform also features support for the WS-I Basic Profile 1.0. This means that in addition to platform independence and complete Web services support, J2EE 1.4 offers platform Web services interoperability.

The J2EE 1.4 platform also introduces the J2EE Management 1.0 API, which defines the information model for J2EE management, including the standard Management EJB (MEJB). The J2EE Management 1.0 API uses the Java Management Extensions API (JMX).

The J2EE 1.4 platform also introduces the J2EE Deployment 1.1 API, which provides a standard API for deployment of J2EE applications.

The J2EE 1.4 platform includes security enhancements via the introduction of the Java Authorization Contract for Containers (JavaACC). The JavaACC API improves security by standardizing how authentication mechanisms are integrated into J2EE containers.

The J2EE platform now makes it easier to develop web front ends with enhancements to Java Servlet and JavaServer Pages (JSP) technologies. Servlets now support request listeners and enhanced filters. JSP technology has simplified the page and extension development models with the introduction of a simple expression language, tag files, and a simpler tag extension API, among other features. This makes it easier than ever for developers to build JSP-enabled pages, especially those who are familiar with scripting languages.

Other enhancements to the J2EE platform include the J2EE Connector Architecture, which provides incoming resource adapter and Java Message Service (JMS) plug ability. New features in Enterprise JavaBeans (EJB) technology include Web service endpoints, a timer service, and enhancements to EJB QL and message-driven beans.

The J2EE 1.4 platform also includes enhancements to deployment descriptors. They are now defined using XML Schema which can also be used by developers to validate their XML structures.

Note: The above information comes from SUN released notes.

10. Is J2EE application only a web-based?
NO. A J2EE application can be web-based or non-web-based. If an application client executes on the client machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to handle tasks such as J2EE system or application administration. It typically has a graphical user interface created from Swing or AWT APIs, or a command-line interface. When user request, it can open an HTTP connection to establish communication with a Servlet running in the web tier.

Monday, October 29, 2007

API's and Javadoc: What are they?

API's and Javadoc: What are they?

An API stands for a "Java Application Programming Interface". It is like a super dictionary of the Java language, that one uses to look something up in. It has an index or collection of all Java packages, classes and interfaces, with all of their methods, fields and constructors, and how to use them. When one programs, there are many classes that are commonly used, and therefore pre created, so that the programmer doesn't need to create them from scratch. Let's look, for example, at a computer window frame. If the programmer had to create one from scratch, he would have to write hundreds of lines of code, to create the scroll down menu, the exit box, etc. Since a window frame is very popular, Sun has written the code for one, and all that you have to do is import the package that contains the window frame, and instantiate one with a new statement.
As with all of Sun's classes, we do not care how it is implemented, all we need to know are what the methods are, the constructors, and it's fields. Hence the name Java Application Programming Interface, the API is a collection of interfaces telling us what each class can do, not telling us how it is done. The API contains many packages for many different purposes, among them, the applet package for creating applets, the awt and swing packages for graphics and GUI, the io package for input and output, the sql package for Java databasing, and many many more. For every package that you use a class from you must import it, with the exception of the java.lang package that deals with basic programming classes, that is automatically imported into your program.

Each API is organized in the following way. When you start the API you are given three frames, the first listing all of the Java packages in that API, and when you click on any particular package, the second frame lists all of the interfaces, classes, and exceptions in that package. The main frame starts with an overview of all of the packages, and shows the index, class hierarchy for each package, and help section when you click for it on the top menu. Also, it gives you the details for each class document. The Index contains an alphabetic list of all classes, interfaces, constructors, methods, and fields. The class document is set up with the top showing that class inheritance diagram and subclasses, the middle showing the field, method, and constructor summaries, and the bottom giving details for the fields, methods, and constructors.


In short, when you start programming, you're constantly going to have to look up something in the API. There's going to be some class or method that you don't know how to use, you're not sure what parameters it takes, etc, and you can find out all of the information in the API. When Shlomo started writing Java, a certain program always crashed during some String methods, and Shlomo spent hours trying to figure it out unsuccessfully. Finally someone looked up the String methods in the API, noticed that the method substring() was spelled substring() instead of the assumed subString(). Well, Shlomo was extremely impressed, until he himself figured out how to use the API, and realized how easy it was.

Javadoc is the ability to create these API looking documents out of your own code. When you write your code you place html tags and javadoc tags in special comments (that look like this)
/*
*
* place comments here
*
*/
These comments you place before the beginning of the code for your class, and before most of your methods. Then instead of typing in java or javac on the CMD console, you type "javadoc nameOfClass" or "javadoc NameOfPackage". The compiler will then create an html document, that explains your methods, fields and constructors, plus whatever HTML that you added, in the same exact way that the API looks.
For more information on javadoc, check out Sun's official tool section .

Basic Java terminology

Basic Java terminology

The purpose of this page is to help the beginner with the basic Java terminology. The terminology below is meant to be easily understood, and is therefore not given a technical definition.
  • processor: The processor is inside the brain of the computer, and it is its job to read, or process, the instructions. It takes each instruction (after it has been broken down into basic computer language by the compiler) and runs it, turning on and off switches, causing the program to execute.

  • CPU: The CPU or Central Processing Unit, is the brain of the computer. It holds inside it the processor, the Arithmetic Logical Unit (ALU: the computer's math machine), and controls and tells the rest of the computer what to do.

  • code: Code just means the instructions that the programmer writes. The code of a program means the part that the programmer wrote up, and will give to the computer to run.
    compiler The compiler "translates" the code that you have written in the language that you understand (like Java) into a language that the computer understands, either assembly language, or pure computer language (ones and zeros).

  • keywords: Keywords are words that have a very specific meaning to the compiler. Whenever the compiler sees one, it knows what it is, and translates it as such. For example, the word "int" means a number. Whenever in the program the programmer writes "int", it has only that meaning, a number. The programmer can never use it for something else. Another example is the word "if". If means try to see if what I am saying is true. If it is then do the next line, if not not. The word if can only mean that, and can never change. There are approximately 30 keywords.

  • control statements: Whenever the computer runs a Java program, it goes straight from the first line of code to the last. However, lets say you only want to run some code on condition. For example, you are writing an adventure game, and your player is hit, do you want him to die, or not. Well, it depends, how many "hits" is he allowed to have before he dies. So you want a control statement that says "if he is down to his last hit, then run the dying code, else subtract the number of hits that he is allowed, and continue". The if else is one kind of control statement, and it changes control to read from a different line of code, instead of the next.

  • Variables: Variables are words in your code, that have different meanings based on different times in the program. Why would I want that? The reason is, that that which makes a computer so powerful, is the ability to be given a set of instructions, and act differently based on the circumstances. For example, in the adventure game, your player has the ability to be hit 5 times before he dies. That number is going to change, as he runs through the game. Sometimes when he gets to the tower (for example) he will have 4 "hits" remaining, sometimes he will be down to his last one, and when the bad guy comes and hits him he will die. How is the computer able to keep track and know this? With variables. There will be one variable that is called "life", and you will start it off with 5. Every time that the player gets hit, you will tell life to subtract from itself one. You will also check, if life equals zero, then run the code to die. Since "life" is a variable and not a keyword, you will create this word. I called it life, but you can call it whatever you like. Also, when you go online, the computer asks you to tell them your name. You type in "Shlomo" (assuming that that is your name). Then for the rest of the time that you are on that site they always call you Shlomo. You go onto a new page, and they say "Shlomo, what do you want to buy?". They don't have a hundred premade web pages for each name. Instead, they collect your name into a variable, let's call firstName, and have one web page that says "print out 'firstName, what do you want to buy'".

  • operations and operands: Operations are symbols that have a specific meaning. Operands are the words that use the operations. For example the line " salary + bonus " means take the two operands of salary and bonus, and use the operation of "+" to add them. In Java the operation of "+" means to add, the operation of "=" means to get, and the operation of "==" means equal. "int payment = salary + bonus " means create a number variable called "payment" and let it get the variable of salary added to the variable of bonus.

  • int : in Java a number is represented by the word int. However, this is only one representation. For a complicated number like 4.5, you will need a different representation, like "double" or "float". The word "int" is a keyword that means number. If you write "int payment" you are saying that you are making a variable called payment that is a number. If you write "int payment = 5" you are saying that you are making a variable called payment that is a number and giving it the value of 5.

  • String : A string is a variable that holds a word, or a few words, or a mixture of characters, that do not mean anything besides for a quote. Meaning: when I go online and they ask me for my name, I tell them "Shlomo". They save that quote of "Shlomo" in a String variable. The actual word "Shlomo" doesn't mean anything to the compiler. However, whenever the program wants to call my name it says "print out that String that we called firstName" and whatever is in that String is printed. For example, if I were to write a piece of code "String message = "How are you today?", I would be telling the computer that there is a variable called message, and whenever I refer to that variable, I am referring to the String of "How are you today?".

  • Primitive : Almost everything in Java is an Object or Class, meaning that it has inside it operations, behaviors and methods. Primitives are the exception. A primitive is only what it is, and nothing more, it can not do anything but hold that one piece of information that it is supposed to hold. For example, an int is a primitive. It can only hold a number. A String is an Object, it can change itself. Meaning, I can tell the String change yourself to be capitalized, and the String of "hello" will change into "HELLO". A primitive can not do anything besides hold itself.

  • Debugging : debugging means finding the errors and fixing them.

  • interfaces, user interfaces, and GUI : An interface simply means the way that two entities communicate with each other. For example, if two people write two separate programs that interact with each other, they communicate with each other through an interface. If you write a program that works on a real system, like an ATM, then in order to communicate with the money dispenser, you will need an interface in between. An interface allows the ability to say I don't know how you do what you are doing, all I need is a common way to communicate and get the information that you are giving me that I need to use, and give you only what you need to use. (In Java there is a special thing called an interface, check out the above note). A user interface is the way that a user interacts with a machine. The user doesn't need to know how the machine works, or what is going on inside, it just needs to be able to interact with it. The command console below is a user interface. A GUI or Graphical User Interface is an user interface, that talks to the user using graphics. For example, Windows is a GUI. Instead of typing in the word "exit", "OK', or whatever you will need to type, in a GUI you can press a button, use a scrollbar, etc.

A Command Line User Interface (CUI)
The ability to talk to the computer. You need a new folder you type md, you need the directory you type dir, etc.




A Graphical User Interface (GUI)
The ability to talk to the computer with graphics. You need a new folder you right click, you need the directory you click the folder, etc.



Sunday, October 28, 2007

Yet another Ajax toolkit: Eclipse RAP 1.0

Yet another Ajax toolkit: Eclipse RAP 1.0

Wouldn’t it be nice if you could write your application once and then reuse the code in both a) a “fat client” for high interactivity and offline usage, and b) a “thin client” inside a web browser for ubiquitous access with zero install? The Eclipse Rich Ajax Platform (RAP) library provides one way to do just that.
RAP version 1.0 was released today. According to the project site,

The RAP project aims to enable developers to build rich, Ajax-enabled Web applications by using the Eclipse development model, plug-ins and a Java-only API.

At its core, RAP provides a port of the Standard Widget Library (SWT) for web applications. The SWT API is pretty general, with implementations running on desktops (on Swing or native windowing APIs), smart phones, and now the web.

With RAP, all your logic runs on the server, and the library intelligently renders the user interface bits using browser-side JavaScript (using qooxdoo under the covers). It’s zero-install, and doesn’t even require a browser plug-in.

RAP lets many existing Eclipse RCP applications based on Java and OSGi standard technologies to be used on the web with minor code changes. For obvious performance reasons, RAP doesn’t go back to the server for every keystroke, and the interactivity isn’t quite the same as you could get with a SWT or Swing fat client. However it works surprising well, especially if you’re deploying on a low-latency intranet system. See this site for a live demo, or download it and judge for yourself.

Inevitably, RAP will be compared to other toolkits like the Google Web Toolkit (GWT), Open Laszlo, Adobe AIR, Backbase, Echo2, and many, many more. There isn’t a single best framework for all applications. AIR (formerly Apollo) is perhaps its closest competitor because both AIR and RAP have a goal of letting you deploy applications on both the desktop and the Web. Both frameworks approach the problem from a different angle - AIR from the point of view of moving Web apps to the desktop, and RAP from the point of view of moving desktop apps to the Web. RAP has the advantage of being completely open source, while AIR has the advantage of a top-tier, well established and funded backer.

I’m still rather fond of GWT, though. GWT lets you split your application into client and server side parts that are written in the same language (Java). One thing that GWT is missing is a fat-client incarnation. While you can support some offline activity using Google Gears, it’s a stretch from there to having a shortcut on your desktop that will launch a local application that doesn’t require any net access.

Top search engines in September 2007

Top search engines in September 2007

by ZDNet Research

Nielsen//NetRatings published a list of top search engines in September 2007.

Top search engines in September 2007

Search engine Searches Growth, YTY Share
Google 3,994,158 41.3% 54.0%
Yahoo! 1,443,244 9.3% 19.5%
MSN 890,685 71.5% 12.0%
AOL 444,493 24.0% 6.0%
Ask.com 158,969 4.5% 2.2%
My Web 61,911 N/A 0.8%
Comcast 38,926 N/A 0.5%
BellSouth 35,740 30.3% 0.5%
SBC Yellow Pages 29,424 42.6% 0.4%
My Way 26,750 -78.4% 0.4%

Source: Nielsen//NetRatings

Google Web Toolkit: Towards a better web

Google Web Toolkit: Towards a better web

8/28/2007 01:12:00 PM

Posted by Bruce Johnson and Dan Peterson, Google Web Toolkit team


We're very pleased to tell you that the Google Web Toolkit (GWT)is no longer in beta as of today's release of GWT 1.4. For Java developers who have used GWT to create high-end web applications over the last year, this may not seem all that surprising. But if you haven't yet heard the story behind GWT, this seems like the perfect time...


If you've been in the technology industry for a while, you probably remember when enterprises and software vendors had to think pretty hard about whether to develop locally-installed desktop applications or web-based browser applications. These days, whether you're building mashups, gadgets, or full-blown applications, it's a no-brainer: the browser is the delivery platform of choice. However, users expect more from the up-and-coming generation of web applications than the simple click-and-wait of yesterweb. And if you're a web developer, you know that this requires AJAX, the cluster of technologies including JavaScript and dynamic HTML that can make browsers do backflips.

But the stark reality of AJAX applications is that, although they can deliver sexy features and great usability, they are unusually hard to engineer. Browser quirks and the anything-goes nature of JavaScript will inevitably frustrate even the most dedicated developers and add risk to your schedule with every line of code written. If you do eventually manage to construct a complex AJAX application that works, you're likely to find that maintaining it over time can be a major challenge. And all that doesn't even scratch the surface of testing, optimizing, securing and internationalizing your application. (If you are currently working on an ambitious AJAX project and haven't yet come to this conclusion, please re-read this post in six months when you're further along!)

We've learned a lot from our experiences building web applications, and we're happy to share the tools we've created. Google Web Toolkit is an open source project that helps Java developers harness the richness of AJAX in a cross-platform, web-friendly environment. The magic trick is that GWT cross-compiles Java source code into standalone JavaScript that you can include in any web page. Instead of spending time becoming JavaScript gurus and fighting browser quirks, developers using GWT spend time productively coding and debugging in the robust Java programming language, using their existing Java tools and expertise. Naturally, GWT is also a great way to easily take advantage of the latest-and-greatest Google APIs and browser enhancements, such as Google Gears.

In addition to making debugging far easier, GWT's unique compilation-based approach to AJAX has the nice property that it rewards developers for good software engineering practices. Java source code that is clear and organized can be easily optimized by the GWT compiler, which is a nice antidote to the frequent hack-and-slash approach that's all too common in JavaScript development. As your application grows, the GWT compiler begins to pay off in even bigger ways. Unused code is automatically removed so that scripts are smaller and pages load faster. Complex code can be automatically coalesced and simplified. Most importantly, because the Java language is statically typed, many common errors can be caught during development rather than production. You can observe the high-performance results yourself in GWT's sample Mail application.


Technical details aside, GWT makes it easy to develop fast, friendly web apps that users love — which is, after all, the point.


Download GWT 1.4.

Google’s new mantra: Making the Web a better platform for all

Google’s new mantra: Making the Web a better platform for all by ZDNet's Dan Farber -- “In the next year we will make a series of announcements and spend hundreds of millions on innovations and giving them away as open source,” said Vic Gundotra, the new head of Google’s developer programs. Google believes that innovation on the Web has been lacking. XML and HTTP Request were innovative technologies in 1998, but [...]

Saturday, October 27, 2007

Java How to Program (6th Edition)

Java How to Program (6th Edition)



Publisher: Prentice Hall; Sixth, book only edition
Language: English
ISBN: 0131483986
Paperback: 1568 pages
Data: August 4, 2004
Format: CHM
Description: The Deitels' groundbreaking How to Program series offers unparalleled breadth and depth of programming concepts and intermediate-level topics for further study. The books in this series feature hundreds of complete, working programs with thousands of lines of code. This edition is completely up-to-date with The Java 2 Platform Standard Edition (J2SE) 1.5. Now includes topics such as autoboxing, enumerations, enhanced for loops, static import statements, variable-length argument lists, and much more. Presents each new concept in the context of a complete, working program, immediately followed by one or more windows showing the program's input/output dialog. Enhances the Live-Code Approach with syntax coloring. Provides Helpful Programming Tips, all marked by icons: Good Programming Practices, Common Programming Errors, Error-Prevention Tips, Performance Tips, Portability Tips, Software Engineering Observations, Look and Feel Observations.

Download - External Mirror

EJB Tutorial.

What Is an EJB?

In a typical J2EE application, Enterprise JavaBeans (EJBs) contain the application's business logic and live business data. Although it is possible to use standard Java objects to contain your business logic and business data, using EJBs addresses many of the issues you would find by using simple Java objects, such as scalability, lifecycle management, and state management.

Beans, Clients, Containers, and Servers

An EJB is essentially a managed component that is created, controlled, and destroyed by the J2EE container in which it lives. This control allows the container to control the number of EJBs currently in existence and the resources they are using, such as memory and database connections. Each container will maintain a pool of EJB instances that are ready to be assigned to a client. When a client no longer needs an EJB, the EJB instance will be returned to the pool and all of its resources will be released. At times of heavy load, even EJB instances that are still in use by clients will be returned to the pool so they can service other clients. When the original client makes another request of its EJB, the container will reconstitute the original EJB instance to service the request. This pooling and recycling of EJB instances means that a few EJB instances, and the resources they use, can be shared between many clients. This maximizes the scalability of the EJB-based application.

The client that uses the EJB instance does not need to know about all of this work by the container. As far as the client is concerned, it is talking to a remote component that supports defined business methods. How those methods are implemented and any magic performed by the container, such as just-in-time instantiation of that specific component instance, are entirely transparent to the client part of the application.

The EJB benefits from certain services provided by the container, such as automatic security, automatic transactions, lifecycle management, and so on. To do this, the EJB must conform to certain rules and implement an appropriate interface that allows the container to manage the component. The EJB is packaged with configuration information that indicates the component's requirements, such as transaction and security requirements. The container will then use this information to perform authentication and control transactions on behalf of the component—the component does not have to contain code to perform such tasks.

The primary purpose of the container is to control and provide services for the EJBs it contains. When it needs to use some underlying functionality, such as creating a transaction on behalf of a bean, it uses the facilities of the underlying EJB server. The EJB server is the base set of services on top of which the container runs. Different types of EJB will run in different containers, but many different EJB containers can run on a single EJB server. EJB servers are generally delivered as part of a J2EE-compliant application server (examples include BEA WebLogic and IBM WebSphere). You will install and run the application server, which will provide the underlying services required of an EJB server and will host EJB containers.

The EJB Landscape


As you have seen, the J2EE Blueprints (
http://java.sun.com/blueprints/enterprise/index.html) define a target architecture for a typical J2EE-based application. In this architecture, EJBs live in the middle tier and are used by other application components that live in the presentation tier. Although it is possible that both of these logical tiers will reside on the same computer, it is most likely that they will reside on different machines. This means that an EJB will usually have to be made available to remote clients.

To offer services to remote clients, EJBs will export their services as RMI remote interfaces. RMI allows you to define distributed interfaces in Java. There are certain caveats on doing this, not only at the implementation level (such as declaring that RemoteExceptions may be thrown when calling a method on an EJB) but also at the design level. Designing remote interfaces is a skill in itself, which will be explored as you progress through topics in this book, such as EJBs and J2EE Patterns.

Because they must use an RMI-based interface to access the functionality of the EJB, the clients of an EJB must have some programming functionality. This means that they are typically either "thick" clients that provide a GUI interface or Web-server components that deliver HTML interfaces to "thin" clients. The different types of client are explored in more detail shortly.

In the other direction, EJBs themselves will make use of data sources, such as databases and mainframe systems, to perform the required business logic. Access to such data and services can be through a JDBC database connection, a J2EE Connector, another EJB, or a dedicated server or class of some form.

Discovering EJBs

While it is quite easy to draw pictures of a 3-tier system containing boxes labelled "EJB," it is important to identify what application functionality should go into an EJB.

At the start of application development, regardless of the precise development process used (Rational Unified Process (RUP), eXtreme Programming (XP), and so on), there is generally some analysis that delivers a Unified Modelling Language (UML) domain model (this identifies the main elements of the business problem to be solved). This can then form the basis of a solution model where the business concepts are mapped into appropriate design-level artefacts, such as components. This is where EJBs come into the design.

The UML model will consist of a set of classes and packages that represent single or grouped business concepts. A class or package can be implemented as an EJB. Generally, only larger individual classes will become EJBs in themselves, because EJBs are intended to be fairly coarse-grained components that incorporate a reasonably large amount of functionality and/or data.

There are generally two types of functionality discovered during analysis—data manipulation and business process flow. The application model will usually contain data-based classes such as Customer or Product. These classes will be manipulated by other classes or roles that represent business processes, such as Purchaser or CustomerManager. There are different types of EJB that can be applied to these different requirements.

Types of EJB

There are three different types of EJB that are suited to different purposes:

· Session EJB—A Session EJB is useful for mapping business process flow (or equivalent application concepts). There are two sub-types of Session EJB — stateless and stateful— that are discussed in more detail on Day 5. Session EJBs commonly represent "pure" functionality that is created as it is needed.

·Entity EJB—An Entity EJB maps a combination of data (or equivalent application concept) and associated functionality. Entity EJBs are usually based on an underlying data store and will be created based on that data within it.

·Message-driven EJB—A Message-driven EJB is very similar in concept to a Session EJB, but is only activated when an asynchronous message arrives.
As an application designer, you should choose the most appropriate type of EJB based on the task to be accomplished.

Common Uses of EJBs

So, given all of this, where would you commonly encounter EJBs and in what roles? Well, the following are some examples:

· In a Web-centric application, the EJBs will provide the business logic that sits behind the Web-oriented components, such as servlets and JSPs. If a Web-oriented application requires a high level of scalability or maintainability, use of EJBs can help to deliver this.

·Thick client applications, such as Swing applications, will use EJBs in a similar way to Web-centric applications. To share business logic in a natural way between different types of client applications, EJBs can be used to house that business logic.

·Business-to-business (B2B) e-commerce applications can also take advantage of EJBs. Because B2B e-commerce frequently revolves around the integration of business processes, EJBs provide an ideal place to house the business process logic. They can also provide a link between the Web technologies frequently used to deliver B2B and the business systems behind.

· Enterprise Application Integration (EAI) applications can incorporate EJBs to house processing and mapping between different applications. Again, this is an encapsulation of the business logic that is needed when transferring data between applications (in this case, in-house applications).

These are all high-level views on how EJBs are applied. There are various other EJB-specific patterns and idioms that can be applied when implementing EJB-based solutions. Given this context, common types of EJB client include the following:

· A servlet or JSP that provides an HTML-based interface for a browser client
· Another EJB that can delegate certain of its own tasks or can work in combination with other EJBs to achieve its own goals
· A Java/Swing application that provides a front-end for the business processes encapsulated in the EJB
· A CORBA application that takes advantage of the EJB's business logic
· An applet that takes advantage of the business logic in a remote EJB so that this business logic does not need to be downloaded to the client

These are common ways that EJBs are applied. What benefits does the use of EJBs give to you as a developer?

Go to page: 1
2 Next
Next article:
Introduction to EJBs: Part 2

A Programmers Guide to Java Certification: A Comprehensive Primer, Second Edition

A Programmers Guide to Java Certification: A Comprehensive Primer, Second Edition


Publisher: Addison-Wesley Professional; 2 edition Language: English ISBN: 0201728281 Paperback: 672 pages Data: August 8, 2003 Format: CHM
Description: What you will find in this book:
* Extensive coverage of all the objectives defined for the Sun Certified Programmer for Java 2 Platform 1.4 exam
* Easy-to-follow structure with chapters organized according to the exam objectives as laid out by Sun Microsystems
* Summaries that clearly state and differentiate the exam objectives and the supplementary objectives to be covered in each chapter
* A list of Sun's objectives for the SCPJ2 1.4 exam, and a guide to taking the exam
* A complete mock exam with new questions (not repeats of review questions)
* A CD that includes several mock exams and a version of the SCJP 1.4 Exam Simulator by Whizlabs Software, which simulates the exam-taking experience
* Numerous exam-relevant review questions to test your understanding of each major topic, with annotated answers
* Programming exercises and solutions at the end of each chapter
* Copious code examples illustrating concepts where the code has been compiled and thoroughly tested on multiple platforms
* Program output demonstrating expected results from running the examples
* Extensive use of UML (Unified Modeling Language) for illustration purposes
* An introduction to basic terminology and concepts in object-oriented programming
* Advice on how to avoid common pitfalls in mastering the language and taking the exam
* Platform-independent coverage--platform-specific details are provided where relevant *
* Information about the SCPJ2 Upgrade exam

Download - External Mirror