Sunday, November 15, 2015

Static vs. Dynamic class loading?

Static class loading

Classes are statically loaded with Java’s “new” operator.

class MyClass {
public static void main(String args[]) {
Car c = new Car();
}
}


Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time. Let us look at how to load classes dynamically.

Class.forName (String className); //static method which returns a Class.The above static method returns the class object associated with the class name.

The string className can be supplied dynamically at run time. Unlike the static loading, the dynamic loading will decide whether to load the class Car or the class Jeep at runtime based on a properties file and/or other runtime conditions. Once the class is dynamically loaded the following method returns an instance of the loaded class. It’s just like creating a class object with no arguments.

class.newInstance (); //A non-static method, which creates an instance of a
                                  //class (i.e. creates an object).

Jeep myJeep = null ; //myClassName should be read from a .properties file or a Constants class.
// stay away from hard coding values in your program. CO
String myClassName = "au.com.Jeep" ;
Class vehicleClass = Class.forName(myClassName) ;
myJeep = (Jeep) vehicleClass.newInstance();
myJeep.setFuelCapacity(50);

Read More 

Java 7 features
How to Reset Arraylist In Java
How HashMap Work in Java
Why wait (), notify () and notifyAll () must be called from synchronized block or method in Java
XPath to locate Information in XML
Internals of Garbage Collector
Reference Type in Java
Different Ways to Create ObjectClass Loaders in Java
Producer Consumer Problem
Why String is Final in Java
Singleton Class using Enum
JSON tutorial
Exceptional Handling in Java  

Difference between Inheritance and Composition in Java OOPS

Difference between Inheritance and Composition in Java OOPS

Though both Inheritance and Composition provides code reusablility, main difference between Composition and Inheritance in Java is that Composition allows reuse of code without extending it but for Inheritance you must extend the class for any reuse of code or functionality. Another difference which comes from this fact is that by using Composition you can reuse code for even final class which is not extensible but Inheritance cannot reuse code in such cases. Also by using Composition you can reuse code from many classes as they are declared as just a member variable, but with Inheritance you can reuse code form just one class because in Java you can only extend one class, because multiple Inheritance is not supported in Java. You can do this in C++ though because there one class can extend more than one class. BTW, You should always prefer Composition over Inheritance in Java.

1) Static vs Dynamic
First difference between Inheritance and Composition comes from flexibility point of view. When you use Inheritance, you have to define which class you are extending in code, it cannot be changed at runtime, but with Composition you just define a Type which you want to use, which can hold its different implementation. In this sense, Composition is much more flexible than Inheritance.

2) Limited code reuse with Inheritance
As I told, with Inheritance you can only extend one class, which means you code can only reuse just one class, not more than one. If you want to leverage functionalities from multiple class, you must use Composition. For example, if your code needs authentication functionality, you can use an Authenticater, for authorization you can use an Authorizer etc, but with Inheritance you just stuck with only class, Why? because Java doesn't support multiple Inheritance. This difference between Inheritance vs Composition actually highlight a severe limitation of later.

3) Unit Testing
This is in my opinion most important difference between Inheritance and Composition in OOP and probably is the deciding factor in whether to use Composition or Inheritance. When you design classes using Composition they are easier to test because you can supply mock implementation of the classes you are using but when you design your class using Inheritance, you must need parent class in order to test child class. Their is no way you can provide mock implementation of parent class.

4) Final classes
Third difference between them also highlight another limitation of Inheritance. Composition allows code reuse even from final classes, which is not possible using Inheritance because you cannot extend final class in Java, which is necessary for Inheritance to reuse code.

5) Encapsulation
Last difference between Composition and Inheritance in Java in this list comes from Encapsulation and robustness point of view. Though both Inheritance and Composition allows code reuse, Inheritance breaks encapsulation because in case of Inheritance, sub class is dependent upon super class behavior. If parent classes changes its behavior than child class is also get affected. If classes are not properly documented and child class has not used the super class in a way it should be used, any change in super class can break functionality in sub class.

Read More 

Java 7 features
How to Reset Arraylist In Java
How HashMap Work in Java
Why wait (), notify () and notifyAll () must be called from synchronized block or method in Java
XPath to locate Information in XML
Internals of Garbage Collector
Reference Type in Java
Different Ways to Create ObjectClass Loaders in Java
Producer Consumer Problem
Why String is Final in Java
Singleton Class using Enum
JSON tutorial
 Exceptional Handling in Java  

What is rt.jar in Java

rt.jar stands for runtime JAR and contains the bootstrap classes, I mean all the classes from Core Java API. I have found that many Java programmer doesn't know what is rt.jar? and often confused with the role of rt.jar file or  why we use of rt.jar file in Java? No surprise, the name is little bit cryptic.  This file always reside inside lib directory of JRE, at least in Windows and Linux. In MacOSX it reside at different location and also has different name i.e. classes.jar, but that is only prior to JDK 1.7. From Java 7 release Apple has stopped distributing Java and if you separately install, it will have same name as rt.jar.  Many developer thinks to include their classes inside rt.jar to solve classpath related problems, but that is a bad idea. You should never be messing with rt.jar, it contains class files which is trusted by JVM and loaded without stringent security check it does for other class files. In this article, we will learn some interesting things about this magical JAR from Java world. For those programmers, who are new to Java and not familiar with JAR file, it is a zip like file, precisely known as Java archive which stores Java class files and any resource needed by program. It can also contain mainfest file, which can include Main-Class entry to make it an executable JAR, which can be run by using java -jar command.


Important Points about rt.jar in Java

1. rt.jar stands for runtime and contains all of the compiled class files for the core Java Runtime environment.

2) You must include rt.jar in your classpath, otherwise you don't have access to core classes e.g. java.lang.String, java.lang.Thread, java.util.ArrayList or java.io.InputStream and all other classes from Java API. You can actually see what is inside rt.jar by opening it by using WinRAR or WinZip client. You can see that it not only contains all Java API but also internal classes specified in com package.

3) In windows, rt.jar will always reside under $JAVA_HOME/jre/lib, where $JAVA_HOME refers to JDK installation directory. Even if you don't install JDK and just install JRE, you will see it in exactly same location, you won't find rt.jar inside $JAVA_HOME/lib directory. BTW, On MacOSX it is called classes.jar and located under /System/Library/Frameworks//Classes directory.
java.util.concurrent package e.g. ConcurrentHashMap, then the JVM will look for it inside the rt.jar, thus enabling it to run correctly.

4) The rt.jar is where all the Java  packages reside. For example, if a class file need to refer a class from java.util.concurrent package e.g. ConcurrentHashMap, then the JVM will look for it inside the rt.jar, thus enabling it to run correctly.

5) One more question Java programmer ask is, where can I find source code for classes included in rt.jar? well, if you have installed JDK, not JRE then you can find all sources inside $JAVA_HOME/src.zip file. BTW, sun.* sources are also included in src.zip but that is proprietary closed source Oracle code. I also suggest you to include this JAR file in your Eclipse, so that you can view source code of any JDK class by just typing Ctrl + T and name of the class, rest will be taken care by Eclipse's Java type search functionality.

6) One of the most important thing to know about rt.jar is that all the classes in this JAR file is known to JVM, which means JVM doesn't do all the checks it does while loading any other JAR from any other location.  This is done due to various performance reason and that's why these classes are loaded by bootstrap or primodial class loaders. Don't try to include your class files in rt.jar, as its not advised by Java. It also compromise with any security.

7) You can see that JDK has three main folders bin, lib and jre. bin directory contains all binary executable e.g. java.exe to run Java program, javac.exe to compile Java program etc. lib contains tools.jar and dt.jar. jre folder again contain bin and lib directory. It's in this lib directory rt.jar reside.

Read More 

Java 7 features
How to Reset Arraylist In Java
How HashMap Work in Java
Why wait (), notify () and notifyAll () must be called from synchronized block or method in Java
XPath to locate Information in XML
Internals of Garbage Collector
Reference Type in Java
Different Ways to Create ObjectClass Loaders in Java
Producer Consumer Problem
Why String is Final in Java
Singleton Class using Enum
JSON tutorial
 Exceptional Handling in Java  

Difference between SOAP and RESTful Web Service in Java

Though both SOAP and RESTful web services allows a client to query server for some information, but the way they are implemented and used is quite different. Main difference between SOAP and REST is that former provides an standard of communication between client, server and other parties and has restricted set of rules and format, while REST leverages ubiquity of HTTP protocol, in both client and servers, to allow them to communicate with each other regardless of their implementation. In short, getting data from a RESTful web service requires less headache then getting data from a SOAP web service. Since everybody is familiar with HTTP requests like GET or POST, its easy to understand and correlated how RESTful webservice are working and which URL of REST web service provides what kind of information. In SOAP, you need to understand lengthy WSDL document to find out right methods and right way to call them.

 Difference between REST and SOAP in Java

Here are some fundamental differences between REST, RESTful and SOAP Web Services, which will help you not only to understand these two key technologies better but also to answer some tricky Java web services questions based upon these two technologies :

Short Form
REST stands for REpresntational State Transfer (REST) while SOAP Stands for Simple Object Access Protocol (SOAP).

Architecture style vs Protocol
REST is an architectural style, on which RESTFul web services are built, while SOAP is a standard devised to streamline communication between client and server in terms of format, structure and method.

Use of HTTP Protocol
REST takes full advantage of HTTP protocol, including methods e.g. GET, POST, PUT, and DELETE to represent action e.g. from an application which provides data related to books, GET request can be used to retrieve books, POST can be used to upload data of a new book, and DELETE can be used to remove a book from library. On the other hand SOAP uses XML messages to communicate with server.

Supported Format
RESTful web service can return response in various format e.g. JSON, XML and HTML, while by using SOAP web service you tie your response with XML because actual response is bundled inside a SOAP message which is always in XML format.

Speed
Processing a RESTful web service request is much faster than processing a SOAP message because you need to less parsing. Because of this reason RESTful web services are faster than SOAP web service.

Bandwidth
SOAP messages consumes more bandwidth than RESTFul messages for same type of operation because XML is more verbose than JSON, standard way to send RESTFul messages and SOAP has additional header for every message, while RESTFul services utilizes HTTP header.

Transport Independence
Since SOAP messages are wrapped inside a SOAP envelop it can be sent over to any transport mechanism e.g. TCP, FTP, SMTP or any other protocol. On the other hand RESTful web services are heavily dependent upon HTTP protocol. They used HTTP commands their operation and depends upon on HTTP for transmitting content to server. Though in real world, SOAP is mostly over HTTP so this advantage of transport independence is not really utilized.

Resource Identification
RESTful web services utilizes URL to identify the desired resources to be accessed, while SOAP uses XML messages to identify the desired web procedure or resource to be invoked.

Security
Security in RESTful web service can be implemented using standard and traditional solutions for authorized access to certain web resources. While to implement security in SOAP based web services you need additional infrastructure in web to enable message or transport level security concerns.

Caching
RESTful web service take full advantage of web caching mechanism because they are basically URL based. On the other hand, SOAP web services totally ignore web caching mechanism.

Approach
In REST based web-services every entity is centered around resources, while in case of SOAP web service, every entity is centered around interfaces and messages.

Read More 

Java 7 features
How to Reset Arraylist In Java
How HashMap Work in Java
Why wait (), notify () and notifyAll () must be called from synchronized block or method in Java
XPath to locate Information in XML
Internals of Garbage Collector
Reference Type in Java
Different Ways to Create ObjectClass Loaders in Java
Producer Consumer Problem
Why String is Final in Java
Singleton Class using Enum
JSON tutorial
 Exceptional Handling in Java

NoClassDefFoundError vs ClassNotFound in Java

Both NoClassDefFoundError and ClassNotFound are Error which comes when JVM or ClassLoader not able to locate class during class loading process. Since different ClassLoader loads classes from different location, sometime this issue may caused because of incorrect CLASSPATH as well i.e. some JAR files from lib is mission or from old version. Though look quite similar there is subtle difference between NoClassDefFoundError and ClassNotFoundException, NoClassDefFoundError indicates that class was present during time of compilation but not available when you run Java program, some time error on static initializer block can also result in NoClassDefFoundError. On the other hand ClassNotFoundException is nothing to do with compile time, ClassNotFoundException comes when you try to load a class in runtime using Reflection, e.g. loading SQL drivers and corresponding Class loader is not able to find this class.


 NoClassDefFoundError vs ClassNotFoundException

  Here are few more difference between both of them in point form :

1) NoClassDefFoundError is an Error which is unchecked in nature, i.e. doesn't require try-catch or finally block. On the other hand ClassNotFoundException is a checked Exception and requires mandatory handing using either try with catch block or try with finally block, failure to do so will result in compile time error.

2) If you are experiencing NoClassDefFoundError in J2EE environment, there could be host of reason, one being multiple class loader and visibility of class among them. See 3 ways to solve NoClassDefFoundError for more details.

3) Often java.lang.ClassNotFoundException is thrown as result of following method call, Class.forName(), ClassLoader.findSystemClass() and ClassLoader.loadClass().

4) Another difference between NoClassDefFoundError and ClassNotFoundException is that NoClassDefFoundError is a LinkageError and can come during linking, while java.lang.ClassNotFoundException is an Exception and occurs during runtime.

Read More 

Java 7 features
How to Reset Arraylist In Java
How HashMap Work in Java
Why wait (), notify () and notifyAll () must be called from synchronized block or method in Java
XPath to locate Information in XML
Internals of Garbage Collector
Reference Type in Java
Different Ways to Create ObjectClass Loaders in Java
Producer Consumer Problem
Why String is Final in Java
Singleton Class using Enum
JSON tutorial
Exceptional Handling in Java