Sunday 27 March 2016

Introduction to Spring Framework

Introduction: 

Spring is an open source framework created to address the complexity of enterprise application development. Enterprise applications has a tremendous need of wiring objects or implementing different behavior of object at runtime that too without imposing much load on application. One of the main advantages of the Spring framework is its layered architecture design, which allows us to wire the objects as and when necessary with reduced maintenance efforts.
Core Features of Spring
  • Lightweight:
1.      Spring provides you different modules and allows you to use any one based to your requirement.  Ideally the spring jar is just 2-3 MB. 
2.      If you compare Spring with EJB, then you have to write very less code and configurations too. The beauty of Spring is that you can actually focus on business logic whereas in EJB you have to write lot of code along with business logic which makes the code bulky and tightly coupled.
3.      Through Spring you are playing with POJO which do not depends on Framework and it improves the testability of your code. 
4.      And, Spring provides seamless integration with frameworks, third party libraries etc.
  • Inversion of control (IOC):
The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about removing dependencies from your code.. No need to directly connect your components and services together in program, instead just describe which services are needed by which components in a configuration file/xml file. The Spring IOC container is then responsible for binding it all up.

  • Aspect oriented (AOP): 
Aspect oriented programming refers to the programming paradigm which isolates secondary or supporting functions from the main program's business logic. AOP is a promising technology for separating crosscutting concerns, something usually hard to do in object-oriented programming. The application's modularity is increased in that way and its maintenance becomes significantly easier.
  • Container:
Spring contains and manages the life cycle and configuration of application objects.
  • MVC Framework:
Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework.
  • Transaction Management:
Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments.
  • JDBC Exception Handling:
The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS

Architecture:
Spring is well-organized architecture consisting  of seven modules. Modules in the Spring framework are:

  1. Spring AOP:
One of the key components of Spring is the AOP framework. AOP is used in Spring:
    • To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management, which builds on Spring's transaction abstraction.
    • To allow users to implement custom aspects, complementing their use of OOP with AOP
  1. Spring ORM:
The ORM package is related to the database access. It provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis.
  
  1. Spring Web:
The Spring Web module is part of Spring?s web application development stack, which includes Spring MVC.


·  Spring DAO:

The DAO (Data Access Object) support in Spring is primarily for standardizing the data access work using the technologies like JDBC, Hibernate or JDO.
 

·  Spring Context:

This package builds on the beans package to add support for message sources and for the Observer design pattern, and the ability for application objects to obtain resources using a consistent API.
  

·  Spring Web MVC:

This is the Module which provides the MVC implementations for the web applications.
  

·  Spring Core:

The Core package is the most import component of the Spring Framework. 
This component provides the Dependency Injection features. The BeanFactory  provides a factory pattern which separates the dependencies like initialization, creation and access of the objects from your actual program logic.




In my next blog post I will let you dive in Dependency injection(ioc) in spring
Keep posting your queries if any

Saturday 26 March 2016

Java Spring Series

Spring Framework is a Java platform that provides comprehensive infrastructure support for developing Java applications. Spring handles the infrastructure so you can focus on your application.
Spring enables you to build applications from “plain old Java objects” (POJOs) and to apply enterprise services non-invasively to POJOs. This capability applies to the Java SE programming model and to full and partial Java EE.

In my coming posts I will be exploring Spring for you.. 

TARGET AUDIENCE

This tutorial is designed for Java programmers who need to understand the Spring 3 framework and its application.

PREREQUISITES:

Before proceeding with this tutorial you should have a good understanding of the Java programming language. 
This is 1 of 13 parts of tutorial series

CONTENT: exploring spring

Introduction to spring framework
Dependency injection(ioc) in spring
Spring hello world example in eclipse
Dependency injection via setter method in spring
Dependency injection via constructor in spring
Spring Bean scopes with examples
Initializing collections in spring
Beans Autowiring in spring 
Inheritance in Spring 
Spring ApplicationContext 
Spring lifetime callbacks 
BeanPostProcessors in Spring 
Annotation based Configuration in spring 


You can post your questions in subsequent topics if any. You can also suggest me if you would like me to add few more points in the content. 

Thursday 10 March 2016

Why Marker Interfaces ?

Why Marker or Tag interface do in Java

1) Looking carefully on marker interface in Java e.g. Serializable, Clonnable and Remote it looks they are used to indicate something to compiler or JVM. So if JVM sees a Class is Serializable it done some special operation on it, similar way if JVM sees one Class is implement Clonnable it performs some operation to support cloning. Same is true for RMI and Remote interface. So in short Marker interface indicate, signal or a command to Compiler or JVM.


This is pretty standard answer of question about marker interface and once you give this answer most of the time interviewee definitely asked "Why this indication can not be done using a flag inside a class?” this make sense right? Yes this can be done by using a boolean flag or a String but doesn't marking a class like Serializable or Clonnable makes it more readable and it also allows to take advantage of Polymorphism in Java.

Where Should I use Marker interface in Java

Apart from using built in marker interface for making a class Serializable or Clonnable. One can also develop his own marker interface. Marker interface is a good way to classify code. You can create marker interface to logically divide your code and if you have your own tool than you can perform some pre-processing operation on those classes. Particularly useful for developing API and framework like Spring or Struts.
After introduction of Annotation on Java5, Annotation is better choice than marker interface and JUnit is a perfect example of using Annotation e.g. @Test for specifying a Test Class. Same can also be achieved by using Test marker interface.


Another use of marker interface in Java

One more use of marker interface in Java can be commenting. a marker interface called Thread Safe can be used to communicate other developers that classes implementing this marker interface gives thread-safe guarantee and any modification should not violate that. Marker interface can also help code coverage or code review tool to find bugs based on specified behavior of marker interfaces.
Again Annotations are better choice @ThreadSafe looks lot better than implementing ThraedSafe marker interface.

In summary marker interface in Java is used to indicate something to compiler, JVM or any other tool but Annotation is better way of doing same thing.

Sunday 6 March 2016

Why and how hashcode - part 1

In Java, every object has a method hashCode that is simple to understand but still it’s sometimes forgotten or misused. We need to understand the real use of HashCode.
An object’s hash code allows algorithms and data structures to put objects into compartments, just like letter types in a printer’s type case. The printer puts all “A” types into the compartment for “A”, and he looks for an “A” only in this one compartment. This simple system lets him find types much faster than searching in an unsorted drawer. That’s also the idea of hash-based collections, such as HashMap and HashSet.

The hashCode contract

The contract is explained in the hashCode method’s JavaDoc. It can be roughly summarized with this statement:
Objects that are equal must have the same hash code within a running process
Please note that this does not imply the following common misconceptions:
  • Unequal objects must have different hash codes – WRONG!
  • Objects with the same hash code must be equal – WRONG!
Whenever you implement equals, you MUST also implement hashCode
If you fail to do so, you will end up with broken objects. Why? An object’s hashCode method must take the same fields into account as its equals method. By overriding the equals method, you’re declaring some objects as equal to other objects, but the original hashCode method treats all objects as different. So you will have equal objects with different hash codes. For example, calling contains() on a HashMap will return false, even though the object has been added.
How to write a good hashCode function is beyond the scope of this article, it is perfectly explained in Joshua Bloch’s popular book Effective Java, which should not be missing in a Java developer’s bookshelf.

Monday 15 February 2016

Optimizing Java Code !! Performance Matters !!

General optimization techniques
Optimiziation is one of most serious concern of Java. Writing a program and generating output is altogether different than to increase the performance of application. There are different ways to making the optimization, in this blog we will be discussing few :-) 

Strength reduction
Strength reduction occurs when an operation is replaced by an equivalent operation that executes faster. The most common example of strength reduction is using the shift operator to multiply and divide integers by a power of 2. For example, x >> 2 can be used in place of x / 4, and x << 1 replaces x * 2.
Common sub expression elimination
Common sub expression elimination removes redundant calculations. Instead of writing
double x = d * (lim / max) * sx;
double y = d * (lim / max) * sy;
the common sub expression is calculated once and used for both calculations:
double depth = d * (lim / max);
double x = depth * sx;
double y = depth * sy;
Code motion
Code motion moves code that performs an operation or calculates an expression whose result doesn't change, or is invariant. The code is moved so that it only executes when the result may change, rather than executing each time the result is required. This is most common with loops, but it can also involve code repeated on each invocation of a method. The following is an example of invariant code motion in a loop:

for (int i = 0; i < x.length; i++)
 x[i] *= Math.PI * Math.cos(y);
becomes
double picosy = Math.PI * Math.cos(y);for (int i = 0; i < x.length; i++)
x[i] *= picosy;
Unrolling loops
Unrolling loops reduces the overhead of loop control code by performing more than one operation each time through the loop, and consequently executing fewer iterations. Working from the previous example, if we know that the length of x[] is always a multiple of two, we might rewrite the loop as:
double picosy = Math.PI * Math.cos(y);for (int i = 0; i < x.length; i += 2) {
x[i] *= picosy;
x[i+1] *= picosy;
}
In practice, unrolling loops such as this -- in which the value of the loop index is used within the loop and must be separately incremented -- does not yield an appreciable speed increase in interpreted Java because the bytecodes lack instructions to efficiently combine the "+1" into the array index.
All of the optimization tips in this article embody one or more of the general techniques listed above.

Sunday 7 February 2016

Some Tough Interview Questions in Java

Why wait and notify is declared in Object class instead of Thread ?
In Java in order to enter critical section of code, Threads needs lock and they wait for lock, they don't know which threads holds lock instead they just know the lock is hold by some thread and they should wait for lock instead of knowing which thread is inside the synchronized block and asking them to release lock. this analogy fits with wait and notify being on object class rather than thread in Java.


Why multiple inheritance is not supported in Java ?
Reason is ambiguity around Diamond problem, consider a class A has foo() method and then B and C derived from A and has there own foo() implementation and now class D derive from B and C using multiple inheritance and if we refer just foo() compiler will not be able to decide which foo() it should invoke. This is also called Diamond problem because structure on this inheritance scenario is similar to 4 edge diamond.


Why String is immutable in Java?
String is Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client's action would affect all another client. For example, if one client changes the value of String "Test" to "TEST", all other clients will also see that value as explained in the first example. Since caching of String objects was important from performance reason this risk was avoided by making String class Immutable. At the same time, String was made final so that no one can compromise invariant of String class e.g. Immutability, Caching, hashcode calculation etc by extending and overriding behaviors. Another reason of why String class is immutable could die due to HashMap. Since Strings are very popular as HashMap key, it's important for them to be immutable so that they can retrieve the value object which was stored in HashMap. Since HashMap works in the principle of hashing, which requires same has value to function properly. Mutable String would produce two different hashcodes at the time of insertion and retrieval if contents of String was modified after insertion, potentially losing the value object in the map.



Tuesday 29 December 2015

What should I learn Java or .NET?

The first question we need to ask - can these two be compared? A 30,000 ft. view of these two will tell you that Java is a programming language (generally speaking) while .Net is a framework. .Net, as you might know, is a platform that supports several languages viz. C#, VB.Net, F# and others. A framework is nothing but a pool of ready-made functionality available at your fingertips when you are writing code using that framework.
Those who are interested in deeper analysis may perform search on the Internet to find out which among the two scores over the other for specific aspects. But generally speaking; both Java and .Net are quite robust and have found applications world-wide in very complex projects.

Which is better for future Java or .NET?

Instead of worrying about that; why not make yourself future-proof? Like I just said, no one can predict the future in the technology domain; because things change here every single minute. As a software engineer / developer - you should *not* stick to any specific language; yet master one that you are currently working on. Let me make it very clear : You need to be master of at least one and jack of several! Any programming language is just a set of tools that help you implement logic. If you hone your logic skills; you should be able to get comfortable with any programming language, tool or framework within short time. I've seen that happen with few of my ex-colleagues. 

Start with any - and learn it with all the interest and try to be excellent. If you pick up Java; don't hate .Net and vice-versa. If your current job demands C# and ASP; learn it. If you are just starting out with a big IT company that has not told you which profile they will assign to you; it just doesn't matter. 

Monday 16 November 2015

Design Patterns in Java

Hi friends...
Hope you guys had wonderful and environmental Diwali. From today onwards we will be discussing different design patterns in Java..
Normally design patterns are classified in following types :

S.N.Pattern & Description
1Creational Patterns
These design patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using new opreator. This gives program more flexibility in deciding which objects need to be created for a given use case.
2Structural Patterns
These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities.
3Behavioral Patterns
These design patterns are specifically concerned with communication between objects.
4J2EE Patterns
These design patterns are specifically concerned with the presentation tier. These patterns are identified by Sun Java Center.
We will star the discussion with different design patterns from in my coming blog 

Tuesday 13 October 2015

Why inner classes ?

Hi folks,

For times you are writing inner class. The definition of inner class is quite simple "Class within a class is inner class". :-)
The problem is most of us doesnt know why the inner classes are required? Though we know, how to write, how to create object and call the methods? Why it is done remains unanswered...

Here I am giving you an example to clear it.. Hope it helps :

Suppose you have a Java GUI (Graphical User Interface) class that acts as a chat client like Gchat or Facebook Chat. Think about what methods would need to be present in a class like that which represents a chat client – you will need a method that will read user input from the chat box, methods to actually send the user input to the server and to whoever the user is chatting with, even a method that detects that you are typing so that Gchat can display the “XZY is typing” text to your friends, etc.

Event handlers

But, there is one key thing missing here. How exactly will those methods be called? Well, as an
example, think about how Gchat works – you type in some text and when you are ready to send it to whoever you’re chatting with, you press the “Enter” or “Return” key on your keyboard. So, the “Enter” key could be considered one event that triggers a call to one of the methods we mentioned earlier. And, if our chat client class wants to detect if someone is typing in a window, then clearly the event that would trigger the call is someone typing – so we would need some code to detect when someone is actually typing in a window in real time – basically when they are pressing a button inside their chat window.
So, these events – like typing in a window and pressing the “RETURN” key – will also need some methods to detect when they occur, and those event handling methods can then call the appropriate chat client methods. For example, when the event handler method that handles the “RETURN” key button pressed event is called, then that method can call the method to send the user input to the server.

There are two types of methods needed in our example

So, it should be clear that there will need to be two different types of methods that will drive your chat client application: 1. Chat client specific methods like those that will read user input from the chat box and send user input to the server. 2. Event handling methods that will respond to actual events that occur in the chat client window – like hitting the “RETURN” key, detecting consistent typing, etc.
Because it’s clear that there will need to be two different types of methods, then from an Object Oriented Design perspective, it seems like we should have two different classes: one class for the chat client specific methods and one class for the event handling methods. That does follow the normal object oriented design practices – because we are creating classes that specialize in what they do.

The problem with having two separate classes

But, in this particular example, there is a problem with having two separate classes. And that problem is the fact that the event handling code is very much related/tied to the code that belongs to the chat client. This makes sense, as we talked about earlier with our GChat example; as soon as a user in GChat hits “RETURN” or “ENTER” on the keyboard that should trigger an event, which should then grab the text from the chat client window. And, the chat client window would be a particular instance (basically an object) of the chat client class. For example, if you are talking to your friend Bob in GChat, he will have one window in Gmail and you will have one window open in Gmail, and each window is an object of the chat client class. So there will be two separate objects of the chat client class – one for you and one for Bob.
Now, if Bob types something and hits the RETURN key, the event handler code that responds to the RETURN key being pushed will need to be able to communicate with Bob’s chat client class object so that it can grab the text from Bob’s chat client class window, or the text field where that text is actually stored. The key here is thinking in terms of objects – an object of the chat client class is created for each person using GChat, so you will have your own object and Bob will have his own object. This means that the event handling code will need to access an chat client object’s text field – which is a member of the class, and an instance variable. So, it should be clear that the event handling code needs access to the members of a chat client class object in order to be able to effectively help.

Why don’t we just combine the event handling code with the chat client code?

Combining the event handling methods with the chat client specific methods in one big class sounds like a good idea at first, but there is one big problem: If both the event handling code and the chat client code need to inherit some code from different classes then you are in trouble, because Java does not support multiple inheritance – meaning that our one “big class” can not inherit from two different classes.
This means that we want some sort of solution where the event handling code is in it’s very own class – which would allow it to inherit from any class it needs, because it’s not bundled together in one class with the chat client code as well. This is also better object oriented design. But, we also want the event handling class to have easy access to the chat client’s member variables – even the private instance variables. One possible solution is to make everything in the chat client class public so that anyone can access it, including the event handling code. But, making everything public is a bad idea.

Inner classes to the rescue

Now, this is why inner classes were created – for situations exactly like the one we described above. An instance of an inner class can access members of an instance of the outer class, because an inner class is just another member of the outer class. And, inner classes can even access the private members of the outer class – yes you did read that correctly!


Thursday 8 October 2015

Everything about public static void main( ) in Java

Its more than thousands time you might have written public static void main( ) java. But how many of you really know the details? Whats the reason to write it? What is the meaning of each and every word of it? 
Well.. I believe strongly, whatever you write in your code, you must be fully convinced about why you are writing it. Else it doesnt makes a sense... really IT DOESNT MAKES A SENSE... 

public is the visibility. This can be public, private, protected or (if you omit a value) default.
static is a special [optional] keyword that indicates that this method can be called without creating an instance of this class. Without it, you have to instantiate this class and call this method from the resulting object.
void is the return type of this method, indicating that this method doesn't return anything. Methods must have a return type.
main( ... ) is the name of this method. Methods have to be named. The parentheses indicate that this is a method.
String[] args is a single parameter for the method. String[] is the type of the parameter, indicating an array of Strings. args is the na
me of the parameter. Parameters must be named.
The method signature can therefore be:
public static void main( String[] args )
public static void main( String... args )
note that the varargs version (...) is only valid from Java 5..
If you want to dig more about it here I go : 
If you look into JDK source code (jdk-src\j2se\src\share\bin\java.c):
/* Get the application's main method */
mainID = (*env)->GetStaticMethodID(env, mainClass, "main",
                   "([Ljava/lang/String;)V");
...
{    /* Make sure the main method is public */
...
mods = (*env)->CallIntMethod(env, obj, mid);
if ((mods & 1) == 0) { /* if (!Modifier.isPublic(mods)) ... */
    message = "Main method not public.";
    messageDest = JNI_TRUE;
    goto leave;
...

Attend Online Java Certification Training and excel your career

Hello Java Developer,  Are you staying at home and worried about your future? Do not waste the time in worrying. International certifi...