08/6/14
Java

Why should use Java as programming language?

Java

Java is one of the most popular language of recent time. World wide programmers love Java and decided to pursue it as their programming language. But this is not the only reason to use Java as programming language. There are lots more reasons available to choose Java for your language. Lets see few most significant reasons to use Java as programming language.

1. Multi-platform  Support: Java is platform independent language and support multiple operating systems. Java does not confined you to specific operating system. Therefore, application written on Windows can easily run on Linux or Mac Operating systems.

2. Object Oriented Language: Java is one of most popular object oriented language, which supports all OOPs features as language. Java is pure object oriented language till very much extents except primitive datatypes.

3. Established Language: Java was first time introduced in 1995 and this is most established language. Huge number of applications development have done on Java and those applications are running successfully on production environment. This is one of most trusted language in IT industry.

4. Rich Libraries Support: Java provides huge numbers of built-in libraries to boost Java application development must faster and safer.

5. Big Community Support: There is big community support is available for Java programming language. Very huge number of programmers works on Java language world wide and provides support to Java community and help to find out suitable resolution for every problem.

6. Open Source Language: As you know Java is an open source language. Therefore, programmer can deeply understand language internals and take good advantage of it in his/ her programming.

7. Low Cost Development: Application developed in Java always has very low cost compare to other languages applications,  because Java and most of it’s frameworks, applications servers and web servers are free and open source. Which affects the application development and deployment cost very much.

8. Research on Java: Just because, Java is an open source language, world wide researchers are doing research on Java language and making it more powerful and robust day by day.

9. Framework Support: There are large numbers of frameworks available in market which supports Java language. Therefore, all applications based on Java can take advantages of these frameworks according to it’s needs. Lots of frameworks available like Spring, Hibernate, Struts, JUnit etc.

10. Memory Management: Garbage collection is one of big reason of Java success in IT industry. Java provide automatic memory management through garbage collection feature. Java has provided different verity of garbage collection algorithms according to applications need. These garbage collection algorithms gives very efficient automatic memory management.

11. Various Applications Development Support: Java is most admired language for developing applications for different types of environments. Java can be use for developing console applications, desktop applications, server side applications , web services, web applications and mobile applications (Android Apps) etc.

12. Application and Web Servers Support: Verity of  applications and web servers are available for Java applications like IBM WebSphere Application Server, WebLogic, JBoss Application Server, Apache Tomcat, Jetty etc.

13. Significant Required Features: Java has all significant and required features built-in, which are most demanded for any programming languages. For example, multi-threading, socket communication, memory managements and lots more, which make Java much more popular than any other language.

Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.


06/25/14
java

Must Reads Books for Java Developers

Reading is always a good habit. Each and every book teaches us something that make us better person. But reading a good content is always beneficial. There are millions of books and contents available in market and internet to read about Java. But among them, there are few most recommended books for Java on specific topics. That is why, those books comes in list of “Must Reads Books for Java Developers”. These books are most appreciated and full of knowledge. Everyone, regardless his/ her experience on Java technologies must read these books once to become best Java developer. In this article, I would mention about good parts of these books, about authors and why these books are in list of “Must Reads Books for Java Developer”?

1. Effective Java, 2nd Edition by Joshua Bloch

Effective Java is one of the most recommended books by Java community. This book contains great topics about Java concepts. This is one of my favorite books. I have experienced that, sometime experienced professional says “If you didn’t read ‘Effective Java’ that means you are not serious about Java programming”. But despite of this comment, I will recommend this book as a must read book. This book is specially written for experienced Java developers, who have good coding experience on core Java. Most significant thing about ‘Effective Java’ is, this book doesn’t teach basics concepts of Java but it teaches you about best practices of Java and helps you to overcome most common mistakes that we made during programming, which help you to write best quality and most effective code in Java. ‘Effective Java’ contains each topic as isolated items, you can read any item of this book any time and these items are not dependent on each other. Jashua Bloch is author of ‘Effective Java’. He do works at Google. Jashua Bloch has great knowledge about API designing and author of well know ‘Java Collection API’. He has write done his great expertise and knowledge in this book. Hence, this book is must read book.

2. Java Concurrency In Practice, by Brian Göetz, Tim Peierls,  Joshua Bloch, Joseph Bowbeer, David Holmes & Doug Lea

‘Java Concurrency in Practice’ is one of my favorite books on Java. This book is specifically written for Java concurrency or multi-threading concepts. As all of you know, writing a multi-threading code is much more difficult as compare to sequential code. Therefore, this book deals with concurrent programming in Java. ‘Java Concurrency in Practice’ will explain each and every important topic on concurrent programming. I will strongly recommend this book for all those guys, who are interested to learn concurrent programming on Java. ‘Java Concurrency in Practice’ book is written by world’s best Java professional. Authors of this book are Brian Göetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea. Hence, this is one most recommended Java book and comes in list of ‘Must reads books for Java Developers’.

3. SCJP 6, by Katherine Sierra & Bert Bates

SCJP 6 stands for, Sun Certified Java Professional. This book is specially written for Java 6 certification for Java, but this could be very nice book for Java beginners, who wants to learn basic Java concepts. SCJP 6 targets Java 6 concepts. This book fulfills dual purpose like, learning basic concepts of Java and Java certification preparation. Author of this book are Kathrine Seirra and Bert Bates, who were Java trainers and exam setter in Sun Microsystem. Both have written good content for Java Certification Preparation. Therefore this is must read book for Java beginners.

4. Cracking The Coding Interview, by Gayle Laakmann

‘Cracking The Coding Interview’ is the book for those guys, who are preparing for coding interviews for world’s best IT or financial companies. This book has very nice and important topics for preparing interviews. One of the important things about this book is that, this book teaches, what approaches need to be take care about during writing any algorithm. This book contains good collections of interview questions and algorithms. Anyone can read this book, regardless of any programming language experience. Author of this book is Gayle Laakmann, who was closely associated with world’s best IT companies. That is why, she has very nice idea of their recruitment processes and technical evaluation processes. With this knowledge, she is trying to help all people, who want to prepare for interviews of reputed companies. Gayle Laakmann is also a founder of website www.careercup.com. This website provides interview questions forum for those guys, who have queries regarding interviews. Hence, this is very nice book for interview preparation.

Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.


06/23/14
Amazon

Hot Deals On Amazon

Promo

Mens Clothing – Launch Offer

Check out our brand new Men’s Clothing store and take advantage of our special launch offer – Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.


Promo

30% off on Bluetooth Headsets

Save up to 30% off on Bluetooth Headsets by Samsung, Jabra, Plantronics and more.

Get Link:
30% off on Bluetooth Headsets


Promo

Save 30% on Power Banks

Keep your phone going. Save up to 30% on a wide range of Power Banks.

Get Link:
Save 30% on Power Banks


Promo

Up to 50% off on Routers

Get up to 50% off on Routers by D-Link, Netgear and more.

Get Link:
Up to 50% off on Routers


Promo

Deals on Tablets

Get up to 25% off on Tablets – Dell, Lenovo, Samsung, HCL and others.

Get Link:
Deals on Tablets


Promo

Games & Gaming Accessories

Save 25% off or more on a wide range of Games and Gaming Accessories.

Get Link:
Games & Gaming Accessories


Promo

Study Aids & Exam Preparations

25% off or more on study guides and exam prep books.

Get Link:
Study Aids & Exam Preparations


Promo

100 Must Read Books

The Amazon.com editors have put together a list of the 100 must-read books in a lifetime. Find great deals on your favourite title.

Get Link:
100 Must Read Books


Promo

Samsung Galaxy Tab 4 T331

Pre order the brand new Samsung Galaxy Tab 4 T331 at a special price.


Promo

Brand New Lava Iris X1

Exclusive Launch: Get the brand new Lava Iris X1 at Amazon.

Get Link:
Lava Iris X1


Promo

50% off on 1000+ Music Albums

Save up to 50% on 1000+ Music Albums – Rock, Classic, Pop, Ghazals and Bollywood.

Get Link:
50% off on Music


Promo

40% off on best-selling Video Games

Save up to 40% off on best-selling Video Games for PS3, Xbox 360 and other platforms.

Get Link:
40% off on best-selling Video Games


Promo

Up to 50% off on Fossil, Sony, Esprit & more

Get up to 50% off on select watches from Fossil, Sony, Esprit, Titan and other brands.

Get Link:
Best Deals in Watches


Promo

Great Deals in Electronics

Find great deals on Mobiles, Smartphones, Cameras, Tablets, MP3 Players, Headphones, Speakers and Electronics Accessories.

Get Link:
Great Deals in Electronics


Promo

Women’s Shoes under 799

Find hundreds of styles from a number of brands for under 799.

Get Link:
Women’s Shoes under 799


Promo

50% off on Bestselling Books

50% off on Bestselling Fiction, Autobiographies, Self-Help and more.

Get Link:
50% off on Bestselling Books


Promo

40% off on Audio & Video

Get up to 40% off on a wide range of iPods, Speakers and Headphones.

Get Link:
Deals on Speakers, Headphones & More


Promo

30% off on Baby Products

Save 30% off on a wide range of Baby Products.

Get Link:
Baby Products Deals


Promo

30% off on select Comedies

Browse our vast selection of English and Hindi comedies, and get an extra 30% off on select titles.

Get Link:
Extra 30% off on select Comedies


Promo

Additional 35% off on Shoes

Check out our newly launched Footwear store, and get an additional 35% off on select shoes by Nike, Fila and more.

Get Link:
Additional 35% off on Shoes


Promo

25% off on Cameras

Get up to 25% off on a wide range of Cameras, and EMI options on orders above Rs.3,000.

Get Link:
25% off on Cameras


Promo

50% off on Fashion & Traditional Jewellery

Get up to 50% off on Fashion and Traditional Jewellery.

Get Link:
50% off on Fashion & Traditional Jewellery


Promo

Up to 50% off on Headphones

Find the best prices on a wide range of Headphones from JBL, Philips, Skullcandy and more.

Get Link:
Up to 50% off on Headphones


Promo 

35% off on Popular Smartphones

Get up to 35% off on select Smartphones from Samsung, Nokia, Apple, Micromax and more.

Get Link:
35% off on Popular Smartphones

 


Promo

50% off on Blu-ray titles

Save up to 50% on select Blu-ray titles.

Get Link:
50% off on Blu-ray titles


Promo 

Up to 50% off on Speakers

Find the best prices on a wide range of Speakers from JBL, Creative, Sony and more.

Get Link:
Up to 50% off on Speakers

 


Promo

Home & Kitchen essentials

Get up to 25% off on select Home & Kitchen essentials.
Get Link:
25% off or more on Home & Kitchen Essentials

 

Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.


06/21/14
Java

What is Reentrant Synchronization or Locking in Java?

Java programming language supports multithreading or concurrency very well. Therefore, when we say multithreading or concurrent programming, it is necessary to have efficient synchronization or locking mechanisms, which saves concurrent program from unexpected concurrency issues like deadlocks. Reentrancy is one of those locking mechanism which help concurrent program to work as expected without any locking issue.

Now, you want to know, what exactly this reentrancy do in Java? Let me explain you reentrancy or reentrant locking in Java, but before moving on it, I would like to tell you about, how Java threads take locks on objects and make operation synchronize or atomic. Therefore, before moving on reentrancy, I would like to explain intrinsic or monitor lock.

Intrinsic Or Monitor Lock

Java provide built-in locking mechanism to make any operation atomic by synchronization in concurrent environment. In Java programming language ‘synchronized‘ keyword is used for taking lock or monitor on object. There are other locking utility also available in Java but we will concentrate on basic locking mechanism (synchronized) only. synchronized keyword can be use with method signature or with particular code block to make that synchronize. These built-in locks known as intrinsic or monitor lock.

Intrinsic Lock Examples

There are few intrinsic or monitor lock examples mentioned below to make code synchronized.
1. Creating object level lock with method signature.

public synchronized void objectLevelLock() {
	// Code to make synchronized or atomic
}

2. Creating object level lock with synchronized block inside method.

public void objectLevelLock () {
	synchronized(lockObject) {
		// Code to make synchronized or atomic
	}
}

3. Creating class level lock on static members of class with method signature

public static synchronized void classLevelLock () {
	// Static members and Code to make synchronized or atomic
}

4. Creating class level lock on static members of class with synchronized block inside method.

public void classLevelLock () {
	synchronized(ClassName.class) {
		// Static members and Code to make synchronized or atomic
	}
}

Reentrant Lock

Reentrancy is a locking mechanism provide by Java, which prevent Java locking from critical concurrency issue like deadlock . Suppose, there are two threads A and B. Thread B is trying to acquire lock or monitor on an object, which is already acquired by thread A. Thread B will be blocked until thread A release lock or monitor. But if thread A will try to acquire lock on other synchronized method or block on same object, it will be succeeded to acquire lock on same object. This facility is known as reentrancy. In other words, a thread who takes lock or monitor on object can be reenter any number of synchronized methods or blocks of same object on which it has already acquired lock. This is because, object locking is performed on per thread basis, not on per invocation basis.

What Could Be The Problem Without Reentrant Lock?

In this section I would like to explain, If reentrancy wouldn’t supported by Java, how it could affect thread execution and create concurrency issue. Please carefully go through the code given below.

public class Reentrancy {
	public synchronized void inner() {
		// Code to make synchronized or atomic
	}
	public synchronized void outer() {
		// Code to make synchronized or atomic
		inner();
	}
}

In this above code what will happen if reentrancy is not supported by Java. Suppose, a thread acquire lock on Reentrancy class object by invoking synchronized method outer(). But if you would notice outer() method invoking inner() method, which is also synchronized method. In such case, if Java wouldn’t support reentrancy, outer() method couldn’t succeeded to acquire lock on inner() method, because, it would be considered already locked and eventually result would be deadlock. But just because reentrancy is supported in Java, the thread who acquire lock on object can enter any synchronized method or block on same object to acquire lock.

How Reentrant Lock Works In Java?

Reentrancy is implemented in Java by associating a counter with each thread. Initially counter initialized with value zero and considered as unlocked. When thread acquires lock on an object, counter get incremented by one. Again, if thread acquires lock on another synchronized method or block, counter again get incremented by one; counter will become two and so on. Same reverse process is followed, when thread release lock by leaving synchronized method or block. When thread releases lock from synchronized method or block; counter get decremented by one and so on. Once again, when counter reached to zero; object gets unlocked. Now other threads are free to acquire lock on that object. This is the approach by which Java manage reentrancy.

Conclusion

That’s all how Java intrinsic and reentrant lock works. After reading this article, you are aware about, what are intrinsic and reentrant locks and how these locks works. I hope this article will help you to understand about Java locking mechanism.

Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.


06/12/14
author

UML relationships like Association, Aggregation, Composition, Abstraction, Generalization, Specialization, Realization and Dependency

In this article, we are specifically taking about few Object Oriented Programming relationships like association, aggregation, composition, abstraction, generalization, specialization, realization and dependency. These relationships are very common for any object oriented programming. Despite of that, lots of developers feels that these terms are little weird and unknown for them. In this article, I would try to explain each and every term with suitable examples. I hope after reading this article few of you would be amazed that these all relationships are so familiar to you. But you do not know them so closely. But after reading this you can understand these relationships very well. These relationships are very important and useful in UML to demonstrate relationships between classes and objects. So let us explore these topics one by one.

Association

In Object Oriented Programming, each object shared some kind of relationships with other objects. Therefore, relationship between objects is known as “Association”. This relationship could be any type like one-to-one, one-to-many or many-to-many. For example, Student and Subject relationship. Relationship between Student and Subject is many-to-many, because one Student can read many Subjects and one subject can be read by many Students. Therefore, Students and Subjects are associated with each other.

Aggregation

Aggregation is special type of association, in which one object contain other object, which is directional relationship. This relationship is also known as “has a” relationship. For example, every Employee has a Department. Therefore, there is an aggregation between Employee object and Department object.

Composition

Composition is special case of aggregation. In this relationship, one object contain other object. This is also a “has a” relationship. But there is one restriction with this relationship, that is, contained object can’t exist without container object. For example, Person has a Address, but Address does not have any importance and can’t exist without Person. Therefore, a Person compose an Address.

Abstraction

Abstraction is one of the important concepts of Object Oriented Programming. Abstraction is to hiding implementation information from user. Instead of exposing implementation, its declare methods or functions and their general detailed information to help implementation. Later on user can provide concreteness by giving correct implementation based on details information provided by abstract layer. Examples of abstraction are Abstract classes and Interfaces.

Generalization

Generalization is a relation between Superclass and Subclass . This relation is “is a” relationship . Generalization is process of moving common code from Subclasses to Superclass. This process will make that common code to general code. So that, this general code can be reuse by any of its Subclass. Generalization is type of inheritance.

Specialization

Specialization is a process of creating a new subclass of existing superclass. In specialization, subclass extends existing general implementation to specific implementation by overriding existing implemented methods. This is also “is a” relationship. Specialization is type of inheritance.

Realization

Realization is a relationship between interface and class. In realization, new class implements all unimplemented abstract methods and provide concrete implementation. This process provides real business logic implementation to any abstract class or interface. This is also “is a” relationship.

Dependency

Dependency is relationship between two or more classes, in which, if any modification done on one class can affect other classes. That means one class depends on second clas . In such way one class has dependency on second class.

Symbols Used By UML To Show Relationships Between Classes Or Objects

UML Symbols

Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.


05/30/14
author

How to make any class immutable in Java?

Immutability is most important topic in respect of coding practice. This is one of the frequently asked topic in Core Java interview. Every interviewer expect that you must have good understanding about immutable classes, advantages of immutable classes and very important that how to create any class immutable in Java. These are few important aspects, which is necessary to know about immutable objects. In this article, I would divide it into three parts, so that you can have better understanding about immutability level by level. Let us talk about immutability concept deeply.

Immutable class in Java

1. What Is Immutable Class?

As you know general meaning of “immutability” in English is “A quality, not to being changeable”. Same a class called immutable, only if it’s internal state never change once it is initialized. When a immutable class get initialize, it create its internal state ( initialize it’s data members ) at the time of initialization by passing arguments through constructor. Once an immutable object get initialized, nobody can changes its internal data members. In Java there are lots of classes, which are immutable in nature, like java.lang.String, java.lang.Integer, java.lang.Double etc.

2. What Are The Advantages Of Immutability?

This is really a nice question that why should we create immutable class? or what are the advantages of immutable class?

The main reason to make any class immutable is it’s internal state safety. Immutable classes are thread-safe. Immutable objects can be passed to untrusted code. Biggest worry in multi-threading environment is that any mutable object shared between threads can spoil its state unpredictably. But immutable objects are totally safe to share between threads.

Second advantage is that its simple to make any class immutable by following some set of simple rules. There are predefined rules which are necessary to follow to protect object state. We will cover all these rules in next section of this article.

Third advantage is that we don’t need to implement cloning on immutable class. We can share same copy anywhere. Because, immutable objects don’t change it’s state anyhow. If you want to learn about cloning, you can read my article, What is cloning and types of cloning in Java?

3. How To Make A Class Immutable?

As of now, you know what is immutability. But how can we make any class immutable in Java? There are some set of rules, which we need to follow at the time of creating any immutable class. In this section we will go through all important rules, what we need to care about and will understand how these rule can make any class immutable. Lets see how we can make a class immutable. Before that, I would like to show you one simple class example (Immutable Class), which gives you an idea, how an immutable class look like and why we say it immutable.

import java.util.ArrayList;
import java.util.List;

public final class Immutable {
	// int is primitive data type.
	private final int value;
	// String is immutable class;
	private final String text;
	// List is mutable type.
	private final List<String> list;
	
	public Immutable(int value, String text, List<String> list) {
		this.value = value;
		this.text = text;
		this.list = copyOfList(list);
	}
	
	public int getValue() {
		return value;
	}
	
	public String getText() {
		return text;
	}
	
	public List<String> getList() {
		return copyOfList(list);
	}
	
	private List<String> copyOfList(List<String> list) {
		List<String> newList = new ArrayList<String>();
		for ( String element : list )
			newList.add(element);
		return newList;
	}

}

Please understand this above example carefully, because in next step, I will use this example to explain all important rules regarding immutability. Lets talk about the immutability rules in detailed manner:

  1. All data members inside class must be private.  Because, private data members cannot access from outside of the class. Therefore, nobody can access and change the state of internal data members.
  2. All data members inside class should be final. It is a good coding practice, but this is not hard and fast rule. Because immutable class don’t allow to access any data member of immutable class outside. Therefore, It doesn’t meter that whether data members of class are final or not.
  3. All data member must be set through constructor. No setter method will be provided for any data member. Because, if class will provide setter methods then anybody can change immutable objects state.
  4. Class must be declared as final. So that no other class can extend this class and spoil its immutability. Now, there could be one question in your mind, how can we break immutability by extending non final class? Lets me show you an example:
    public class Immutable {
         private final Object value;
    
         public Immutable(Object value) {
             this.value = value;
         }
    
         public Object getValue() {
             return value;
         }
    }
    public class Mutable extends Immutable {
         private Object realValue;
    
         public Mutable(Object value) {
             super(value);
             realValue = value;
         }
    
         public Object getValue() {
             return realValue;
         }
    
         public void setValue(Object newValue) {
             realValue = newValue;
         }
    }

    Here you can see how extended class Mutable can pass its own Object in it’s superclass Immutable constructor. Now Mutable class can easily break immutability of Immutable class by changing its own Object. That is why it is significant to make class final.

  5. All mutable objects coming in through constructor should not use directly, instead of that, create new object copy of that object, which must be equal to passed object. As you can see in my topmost coding example (Immutable Class), inside constructor I have used this.list = copyOfList(list);  instead of using this.list = list; Here I have create an copy of list object rather than passing it directly.
  6. All mutable objects going outside through getter methods must return new copy of mutable object instead of returning same object outside. New returned copy object must be equal to the original object. As you can see in my topmost coding example (Immutable Class), I have used return copyOfList(list); inside getList() method instead of using return list; Because I don’t want to share my internal reference to outside the world.
  7. But primitive and immutable reference can be used directly and can be shared outside the world without any hesitation. Because primitive and immutable reference cannot change anyhow. 

Conclusion

That is all about immutability concept. By reading this article, you know about immutability, advantage of immutability and all important rules to make class immutable. This concept don’t belong to any specific language. You can follow these rules to make your class immutable in any language. I hope this article will encourage you to use immutability in your coding practices.

Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.


05/23/14
author

What is cloning and how many types of cloning exist in Java?

There are lots of ways to create objects in Java. You can create an object by new keyword with constructor, by Java reflection, by Java deserialization to a serialized object and by Java cloning. But here we are specially taking about Java cloning. Java cloning is process to create an exact copy of an object or clone of an object. Java cloning creates copy of an object without invoking any construct. There are two types of cloning in Java Shallow Copy and Deep Copy cloning. I will discuss these topics later-on in this article. Java cloning is an controversial topic in Java. Lots of people do not think that cloning is a best implementation in Java. But we are not talking about that controversy here, instead of that we are discussing on present cloning feature in Java and its mechanism.

How To Create A Class Clone-able?

There are few requirements to create a class clone-able. First of all your class must implement java.lang.Cloneable interface, which is a marker interface in Java. Therefore, java.lang.Cloneable interface does not declare any abstract method, this is an empty interface, which tell the JVM that, this class supports cloning mechanism. If class doesn’t implement java.lang.Cloneable interface then it will throw java.lang.CloneNotSupportedException. This is a checked exception in Java, which is mandatory to handle during cloning.

Second and important requirement is to override clone() method of java.lang.Object class. This method is declared as protected and native in java.lang.Object class. Therefore clone() method create clone of object by calling super.clone() method of its parent class and eventually it will call the clone() method of java.lang.Object class. As I told you earlier that cloning process does not invoke constructor of class to create copy of object. That is why cloning use native approach to initialize new object and equal object in memory.

Important Aspects About Java Cloning

As you know Java cloning is a process to create a exact copy of an object. But there are some important aspects and contract between original object and cloned object. Which is really significant to understand before writing cloning mechanism in Java. Lets talk about them.

  1. To support cloning in Java, class must implement java.lang.Cloneable interface.
  2. After implementing java.lang.Cloneable interface, class must override clone() method of java.lang.Object class.
  3. Cloning should not use constructor to create copy of object. You can use native approach to initialize new cloned object.
  4. Cloned object must be a new object in memory. clone() method should not return same instance (this) on which clone() method is invoked. Therefore x == x.clone() must be false.
  5. x.getClass() == x.clone().getClass() will be true, But its not an absolute requirement.
  6. Cloned object must have same internal state as it’s original object. Both original and cloned object’s  data members must have similar state or value. Therefore,  x.clone().equals(x) must be true.
  7. Checked exception java.lang.CloneNotSupportedException must be handled at the time of cloning.

Java Cloning Implementation Example

public class Foo implements Cloneable{
	
	private int number = 0;

	public void setNumber(int number) {
		this.number = number;
	}

	public int getNumber() {
		return number;
	}
	
	@Override
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
}

Types Of Cloning In Java

Now you know, what is cloning and all significant aspects about cloning in Java. But types of cloning is also very important aspect in Java. It is most important, if you want to implement clone-able class by yourself.

There are two types of cloning in Java and both have significant differences.

  1. Shallow Copy
  2. Deep Copy

 Shallow Copy

Shallow copy is a new copy (clone) of original object, but all internal variables of new cloned object are same as original object. Java by default create shallow copy during object cloning. As you have seen above  in Foo class example, Foo class’s override clone() method call super.clone() native method of java.lang.Object class. That’s mean native clone() method of java.lang.Object class assign similar internal variable reference of original object to cloned object’s variable. In that case, we have two different objects but internally they holding same references as their data members. Means variables of original object and cloned object both referring same objects on heap. This technique is correct if your class holding only primitives or immutable objects, but this technique goes wrong, if your class hold any mutable object. Because any change made on mutable reference of original object will be reflect on  cloned object or vice-versa. Therefore, shallow copy technique somewhere breaking cloning purpose. In such way original object and cloned object are not totally independent, somewhere both are dependent on each other. You can see below diagram, how original and shallow copy objects share internal references.

Java Shallow Copy Cloning

Lets see shallow copy example and its disadvantage.

public class Foo implements Cloneable{
	// Primitive Reference
	private int number = 0;
	// Immutable Reference
	private String name;
	// Mutable Reference
	private Bar bar;
	

	public void setNumber(int number) {
		this.number = number;
	}

	public int getNumber() {
		return number;
	}
	
	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}
	
	public void setBar(Bar bar) {
		this.bar = bar;
	}

	public Bar getBar() {
		return bar;
	}
	
	@Override
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
}

ShallowCopyCloneTest.java class shows that, how should we create a clone object from cloneable class. This class will also put some light on problem exist in shallow copy technique.

public class ShallowCopyCloneTest {

	public static void main(String[] args) {
		try {
			Bar bar = new Bar();
			bar.setValue("Hi");
			Foo object = new Foo();
			object.setNumber(20);
			object.setName("Hawk");
			object.setBar(bar);
			
			Foo	clone = (Foo) object.clone();
			
			System.out.println("Foo Orignial# Number:" + object.getNumber() + " Name:" + object.getName() +" Bar-Value:" + object.getBar().getValue());
			System.out.println("Foo Cloned# Number:" + clone.getNumber() + " Name:" + clone.getName() +" Bar-Value:" + clone.getBar().getValue());
			
			object.setNumber(40);
			object.setName("Eagle");
			object.getBar().setValue("Hello");
			object.setBar(bar);
			
			System.out.println("Foo Original Object Changed....");
			
			System.out.println("Foo Orignial After Change# Number:" + object.getNumber() + " Name:" + object.getName() +" Bar-Value:" + object.getBar().getValue());
			System.out.println("Foo Cloned Without Change# Number:" + clone.getNumber() + " Name:" + clone.getName() +" Bar-Value:" + clone.getBar().getValue());

		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
	}
}

Output after running shallowCopyCloneTest.java class

Foo Orignial# Number:20 Name:Hawk Bar-Value:Hi
Foo Cloned# Number:20 Name:Hawk Bar-Value:Hi
Foo Original Object Changed....
Foo Orignial After Change# Number:40 Name:Eagle Bar-Value:Hello
Foo Cloned Without Change# Number:20 Name:Hawk Bar-Value:Hello

If you would see the code and output carefully, you can understand that cloned object looks like exact copy of original object before any modification done on original object. But after making modification on original object ‘Number’ and ‘Name’ data member of cloned object doesn’t get change, because ‘Number’ is primitive data type and ‘Name’ is String type, which is immutable in Java, that mean they are safe to share between objects. But ‘Bar-Value, of cloned object get changed itself with modification on  ‘Bar’ reference of original object, this is because ‘Bar’ reference is mutable, which is not safe to share between objects. This is how shallow copy break rule of cloning that both original and cloned object should be conceptually equal and independent. Modification on one object should not reflect on other object.

Deep Copy

Deep copy cloning is a solution for references sharing problem of shallow copy cloning. Deep copy cloning is very important and useful cloning technique, which takes guaranty that cloned copy will be an equal object as original object and both objects will be totally independent, that means no internal references will be shared (Modification on original object will not affect cloned object any more or vice-versa). In deep copy cloning all mutable variables further get manual deep cloned before returning cloned object to client. This is the responsibility of class author that if your class is cloneable, then you will use deep copy cloning techniques, so that your class can return deep copy as cloned object. But somewhere we have to compromise with some basic cloning rules, like “We should not use constructor during cloning”. But if we have to create deep copy cloning, somewhere we have to use constructor to create deep copy object, that means we have to create new references for cloned object.

Java Deep Copy Cloning

Here, I would like to use an best example, which is illustrated by Jashua Bloch in his book “Effective Java” . This is an amazing book for Java concepts. Everyone must read this book once.  In this simple example he has shown that how java.util.HashTable class has implemented deep copy cloning inside this class. In java.util.HashTable class Entry[] array is an mutable reference, which is deep cloned by deepCopy() method. Go through this example, it will give you a good idea about, how should we create deep copy for a cloned object.

public class HashTable implements Cloneable {
    private Entry[] buckets = ...;

    private static class Entry {
        final Object key;
        Object value;
        Entry next;
        Entry(Object key, Object value, Entry next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }

        // Recursively copy the linked list headed by this Entry
        Entry deepCopy() {
            return new Entry(key, value,
                    next == null ? null : next.deepCopy());
        }
    }
    @Override 
    public HashTable clone() {
        try {
            HashTable result = (HashTable) super.clone();
            result.buckets = new Entry[buckets.length];
            for (int i = 0; i < buckets.length; i++)
                if (buckets[i] != null)
                    result.buckets[i] = buckets[i].deepCopy();
            return result;
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }
}

Conclusion

That is all about Java cloning. In this article you have understand basic requirement for cloning, all important rules to implement cloning. You have read about differences between shallow copy and deep copy cloning. Now you know what types of problems, you may encounter with in case of shallow copy cloning. But most important thing is that, Now you have a good idea about deep copy cloning and you know what approach you should take to write your own deep copy cloning approach. I hope this article will help you somewhere to write correct and robust code.

Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.


05/4/14
author

What is Bridge Method and Type Erasure in Java Generics?

Bridge method and type erasure in Java generics are advance concepts. These concepts are important for experienced Java professionals. These are basically a low level typics, I mean Java Bytecode compilation level topics. Therefore, It is necessary that you must have good understanding of Java generics and it’s implementation before going more deep in these concepts. Bridge method and type erasure are really interesting topics in Java. After reading this article, you would be amazed that how generics classes work internally. Apart from that, these topics are also important for all experienced Java professionals, who wants to have good understanding behind Java Generics. Because, most of interviewers would expect from you that you would have understanding of JVM internal execution and Java Bytecode compilation. If you are really interested to know, let us talk about bridge method and type erasure.

java bridge method

But before going on these topics let us understand what is Java generic and how does generic works behind? When we do create generics classes or interfaces, they do not declare any concert types, while they do not aware of, what kind of objects they will contain at real time. But we tell and specify to generic type,  some specific concert objects types at the time of compilation. These specific concert objects types declaration occurs, when we actually extends, implements and use these generics classes or interfaces. But now question arise, if generics classes or interfaces do not know about concert objects on which they have to perform operations, then how do they manages their internal execution without knowing their concert types? Answer of this question is by type erasure. Lets take a generics coding example to illustrate this.

public interface Foo<T> {

     public void setName(T name);

     public T getName();
}

public class Bar implements Foo<String> {

     private String name;

     public void setName(String name) {
         this.name = name;
     }
 
     public String getName() {
         return this.name;
     }

}

In this example you can see that  Foo<T> interface is generic type and its implementation Bar class can use any kind of concert object in its implementation, here we have used String type object for Bar class implementation. Now you can see that generic type setName and getName methods can accept and return String types objects. But how any generic types can accept any specific concert objects. This problem can be resolve by using type erasure.

Type Erasure In Java

Type erasure is a process to map a generic parameter type or method to its unique bytecode representation.

The compiler generates single unique bytecode representation for generic type or method by eliding type parameters and arguments. All instances of generics types get mapped with unique bytecode representation. This unique bytecode representation is created by type erasure. To create an unique bytecode representation, compiler elide generic type to java.lang.Object type (List<T>  → List<Object>), which can accept any kind of objects. If generic type is extended by one of specific type then it is elide to that specific type (List<T extends Animal> → List<Animal>).

Bridge Method In Java

Bridge method is a auto-generated method or unique representation generated by compiler after type erasure to any generic type method. These bridge methods are unique bytecode representations which are used to perform generic operations.

The compiler insert a bridge method in sub class of generic super class by type erasure. So that sub class can work as expected. Lets see bridge methods example.

public interface Foo {
	// Bride Method Declaration By Type Erasure
	public void setName(Object name); 
	
	// Bride Method Declaration By Type Erasure
	public Object getName();

}

public class Bar implements Foo {

	private String name;
	
	public void setName(String name) {
		this.name = name;
	}
	
	// Bride Method Declaration By Type Erasure
	public void setName(Object name) {
		this.setName((String) name);
	}
	
	public String getName() {
		return this.name;
	}
	
	// Bride Method Declaration By Type Erasure
	public Object getName() {
		return this.getName();
	}
}

After type erasure conversion by compiler setName(String name) is not implementation of Foo interface. Because Foo interface required setName(Object name) implementation, which is introduced by compiler as bridge method. Therefore bridge method provides accurate implementation. But these bridge methods delegate original methods internally in bridge methods. Bridge methods can not access by client directly, because Java do not expose bridge methods for user to use. But still there is a way to break this rule. Because bridge methods can access by Java reflection. Through refection you can even invoke private methods of class, same you can invoke bridge methods of class through reflection as well.

This is how generic type classes or interface transform from generic type to any specific type. In this conversion bridge method and type erasure play an important role. Without bridge methods it would not be possible to map concert type objects with generics types. I hope you would like this post and this post will help you to understand mechanism behind generics.

Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.


04/16/14
author

What is assertion or assert in Java?

Assertion or assert is a less known feature of Java. Most of developers don’t use assert in their daily routine coding, that is why most of developers don’t much bother about it. But frankly speeking, this is a useful feature of Java and every developer need to know about it. Most of you, who have used JUnit framework for unit testing, have used assertion to test any test case. JUnit is the best example of Java assertion. Lets discuss little more about assertion in Java. Since JDK 1.4, Java has introduced assert keyword to support assertion. Assertion is basically used for validation checks in program, if validation fails during assertion check, it throw AssertionError and program got terminated, otherwise it allow program execution as usual.

What Is Assertion?

Assertion facility introduced in Java since JDK 1.4. Java introduced assertion by assert keyword. An assertion is a boolean expression that a developer specifically proclaims to be true at runtime.

There are two forms of assertion in Java

assert Expression1;
or
assert Expression1 : Expression2;

Expression1 must be a boolean expression, which is evaluated at runtime, if it is false, an AssertionError is thrown.
Expression2 value is typically a String, but could also be anything that expression returns. This expression must not return void. It is basically used to customize message for AssertionError.

Note: AssertionError is an error, which is subclass of java.lang.Error class and not recoverable. It is used for logging purpose only.

assertion

Where To Use Assertion?

An assertion is a statement, which assumed to be true during the execution of program. It returns a boolean result. If result is true, code executes normally. Otherwise it throw AssertionError and terminate program execution. Assertion is basically validate the result. It is good to use assertion with one of the following:

1. Precondition is a assert condition which must be true, when method is invoked. If an argument is invalid for any method, its validation before using it in method is known as precondition check.  Precondition assertion check must be use in non-public methods. For public methods you must throw IllegalArgumentExcetption.  Because, public methods can be invoked by any client code, if client is invoking any method with illegal value then client must be informed by exception that passed value as argument is illegal for this method. If we use assertion instead of exception here, client would not be aware about his/ her mistake. Therefore precondition assertion must be use for non-public methods. For example. 

private void myMethod(int arg) { 
assert arg>0 && arg <=1000 : “Bad arg: ”+arg; 
… 
}

2. Internal Invariant is an assumption of program behavior. If somewhere in program any abnormal condition occurs that you can check with assertion. For example.

if (x%3 == 0) { 
… 
} else if (x%3 == 1) { 
… 
} else { 
 assert x%3 == 2 : x; 
 // x modulo 3 should be only 0, 1 or 2. Everything 
 // would work fine until you get negative x’s. 
 // *A simple assertion help to discover unsupported results. 
} 

//-------------------------------------- 
switch (key) { 
case CST_VALUE_A : 
 … 
 break; 
case CST_VALUE_B : 
 … 
 break; 
 … 
 default: 
 assert false : key; 
 // *A simple assertion help to discover unsupported values. 
}

3. Postcondition is a assert condition which, must be true, when method is about to finish its work and ready with final resultant. If final result ready to return, its validation before return by method is known as postcondition check.  Postcondition assertion check can be use in public or  non-public methods.

public double square(double val) { 
 .. // compute square 
 assert result*result == val : val; 
}

4. Class Invariant is type of internal invariant, which must be true with every instance of class. For example implementation of heap. Heap must be balanced with every instance is created inside it.

private boolean balanced { 
 … 
} 

public void addValue(double key, Object obj) { 
 … // implementation all method should check if heap is balanced prior to its return. 
 assert balanced(); 
}

5. Control Flow is a assertion check that would check a location that will never be executed.

if (…) {
…
return;
}
assert false; // should never be reached

Where To Avoid Assertion

There are few situations, where it is recommended to avoid assertion. Following are the situations:

  • Argument checking for public method by assertion is not recommended. Reason behind this is same, what is mentioned in precondition,s description.
  • In your application where you required correct operation, you must avoid assertion there. Expression evaluation during assert code can be harmful.
  • Evaluating the expression should not affect any state that is visible after the evaluation is complete. There is one exception in this rule is that assertion can modify the state that is used only form within other assertions.

Differences Between Exception and Assertion

Exception Assertion
Exception tells the programmer that something gone wrong in the program. Assertion document or log the program, when it fail and tell that program has bug.
Exception are created to inform and deal with problems which might occur in program. Assertion are create to validate accuracy of program.
Exception are used to test input or output as well as whether the program is legal or not Assertion are used to document and find bug in program. Assertion are also used for debugging purpose.

Important Points about Assertion

  •  Assertion is introduced since JDK 1.4.
  • In order to compile class with assertions using javac compiler, you must use the -source 1.4 command-line option as in this example:
     javac -source 1.4 MyClass.java

    This flag is necessary so as not to cause source compatibility problems.

  • Assertion can be enable and disable at runtime by using switches -enableassertions or -ea and -disableassertions or -da.
  • Running 1.4 binaries needs a 1.4 runtime engine. Assertion are default disabled. To
    activate them, use the following syntaxes:

    Syntax Purpose
     java -ea  Enable assertions in all classes excepted system classes
     java –ea:<className>  Enable assertions for a specific class
     java –ea:<packageName>…  Enable assertions for a package and any sub-packages
     java –ea:…  Enable assertions in the unnamed package in the current working directory
     java -da  Disable assertions (default)
     java –da:<className>  Disable assertions for a specific class
     java –da:<packageName>…  Disable assertions for a package and any sub-packages
     java –da:…  Disable assertions in the unnamed package in the current working directory
     java -esa  Enable assertions in system classes
     java -dsa  Disable assertions in system classes

     

Conclusion

That’s all about Java assertion. After reading this article, you understand Java assertions, where to use assertions, how to use assertion and where should avoid using assertions. I hope you will use assertions in your programs to make them more robust.

Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.


04/8/14
author

Classloading Mechanism in Java

Classes loading on Virtual Machine is a hidden process of any programming language. Most of the developers do not bother about it. Because this is the responsibility of frameworks to load their respective classes to run Virtual Machine and application on it. But believe me, this is really very important to know about classloaders and classloading mechanism. If you are writing higher end applications or frameworks, which has wide scope of work to do, there might be chance, you need to write your own custom classloaders for your applications. Lots of Java based frameworks have implemented their custom classloaders, which solve their concerned problems. Here we specifically talking about Java classloaders, Lets we discuss about classloading mechanism in Java Virtual Machine.

Class Loading on JVM

Classloading is a process to load required classes on Virtual Machine. Only after loading required classes your application can run on JVM. There are two types of classloading.

  1. Eager Classloading is process of loading all classes comprising the source of application before run the application on VM. Application can take some time to run on VM, because classloaders will first load all classes to VM and after that they will run application on VM.
  2. Lazy Classloading is process of loading classes, at first active use of class rather that loading them on start-up of application on VM.

The first active use of class occurs, when one of the following event occurs:

  • An instance of that class is created.
  • An instance of one of its subclass is initialized.
  • One of its static fields is initialized.

These two are the types of classloading on VM. But its totally depends of JVM vender that what types of classloading they are providing with their JVM. Note that, JVM provided by IBM supports both types of classloading but JVM provided by Oracle (Sun) is only support Lazy classloading.

java.lang.ClassLoader class

Before describe more about classloading mechanism in JVM, I would like to tell you somethings about java.lang.ClassLoader class, which will  help you to under classloading mechanism. According to JavaDoc, the class ClassLoader is an abstract class. If you want to create your own custom class loader for your application or framework then you can extend your classloader class from java.lang.ClassLoader class. There are methods available in ClassLoader class to load and define classes from file system. ClassLoader class load any class by its binary name and return java.lang.Class class object. Every java.lang.Class object contain reference of it ClassLoader.

java.lang.Class objects for array classes are not created by classloaders, but are created automatically as required by the Java runtime. The ClassLoader for an array class, as returned by Class.getClassLoader() is the same as the classloader for its element type; if the element type is a primitive type, then the array class has no ClassLoader.

The ClassLoader class uses a delegation model to search for classes and resources. Each instance of classloader has an associated parent classloader. When requested to find a class or resource, a ClassLoader instance will delegate the search for the class or resource to its parent class loader before attempting to find the class or resource itself. The Virtual Machine’s built-in class loader, called the “bootstrap classloader“, does not itself have a parent but may serve as the parent of a ClassLoader instance.

Class loaders that support concurrent loading of classes are known as parallel capable classloaders and are required to register themselves at their class initialization time by invoking the ClassLoader.registerAsParallelCapable() method. Note that the ClassLoader class is registered as parallel capable by default. However, its subclasses still need to register themselves if they are parallel capable.

In environments in which the delegation model is not strictly hierarchical, class loaders need to be parallel capable, otherwise class loading can lead to deadlocks because the loader lock is held for the duration of the class loading process (see loadClass methods).

Normally, the Java Virtual Machine loads classes from the local file system in a platform-dependent manner. For example, on UNIX systems, the virtual machine loads classes from the directory defined by the CLASSPATH environment variable.

However, some classes may not originate from a file; they may originate from other sources, such as the network, or they could be constructed by an application. The method defineClass() converts an array of bytes into an instance of class java.lang.Class. Instances of this newly defined class can be created using Class.newInstance().

ClassLoaders Hierarchy 

Java has it own classloaders hierarchy to load classes on JVM. Java has three in-built classloaders, which are shown bellow in classloaders hierarchy diagram.

classloader_hierarchy

As you can see in above diagram, these three core classloaders communicate with each other through there hierarchy protocols, which I would mention later-on in this article. Now lets understand about particular classloader individually, their hierarchy and responsibilities:

  • Bootstrap classloader : Bootstrap classloader is core native classloader of Java. This is the topmost  classloader of classloaders hierarchy, it wouldn’t be wrong, if would say, this is the parent of every classloader in Java, like java.lang.Object class is parent class of every class in Java. Because this is native classloader, therefore it’s implementation could be vary with different JVMs. Native classloaders are mostly implemented in C language. Bootstrap classloader is responsible to load all available classes in rt.jar file, which is located at $JAVAHOME/jre/lib/rt.jar
  • Extension classloader: Extension classloader come done next to Bootstrap classloader, in other word, this is child classloader of Bootstrap classloader. It is implemented by sun.misc.Launcher$ExtClassLoader class. This classloader is responsible to load all classes available in ext folder, which is located at  $JAVAHOME/jre/lib/ext/*.jar or any other directory specified by java.ext.dirs system property.
  • System classloader: System classloader is also known as Application classloader. It is implemented by sun.misc.Launcher$AppClassLoader class, which come done next to Extension classloader. This is child classloader of Extension classloader. The main responsibility of this classloader is to load all available classes in $CLASSPATH or java.class.path  location.
  • User Defined ClassLoaders: User defined or Custom classloader are those classloaders, which are defined by developers itself for their applications or frameworks. If you want to create your own classloader then you have to extend your classloader class by java.lang.ClassLoader class. These custom classloaders will come done under System classloader in hierarchy. Their class loading responsibility would be defined by the developers.

Classloading Procedures

This is very important and interesting to understand, how does JVM load any class internally. Till now you almost clear about ClassLoaders, their hierarchy and their individual responsibilities. Now its time to understand communication between classloaders, their overall class loading mechanism and workflow. Now have smile, lets go little deep and understand it better.

Whenever JVM instantiate any class, then JVM will load this class, this is known as Lazy classloading. JVM uses a delegation model to load classes.  Basic idea of delegation model is that classloader has a parent classloader, when classloader load a class, it first delegate the search for class to its parent classloader, before attempting to find the class itself.

class-loading-mechanism

Classloading is a recursive process, When a classloader get request to load a class, it will initiate class loading. First of all it pass the request to it parent classloader, if that parent class loader has any of its parent classloader then it will pass request to its parent classloader and so on. Such way topmost classloader in hierarchy will first search that class in its directory and its cache ( Every ClassLoader maintain its own cache ), whether this class is already been loaded by this classloader, if yes then classloader will return class from cache, otherwise classloader will find that class in its directory. If class exist there in directory, it will store that class in its cache and return that class to its child classloader and so on. In other hand, if parent classloader did not find that class in its directory and cache, it will throw ClassNotFoundException. Now its child classloader catch this exception and try to find that class in its directory location. The same procedure will go on until that class would not found by any classloader in that hierarchy. If still that class is not available in overall hierarchy of classloader, eventually classloader, who initiate class loading will throw ClassNotFoundException and stop the execution.

There are few observations about classloading, which are important in this classloading mechanism:

  • Parent classloader has always opportunities to load class first.
  • Each classloader maintain their own cache and check any class first in its cache, if it is not available in cache then check it in its directory and try to load it.
  • It is ensure that one classlaoder can only see classes loaded by itself or by its parent classloaders, but  not by its children and siblings classloaders.

ClassLoader Call Flow

In previous section of this article you have learnt about classloading mechanism. Now you are aware about how does classloading take place internally in JVM. In this section, I would like to explain, how custom classloader are implemented by extending java.lang.ClassLoader class and what is the ClassLoader’s methods call flow to load and define a class in JVM.

There are three important methods of ClassLoader class, which play significant role to load and define a class in JVM. These methods of ClassLoader class are given bellow:

  1. public Class<?> loadClass(String name) throws ClassNotFoundException;
  2. protected Class<?> findClass(String name) throws ClassNotFoundException;
  3. protected final Class<?> defineClass(String name, byte[] b, int off, int len) throws ClassFormatError;

Whenever a ClassLoader is created, it is assigned a parent ClassLoader. As per parent delegation model, when client invoke loadClass(String name) method of ClassLoader class, it will call the loadClass method of parent ClassLoader, where is classloading algorithms is implemented. Before JDK 1.2, loadClass method was abstract, every ClassLoader was required to provide its own classloading algorithm. But later on it is observed that class loading is a critical, complicated and important for JVM, therefore since JDK 1.2 JVM introduced parent delegation model and provide default implementation for loadClass method. After that loadClass method invoke findClass(String name) method of ClassLoader class. Every Custom or User Defined ClassLoader should override findClass(String name) method to specify custom location, where classes need to be search before loading. The findClass method invoke search for given class in specified location, if class found, it read that class and return bytecodes of the class. This bytecodes of class is passed as byte array to the defineClass(String name, byte[] b, int off, int len) method, defineClass method returns java.lang.Class class, which define that given class. This java.lang.Class instance can be used to instantiate that class in Java application. This is the way, how a class get loading and defined in JVM.

Conclusion

This article describes, how important a classloading mechanism is to understand, if you a Java developer. This articles explain entire important aspects regarding classloading and ClassLoaders. After reading this article you can create your own ClassLoader, which suites to your applications. Hope you would like this article. This article encourages you to go more deep in concepts.

Shop for Rs.995 or more, Get 25% off. Shop for Rs.1,995 or more, Get 35% off.