Posts

Showing posts from 2010

Java Puzzle–Immutable String

what will be output of the following program ? 1: class StringTest2 2: { 3: public static void main(String[] args) 4: { 5: String str1 = " Hello "; 6: String str2 = " HELLO "; 7: String str3 = str1.toUpperCase(); 8: String str4 = str2.toUpperCase(); 9: System.out.println(str1 == str3); 10: System.out.println(str2 == str4); 11: } 12: }

Java puzzle–StringBuffer

What will be the output of following program ? 1: class StringBufferTest2 2: { 3: public static void main(String[] args) 4: { 5: StringBuffer sb1,sb2; 6: sb1 = new StringBuffer(); 7: sb2 = new StringBuffer(); 8: sb1.append(" Hello "); 9: sb1.append(" Hello "); 10: boolean result = sb1.equals(sb2); 11: System.out.println(" Result = "+ result); 12: } 13: }

Java Puzzle – private fields

Will following program work ? class MyClass { private int privateId = 101; public static void main(String[] args) { System.out.println(" Hello World! "); new MyClass().doStuff( new MyClass()); } public void doStuff(MyClass obj){ //accessing private instance variable System.out.println(obj.privateId); } }

Static Class vs. Singleton Class

I have explained two different implementation for making a class to Singleton, means restricting no of instance of a class to only one.You can refer previous posts Singleton Design Pattern by example & Alternative implementation for Singleton Class . Here by Static Class means a class that’s has only public static methods. Two different implementations as per previous post for restricting class instances to only one are making all constructor private referred as  Singleton  class and declaring all public methods as static.  Singleton class has several advantages over Static class pattern 1. A singleton class can extends class and implement interfaces , while Static class can not. 2. A singleton can be instantiated lazily or asynchronously while a static class is generally initialized when it is first loaded. 3.A singleton class can extended and its methods can be overridden. 4. The most important advantage is the singleton can be handled polymorphic ally withou...

Alternative implementation for Singleton Class

In previous posts on Singleton Designing pattern I have explained one of the way of implementing and solving concurrency issue. Singleton pattern insures that only one instance of the class should be available throughout the application context. There is an alternative implementation for insuring the same functionality that is nothing but “a class with all public static methods” . A static method can be accessed directly by Class name without any class instance. It will serve same purpose as Singleton Class, means it shares only one state across the application. Here is a sample implementation import java.util.*; class SingletonMap { private static Map<String,String> map; static { map = new HashMap<String,String>(); } public static String getValue(String key){ return map.get(key); } public static void putValue(String key, String value){ map.put(key,value); } } Here the SingletonMap class with all methods declared as “static” and private stati...

StringBuilder over StringBuffer

As String is an immutable class , any update operations  like replace/substring/append is very expensive. As solution for this StringBuffer class has been introduced for all string update related operations. But problem with StringBuffer is that it is a synchronized class. All its public methods are tagged as “synchronized”. This adds an extra cost to string update operation whenever synchronized is actually not needed. As part of JDK 1.5 a new utility class called StringBuilder has been introduced for non-synchronized string update operations. StringBuilder is designed as a replacement for StringBuffer in single-threaded usage. It means using StrinBuilder instead of StringBuffer where ever synchronization is not an issue will be added to program performance.

Covariant Return Type

One of the pillars of Object Oriented Java language is Polymorphism. Polymorphism allows two or more methods within the same class that share the same name, as long as their parameter declarations are different .  It also allows two or more methods in class hierarchy where child class can have same method name as of parent class, but their signature should be same. Here is a limitation on overridden methods, they can not have different return types. J2SE 5.0 has come up with a solution for this limitation. Onwards J2SE 5.0 new feature called “Covariant Return Types”. “As per Covariant Return Types, a method in a subclass may return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.” Consider following example 1: class ParentClass 2: { 3: public SuperValue getValue(){ 4: System.out.println(" ParentClass.getValue() "); 5: return new SuperValue(); 6: } 7: 8: } 9: 10: 11: public c...

Aspect Oriented Programming

Image
Overview : AOP allows you to dynamically modify your static model consisting mainly of business logic to include the code required to fulfill the secondary requirements or in AOP terminology called cross-cutting concerns (i.e. secondary requirements) like auditing, logging, security, exception handling etc without having to modify the original static model (in fact, we don't even need to have the original code). Aspect Oriented Programming is a concept for separating cross-cutting concern into single units called Aspects.   The best possible uses of AOP are like  auditing, logging, security, exception handling etc without having to modify the original static model. Object Oriented vs Aspect Oriented programming : In OOP real world problems are mapping to Objects. OOP encourages software re-use  using encapsulation, inheritance and polymorphism. It is very difficult to cleanly maintain separate concerns into modules. An attempt to do a minor change in the program d...

CountDownLatch by example

     Java concurrent package provides CountDownLatch class which helps to control execution of set of threads depends on some external activity. CountDownLatch has two main methods countdown() and await().      CountDownLatch’s constructor takes an integer as a parameter which decides its behavior. Calling await() holds execution till countdownLatch’s count(constructor parameter) become zero and countdown() reduces the count on every call.      To explain its use, here is an example of horse race. Here every horse is thread and if you have to stimulate race condition , these threads have to start at a time.  As well as you should know when all complete the race. We can stimulate this functionality using CountDownLatch. 1: import java.util.*; 2: import java.util.concurrent.*; 3: public class TestCountDownLatch 4: { 5: public static void main(String[] args) throws Exception 6: { 7: List...

Map maintaining insert order of key-value pairs

Many time we want to maintain order of entries as it is inserted. HashMap does not satisfy this requirement. For all such requirement java collection framework has provided LinkedHashMap. Following example explains : 1: import java.util.*; 2: class MapTest 3: { 4: public static void main(String[] args) 5: { 6: System.out.println(" Using HashMap: "); 7: Map hashMap = new HashMap(); 8: hashMap.put(" One "," One "); 9: hashMap.put(" Two "," Two "); 10: hashMap.put(" Three "," Three "); 11: hashMap.put(" Four "," Four "); 12: hashMap.put(" Five "," Five "); 13: System.out.println(" Complete Map content : "+ hashMap.toString()); 14: System.out.println(" Iterating Key-Value: "); 15: Iterator itr = hashMap.keySet().iterator(); 16: while (itr.hasNext()){ 17: System.out.println(hashMap.get(itr.next()));...

Explaining Semaphore by example

     This post helps to explore more into java.util.concurrent package. It explains java.util.concurrent.Semaphore class with example. Many time while developing multi threaded application , we may have multiple threads accessing particular system resource concurrently. If you want to limit no of open request for the resource then Semaphore is the option available in java.       Limiting no of open request we can improve throughout of a systemn. Using Semaphore we can control no of running thread at a time out of all available running threads. Following example explains using Semaphore 1: import java.util.*; 2: import java.util.concurrent.*; 3: class SemaphoreTest 4: { 5: public static void main(String[] args) 6: { 7: // Limiting No on threads running to 2 8: Semaphore semaphore = new Semaphore(2); 9: for ( int i=0 ;i<5;i++){ 10: new MyThread(String.valueOf(i),semaphore).start(); 11: } 12: ...

HashMap hashCode collision by example

Image
As we all know Hash is a part of Java Collection framework and stores key-value pairs. HashMap uses hash Code value of key object to locate their possible in under line collection data structure, to be specific it is nothing but array. Hash code value of key object decide index of array where value object get stored. As per hashcode – equals method implementation rules Objects that are equal according to the equals method must return the same hashCode value. & If two objects are not equal according to equals, they are not required to return different hashCode values. As per above statement it is possible that two different object may have same hashcode values, this is called hashcode collision . To overcome this problem concept of bucket has been introduced. All the Value objects whose corresponding Key’s hashcode values are same , they fall under same bucket. Above diagram explains hash code collision. There are three key-value entries are shown , out of which second and thi...

getResourceAsStream in details

Image
Here I am putting my analysis for retrieving file as resource stream

Understanding Java Collection Framework

Image
Thought of sharing my understanding about utilizing java collection classes , so here is the post History : Vector & HashTable are introduced very first in JDK 1.0 and then complete collection framework is introduced in JDK 1.2. You can see complete hierarchy of collection framework here . Here i am going to explain their uses in short