Sunday, 22 September 2013

JAVA OO Concepts

Object-Oriented Programming (OOP) is a programming paradigm using "objects" to design applications. 
An object is a thing which has its own identity. An object contains both state and behavior. State of an object is the current data and behavior is implemented as methods. An object in an OO language can be easily compared to a real world object. Consider a car. A car has some properties like model, fuel type etc which are the state (or properties) of that object. Similarly it will also have functions.
Object-Oriented Programming (OOP) has certain important features like Encapsulation, Polymorphism, Inheritance and Abstraction. These features are also referred to as OOPS concepts.

ENCAPSULATION

Encapsulate in plain English means to enclose or be enclosed in or as if in a capsule. A capsule is an unit. In languages such as C and C++, we can have global variables outside classes. But in Java, everything is within a class or interface. So everything is within some unit. Encapsulation in Java is the process of wrapping up of data (properties) and behavior (methods) of an object into a single unit; and the unit here is a Class (or interface).
Encapsulation enables data hiding, in which, an object hide its attributes behind its operations. An object hides its attributes from the outside world by making it private, and then exposes them through setters and getters. A setter is a method used to change the value of an attribute and a getter is a method used to get the value of an attribute. There is also a standard naming convention for getters and setters, but Java compiler won't complain even otherwise.
Example: Consider a variable name and its getter and setter:
private String name;
public String getName() {
  return name;
}
public void setName(String name) {
  this.name=name;
}
Since this is a standard convention, many IDEs like eclipse will generate it for you.
Without encapsulation, the code would become dependent on attributes. It would be then difficult to change the internal representation of the object in future. Consider the example of a linked list’s getsize method. We might be now using a variable named size that is updated on every insert / delete operation. Later we might decide to traverse the list and find size every time someone ask for size. But if some code was directly accessing the size variable, we would have to change all those code for this change. However if we were accessing the size variable through a getsize method, other code can still call that method and we can do our changes in that method.

INHERITANCE

Inheritance allows us to specify that a class gets some of its characteristics from a parent class and then adds unique features of its own.
For example consider a Vehicle parent class and a child class Car. Vehicle class will have all common properties and functionalities for all vehicles in common and Car will inherit those common properties from the Vehicle class and then add those properties which are specific to a car. Here, Vehicle is known as base class, parent class, or superclass. Car is known as derived class, Child class or subclass.
Java supports single inheritance (single parent) in a class context referred to as implementation inheritance. Java also supports multiple inheritance (multiple parents) limited to an interface content, which is also referred to as interface inheritance.

POLYMORPHISM

The ability to change form is known as polymorphism. Java supports different kinds of polymorphism like oveloading, overriding, parametric etc.
Overloading
The same method name (method overloading) or operator symbol (operator overloading) can be used in different contents. In method overloading, multiple methods having same name can appear in a class, but with different signature. And based on the number and type of arguments we provide while calling the method, the correct method will be called.
Java doesn't allow operator overloading yet + is overloaded for class String. The ‘+’ operator can be used for addition as well as string concatenation.
Overriding (or subtype polymorphism)
Overriding is defining a method in a subclass with the same name and type signature as a method in its superclass and when this subclass instance appears in the superclass context like Parent p = new Child() and when we execute an overridden method as p.myMethod(), the subtype’s version of that method is executed. Here, the actual method called will depend on the object at runtime, not the reference type.
Consider an example class Shape with a draw() method. It can have subclasses Circle and Square. An object of Circle or Square can be assigned to a Shape reference as Shape s = new Circle();. While executing draw() on the Shape reference, it will draw a Circle or Square based on the actual object assigned to it at runtime.
In java, only instance methods are overridden. Static methods, static variables and instance variables are just re-declared (hiding parent method) in the child class, but not overridden. Here, the actual method called depend on the reference type and not the object at runtime. Hence by calling a method using a parent reference executes the parent class versions of that method.
In java 5 and above, we can confirm whether we are doing valid override by using the @Override annotation above the subclass's method. Compiler will throw error when @Override is applied on static methods, static variables or instance variables as only instance methods are overriden.
Parametric polymorphism through generics
Within a class declaration, a field name can associate with different types and a method name can associate with different parameter and return types. Java supports parametric polymorphism via generics.
An example is a list which can accept the type of data it contains through generics.
List<String> list = new ArrayList<String>();
Coercion (or implicit conversion)
An operation can serve multiple types through implicit type conversion.
For example, in case of a division operation, if one operand is an integer and other is a floating point, the compiler coerces (implicitly converts) the integer to a floating point value, to prevent a type error.
Another example is passing a subclass object reference to a method’s superclass parameter type. The compiler coerces the subclass type to the superclass type, to restrict operation to those of the superclass.
Note: Many text books consider only oveloading, overriding and parametric as types of polymorphism.

ABSTRACTION

In plain English, abstract means a concept or idea not associated with any specific instance and does not have a concrete existence. Abstraction in Object Oriented Programming refers to the ability to make a class abstract. Abstraction captures only those details about an object that are relevant to the current perspective. Abstraction tries to reduce and factor out details so that the programmer can focus on a few concepts at a time. Java provides interfaces and abstract classes for describing abstract types. An interface is a contract or specification without any implementation. An interface can't have behavior or state. An abstract class is a class that cannot be instantiated. All other functionality of the class still exists. Abstract classes can have state and can be used to provide a skeletal implementation.

Coupling vs Cohesion

Coupling and cohesion are two important concepts in the OO design and hence we will briefly discuss it here.
Coupling is the degree to which one class knows about another class. If the knowledge is only through exposed interfaces (data hiding), it is called loosely coupled. If the knowledge is more like accessing data members directly, it is called tightly coupled. We should try to make our code as loosely coupled as possible. Even though you make some change in a class adhering strictly to the class's API, tight coupling can make other classes that use this class not working properly after the change.
The term cohesion is used to indicate the degree to which a class has a single, well-focused purpose. The more focused a class is, the higher its cohesiveness, which is a good thing. The key benefit of high cohesion is that such classes are typically much easier to maintain than classes with low cohesion. Another benefit of high cohesion is that classes with a well-focused purpose tend to be more reusable than other classes.

Main concept: Object-oriented programming is all about creating a society of cooperating, active "agents" (objects) that, working together, accomplish the desired task.

Classes and objects
A class describes the data and the methods of its objects. Every object belongs to some class.
An object contains data (instance variables) representing its state, and instance methods, which are the things it can do.
A class may also contain its own data (class variables) and class methods. The keyword static denotes such data and methods.
An object "knows" what class it belongs to, and can use class data and class methods, but a class does not "know" about its objects.
Classes form a hierarchy (tree), with Object at the root. Every class, except Object, has one and only one immediate superclass, but that class has its own immediate superclass, and so on all the way up to Object at the root, and all of these are superclasses of the class. The keyword extends denotes the immediate superclass.
A class contains one or more constructors for making new objects of that class. If (and only if) the programmer does not write a constructor, Java provides a default constructor with no arguments. The default constructor sets instance variables as follows: numeric types are set to zero, boolean variables are set to false, char variables are set to '\0', and object variables are set to null.
The purpose of a constructor is to create an object in a valid state. No other work should be done in a constructor.
When a constructor executes, the very first thing it does is call the constructor for its superclass. You can write this constructor call explicitly, with super(...);, or you can let it implicitly call the default constructor.
A constructor for a class can call another constructor for the same class by putting this(...); as the first thing in the constructor. This allows you to avoid repeating code.
Objects are declared just like primitive values, with the syntax ClassName objectName; but are not defined (allocated space and given a value) until you create one by calling the constructor with the keyword new.
Classes inherit all the data and all the methods of their superclasses, but do not inherit constructors.
You can assign an object of a class to a variable (that is, variable = object) declared to be of that class or any of its superclasses (thus, you can assign any object to a variable of type Object). If you have an object in a more general variable or expression (for example, a String value in an Object variable), you can cast it to the correct type with the syntax (type)variable or (type)(expression).
Casting an object to a more general type is called upcasting, and is always legal. Casting an object to a more specific type is called downcasting, and Java inserts a run-time check to ensure that the cast is legal. Casting does not affect what the object is, it only changes what fields and methods are available on the object at the position the cast occurs.
A class that is declared as final may not be extended by subclasses.
The instanceof operator tests whether its left operand (an object) is an instance of its right operand (a class or interface). The result will be true if the right operand is the class or any superclass of the object. Well-designed programs have very little need for the instanceof operator.
A Java source file may contain only one public class, though it may contain additional non-public classes. The name of the file must be the same as the name of the class, but with the .java extension.
Classes should be as self-contained and independent as it is reasonable to make them. The interface (the fields and methods it makes available outside the class) should be kept small.
An object is responsible for keeping itself in a valid state. Therefore, it should limit write access to essential fields.
Access
Variables and methods are accessed by name.
There are three dimensions to accessing names: namespaces, scope, and access modifiers.
Java uses six different namespaces: package names, type names, field (variable) names, method names, local variable names (including parameters), and labels. Identical names of different types do not conflict; for example, a method may be named the same as a local variable. However, it's best to avoid reusing names in this manner.
The scope of a name is the part of a class in which it can be seen.
  • A variable declared anywhere in a class can be seen everywhere in a class.
  • The scope of a method's formal parameters is the entire method.
  • The scope of a variable declared in a block (indicated by braces, { }) extends from the declaration to the closing brace. A method body is always a block.
  • The scope of a variable declared in the initialization part of a for loop is the entire for loop.
Class variables and class methods (denoted by the keyword static) can be used anywhere within the class.
Instance variables and instance methods can be used anywhere within the class except in static methods.
Within an instance method, the keyword this refers to the object currently executing the method.
When an instance variable and a formal parameter have the same name, the name refers to the formal parameter; prefix the name with this. to refer to the instance variable.
To refer to an instance name in a different object, use the syntax otherObject.name. To refer to a class (static) name in a different class, use the syntax OtherClass.name.
You can refer to a name (class or instance) in another class if and only if you have access privileges. Possible access privileges are:
  • public : You can access it from anywhere.
  • protected : You can access it from any other class in the same directory (folder), or from any subclass.
  • package (default) : You can access it from any other class in the same directory.
  • private : You cannot access it from outside the class. Surprisingly, private variables and methods can be accessed by other objects in the same class.
You can refer to a name in a class in another package in either of two ways:
  • You can use the fully-qualified name, for instance java.awt.Color.RED
  • You can import a specific class or (with *) all classes in a given package, then use the name with or without the package qualification, for instance Color.RED.

Methods
A method is a named executable chunk of code.
All executable statements must be in methods. (Exception: "initialization blocks," not covered here.)
A method has a signature consisting of its name and the number and types of its parameters (also called "arguments"). The parameters in the method declaration are its formal parameters.
A method has a return type, which is not part of its signature. If the return type is other than void, then the method must return a value of the specified type.
A method may have local variables (also called method variables). These follow the scope rules, and are never available anywhere outside the method. The concepts static, public, protected, package, and private do not apply to local variables. Local variables have undefined values upon method entry. Formal parameters are a kind of local variable, but have initial values as supplied by the corresponding actual parameters.
Every method must have a signature that is unique within its class. Methods in other classes (even superclasses and subclasses) may have the same signature.
An instance method is executed by sending a message to its object. The message consists of: a reference to the object (typically its name), a dot, the name of the method, and zero or more actual parameters enclosed in parentheses. The object will respond by executing the corresponding method in the actual class of the object, which may be different from the type of the variable holding the object.
A class method is executed by sending a message to the class. The message consists of: the name of the class, a dot, the name of the method, and zero or more actual parameters enclosed in parentheses. The class will respond by executing the corresponding static method in that class.
When a message is sent, and before the method executes, the values of the actual parameters are copied into the corresponding formal parameters. Then the method body executes. Then the return value replaces the message, and all local names are forgotten.
Polymorphism

The two kinds of polymorphism are overloading and overriding.
Overloading occurs when a class declares two or more methods with the same name but different signatures. When a message is sent to an object or class with overloaded methods, the method with the best matching signature is the one that is used ("invoked").
  • If the message and the method have a different number of parameters, no match is possible.
  • If the message and the method have exactly the same types of parameters, that is the best possible match.
  • Messages with specific actual parameter types can invoke methods with more general formal parameter types. For example if the formal parameter type is Object, an actual parameter of type String is acceptable (since a String value can be assigned to an Object variable). If the formal parameter is type double, an actual parameter of type int can be used (for similar reasons).
  • If there is no clear best match, Java reports a syntax error.
Overriding occurs when a class declares a method with the same signature as that of an inherited method. When a message is sent to the object (or class, if it's a class method), the locally-defined method is the one that is used.
  • Overriding is commonly used to make methods more specific.
  • When a method name is overridden, you can still invoke the superclass' method (from inside the class) with the syntax super.name(parameters).
  • From outside the class, you can cast an object to its superclass and then invoke the method, with the syntax ((Superclass)object).name(parameters).
  • Restrictions:
    • Although the return type is not part of the signature, an overriding method must have the same return type as the method it overrides.
    • The overriding method cannot be more private than the method it overides (public > protected > package > private).
    • The overriding method may not throw any exception types in addition to those thrown by the method it overrides (although it may throw fewer exception types).
A class can declare a variable with the same name as an inherited variable, thus "hiding" or shadowing the inherited version. (This is like overriding, but for variables.)
  • Shadowing should be avoided.
  • When shadowing does happen, you can access the superclass name by either the syntax super.name or by casting the object to its superclass, with the syntax ((Superclass)object).name.
Interfaces and abstract classes

The purpose of interfaces and abstract methods is to ensure that any classes derived from them will share the same set of methods.
An abstract method is a method that is declared but not defined. It is declared with the keyword abstract, and has a header like any other method, but ends with a semicolon instead of a method body.
An abstract class is one that contains one or more abstract methods; it must itself be declared with the abstract keyword. A class may be declared abstract even if it does not contain any abstract methods. A non-abstract class is sometimes called a concrete class.
An abstract class cannot be instantiated; that is, no objects of that class can be created. Instead, you can create subclasses that define (in the usual way) the inherited abstract methods, and these subclasses can be instantiated.
An interface is declared with the keyword interface instead of the keyword class. An interface may contain only public abstract methods and definitions of constants (that is, final variables). The keywords public and abstract before each method are optional.
A class may extend only one other class, but it may implement any number of interfaces. The syntax is: class Class extends Superclass implements Interface1, Interface2, .... When a class extends an interface, it may implement (define) some or all of the inherited abstract methods. A class must itself be declared abstract if it inherits abstract methods that it does not define.
A variable may be declared to have a type that is an abstract class or an interface; any object whose type implements or extends the variable's type may be assigned to that variable. The instanceof operator may take a class, abstract class, or interface as its right operand.
Inner classes
An inner class is a class declared within another class. The four kinds of inner class are: (1) member class, (2) static member class, (3) local inner class, and (4) anonymous inner class. Unlike "outer" classes, the usual scope rules apply to inner classes.
A member class is defined at the top level of the class, along with fields and methods. It may have the same access modifiers as variables (public, protected, package, static, final), and is accessed in much the same way as variables of that class.
A static member class is defined like a member class, but with the keyword static. Despite its position inside another class, a static member class is actually an "outer" class--it has no special access to names in its containing class. To refer to the static inner class from a class outside the containing class, use the syntax OuterClassName.InnerClassName. A static member class may contain static fields and methods.
A local inner class is defined within a method, and the usual scope rules apply to it. It is only accessible within that method, therefore access restrictions (public, protected, package) do not apply. However, because objects (and their methods) created from this class may persist after the method returns, a local inner class may not refer to parameters or non-final local variables of the method.
An anonymous inner class is one that is declared and used to create one object (typically as a parameter to a method), all within a single statement. The anonymous inner class may either extend a class or implement an interface; the syntax is the same for both: new Super(parameters){methods}, where Super is the name of the extended class or implemented interface, parameters are the parameters to the constructor for that class or interface (usually just ()), and methods override any inherited methods.
The keyword static may not be used within any inner class except a static member class.

Sunday, 1 September 2013

The Java Virtual Machine

Java is platform independent. This means that it will run on just about any operating system. So whether your computer runs Windows, Linux, Mac OS, it's all the same to Java! The reason it can run on any operating system is because of the Java Virtual Machine. The Virtual Machine is a programme that processes all your code correctly. So you need to install this programme (Virtual Machine) before you can run any Java code.
Java is owned by a company called Sun Microsystems, so you need to head over to Sun's website to get the Java Virtual Machine, also known as the Java Runtime Environment (JRE).
You can check to see if you already have the JRE on your computer by clicking the link "Do I have Java?". You'll find this link under the big Download button at the top of the page. (Unless Sun have changed things around, again!) When you click the link, your computer will be scanned for the JRE. You will then be told whether you have it or not. If not, you'll be given the opportunity to download and install it.

The "manual" in the above links means "manual download". The page gives you download links and instructions for a wide variety of operating systems.
After downloading and installing, you may need to restart you computer. When you do, you will have the Java Virtual Machine.


The Java Software Development Kit

At this stage, you still can't write any programmes. The only thing you've done is to install software so that Java programmes can be run on your computer. To write code and test it out, you need something called a Software Development kit.

The one we're going to be using is called Java SE. (The SE stands for Standard Edition.). Click on that link, then on "Java SE (JDK) 6 Download". You'll then find yourself on a page with a bewildering list of options to download. Because we're going to be using NetBeans, locate this:
JDK 6 Update X with NetBeans 6.x
Click the Download link to be taken to yet another page. Click the top download to be taken to a page that asks you to select your operating system. Click Continue to finally get the download you need. A word of warning, though - this download will be big, at over a 130 megabytes at the time of writing! Once you've downloaded the JDK and NetBeans, install it on your computer.
We're going to be using NetBeans to write our code. Before launching the software, however, here's how things work in the world of Java.

How things work in Java

You write the actual code for your programmes in a text editor. (In NetBeans, there's a special area for you to write code.) The code is called source code, and is saved with the file extension .java. A programme called Javac is then used to turn the source code into Java Byte Code. This is known as compiling. After Javac has finished compiling the Java Byte Code, it creates a new file with the extension .class. (At least, it does if no errors are detected.) Once the class file has been created, it can be run on the Java Virtual Machine. So:
  • Create source code with the extension .java
  • Use Javac to create (compile) a file ending in .class
  • Run the compiled class
NetBeans handles all the creating and compiling for you. Behind the scenes, though, it takes your sources code and creates the java file. It will launch Javac and compile the class file. NetBeans can then run your programme inside its own software. This saves you the hassle of opening up a terminal window and typing long strings of commands.
Now that you have a general idea of how Java works, launch your NetBeans software. Then click the link below to go to continue with the lesson.

Thursday, 22 August 2013

Java OOPs Concept

Lesson: 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.

Tuesday, 20 August 2013

10 Best Java Web Development Framework

10 Best Java Web Development Framework

There are a majority of enterprises running Java applications and working on Java web development framework. What remains to be seen is that a number of companies are tied to the conventional web development framework and haven’t actually started to anticipate what could be the best Java web development framework. Even the Java-one might hold no unified voice for what web framework is best. There are several easy to use Java web frameworks that are out now a days, and they are too many. Essentially choosing the best web development framework has become more intricate, specifically due to three reasons. On a broader perspective, the web technology landscape has undergone a sea change; far more choice of technology; and changing requirements for modern web applications. After an extensive research we assorted the 10 best Java web development framework that we would like to share with you.

1. Struts 2

Apache Struts 2 is an enterprise-ready web framework for Java application. It has been designed to streamline the entire development cycle starting from building to deploying. Struts 2 is a combined effort of WebWork and Struts communities. Unlike conventional web applications, it can create dynamic responses. Struts 2 comes with an improved design with clean code for HTTP-independent framework interfaces. Added interactivity and flexibility with AJAX tags gives the look and feel just like standard Struts tags. It doesn’t use Action forms, instead Struts 2 uses JavaBean to capture form input or put properties directly on an Action class. POJO Actions enables class to used as an action class with optional interface. Plugin APIs for the framework include config browser, JasperReports, JavaServer Faces, Pell Multipart, Plexus, sitegraph, sitemesh, tiles and Struts 1. The framework essentially requires Servlet API 2.4, JSP API 2.0 and Java 5.
Struts 2 could be a great option for small teams looking to learn about the open source tools they use. It’s not for armchair programmers looking for drag and drop development.


2. JSF

JavaServer Faces (JSF) is a java web application framework established the standard for development of server-side user interfaces for Java EE application. The JSF APIs are designed to leverage tools that would make we application development increasingly easier. It uses a component based approach. JSF uses JavaServer Pages JSP as its display technology, but it can also support other technologies such as XUL and Facelets . The UI is saved on clients request for new page and restored when the response is returned.
JSF has a set of API for representing user interface components and manages their state, converting values, input validation and event handling, defining page navigation and support for accessibility and internationalization. It has two JavaServer Pages (JSP) custom tag libraries for expressing a JavaServer Faces interface within a JSP page. Some of its key features include server-side event model, state management, JavaBeans with dependency injection and Unified Expression Language for both JSP 2.0 and JSF 1.2. JSF 2.0 offers improved support for Ajax by allowing UI logic to run partly on the client and not on the server.
For the latest, in the public draft for JEE6, Facelets would be adopted as the official view technology for JSF 2.0. This would resolve the life-cycle conflicts with JSP that forced developers to go for workarounds.
    Pros
  • Java EE standard with lots of demand and jobs
  • Initially was fast and easy to develop
  • Loads of component libraries
    Cons
  • Tag soup for JSPs
  • Lacks unified source for implementation
  • Doesn’t support REST or Security well

3. Spring MVC

It is a layered Java/J2EE framework integrating a number of different technologies and is applicable to wide range of projects. Spring is based on code published in Expert One-on-One J2EE Design and Development. Spring clearly separates business, navigation and presentation logic. It is a proven web mechanism constructed with a clean web tier. Spring MVC allows users to use any object as a command or form object – there is no need to implement a framework-specific interface or base class. Spring’s features a highly flexible data binding. MVC Model and VIew is based on the map interface that is highly configurable, either via bean names, via a properties file, or via your own ViewResolver implementation. Spring supports controller as an optional command or form object. It has an extremely flexible view resolution that can even write a view directly to the response.
It should be considered a strategic base platform for web application development.


4. Wicket

Apache Wicket is a lightweight component based web application framework for the Java programming language. Wicket is patterned after stateful GUI frameworks. It features trees of components that use listener delegates to react to HTTP requests against links and forms. With XHTML for templates it separate presentation and business logic and allows templates to be edited with conventional WYSIWYG design tools. Within the framework each component is backed by its own model that represents the state of the components. Wicket might be the best framework for making use of your developers resources.


5. Stripes

The web framework offers a lot of complex data interactions. It offers powerful type conversion, binding and validation. Stripes has been designed to manage large, complex forms and maps them directly to objects etc. Stripes requires zero external configuration beyond the registration of one servlet and one filter. Most importantly, Stripes provides simple and effective solution to common problems such as indexed properties, multi-event forms, localization and use of domain objects in the web tier. It is a compact web development framework with just few dependencies.


6. Tapestry

It is an object oriented powerful, open-source, all-Java framework for creating leading edge web applications in Java. The framework allows implementation of applications according to the model-view-controller design pattern. Tapestry offers an innovative web application development concept in terms of objects, methods and properties instead of URLs and query parameters. It adopts a modular approach to web development by combining user interface components (objects) on the web page and their corresponding Java classes.
It could be a rescue for those looking to avoid scripting environments such as JavaServer Pages or Velocity. It provides a complete framework for creating extremely dynamic applications with minimal amounts of coding. The web development framework focuses on simplicity, ease of use, and relieves programmers from creating enormous block codes.
For the latest Tapestry offers a new approach with an entirely new code base, centered on Plain Old Java Objects, annotations and naming conventions, and runtime bytecode enhancement.


7 . RIFE

This is a unique framework for web development and design with tools and APIs to implement commonly used web features. It has been designed for separating tasks during a development cycle, ensuring that each developer or designer focuses on his own tasks. If needed the any work can be effortlessly integrated with the work of the rest of the team. RIFE’s has a number of independently usable toolkits, which can be integrated to boost productivity. All the declaration and definitions in RIFE is handled in one place in the code. This makes it easy for the developers to reduce code replication, enforce consistency, and ease the maintenance. This results in a loosely coupled and very robust system.
It combines the best of request based and component approach to offer consistent component based object model. RIFE’s design provides the best of request-based and component-based approaches and blends them together in a consistent component object model. The web engine provides a solution that values maintainability without compromising on productivity. Through a centralized site structure, an application can be split up into easily reusable binary modules that can be seamlessly integrated into other projects. There is a wide scope for incremental improvements with little or no risk of unwanted anomalies in the system.


8. Seam

It’s a powerful open source web application framework developed by JBoss. Seam offers a perfect platform for building rich Internet applications in Java. It is a unified full-stack solution that integrates technologies such as Ajax, JavaServer Faces (JSF), Java Persistence (JPA), Enterprise Java Beans (EJB 3.0) and Business Process Management (BPM) into tooling. Seam also expands the concept of contexts. All the Seam component are enclosed within a context. The default Seam context is conversation which can span multiple pages and usually spans the whole business flow, from start to finish. All the actions in a session context is captured until the user logs out or closes the browser. WYSIWYG development in Seam is facilitated through the use of JBoss Tools.
Seam overcomes design issues by eliminating both eliminate complexity at both architecture and API levels. It enables developers to assemble complex web applications using simple annotated Java classes, a rich set of UI components, and XML in parts. Above all, it offers outstanding support for conversations and declarative state management that can introduce a more sophisticated user experience. At the same time it eliminates the common bugs found in traditional web applications.
Exceptionally, Seam features a PDF document creator, e-mailing, graph creation and creation of Microsoft Excel worksheets.


9. Google Web Toolkit (GWT)

GWT is a Java software development framework that allows web developers to build and maintain complex Javascript front-end applications in Java. The web development framework makes it easy for developers to write AJAX applications like Google Maps and Gmail. Other than a few native libraries, everything is Java source that can be built on any supported platform with the included GWT Ant build files. GWT focuses on reusable, efficient solutions for asynchronous remote procedure calls, Internationalization, history management, bookmarking and cross-browser portability. It allows developers to develop and debug AJAX applications in the Java language with any Java development tools of their choice. However, due to lack of modularity in JavaScript, sharing, testing, and reusing AJAX components becomes a hassle.


10 . OpenXava

It is a web development framework for creating Ajax Enterprise applications with Java. OpenXava has been designed by Java developers looking for a productive Java Enterprise applications. In OpenXava developers have to provide only the JPA classes to obtain a full featured application ready for production. It requires no code generation. It allows rapid and easy generation of CRUD modules and report generation. It also allows the flexibility to develop complex real life business applications as customer relationship, invoicing, accounting packages, warehouse management, etc. It The web framework offers full Ajax support and can be used on application server (Tomcat, JBoss, WebSphere, etc).
It is a faster framework than Ruby On Rails, Spring MVC, or any other MVC framework.

Sunday, 18 August 2013

File Structure
  • Each source file can contain only one public class or interface. Two public classes in the same file are not allowed.
  • A source file can contain any number of non-public classes. Each class will be compiled into a separate .class file.
  • The source file name must be the name of the public class or the interface.
  • The source file structure should be as follows :
    Package declaration
    Import statement
    Class or interface definition
  • A package statement must appear as the first statement of a source file followed by import statements and class or interface definition.
  • Packages are a collection of related classes and interfaces.
  • If a class or interface is without a package name, then those are put into a default no-name package.
  • java.lang package is imported by default, we don't have to import it explicitly.
main method
  • All java application programs must have a main() method.
  • main method() is the application's entry point, which would be called by the JVM.
  • main method()'s return type is void, access specifier is public, argument is String array and it is static.
  • order of public and static does not matter but void should always come before main().
  • main() can be declared as final.
  • Applets need not have a main() method. It's not a problem even if they have a main method.
Primitives
  • There are 8 primitive data types in java. They are not objects.
  • boolean is 8 bits in size and stores true or false. It's default value is false.
  • byte is 8 bit signed integer and stores values in the range of -27 to 27 -1.It's default value is 0.
  • char is 16 bit unsigned integer and stores values in the range of 0 to 216-1 ie between '\u0000' to '\uffff'. It's default value is '\u0000'.
  • short is 16 bit signed integer and stores values in the range of -215 to 215 -1. It's default value is 0.
  • int is 32 bit signed integer and stores values in the range of -231 to 231 -1. It's default value is 0.
  • long is 64 bit signed integer and stores values in the range of -263 to 263 -1. It's default value is 0l.
  • float stores 32 bit floating point values. It's default value is 0.0f.
  • double stores 64 bit floating point values. It's default value is 0.0d.
Variables
  • Variables declared at class level are called as field or instance variables.
  • Variables declared inside a method are called as local variables or automatic variables.
  • Field variables are automatically intialized to their default values.
  • Local variables are not initialized automatically. They have to be initialzed before using them.
  • Arrays, whether local or class-level, are always initialized.
Operators
  • The modoulo (%) operator gives the remainder as result, when one operand is divided by another.
  • When a int is divided by zero, java.lang.ArithmeticException will be thrown.
  • == and != operators are used to check, if the objects are of the same instance.
  • equals() method of the object class is used to check, if two objects have the same value.
  • instanceof operator is used to determine, if an object reference on the left hand side is an instance of the class or an interface on the right operand.
Arrays
  • Arrays are objects.
  • The following are legal declarations of an array.
    int i[];
    int[] i;
    int i [][];
    int[] x[];
  • The following are the two ways to create an array.
    int i[] = {1,2,3,4,5};
    String str[] = new String[4];
  • Array indexes start at 0. str.length for the above statement will result as 5. length is a property of array and is not a method.
  • primitives are passed by value and objects are passed by reference. Since arrays are objects, they are always passed by reference.
Access Modifiers
  • public access modifier allows access outside of the members package. A class,constructor,method and variables can be declared as public.
  • private access modifier allows access only from within the class. A constructor,method and variables can be declared as private. A class cannot be declared as private.
  • protected members can be accessed only by classes within the same package and its subclasses in any package. A constructor,method and variables can be declared as protected. A class cannot be declared as protected.
  • When no access specifiers are declared, the members can only be accessed within the same package. A class,constructor,method and variables can be declared without any access.
  • The accessibilty hierarchy from most restrictive to least restrictive is as follows :
    private -> package(default) -> protected -> public
  • Access specifiers are used to provide encapsulation.
Static Modifier
  • static access modifier is applicable to a class a whole and not to any particular instance.
  • A method or a variable or a block of code can be declared as static.
  • When a variable is declared as static, there is only one copy for all instances of the class. If any one of the instance change the value, the change gets reflected to other instances.
  • When a method is declared as static, it can be called without creating an instance of the class.
  • A static method should not refer to instance variables without using an instance of the class. 'this' keyword should not be used when referring to the instance.
  • Static block gets executed when the class is loaded. Static block gets executed even before instance creation.
Final Modifier
  • classes,methods and variables can be declared as final.
  • A class declared as final cannot be inherited.
  • A method declared as final cannot be overridden.
  • A variable declared as final may not be changed.
Abstract modifier
  • abstract modifier is used to defer implementation to the subclass i.e to provide abstraction.
  • classes and methods can be defined as abstract.
  • abstract classes cannot be instantiated.
  • abstract method doesn't have a body and it is replaced with a semicolon.
  • abstract class may or may not have abstract methods but if a class has one abstract method then the class should be abstract.
  • abstract class can have non abstract methods.
  • abstract without being inherited is of no use. Hence an abstract class cannot be declared as final.
Synchronized Modifier
  • methods and blocks of code can be declared as synchronized.
  • synchronized methods can be accessed by only one thread concurrently for an instance.
  • A class level lock has to be acquired to execute a synchronised static method.
Transient Modifier
  • only field(instance) variables can be declared as transient. Local variables cannot be declared as transient.
  • transient variables may not be serialized.
Native Modifier
  • only methods can be declared as native.
  • native modifier indicates method accessing code written in other programming language.
Volatile Modifier
  • only field(instance) variables can be declared as volatile. Local variables cannot be declared as volatile.
  • volatile variables cannot be declared as final.
  • volatile variables may be modified asynchronously by concurrently running threads.
Flow Control
  • if..else and switch..case are conditional statements.
  • for,while and do..while are iterative or looping statements.
  • The following are examples of endless loops:
    for( ; ; ){}
    while(true){}
  • do..while(condition) loop will get executed atleast once. while(condition) loop will only get executed on the condition being true.
  • break statement and default condition in switch statement are optional.
  • break statement inside a loop causes the control to come out of the loop.
  • continue statement inside a loop causes the control to continue with the next iteration.
  • There is no goto statement in java.
  • Unreachable code results in compilation error. The following is an example:
    while(false ){
    Sytem.out.println("unreachable code");
    }
Constructors
  • Constructors are used for initializing an instance.
  • Constructor name should be the same as the class name.
  • Constructor's doesn't have a return type.
  • Constructors are not inherited.
  • Constructors can be overaloaded.
  • When no constructors are specified, java provides a no argument constructor by default.
  • this() is used to access overloaded constructors and super() is used to access parent-class constructors.
  • this() or super(), if used,should be the first line of the constructor code block.
  • this() and super() cannot be used at the same time in the constructor.
Inheritance,Overloading,Overriding
  • In Java, Polymorphism is achieved using inheritance,overloading and overriding.
  • Java supports only single inheritance.
  • extends keyword is used for inheritance.
  • A class cannot extend more than one class.
  • A subclass inherits only the non-private members of the parent class.
  • Methods and constructors can be overloaded. Overloading is used for code simplicity and runtime polymorphism.
  • Methods in the same class with same name but different arguements and return type is said to be overloaded. A method is not overloaded, if the return type alone is different.
  • Only methods can be overridden. Overriding is used to provide a different method behavior in the subclass.
  • Overriding method in the subclass must have same signature and return type as the overriden method of the super class.
  • Overriding method cannot reduce the access visibility (private is most restrictive) but it can increase the access visibility (public is least restrictive).
  • Overriding method can only throw exceptions that the overridden method in the super class throws or it may not throw any exception at all. But it cannot throw new exceptions from different class hierarchy.
Interfaces
  • Interfaces along with abstract classes provide abstraction in java.
  • Interfaces are used to define abstract methods and constant(static final) variables.
  • Classes use implements keyword to make use of interfaces. A class can implement any number of interfaces.
  • An interface can extend more than one interface. But the same is not true for classes.
  • A class implementing a interface should provide implementation for all the methods declared in the interface. If it doesn't, the class becomes abstract.
  • Variable declartion inside a interface can be public or package access and/or abstract.
  • Methods declartion inside a interface can be public or package access and/or static/final.
Exception Handling
  • java.lang.Exception is the base class of all exceptions.
  • java.lang.Throwable is the super class of Exception and Error classes.
  • Java uses try..catch..finally constructs to handle exceptions.
  • finally block will be executed whether or not an exception is thrown.
  • finally block can exist with a try block without a catch block. The exception blocks can be in any of the following combinations - try{}catch(){} or try{}catch(){}finally{} or try{}finally{}.
  • Checked exceptions and unchecked exceptions are the ways of classifying exceptions.
  • Checked exceptions needs to be explicitly handled using throws clause or catch block.
  • Unchecked exceptions are runtime exceptions ie subclass of java.lang.RuntimeException and need not be explicitly handled.
  • throw is used to explicitly raise a exception within the program.
  • throws clause is used to indicate the exceptions which are not handled by the method. If multiple exceptions are not handled, then they are separated by a comma.
  • An overriding method in a subclass must only throw exceptions declared in the parent class or children of the exceptions declared in the parent class or the overriding method may not throw any exception at all.
  • The subclass exception should precede the base class exception when used within the catch clause.
  • System.exit() will abruptly terminate the JVM. Hence if there is a System.exit() statement in the try/catch/finally blocks, finally will not complete.
Garbage Collection
  • In Java, Garbage Collection is automatic. No explicit coding (like destructors) is required.
  • Garbage Collector Thread runs as a low priority daemon thread freeing memory.
  • An Object is eligble for garbage collection, when there are no references to the object.
  • System.gc() and Runtime.gc() methods inform the JVM to run garbage collection but this is only a request to the JVM and it is up to the JVM to run GC immediately or run it when it gets time. Garbage collection can't be forced.
  • finalize() method is called by the GC just before releasing the object's memory. It is advised to do a final cleanup of the object in finalize() method.
  • When an object is not required, its reference may be nullified which increases the likelihood of garbage collection.
Threads
  • A thread is a single sequential flow of control within a program.
  • The following are the two ways to create a new thread:
    - Extend the Thread class and override the run() method.
    - Implement the Runnable interface and implement the run() method.
  • The following are the states of a thread :
    Ready - instance created but not yet started.
    Running - currently executing.
    Waiting - currently not executing.
    Dead - completed processing.
  • start() method puts the thread in ready state and makes the thread eligible to run. start() method automatically calls the run() method.
  • wait(), notify(), and notifyAll() are methods defined in the Object class. These methods throw InterruptedException.
  • wait() method releases CPU, releases object's lock and puts the thread into pool of waiting threads.
  • notify() method moves a thread out of the waiting pool to ready state, but there is no guaranty which thread will be moved out of the pool.
  • notifyAll() method moves all waiting threads from the waiting pool to ready state.
  • A Thread's priority will be same as the thread which started it. setPriority(int priority) is used to change the priority of a thread.
  • yield() is a static method of the thread class which puts currently running thread in to ready state.
  • sleep() is a static method of the thread class which puts the current running thread to its waiting state. sleep() throws InterruptedException at runtime.
  • setDaemon() method is used to make a thread as daemon thread. Daemon thread is a low priority thread which runs in the background.
  • A thread dies after the completetion of run() method. A dead thread cannot not be restarted.
  • methods and blocks of code can be declared as synchronized.
  • synchronized methods can be accessed by only one thread concurrently for an instance.
  • A class level lock has to be acquired to execute a synchronized static method.  

Friday, 16 August 2013


sizeOf()


Java does not have a sizeof operator like that in C/C++. All primitive types have a standard size (or at least appear to have a standard size), so you don’t really need one. There are typically no pad or alignment bytes.
Java Object Size
typesize in bytes
overhead~8 bytes/object
boolean1
byte1
char2
short2
int4
long8
float4
double8
reference4/8†
Stringlength * 2 + 4
† addresses are 4 bytes in a 32-bit JVM (Java Virtual Machine) and 8-bytes in a 64-bit JVM.
A JVM is free to store data any way it pleases internally, big or little endian, with any amount of padding or overhead, though primitives must behave as if they had the official sizes. For example, the JVM or native compiler might decide to store a boolean[] in 64-bit long chunks like a BitSet. It does not have to tell you, so long as the program gives the same answers. It might allocate some temporary Objects on the stack. It may optimise some variables or method calls totally out of existence replacing them with constants. It might version methods or loops, i.e. compile two versions of a method, each optimised for a certain situation, then decide up front which one to call. Then of course the hardware and OS (Operating System) have multilayer caches, on chip-cache, SRAM (Static Random Access Memory) cache, DRAM (Dynamic RAM) cache, ordinary RAM (Random Access Memory) working set and backing store on disk. Your data may be duplicated at every cache level. All this complexity means you can only very roughly predict RAM consumption.
There is a header on each object, typically 8 bytes for objects and 12 bytes for arrays, and 16 bytes in JET.
In Java version 1.5 or later you can use java.lang.instrument. Instrumentation. getObjectSize()
Other methods you may find useful in estimating RAM use:

Minimum and Maximum Possible Primitive Values

Primitive variables include boolean, char, byte, short, int, long, float and double. Strings, arrays and Objects are not considered primitives.
Java Primitives
TypeSigned?BitsBytesDigitsLowestHighestMnemonic
booleann/a111falsetruezero/one
charunsigned Unicode1624:5'\u0000' [0] aka Character. MIN_VALUE'\uffff' [216-1] aka Character.MAX_VALUEUnicode chars are twice as big as C’s.
bytesigned812:3-128 [-27] aka Byte. MIN_VALUE+127 [27-1]aka Byte. MAX_VALUEBytes are signed, so half the usual 255 range.
shortsigned1624:5-32,768 [-215] aka Short. MIN_VALUE+32,767 [215-1] aka Short. MAX_VALUE32K
intsigned3249:10-2,147,483,648 [-231] akaInteger.MIN_VALUE aka -2 gig, roughly -2 billion+2,147,483,647 [231-1] aka Integer.MAX_VALUE. aka 2 gig, roughly 2 billion2 gig
longsigned6481:19-9,223,372,036,854,775,807 [-263] akaLong. MIN_VALUE about -9×10189,223,372,036,854,775,808 [+263-1] akaLong. MAX_VALUE about 9×10189 exabytes, or 9 billion gig
floatsigned exponent and mantissa3247±1.40129846432481707e-45 aka Float.MIN_VALUE±3.40282346638528860e+38 aka Float.MAX_VALUE 
or roughly ±2127 
with about 7 significant digits of accuracy. 
A float can exactly represent integers 
in the range -224 to +224.
rough, compact float
doublesigned exponent and mantissa64816±4.94065645841246544e-324 aka Double.MIN_VALUE±1.79769313486231570e+308 aka Double.MAX_VALUE 
or roughly ±21023 
with 15 significant digits of accuracy, almost 16with 15.95 significant digits. 
A double can exactly represent integers 
in the range -253 to +253.
high precision float