Monday, January 28, 2013

Difference between IdentityHashMap and HashMap in Java

IdentityHashMap in Java was added in Java 1.4 but still its one of those lessor known class in Java. Main difference between IdentityHashMap and HashMap in Java is that IdentityHashMap is a special implementation of Map interface which doesn't use equals() and hashCode() method for comparing object unlike other implementation of Map e.g. HashMap. Instead IdentityHashMap use equality operator "=="  to compare keys and values in Java which makes it faster compare to HashMap and suitable where you need reference equality check and instead of logical equality. By the way IdentityHashMap is special implementation of Map interface much like EnumMap but it also violates general contract of Map interface which mandates using equals method for comparing Object. Also IdentityHashMap vs HashMap is a good Java question and have been asked couple of times.  Though this question is not as popular as How HashMap works in Java or Difference between Hashtable and HashMap, it’s still a good question to ask. In this Java tutorial we will see example of IdentityHashMap and explores some key differences between IdentityHashMap and HashMap in Java.

Saturday, January 26, 2013

Spring - java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener Quick Solution

If you have worked in Spring MVC than you may be familiar with  
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
which is common problem during deployment. Spring MVC throws  java.lang.ClassNotFoundException:                           org.springframework.web.context.ContextLoaderListener ,
when its not able to find org.springframework.web.context.ContextLoaderListener class which is used to load spring MVC configuration files like application-context.xml and other Spring Framework configuration files defined in context-param element of web.xml in an Spring MVC web application as:

Thursday, January 24, 2013

JAXB XML Binding tutorial - Marshalling UnMarshalling Java Object to XML

XML binding is a concept of generating Java objects from XML and opposite  i.e. XML documents from Java object. Along with parsing XML documents using DOM and SAX parser, XML binding is a key concept to learn if you are working in a Java application which uses XML in any way e.g. for storing persistence data like user preferences or for transmitting messages between two system etc. XML binding is also a popular XML Interview question in Java. JAXB and XMLBeans are two common ways to achieve XML binding in Java.  XML binding, also known as XML marshaling and marshaling has two sides, first converting XML document to Java object, modify Java object and than converting back to XML file. Once you have XML document as Java object, You can use power of Java programming language to process and manipulate the XML elements, attributes etc. In last couple of Java XML tutorials we have seen How to parse XML using DOM parser and How to evaluate XPATH expression in Java. In this Java XML tutorial we will talk about JAXB (Java API for XML Binding) which is an annotation based library integrated into Java SDK. Beauty of JAXB is that it doesn't require XML Schema to generate XML documents from Java objects unlike XMLBeans and simply rely on POJO(Plain old Java objects) and annotations.

Tuesday, January 22, 2013

Difference between Stack and Heap memory in Java

Difference between stack and heap memory is common programming question asked by beginners learning Java or any other programming language. Stack and heap memory are two terms programmers starts hearing once they started programming but without any clear and definite explanation. Lack of knowledge on what is heap in Java and what is stack memory in Java, results in misconcepts related to stack and heap. To add to this confusion, stack is also a data structure which is used to store elements in LIFO(Last In First out) order and available in Java API as java.util.Stack. In general both stack and heap are part of memory, a program is allocated and used for different purposes. Java program runs inside JVM which is launched as a process by "java" command. Java also uses both stack and heap memory for different needs. In our last article 10 points on Java heap space I have touched base on Java heap space and in this article we will see difference between stack and heap memory in Java.

Monday, January 21, 2013

Display Tag Export Example in JSP – Issue Fix Java Tutorial

Display tag provides export options to export page into PDF, CSV, Excel and XML in Java web application written using JSP, Servlet, Struts or Spring MVC framework. Display tag is a tag library and you just need to use it in your JSP page to display tabular data or generate HTML tables dynamically. Earlier we have seen 10 display tag tips for getting most out of display tag and in this JSP Servlet tutorial we will see one display tag export issue, which prevent display tag export functionality to work properly. Display tag experience is considered good in various JSP Interview and some questions related to sorting, paging, both internal paging and external paging and exporting on display tag also appear as various J2EE and Servlet Interview questions. In my opinion, after JSTL core tag library, display tag is most popular tag library and every Servlet and JSP developer should familiar with display tag.

Saturday, January 19, 2013

How to fix Failed to load Main-Class manifest attribute from jar - Java Eclipse Netbeans Tutorial

If you have tried creating JAR file and running Java program form command line you may have encountered "Failed to load Main-Class manifest attribute from jar" , This error which haunts many Java programmer when they enter into command line arena and tries to create JAR file in command line or IDE like Netbeans and Eclipse. Major problem with "Failed to load Main-Class manifest attribute from jar" error is that, it’s unnecessary creates panic which it doesn't deserve, may be because process involves of creating and running JAR is not that common like running Java program using "java" command. Anyway in this Java tutorial we will see Why  "Failed to load Main-Class manifest attribute from jar" comes and How to fix  Failed to load Main-Class manifest attribute from jar error.

Friday, January 18, 2013

How to setup JNDI Database Connection pool in Tomcat - Spring Tutorial Example

Setting JNDI Database Connection pool in Spring and Tomcat is pretty easy. Tomcat server documentation gives enough information on how to setup connection pool in Tomcat 5, 6 or 7. Here we will use Tomcat 7 along with spring framework for creating connection pool in Tomcat server and accessing them in Spring using JNDI code. In our last article we have seen how to setup database connection pool in Spring for core Java application which doesn't run on web server or application server and doesn't have managed J2EE container. but if you are developing web application than its better to use server managed connection pool and access them using JNDI. Spring configuration will be generic and just based on JNDI name of Datasource so it will work on any J2EE Server e.g. glassfish, WebLogic, JBoss or WebSphere until JNDI name is same. Tomcat is my favorite web server and I use it a lot on development and its comes integrated with IDE like Eclipse and Netbeans. I am using it for all test and development purpose, Though beware with java.lang.OutOfMemoryError: PermGen space in tomcat,

Wednesday, January 16, 2013

How to check if a Number is Positive or Negative in Java - Interview Question

Write a Java program to check if a number is positive or negative is one of the popular Java coding interview question, it may look easy but programmers often fumble on this question. One of the tricky part of this question is that Java has multiple data type to support numbers like byte, short, char, int, long, float and double, out of those all are signed except char, which can not represent negative numbers. Some solution work for int and long but may not work for floating point number e.g. float and double. This is also a tricky Java question, another tricky point is considering special case like positive infinity, negative infinity or NaN in case of checking floating point numbers. Things gets more complicated when, as followup questions, interviewer put additional conditions such as you can not use relational operator etc. Nevertheless Java provides several way to check if a number whether integer or floating point is positive or negative. In this Java tutorial, we will see such methods of checking sign of number in Java.

Monday, January 14, 2013

ThreadLocal Memory Leak in Java web application - Tomcat

ThreadLocal variables are infamous for creating memory leaks. A memory leak in Java is amount of memory hold by object which are not in use and should have been garbage collected, but because of unintended strong references, they still live in Java heap space. There are many ways memory leak can be caused in Java but when this memory leak is caused due to ThreadLocal variable, it’s refereed as ThreadLocal memory leak. In our last post about ThreadLocal variable, we have seen How ThreadLocal variable can make SimpleDateFormat thread-safe and also raised point that in managed environment like J2EE application server or web server like Tomcat, Jetty, WebSphere or Weblogic use of ThreadLocal should be avoided. In this post we will go little deep and find out How ThreadLocal variables creates memory leak in Java web application, much like we have seen How to fix PermGen memory leak in Tomcat. If you are not familiar with ThreadLocal variables I suggest to go through my previous post. Before going into detail let's recap How ThreadLocal class works in Java.

Friday, January 11, 2013

How to decompile class file in Java and Eclipse - Javap command example

Ability to decompile a Java class file is quite helpful for any Java developer who wants to look into the source of any open source or propriety library used in project. Though I always prefer to attach source in Eclipse of most common libraries like JDK but it’s not always possible with increasing number of dependencies. Java decompiler (a program which can decompile Java class files to produce source files) is very helpful on such situation. By using Java decompiler you can easily check out source of any .class file. Thanks to Eclipse IDE and increasing number of free plug-in available for Java developers, You can have powerful Java decompile in your armory. Earlier I used to used JadEclipse an Eclipse plugin which works well with JAD decompiler but knowing about JAD decompiler is not supporting Java 1.5 source, I was in hunt of another suitable and useful Eclipse plugin which can decompile .class file. My search ends with JD-Eclipse , this is another free Eclipse plugin for non commercial and personal use which helps you to get source from class files. JD-Eclipse is easy to install and its site has detailed step by step guide on how to install JD-Eclipse plug-in. If you are already familiar with Eclipse plugin installation than it just a cake walk.

Thursday, January 10, 2013

Difference between Sun (Oracle) JVM and IBM JVM

There are different JVM implementation available apart form popular Sun's (now Oracle) hotspot JVM like IBM's JVM. Now question comes, what makes two JVM different to each other? Quite a lot of thing can be different even if two JVMs are implemented by following Java virtual machine specification. IBM has its own JVM implementation which is different than Oracle's JVM in many things like JIT(Just in Time) Compiler, structure of Java heap, garbage collectors and support for monitoring and management. Though I have mostly used Sun’s hotspot JVM recently got chance to run some Java program on IBM JVM on AIX platform and In this article I will shared some differences between Oracle and IBM JVM which is worth remembering. IBM's JVM is particularly useful on platform which is not supported by Oracle like AIX systems.

Monday, January 7, 2013

Java Best Practices to Follow while Overloading Method and Constructor

Method overloading in Java needs to be use carefully. Poorly overloaded method add not only add confusions among developers who use that but also they are error prone and leaves your program on compiler's mercy to select proper method. It's best to avoid issues related to method overloading in Java by following some Java best practices. For those who doesn’t know What is method overloading in Java, method overloading means declaring two method with same name but different method signatures. This is generally done to create method which operates on different data types e.g. System.out.println() which is overloaded to accept different types of parameters like String, double, int etc, see this Java tutorial on method overloading and static vs dynamic binding for more details. By the way all of these Java best practices which are explained in context of method overloading are equally applicable to constructor overloading in Java, because in terms of overloading method and constructors are almost same.

Sunday, January 6, 2013

Top 9 Java Programming Books - Best of lot, Must Read

These top Java programming books are some of the good Java books and I would say best of them all. Whenever a programmer starts learning the Java first question he asks is "Which book should I refer to learn Java?", That itself says, how important Java books are for programmers especially beginners. Despite having so much free resource available in Java like tutorials, tips, blogs and code examples, Java books has there own place because of two reason :
  • They are written by programmers who are authority in subject
  • They cover the subject with more details and explanation.
These Java books are my personal favorites and whenever I get some time I prefer to read them to refresh my knowledge. Though I have read many of them already, like I have read Effective Java almost 3 to 4 times, I  have always learned something new. They are kind of best Java books available today and equally useful for beginners, experienced and advanced Java programmer. It doesn't matter whether you are completely new in Java or doing Java programming for 5 years, you will definitely learn lot of new things by going through this book. Having said that not all book is equally suitable for all programmers, for Java beginners, Head First Java should be the first book and for advanced Java developer, Effective Java should be the first book.

Saturday, January 5, 2013

10 XML Interview questions and answers for Java Programmer

XML Interview questions are very popular in various programming job interviews, including Java interviews for web developer. XML is a matured technology and often used as standard for transporting data from one platform other. XML Interview questions contains questions from various XML technologies like XSLT which is used to transform XML files, XPATH, XQuery and fundamentals of XML e.g. DTD or Schema. In this article we will see 10 frequently asked XML Interview questions and answers from above topics. These questions are mostly asked in various Java interviews but they are equally useful in other programming interviews  like C, C++, Scala or any other programming language. Since XML is not tied with any programming language and like SQL its one of the desired skill in programmer, it make sense to practice some XML questions before appearing in any technical job interview

Friday, January 4, 2013

What is NavigableMap in Java 6 - Creating subMap from Map with Example

NavigableMap in Java 6 is an extension of SortedMap  like TreeMap which provides convenient navigation method like lowerKey, floorKey, ceilingKey and higherKey. NavigableMap is added on Java 1.6 and along with these popular navigation method it also provide ways to create a Sub Map from existing Map in Java e.g. headMap whose keys are less than specified key, tailMap whose keys are greater than specified key and a subMap which is strictly contains keys which falls between toKey and fromKey. All of these methods also provides a boolean to include specified key or not. TreeMap and ConcurrentSkipListMap are two concrete implementation of NavigableMap in Java 1.6 API. Though NavigableMap is not as popular as HashMap, ConcurrentHashMap or Hashtable but given that TreeMap implements NavigableMap you already get all good things in a well known Map implementation.

Thursday, January 3, 2013

Difference between Factory and Abstract Factory design pattern in Java

Both Abstract Factory and Factory design pattern are creational design pattern and use to decouple clients from creating object they need, But there is a significant difference between Factory and Abstract Factory design pattern, Factory design pattern produces implementation of Products e.g. Garment Factory produce different kinds of clothes, On the other hand Abstract Factory design pattern adds another layer of abstraction over Factory Pattern and Abstract Factory implementation itself e.g. Abstract Factory will allow you to choose a particular Factory implementation based upon need which will then produce different kinds of products.

In short
1) Abstract Factory design pattern  creates Factory
2) Factory design pattern creates Products

Wednesday, January 2, 2013

JDBC Batch INSERT and UPDATE example in Java with PreparedStatement

JDBC API in Java allows program to batch insert and update data into database, which tends to provide better performance by simple virtue of fact that it reduce lot of database round-trip which eventually improves overall performance. In fact it’s one of JDBC best practices to insert and update data in batches. For those who doesn’t know what is batch insert and update, Java provides several ways to execute SQL queries, one of them is JDBC batch insert and update, on which instead of executing sql query one by one using either Statement or PreparedSatement, you execute query in batch and send a batch of query to database for execution instead of single query. Since multiple queries are combined into batch and one batch is sent to database instead of individual queries, it reduce database round trip by factor of batch size. Batch size can be anything but needs to be decided carefully. JDBC specification supports upto 100 but individual database e.g. Oracle, MySQL, Sybase or SQL Server has there own limit on maximum batch size, , normal jdbc batch size ranges from 50 to 100. JDBC API provides addBatch() method to add queries into batch and than later execute them using executeBatch() method. Both Statement and PreparedStatement can be used to execute batch queries in Java. By the way batch insert and update also provide performance boost to Data access Object or DAO layer,  as discussed in our last post 4 ways to improve Performance of JDBC applications.

Tuesday, January 1, 2013

Data Access Object (DAO) design pattern in Java - Tutorial Example

Data Access Object or DAO design pattern is a popular design pattern to implement persistence layer of Java application. DAO pattern is based on abstraction and encapsulation design principles and shields rest of application from any change on persistence layer e.g. change of database from Oracle to MySQL, change of persistence technology e.g. from File System to Database. For example if you are authenticating user using relational database and later your company wants to use LDAP to perform authentication. If you are using DAO design pattern to access database, it would be relatively safe as you only need to make change on Data Access Layer. DAO design pattern also keeps coupling low between different parts of application. By using DAO design pattern your View Layer is completely independent to DAO layer and only Service layer has dependency on it which is also abstracted by using DAO interface. You can further use Generics to template your DAO layer. If you are using Spring than you can leverage JdbcTemplate for performing JDBC calls which saves lot of boiler plate coding. Using DAO pattern to access database is one of the JDBC best practices to follow.