Friday, July 22, 2011

How to use Java 1. 7 Multiple Catch Block with example - JDK 7 tutorial

As the release of JDK 7 approaching General Availability (GA) on 2011/07/28, I thought to have a look on language enhancement as part of project coin, also called as Small language enhancements or JSR 334. Though there are not any major changes like Enum or Generics of Java 1.5,  but they are still very useful, in terms of simplifying your day to day programming task. Some of the interesting changes are allowing String in Switch cases, inclusion of fork-join framework in JDK itself , type inference using a diamond operator, automatic resource management using  try with resource feature, and ability to catch multiple Exception in the single catch block . In this Java 7 tutorial, we will learn how multi catch block of JDK 1.7 makes Exception handling code simpler and elegant. Multiple catch block will allow you to catch multiple exceptions in one block but it’s only available in JDK7 and you need to compile your code with source 1.7. 

Wednesday, July 20, 2011

Top 15 Java Multithreading, Concurrency Interview Questions Answers asked in Investment banks

Thread interview questions Java
Multi-threading and concurrency questions are essential part of any Java interview. If you are going for any Java interview on any Investment bank for equities front office position expect lots of muti-threading interview questions on your way. Multi-threading and concurrency is a favorite topics on Investment banking specially on electronic trading development and they grill candidate on many confusing java thread interview questions. They just want to ensure that the guy has solid knowledge of multi-threading and concurrent programming in Java  because most of them are in business of performance. High volume and low latency Electronic trading System which is used for Direct to Market (DMA) trading is usually concurrent in nature. These are my favorite thread interview questions on Java  asked on different on different time. I am not providing answer of these thread interview questions but I will give you hint whenever possible, some time hint is enough to answer. I will update the post further with detailed answers just like I did for 10 Singleton interview questions in Java recently.  With introduction of concurrency package in Java 5 questions on concurrent utility and concurrent collections are on rise as well. ThreadLocal, BlockingQueue, Counting Semaphore and ConcurrentHashMap are popular among those.

Saturday, July 16, 2011

Difference between ClassNotFoundException vs NoClassDefFoundError in Java

ClassNotFoundException vs NoClassDefFoundError
Though both of these errors are related to missing classes in the classpath, the main difference between them is their root cause. ClassNotFoundExcpetion comes when you try to load a class at runtime by using Class.forName() or loadClass() and requested class is not present in classpath for example when you try to load MySQL or Oracle driver class and their JAR is not available, while in case of NoClassDefFoundError requested class was present at compile time but not available at runtime. Sometimes due to an exception during class initialization e.g. exception from static block causes NoClassDefFoundError when a failed-to-load class was later referenced by the runtime. 

Wednesday, July 13, 2011

Why multiple inheritances are not supported in Java

Why multiple inheritence is not supported implemented in javaRecently one of my friend appeared for an interview and after few so called easy questions he was asked "Why multiple inheritance is not supported in Java" , though he has a brief idea that in Java we can support multiple inheritance in java via interface but interviewer was keep pressing on why part , may be he was just read any blog post about it :). So after the interview my friend comes to me and in usual talk he told me about this questions and ask me the answer. Well this is very classical question like Why String is immutable in Java; similarity between these two questions is they are mainly driven by design decision taken by java's creator or designer. Though following two reason make sense to me on Why Java doesn't support multiple inheritances:

Saturday, July 9, 2011

String vs StringBuffer vs StringBuilder in Java

Difference between String, StringBuffer, and StringBuilder
The String is one of the most important classes in Java and anyone who starts with Java programming uses String to print something on the console by using famous System.out.println() statements. Many Java beginners not aware that String is immutable and final in Java and every modification in String creates a new String object. For example, when you get the substring, you get a new String, when you convert uppercase String to lowercase, a new String is created. Even when you remove space by calling the trim() method, a new String is returned. So, now the big question is how do you manipulate String in Java without creating String garbage? StringBuilder and StringBuffer are the answer to this question. StringBuffer is old class but StringBuilder is newly added in Java 5 along with major improvements in Enum, Generics, varargs methods and Autoboxing in Java.

Wednesday, July 6, 2011

10 Tips to Debug Java Program in Eclipse

How to debug java program in Eclipse

Debugging is a must have skill for any java developer. Having ability to debug java program enables to find you any subtle bug which is not visible during code review or comes when a particular condition offer, This becomes even more important if you are working in high frequency trading or electronic trading system project where time to fix a bug is very less and bug usually comes on production environment and doesn't appear in your Windows XP machine. in my experience debugging java application also helps you understand flow of java program. In this java tutorial we will see how to debug a java program, setting up remote debugging in java and some java debugging tips on Eclipse and Netbeans IDE. It’s also good to know various java debug tool available and how java debugger or jdb works but it’s not mandatory for doing debugging in Java. To start java debugging you just needs your project to be configured in a modern IDE like eclipse and Netbeans and you are ready to debug java program.

Friday, July 1, 2011

How to resolve java.lang.UnsupportedClassVersionError with example

java.lang.UnsupportedClassVersionError  is a quite common error after NoClassDefFoundError or ClassNotFoundException they all seems to related to class files but they all are different and there cause and resolution are different. In this java tutorial we will see what is UnsupportedClassVersionError in Java? Why UnsupportedClassVersionError comes in Java? What is class file format and version numbers associated with it and finally how to resolve UnsupportedClassVersionError in Java. 

This article is in continuation of debugging tutorials like How to remote debug Java program in Eclipse and 10 Java debugging tips in Eclipse. If you have not read those article you may find them useful.


How to resolve UnsupportedClassVersionError in Java

What is UnSupportedClassVersionError in Java?

UnSupportedClassVersionError, java.lang.UnsupportedClassVersionErrorJava.lang.UnsupportedClassVersionError is a subclass of java.lang.ClassFormatError. This is a kind of linking error which occurs during linking phase accordingly java.lang.ClassFormatError has also derived from java.lang.LinkageError. As the name suggests "UnSupportedClassVersionError" so it’s related to unsupported class version, now questions comes what is class version in Java? Well every source file is compiled into class file and each class file has two versions associated with it, major version and minor version. 

The Version of class file is represented as major_version.minor_version. This version is used to determine format of class file in Java.

According to Java Virtual Machine specification, “A JVM implementation can support a class file format of version v if and only if v lies in some contiguous range Mi.0 v Mj.m. Only Sun can specify what range of versions a JVM implementation conforming to a certain release level of the Java platform may support.” For example: JDK 1.2 supports class file formats from version 45.0 to version 46.0 inclusive. So if a class file has version 48.0 it means that major version of class file is "48" and minor version is "0", which tells us that JDK 1.4 has been used to compile and generate that class file.

When UnSupportedClassVersionError in Java comes:

So now we got the theory behind class file format and major and minor version of class file in Java. Now a million dollar question is when UnSupportedClassVersionError in Java does occur?  precise answer of this is "When JVM tries to load a class and found that class file version is not supported it throws UnSupportedClassVersionError and it generally occurs if a higher JDK version  is used to compile the source file and  a lower JDK version is used to run the program. for example if you compile your java source file in JDK 1.5 and you will try to run it on JDK 1.4 you will get error "java.lang.UnsupportedClassVersionError: Bad version number in .class file [at java.lang.ClassLoader.defineClass1(Native Method)]".

But its important to note is that vice-versa is not true "you can compile your program in J2SE 1.4 and run on J2SE 1.5 and you will not get any UnSupportedClassVersionError". When a higher JDK is used for compilation it creates class file with higher version and when a lower JDK is used to run the program it found that higher version of class file not supported at JVM level and results in java.lang.UnsupportedClassVersionError.

How to fix UnSupportedClassVersionError

Now we know the root cause of UnSupportedClassVersionError that we are using a lower JVM for running the program. But major problem is that stack trace of UnSupportedClassVersionError will not tell you for which class it’s coming. So if you are using multiple third party jars in your application you find that it comes at a particular part when JVM tries to load a class from a particular jar. anyway we all know that latest version of JDK is 1.6 so maximum version of class file could be generated by JDK 6, so by using JDK 6 we can solve UnSupportedClassVersionError, but many times its not easy to just move to higher JDK version. So I would suggest:

1) Find out due to which jar or class file this UnSupportedClassVersionError is coming?
2) Try to compile source code of that jar with the JDK version you are using to run your program, if source is available.
3) If you don't have source try to find the compatible version of that library.
4) Increase the JRE version you are using to run your program.

You can go by any approach to resolve UnSupportedClassVersionError based upon your need. Generally a higher JVM version is ok and does not cause any problem unless the class file format is quite old and no more supported by Sun in higher JVMs. The best way to deal with UnSupportedClassVersionError in Java is to use same version or JDK and JRE for compiling and running your program.

Example of UnSupportedClassVersionError in Java

You can easily reproduce UnSupportedClassVersionError by using javac of higher JDK and "java" from lower Java version. Let’s see some of examples of UnSupportedClassVersionError in Java:

1) java.lang.UnsupportedClassVersionError: EquityTradingManager (Unsupported major.minor version 49.0)
      at java.lang.ClassLoader.defineClass0(Native Method)
      at java.lang.ClassLoader.defineClass(
==>Since we know that major version 49 is supported by JDK 1.5, so these will "java.lang.UnsupportedClassVersionError” will come if JVM used to run this program is lower than Java 1.5.

2) Java.lang.UnsupportedClassVersionError: Bad version number in .class file

3) java.lang.unsupportedclassversionerror unsupported classversion 50.0
==> Compile in JDK 1.6 and running on lower version than Java 6.

4) java.lang.unsupportedclassversionerror unsupported classversion 49.0
==> compiled in Java 5 and running on lower JVM than JDK 5.

5) java.lang.unsupportedclassversionerror bad version number in eclipse.
java.lang.unsupportedclassversionerror unsupported classversion 49.0 or 50.0
==> Most of us use eclipse for building and running project some of us also use ant for building project. In eclipse there is some setting related to java source version which if you got incorrect can result in "java.lang.unsupportedclassversionerror bad version number". so make sure you have correct configuration. For example if you compile with source compatible 1.6 you need JRE 6 to execute the program. To check the compiler setting in eclipse go to project  ==>Properties==>Java Compiler as shown in image

Important point about UnSupportedClassVersionError in Java:

1) If you encounter UnSupportedClassVersionError, check the JRE version you are using to run program and switch to higher version for quick solution.
2) java.lang.UnsupportedClassVersionError is derived from java.lang.LinkageError, so it will not be detected in compile time and it will only come on runtime, precisely when JVM tries to load a class.
3) Class file format which is identified using major version and minor version. Class file format is assigned when you compile source file and its depends on JDK version used to compile.
4) Its always best practice to use same version of java for compilation and execution to avoid any chance of UnSupportedClassVersionError.
5) UnSupportedClassVersionError is not related to java classpath , so don't confuse this with NoClassDefFoundError or ClassNotFoundException.

Major Class Versions of Various JDK

Following are the major version of class file format in standard JDK environment.

JDK 1.1 = 45
JDK 1.2 = 46
JDK 1.3 = 47
JDK 1.4 = 48
JDK 1.5 = 49
JDK 1.6 = 50

You can also get version of "javac" (used for compilation) and version of "java" (used for execution) as below
C:\equity trading\stocks>javac -version
javac 1.6.0-beta2

C:\equity trading\stocks>java -version
java version "1.6.0-beta2"
Java(TM) SE Runtime Environment (build 1.6.0-beta2-b86)
Java HotSpot(TM) Client VM (build 1.6.0-beta2-b86, mixed mode, sharing)

Now you can identify your JDK version based on class file format version whenever you see java.lang.UnsupportedClassVersionError :)

So next time when you see UnsupportedClassVersionError don't be afraid and follow the best approach based upon your need.

If you like this post you may find my other tutorial how java hashmap works, why String is immutable in java, why wait and notify needs to call from synchronized context  interesting.