Tuesday, 13 October 2015

Fundamentals of Object Oriented Programming in Java

0 comments
I remember when I was doing my engineering , OOPS concept was in first semester. Back then it looks like some alien things to me, because I have never done programming and even the smallest program we get to write e.g. checking whether number is palindrome or not , or printing Fibonacci series , we never really needed to use OOPS. When needed, I just memorize things and written down in exam :). That worked, I passed the exam but effectively I didn't learn OOP or Object Oriented Programming on those days. It's when, I started learning java (an almost truly object oriented programming language) and introduced to concept like abstract classes, interface, and method overriding; some thing started to going in my mind. This blog post is very basic in nature, but I really hope it could help beginners on understanding things like class, object, abstraction , polymorphism, inheritance ,encapsulation , composition, cohesion, coupling, interface programming etc.

What is Object Oriented Programming


What is object oriented programming in JavaI am planning to write clear and concise post on each of these, because I really don't like too much information in one shot. It never worked with me , I believe learning is gradual process and always start with most simple things, which eventually turned out to be most important one.

So What is Object Oriented programming ?

Simple programming which is oriented on objects :) means treat everything surrounding you as an
object.

Now question comes, what is Object?

An Object is a particular concrete instance of Class, and what is class? A Class is a blueprint from
which object gets created which has attributes and behavior , we call attribute as members and behavior as methods.

lets see one example : how about representing a classroom using OOPS?

A classroom is a room , which has certain no of chairs , desks , blackboard , teacher , students etc.

Now in order to represent that in code, we need to write a program. In Java we will write like this.

public class ClassRoom {

//members
int noOfChairs;
int noOfDesks;
Teacher currentTeacher;
Students [] students;
Blackboard blackboard;


//methods
public int getNoOfChairs(){

}

public Teacher getNoOfTeacher(){

}

.....

}

I have omitted most of the methods, just to focus on concept rather than implementation. So now we know that class is blueprint, which has member variable and methods and used to create object. Now what is object here, any classroom in which any lecture is going on , your first lecture would be one instance, second lecture would be another instance.

See the point, every object of same class has same no of variables but there value gets changed e.g. lecture 1 was attended by 15 students by teacher called Mr. Gupta , lecture 2 was attended by 18 students which was by Miss Amrita.

Any thing which you see around can be represented in class and object e.g. this blog is an instance of Blog class, a particular movie can be instance of Movie class e.g. Titanic is an instance of Movie where actor/director are different than other movie.

That's all on fundamentals of object oriented programming in Java. I hope you got the idea of representing real world things on class and objects, by doing this we try to create applications which solves real world problems. Visualizing and understanding in terms of object also makes programming easy to write, read and maintain.

What is difference between Enumeration and Iterator in Java?

0 comments
Though both Iterator and Enumeration allows you to traverse over elements of Collections in Java, there is some significant difference between them e.g. Iterator also allows you to remove elements from collection during traversal but Enumeration doesn't allow that, it doesn't got the remove() method. Enumeration is also a legacy class and not all Collection supports it e.g. Vector supports Enumeration but ArrayList doesn't. On the other hand Iterator is the standard class for iteration and traversal. By the way,  what is difference between Enumeration and Iterator in Java?  This question is from early ages of  Java interview , I have not seen this question on recent interviews but it was quite common during 2000 to 2007 period, now days questions like implementation of HashMap or ConcurrentHashMap etc has taken its place, nonetheless its very important to know the fundamental difference between Iterator and Enumeration. Some time its also asked as Iterator vs Enumeration or Enumeration vs Iterator which is same. Important point to note is that both Iterator and Enumeration provides way to traverse or navigate through entire collection in Java.

Iterator vs Enumeration


difference between iterator and enumeration in javaBetween Enumeration and Iterator, Enumeration is older and its there from JDK1.0, while iterator was introduced later. Iterator can be used with ArrayList, HashSet and other collection classes.  Another similarity between Iterator and Enumeration in Java is that  functionality of Enumeration interface is duplicated by the Iterator interface.

Only major difference between Enumeration and iterator is Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as by using Iterator we can manipulate the objects like adding and removing the objects from collection e.g. Arraylist.

Also Iterator is more secure and safe as compared to Enumeration because it  does not allow other thread to modify the collection object while some thread is iterating over it and throws ConcurrentModificationException. This is by far most important fact for me for deciding between Iterator vs Enumeration in Java.

In Summary both Enumeration and Iterator will give successive elements, but Iterator is new and improved version where method names are shorter, and has new method called remove. Here is a short comparison:

Enumeration
hasMoreElement()
nextElement()
N/A


Iterator
hasNext()
next()
remove()

So Enumeration is used when ever we want to make Collection objects as Read-only.

If you are looking for some quality interview questions you can also check.

What is difference between HashMap and Hashtable in Java?

0 comments

HashMap vs Hashtable in Java

Though both Hashtable and HashMap are data-structure based upon hashing and implementation of Map interface, main difference between them is that HashMap is not thread-safe but Hashtable is thread-safe. Which means you cannot use HashMap in multi-threaded Java application without external synchronization. Another difference is HashMap allows one null key and null values but Hashtable doesn't allow null key or values. Also thread-safety of hash table is achieved using internal synchronization, which makes it slower than HashMap. By the way difference between HashMap and Hashtable in Java is one of the frequently asked in core Java interviews to check whether candidate understand correct usage of collection classes and aware of alternative solutions available. Along with How HashMap internally works in Java and ArrayList vs Vector, this  is one of the oldest question from Collection framework in Java. Hashtable is a legacy Collection class and it's there in Java API from long time but it got re-factored to implement Map interface in Java 4 and from there Hashtable became part of Java Collection framework. Hashtable vs HashMap in Java is so popular a question that it can top any list of Java Collection interview Question. You just can't afford not to prepare HashMap vs Hashtable before going to any Java programming interview. In this Java article we will not only see some important differences between HashMap and Hashtable but also some similarities between these two collection classes. Let's first see How different they are :

Difference between HashMap and Hashtable in Java


Both HashMap and Hashtable implements Map interface but there are some significant difference between them which is important to remember before deciding whether to use HashMap or Hashtable in Java. Some of them is thread-safety, synchronization and speed. here are those differences :

1.The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).

2. One of the major differences between HashMap and Hashtable is that HashMap is non synchronized whereas Hashtable is synchronized, which means Hashtable is thread-safe and can be shared between multiple threads but HashMap can not be shared between multiple threads without proper synchronization. Java 5 introduces ConcurrentHashMap which is an alternative of Hashtable and provides better scalability than Hashtable in Java.

3. Another significant difference between HashMap vs Hashtable is that Iterator in the HashMap is  a fail-fast iterator  while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally  by adding or removing any element except Iterator's own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort. This is also an important difference between Enumeration and Iterator in Java. 

4. One more notable difference between Hashtable and HashMap is that because of thread-safety and synchronization Hashtable is much slower than HashMap if used in Single threaded environment. So if you don't need synchronization and HashMap is only used by one thread, it out perform Hashtable in Java.

5. HashMap does not guarantee that the order of the map will remain constant over time.

Difference between HashMap and Hashtable in Java

HashMap and Hashtable : note on Some Important Terms

1)Synchronized means only one Thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a Hashtable will have to acquire a lock on the object while others will wait for lock to be released.

2) Fail-safe is relevant from the context of iterators. If an Iterator or ListIterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.

3) Structurally modification means deleting or inserting element which could effectively change the structure of map.

HashMap can be synchronized by

Map m = Collections.synchronizeMap(hashMap);

In Summary there are significant differences between Hashtable and HashMap in Java e.g. thread-safety and speed and based upon that only use Hashtable if you absolutely need thread-safety, if you are running Java 5 consider using ConcurrentHashMap in Java.

What is difference between Synchronized and Concurrent Collections in Java?

0 comments

Synchronized vs Concurrent Collections

Though both Synchronized and Concurrent Collection class provide thread-safety, main difference between them is in performance, scalability and how they achieve thread-safety. Synchronized collections like synchronized HashMap, Hashtable, HashSet, Vector and synchronized ArrayList are much slower than their concurrent counterparts ConcurrentHashMap, CopyOnWriteArrayList and CopyOnWriteHashSet. Main reason of this slowness is locking, synchronized collection locks whole object, while concurrent collection achieves thread-safety smartly e.g. ConcurrentHashMap divides the whole map into several segments and locks only on segments, which allows multiple threads to access other collections without locking. CopyOnWriteArrayList allows multiple reader thread to read without synchronization and when their is write happens it copies the ArrayList and swaps. So if you use concurrent collection classes in their favorable conditions e.g. for more reading and less updates, they are much more scalable than synchronized collections. By the way, Collection classes are heart of Java API though I feel using them judiciously is an art. It's my personal experience where I have improved performance by using ArrayList where legacy codes are unnecessarily used Vector etc. JDK 1.5 introduce some good concurrent collections which is highly efficient for high volume, low latency Java application.

Synchronized Collections vs Concurrent Collections in Java


The synchronized collections classes, Hashtable and Vector, and the synchronized wrapper classes, Collections.synchronizedMap() and Collections.synchronizedList(), provides a basic conditionally thread-safe implementation of Map and List.
However, several factors make them unsuitable for use in highly concurrent applications -- their single collection-wide lock is an impediment to scalability and it often becomes necessary to lock a collection for a considerable time during iteration to prevent ConcurrentModificationException.

The ConcurrentHashMap and CopyOnWriteArrayList implementations provide much higher concurrency while preserving thread safety, with some minor compromises in their promises to callers. ConcurrentHashMap and CopyOnWriteArrayList are not necessarily useful everywhere you might use HashMap or ArrayList, but are designed to optimize specific common situations. Many concurrent applications will benefit from their use.

So what is the difference between Hashtable and ConcurrentHashMap , both can be used in multi-threaded environment but once the size of Hashtable becomes considerable large performance degrade because for iteration it has to be locked for longer duration.

Since ConcurrentHashMap introduced concept of segmentation, It doesn't mater whether how large it becomes because only certain part of it get locked to provide thread safety so many other readers can still access map without waiting for iteration to complete.

In Summary ConcurrentHashMap only locks certain portion of Map while Hashtable lock full map while doing iteration or performing any write operation.

As always comments and suggestions are welcome.

What is the use of class “java.lang.Class” in Java?

0 comments
java.lang.Class is one of the most important class in java but mostly overlooked by Java developers. It is very useful in the sense that it provides several utility methods e.g. getClass(), forName() which is used to find and load a class, you might have used to load Oracle or MySQL drivers. It also provides methods like Class.newInstance() which is the backbone of reflection and allow you to create instance of a class without using new() operator.  Class has no public constructor and it's instance is created by JVM when a class is loaded. Object of class Class is also used to represent classes, enum, interfaces and annotation in a running Java application. The primitive types e.g. byte, short, char, int, float, double and boolean are also represent by Class instances. You can get the corresponding Class instance by using class literals e.g. int.class, float.class or boolean.class. It is also used to represent instance of array in Java. Every array with same type and same dimension share same instance of class Class. Another use of java.lang.Class is while implementing equals() method to check whether two objects are of same type or not.

java.lang.Class is one of the most important class in java but mostly overlooked by Java developers. It is very useful in the sense that it provides several utility methods e.g. getClass(), forName() which is used to find and load a class, you might have used to load Oracle or MySQL drivers. It also provides methods like Class.newInstance() which is the backbone of reflection and allow you to create instance of a class without using new() operator.  Class has no public constructor and it's instance is created by JVM when a class is loaded. Object of class Class is also used to represent classes, enum, interfaces and annotation in a running Java application. The primitive types e.g. byte, short, char, int, float, double and boolean are also represent by Class instances. You can get the corresponding Class instance by using class literals e.g. int.class, float.class or boolean.class. It is also used to represent instance of array in Java. Every array with same type and same dimension share same instance of class Class. Another use of java.lang.Class is while implementing equals() method to check whether two objects are of same type or not.

java.lang.Class class in Java


What is java.lang.Class in JavaEvery time JVM creates an object, it also creates a java.lang.Class object that describes the type of the object. All instances of the same class share the same Class object and you can obtain the Class object by calling the getClass() method of the object. By the way this method is inherited from java.lang.Object class.

Suppose you create two instances of class called Person e.g.

Person A = new Person();
Person B = new Person();

if(A.getClass() == B.getClass()){
    System.out.println("A and B are instances of same class");
}else{
    System.out.println("A and B are instances of different class");
}

In this case it will print "A and B are instances of same class" because they are both instance of class Person.

We need forName() and newInstance() because many times it happens that we don’t know the name of the class to instantiate while writing code , we may get it from config files, database,network  or from any upstream Java or C++ application.

This is what we called reflective way of creating object which is one of the most powerful feature of Java and which makes way for many frameworks e.g. Spring ,Struts which uses Java reflection.

Why Comparing Integer using == in Java 5 is Bad?

0 comments
Java 5 introduced auto-boxing which automatically converts int to Integer and because of that many Java developers started writing code for comparing int variable to Integer object and Integer to Integer using == operator. You should avoid that because it can create subtle bugs in your program because it only works for a particular range of integers and not for all. There is another problem as well, when you compare int variable to Integer object using == operator, the Integer object is converted to primitive value. This can throw null pointer exception if the Integer object is null, which can crash your program. Now when you compare two Integer object using == operator, Java doesn't compare them by value, but it does reference comparison. When means even if the two integer has same value, == can return false because they are two different object in heap. That's why you should use equals() method to compare objects. There is one more point which makes thing tricky, caching of integer objects by Integer.valueOf() method. What this mean is that your program will work for some input but not for others. This happens because auto boxing uses Integer.valueOf() method to convert Integer to int and since method caches Integer object for range -128 to 127, it return same Integer object in heap, and that's why == operator return true if you compare two Integer object in the range -128 to 127, but return false afterwards, causing bug. Before Java 1.4 that was not a problem because there was no autoboxing, so you always knew that == will check reference in heap instead of value comparison.

Comparing Integer object with == in Java

Why you should not compare Integer using == in Java 5Some of the JVM cache objects of some wrapper class e.g. Integer from -128 to 127 and return same object which if compare via “ ==” can return true but after this range this validity doesn't work and to make it worse this behavior is JVM dependent so better avoid this kind of check and use equals() method. e.g.

Integer i1 = 260;
Integer i2 = 260;

if (i1 == i2) {
    System.out.println("i1 and i2 is equal");
} else {
   System.out.println("i1 and i2 is not equal ");
}

Here you will most probably get "i1 and i2 is not equal " at least in my machine.
because in this case, unboxing operation is not involved. The literal 260 is boxed into two different Integer objects ( again it varies between JVM to JVM) , and then those objects are compared with ==. The result is false, as the two objects are different instances, with different memory addresses. Because both sides of the == expression contain objects, no unboxing occurs.

Integer i1 = 100;
Integer i2 = 100;

if (i1 == i2) {
    System.out.println("i1 and i2 is equal");
} else {
   System.out.println("i1 and i2 is not equal ");
}


Here, most probably you will get the text "i1 and i2 is equal".
Because int values from -127 to 127 are in a range which most JVM will like to cache so the VM actually uses the same object instance (and therefore memory address) for both i1 and i2. As a result, == returns a true result. 

This is very indeterministic and only shown by example since some JVM do optimization at certain integer value and try to return same object every time but its not guaranteed or written behavior.

So best is to avoid this kind of code in post Java 1.5 and instead use equals() method to compare Integers in Java, which is more deterministic and correct.

Monday, 12 October 2015

How do you find length of a Singly Linked list

0 comments
Hi Guys,

Here is one of the classical questions asked to me on an interview with multinational Investment bank after that this question asked to me on several times in other interviews also . what makes this question interesting is that java developers are not that great with data structure relative to C++ developer which is obvious because of fundamental difference between this two language.C++ is more of system programming language while java is more on application programming , also rich set of java API allows programmer to skip this kind of basic programming techniques.


anyway lets come back to the question , everybody knows that Linked lists is last element will point to "null" element , so first answer would most of the times would be "I will use a counter and increment till we reach the end of the element" e.g.


Iterative Solutions


public int length(){
int count=0;
Node current = this.head;

while(current != null){
count++;
current=current.next()
}
return count;
}

If you answer this question without any difficulty most interviewer will ask you to write a "recursive" solution for this just to check how you deal with recursion if your first answer would have been recursive they will ask you to write an "iterative solution" as shown above.

Recursive Solution:

public int length(Node current){
if(current == null) //base case
return 0;

return 1+length(current.next());
}

as always suggestions , comments , innovative and better answers are most welcome.
 
© 2013 JAVA | Designed by Making Different | Provided by All Tech Buzz | Powered by Blogger