Tuesday, 26 August 2014

How to replace String/Characters from String

public String replaceBetweenString(String str, String prefix, String postfix, String replaceString) {
     String regex = "(" + prefix + ".*?" + postfix + ")";
     return str.replaceAll(regex, prefix + replaceString + postfix);
 }




Friday, 22 August 2014

Initial Java 9 Features

As of now, the revealed Java 9 features are small and over a period there might be additions. Approximately two more years available for the Java SE 9 release and it will become bulky by then. Still I doubt that it cannot beat Java 8 features.

Proposed for JDK 9

  1. Process API Updates (JEP 102): this is to improve the API for controlling and managing operating system processes. It may bring in features like the ability to get the pid of the JVM or the processes, ability to enumerate JVM and processes, ability to deal with hundreds of sub-processes by multiplexing the output or error streams.
  2. HTTP 2 Client (JEP 110): This is to replace the legacy HttpURLConnection with a brand new Http client API which implements HTTP 2.0 and websockets. Existing API is outdated, hard to use and maintain. This is expected to provide rich options with ease of use.
  3. Light-Weight JSON API (JEP 198): Wow! this is really important and much needed. We need a sound JSON API for generating and consuming JSON data. Presently we are using different third party APIs and this is going to provide relief for many. This may adhere to the existing JSR 353.
  4. Improve Contended Locking (JEP 102): to improve the performance of contended Java object monitors.
  5. Segmented Code Cache (JEP 197): to improve the performance of the compiler with short sweep times by dividing the code cache into distinct segments and other array of changes for better performance.
  6. Smart Java Compilation, Phase Two (JEP 199): it is an enhancement over the already existing JEP 139. This will gradually build over it to improve the sjavactool. It is used to build the JDK, it may be generalized so that it can be used as a build tool for any large projects. Watch out!
  7. Modular Source Code (JEP 201): This is project Jigsaw, previously it was planned for Java SE 7 and latter postponed to Java SE 9. This is going to be one of the major features in Java 9. This is about reorganizing the source code in modules so that it can be easily scaled down for small devices, to enable better security, improve performance and maintainability. To introduce better tools to support the Java developers.
This is a summary of the features that may be part of Java 9. Read the JEPs, try to contribute to the development, commit patches and be part of the next big Java release.

Monday, 23 December 2013

Interface Segregation Principle (ISP)

Motivation


When we design an application we should take care how we are going to make abstract a module which contains several submodules. Considering the module implemented by a class, we can have an abstraction of the system done in an interface. But if we want to extend our application adding another module that contains only some of the submodules of the original system, we are forced to implement the full interface and to write some dummy methods. Such an interface is named fat interface or polluted interface. Having an interface pollution is not a good solution and might induce inappropriate behavior in the system.

The Interface Segregation Principle states that clients should not be forced to implement interfaces they don't use. Instead of one fat interface many small interfaces are preferred based on groups of methods, each one serving one submodule.


Intent


Clients should not be forced to depend upon interfaces that they don't use.

Example


Below is an example which violates the Interface Segregation Principle. We have a Manager class which represent the person which manages the workers. And we have 2 types of workers some average and some very efficient workers. Both types of workers works and they need a daily lunch break to eat. But now some robots came in the company they work as well , but they don't eat so they don't need a lunch break. One on side the new Robot class need to implement the IWorker interface because robots works. On the other side, the don't have to implement it because they don't eat.

This is why in this case the IWorker is considered a polluted interface.

If we keep the present design, the new Robot class is forced to implement the eat method. We can write a dummy class which does nothing(let's say a lunch break of 1 second daily), and can have undesired effects in the application(For example the reports seen by managers will report more lunches taken than the number of people).

According to the Interface Segregation Principle, a flexible design will not have polluted interfaces. In our case the IWorker interface should be split in 2 different interfaces.


// interface segregation principle - bad example
interface IWorker {
                public void work();
                public void eat();
}

class Worker implements IWorker{
                public void work() {
                                // ....working
                }
                public void eat() {
                                // ...... eating in lunch break
                }
}

class SuperWorker implements IWorker{
                public void work() {
                                //.... working much more
                }

                public void eat() {
                                //.... eating in lunch break
                }
}

class Manager {
                IWorker worker;

                public void setWorker(IWorker w) {
                                worker=w;
                }

                public void manage() {
                                worker.work();
                }
}




Following it's the code supporting the Interface Segregation Principle. By splitting the IWorker interface in 2 different interfaces the new Robot class is no longer forced to implement the eat method. Also if we need another functionality for the robot like recharging we create another interface IRechargeble with a method recharge.


// interface segregation principle - good example
interface IWorker extends Feedable, Workable {
}

interface IWorkable {
                public void work();
}

interface IFeedable{
                public void eat();
}

class Worker implements IWorkable, IFeedable{
                public void work() {
                                // ....working
                }

                public void eat() {
                                //.... eating in lunch break
                }
}

class Robot implements IWorkable{
                public void work() {
                                // ....working
                }
}

class SuperWorker implements IWorkable, IFeedable{
                public void work() {
                                //.... working much more
                }

                public void eat() {
                                //.... eating in lunch break
                }
}

class Manager {
                Workable worker;

                public void setWorker(Workable w) {
                                worker=w;
                }

                public void manage() {
                                worker.work();
                }
}


Conclusion


If the design is already done fat interfaces can be segregated using the Adapter pattern.

Like every principle Interface Segregation Principle is one principle which require additional time and effort spent to apply it during the design time and increase the complexity of code. But it produce a flexible design. If we are going to apply it more than is necessary it will result a code containing a lot of interfaces with single methods, so applying should be done based on experience and common sense in identifying the areas where extension of code are more likely to happens in the future.

Saturday, 22 June 2013

How HashMap works in Java

HashMap  works on principle of hashing, we have put() and get() method for storing and retrieving object form HashMap .When we pass an both key and value to put() method to store on HashMap , it uses key object hashcode() method to calculate hashcode and they by applying hashing on that hashcode it identifies bucket location for storing value object. While retrieving it uses key object equals method to find out correct key value pair and return value object associated with that key. HashMap  uses linked list in case of collision and object will be stored in next node of linked list.
Also HashMap  stores both key and value tuple in every node of linked list

What will happen if two different HashMap  key objects have same hashcode?

They will be stored in same bucket but no next node of linked list. And keys equals () method will be used to identify correct key value pair in HashMap .

Have you used HashMap before" or  "What is HashMap? Why do we use it 

Almost everybody answers this with yes and then interviewee keep talking about common facts about HashMap like HashMap accept null while Hashtable doesn't, HashMap is not synchronized, HashMap is fast and so on along with basics like its stores key and value pairs etc. This shows that person has used HashMap  and quite familiar with the functionality HashMap offers but interview takes a sharp turn from here and next set of follow-up questions gets more detailed about fundamentals involved with HashMap in Java . Interviewer struck back with questions like

"Do you Know how HashMap works in Java" or "How does get () method of HashMap works in Java"

And then you get answers like I don't bother its standard Java API, you better look code on Java source or Open JDK; I can find it out in Google at any time etc. But some interviewee definitely answer this and will say "HashMap works on principle of hashing, we have put(key, value) and get(key) method for storing and retrieving Objects from HashMap. When we pass Key and Value object  toput() method on Java HashMap, HashMap implementation calls hashCode method on Key object and applies returned hashcode into its own hashing function to find a bucket location for storing Entry object, important point to mention is that HashMap in Java stores both key and value object as Map.Entry in bucket which is essential to understand the retrieving logic. If people fails to recognize this and say it only stores Value in the bucket they will fail to explain the retrieving logic of any object stored in Java HashMap . This answer is very much acceptable and does make sense that interviewee has fair bit of knowledge on how hashing works and how HashMap  works in Java. But this is just start of story and confusion increases when you put interviewee on scenarios faced by Java developers on day by day basis. Next question could be about collision detection and collision resolution in Java HashMap  e.g. 


"What will happen if two different objects have same hashcode?"

Now from here onwards real confusion starts, Some time candidate will say that since hashcode is equal, both objects are equal and HashMap  will throw exception or not store them again etc, Then you might want to remind them about equals() and hashCode() contract  that two unequal object in Java can have same hashcode. Some will give up at this point and few will move ahead and say "Since hashcode is same, bucket location would be same and collision will occur in HashMap, Since HashMap use LinkedList to store object, this entry (object of Map.Entry comprise key and value )  will be stored in LinkedList. Great this answer make sense though there are many collision resolution methods available this is simplest and HashMap in Java does follow this. But story does not end here and interviewer asks

"How will you retrieve Value object  if two Keys will have same hashcode?"

Interviewee will say we will call get() method and then HashMap uses Key Object's hashcode to find out bucket location and retrieves Value object but then you need to remind him that there are two Value objects are stored in same bucket , so they will say about traversal in LinkedList until we find the value object , then you ask how do you identify value object because you don't  have value object to compare ,Until they know that HashMap  stores both Key and Value in LinkedList node or as Map.Entry they won't be able to resolve this issue and will try and fail.

But those bunch of people who remember this key information will say that after finding bucket location , we will call keys.equals() method to identify correct node in LinkedList and return associated value object for that key in Java HashMap . Perfect this is the correct answer.

In many cases interviewee fails at this stage because they get confused between hashCode() and equals() or keys and values object in Java HashMap  which is pretty obvious because they are dealing with the hashcode() in all previous questions and equals() come in picture only in case of retrieving value object from HashMap in Java. Some good developer point out here that using immutable,final object with proper equals() and hashcode() implementation would act as perfect Java HashMap  keys and improve performance of Java HashMap  by reducing collision. Immutability also allows caching there hashcode of different keys which makes overall retrieval process very fast and suggest that String and various wrapper classes e.g. Integer very good keys in Java HashMap.

Now if you clear this entire Java HashMap interview,  You will be surprised by this very interesting question "What happens On HashMap in Java if the size of the HashMap  exceeds a given threshold defined by load factor ?". Until you know how HashMap  works exactly you won't be able to answer this question. If the size of the Map exceeds a given threshold defined by load-factor e.g. if load factor is .75 it will act to re-size the map once it filled 75%. Similar to other collection classes like ArrayList,  Java HashMap re-size itself by creating a new bucket array of size twice of previous size of HashMap , and then start putting every old element into that new bucket array. This process is called rehashing because it also applies hash function to find new bucket location. 

If you manage to answer this question on HashMap in Java you will be greeted by "do you see any problem with resizing of HashMap  in Java" , you might not be able to pick the context and then he will try to give you hint about multiple thread accessing the Java HashMap and potentially looking for race condition on HashMap  in Java. 

So the answer is Yes there is potential race condition exists while resizing HashMap in Java, if two thread at the same time found that now HashMap needs resizing and they both try to resizing. on the process of resizing of HashMap in Java , the element in bucket which is stored in linked list get reversed in order during there migration to new bucket because java HashMap  doesn't append the new element at tail instead it append new element at head to avoid tail traversing. If race condition happens then you will end up with an infinite loop. Though this point you can potentially argue that what the hell makes you think to use HashMap  in multi-threaded environment to interviewer

Few more question on HashMap

1) Why String, Integer and other wrapper classes are considered good keys ?
String, Integer and other wrapper classes are natural candidates of HashMap key, and String is most frequently used key as well because String is immutable and final,and overrides equals and hashcode() method. Other wrapper class also shares similar property. Immutabiility is required, in order to prevent changes on fields used to calculate hashCode() because if key object return different hashCode during insertion and retrieval than it won't be possible to get object from HashMap. Immutability is best as it offers other advantages as well like thread-safety, If you can  keep your hashCode same by only making certain fields final, then you go for that as well. Since equals() and hashCode() method is used during reterival of value object from HashMap, its important that key object correctly override these methods and follow contact. If unequal object return different hashcode than chances of collision will be less which subsequently improve performance of HashMap.

2) Can we use any custom object as key in HashMap ?
This is an extension of previous questions. Ofcourse you can use any Object as key in Java HashMap provided it follows equals and hashCode contract and its hashCode should not vary once the object is inserted into Map. If custom object is Immutable than this will be already taken care because you can not change it once created.

3) Can we use ConcurrentHashMap in place of Hashtable ?
This is another question which getting popular due to increasing popularity of ConcurrentHashMap. Since we know Hashtable is synchronized but ConcurrentHashMap provides better concurrency by only locking portion of map determined by concurrency level. ConcurrentHashMap is certainly introduced as Hashtable and can be used in place of it but Hashtable provide stronger thread-safety than ConcurrentHashMap.

Friday, 2 November 2012

How to call a C program from Java?

Calling a C program may be useful when we prefer to use C libraries and to reuse an existing C program. When we compile a C program, the source gets converted to obj file. It is a platform dependent intermediate machine code which will be converted to exe and then executed.
Java native interface (JNI) is a framework provided by java that enables java programs to call native code and vice-versa.

Using JNI a java program has the capability to call the native C code. But we lose the core objective of java which is platform independence. So calling a C program from java should be used judiciously.
JNI provides the specification and native code should be written/ported accordingly. JDK vendor should provide the needed implementation for the JNI.

Steps to call a C program from Java

1. Write the Java Program and Compile
2. Generate header file from java class
3. Write the C Program
4. Generate Shared Library File
5. Run Java Program

1. Write the Java Program

public class JavaToC {
          public native void helloC();

          static {
                     System.loadLibrary("HelloWorld");
           }

          public static void main(String[] args) {
                   new JavaToC().helloC();
          }
}

Note two things in this program,
  • Use of native keyword. This is a method declaration and it informs the java compiler that the implementation for this method is a native one. This method helloC() is present in C source file and that is what we are going to call.
  • Loading the library HelloWorld using static keyword. This library file will be compiled out of the C source in the coming steps.

2. Generate header file from java class

  • JDK provides a tool named javah which can be used to generate the header file.
  • We will use the generated header file as include in C source.
  • Remember to compile the java program before using javah
javah JavaToC
Following is the header file generated,


/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class JavaToC */
 
#ifndef _Included_JavaToC
#define _Included_JavaToC
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class:     JavaToC
* Method:    helloC
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_JavaToC_helloC
(JNIEnv *, jobject);
 
#ifdef __cplusplus
}
#endif
#endif

3. Write the C Program

#include <stdio.h>
#include <jni.h>
#include "JavaToC.h"
JNIEXPORT void JNICALL Java_JavaToC_helloC(JNIEnv *env, jobject javaobj)
{
  printf("Hello World: From C");
  return;
}
  • stdio.h is the standard C header file include.
  • jni.h is the header file that provides the java to C mapping and it is available in JDK.
  • JavaToC.h is the header file generated from the java source file.

4. Generate Shared Library File

  • Now compile the above C source file. We need a C compiler and I have chosen Tiny C.
  • Tiny C can be downloaded from http://mirror.veriportal.com/savannah//tinycc/tcc-0.9.25-win32-bin.zip
    Download and unzip the file and set OS path to tcc.exe
  • tcc HelloWorld.C -I C:/Progra~1/Java/jdk1.7.0_07/include -I C:/Progra~1/Java/jdk1.7.0_07/include/win32 -shared -o HelloWorld.dll
  • Above is the command to generate the shared library file dll which is loaded in the java program. Two directories are included in the compile command, those are to include the jni.h and jni_md.h

5. Run Java Program

We are all set, now run the java program to get the following output,
Hello World: From C

Wednesday, 26 September 2012

Top 10 Java Classes

Thought of compiling a list of classes that are popular among java programmers. Should I say most essential? There is no strict rules for the selection, in fact there are no rules followed. Classes that popped up on top of mind are listed below. You are welcome to add your own list. This list will vary depending on the type of java project you work on. These classes I have listed does not require any introduction and they are as popular as Salmankhan in java world.
  1. java.lang.String
    String class will be the undisputed champion on any day by popularity and none will deny that. This is a final class and used to create / operate immutable string literals. It was available from JDK 1.0
  2. java.lang.System
    Usage of System depends on the type of project you work on. You may not be using it in your project but still it is one of the popular java classes around. This is a utility class and cannot be instantiated. Main uses of this class are access to standard input, output, environment variables, etc. Available since JDK 1.0
  3. java.lang.Exception
    Throwable is the super class of all Errors and Exceptions. All abnormal conditions that can be handled comes under Exception. NullPointerException is the most popular among all the exceptions. Exception is at top of hierarchy of all such exceptions. Available since JDK 1.0
  4. java.util.ArrayList
    An implementation of array data structure. This class implements List interface and is the most popular member or java collections framework. Difference between ArrayList and Vector is one popular topic among the beginners and frequently asked question in java interviews. It was introduced in JDK 1.2
  5. java.util.HashMap
    An implementation of a key-value pair data structure. This class implements Map interface. As similar to ArrayList vs Vector, we have HashMap vs Hashtable popular comparisons. This happens to be a popular collection class that acts as a container for property-value pairs and works as a transport agent between multiple layers of an application. It was introduced in JDK 1.2
  6. java.lang.Object
    Great grandfather of all java classes. Every java class is a subclass of Object. It will be used often when we work on a platform/framework. It contains the important methods like equals, hashcode, clone, toString, etc. It is available from day one of java (JDK 1.0)
  7. java.lang.Thread
    A thread is a single sequence of execution, where multiple thread can co-exist and share resources. We can extend this Thread class and create our own threads. Using Runnable is also another option. Usage of this class depends on the domain of your application. It is not absolutely necessary to build a usual application. It was available from JDK 1.0
  8. java.lang.Class
    Class is a direct subclass of Object. There is no constructor in this class and their objects are loaded in JVM by classloaders. Most of us may not have used it directly but I think its an essential class. It is an important class in doing reflection. It is available from JDK 1.0
  9. java.util.Date
    This is used to work with date. Sometimes we feel that this class should have added more utility methods and we end up creating those. Every enterprise application we create has a date utility. Introduced in JDK 1.0 and later made huge changes in JDK1.1 by deprecating a whole lot of methods.
  10. java.util.Iterator
    This is an interface. It is very popular and came as a replacement for Enumeration. It is a simple to use convenience utility and works in sync with Iterable. It was introduced in JDK 1.2

Saturday, 22 September 2012

 Top 10 Java Debugging Tips with Eclipse

About debugging java applications using Eclipse. Debugging helps us to identify and fix defects in the application. We will focus on run-time issues and not compile time errors. There are command line debuggers like gdb available. In this tutorial we will focus on GUI based debugger and we take our favourite IDE Eclipse to run through the tutorial. Though we say Eclipse, the points are mostly generic and is suitable for debugging using most of the IDEs like NetBeans too.
Before going through this tutorial, I recommend you to have a look at Eclipse shortcuts and it will really help. My Eclipse version is Juno as of writing this tutorial.
  • Do not use System.out.println  as a tool to debug.
  • Enable detailed log level of all the components involved.
  • Use a log analyzer to read logs.

1. Conditional Breakpoint

Hope we know how to add a breakpoint. If not, just click on the left pane (just before the line number) and a breakpoint will be created. In debug perspective, ‘Breakpoints’ view will list the breakpoint created. We can add a boolean condition to it. That is, the breakpoint will be activated and execution will hold only if the boolean condition is met otherwise this breakpoint will be skipped.

2. Exception Breakpoint

In Breakpoints view there is a button labeled as J! We can use that button to add a java exception based breakpoint. For example we want the program to halt and allow to debug when a NullPointerException is thrown we can add a breakpoint using this.

3. Watch Point

This is one nice feature I love. When a chosen attribute is accessed or modified program execution will halt and allow to debug. Select a class variable in Outline view and from its context menu select Toggle Watchpoint. This will create a watch point for that attribute and it will be listed in Breakpoints view.

4. Evaluation (Display or Inspect or Watch)

Ctrl+Shift+d or Ctrl+Shift+i on a selected variable or expression will show the value. We can also add a permanent watch on an expression/variable which will be shown in Expressions view when debug is on.

5. Change Variable Values

We can change the value of a variable on the fly during debug. Choose a variable and go to Variables view and select the value, type and enter.

6. Stop in Main

In Run/Debug Settings, Edit Configuration we can enable a check box that says Stop in main. If enabled when we debug a java program that launches with a main method, the execution halts at first line of main method.

7. Environment Variables

Instead of going to System properties to add an environment variable, we can conveniently add it through Edit Configuration dialog box.

8. Drop to Frame

This is the second best feature I love. We can just return the control to any frame in the call stack during debug. Changes made to variables will not be reset. Choose the stack level which you want to go back and restart debug from there and click the drop to frame button from debug toolbar. Eclipse is cool!

9. Step Filter

When we Step Into (F5) a method we may go into external libraries (like java) and we may not need it. We can add a filter in preferences and exclude packages.

10. Step Into, Over and Return

I kept this as the last point as this is the first thing to learn in debugging :-)
  • F5 – Step Into: moves to next step and if the current line has a method call the control will go into the first line of the called method.
  • F6 – Step Over: moves the control to next line. If there is a method call in the current line, it executes the method call internally and just moves the control to next line.
  • F7 – Step Return: When done from inside a method the control will move to the calling line from where the current method is invoked.
  • F8 – Move to next breakpoint.