Monday, June 30, 2014

How to create Custom Exception in Java - Tutorial Example

Sometime we need to create custom Exception in Java, i.e. Exceptions which are not defined in JDK or any third party library your application is using. Though it’s widely recommended on several Exception best practices article, even Joshua Bloch has recommended in Effective Java to prefer standard exception over custom exception, sometime you really need it. There are certain guidelines to help to find whether you really need a custom exception or not. You should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else's.

  •     Do you need an exception type that isn't represented by those in the Java platform?
  •     Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?
  •     Does your code throw more than one related exception?
  •     If you use someone else's exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained?

Thursday, June 26, 2014

How to use CopyOnWriteArraySet in Java with Example

CopyOnWriteArraySet is little brother of CopyOnWriteArrayList class. These are special purpose collection classes which was added on JDK 1.5, along with their most popular cousin ConcurrentHashMap. They are part of concurrent collection framework and reside in java.util.concurrent package. CopyOnWriteArraySet is best suited as read-only collection whose size is small enough to copy if some mutative operation happens, for example you can use CopyOnWriteArraySet to store object at start-up of application and let multiple application thread access them during application life time. If an new condition or object comes up during that time, it can also be added into this Set, with incurring cost of creating a new array. One of the most important thing to know about CopyOnWriteArraySet is that it is backed by CopyOnWriteArrayList, which means it also share all basic properties of CopyOnWriteArrayList. Another important thing to remember is that Iterators of this collection class doesn't support remove() operation, trying to remove an element while iterating will result in UnSupportedOperationException. This is done to ensure speed during traversal, traversing this set implementation using Iterator is fast and cannot encounter interference from other threads. Iterators actually rely on unchanging snapshots of the array at the time the iterators were constructed. In short, use CopyOnWriteArraySet if set is small enough to copy on add, set or remove, and main purpose is to read data with occasional updates. Also if you want to remove elements during iteration, don't use this Set implementation because its iterator doesn't support remove(), and throws java.lang.UnsupportedOperationException as shown below :

Monday, June 23, 2014

20 Fancy Acronyms Programmers should know?

Do you read blogs on Internet? Do you understand what TL;DR or ITT means, Well I didn't, not until last year. Internet is full of acronyms. Techies, programmers, developers and bloggers has developed a lot more fancy acronyms than you can think of. If you participate or read articles on sites like Reddit, Hacker news or StackOverFlow, you will see extensive use of these mysterious acronyms. If you don't know meanings of acronyms like TL;DR, AFAIK, PSA, YSK or TIL, there is good chance that you will lost in conversation and comments. So when I come across this list of acronyms, I thought to share it with you guys. This list contains lots of popular acronyms, which is been used by many bloggers around internet and community web-sites like Reddit, Hacker News, DZone and StackOverFlow. Next time, you encounter a fancy acronym, you might not need to Google, to know its meaning and then go back to the thread to read further. By the way, if you know any other fancy Internet acronyms, popular among programmers, web developers and bloggers, then feel free to share with us. Acronyms are not arranged in any particular order but in my preference of their usage. By the way, there are a lot of acronyms in use on reddit, so this is just a list of some of the main ones you'll see.

Tuesday, June 17, 2014

How to Count number of Set bits or 1's in Integer on Java?

There are multiple ways to count number of 1's or set bits in a integer number in Java. You can use bitwise and bit shift operator by your own, or, you can use Java API to count number of set bits. Java 1.5 added two utility method called bitCount(int i) which returns number of 1's in your integer number, java.lang.Long class has similar bitCount(long number) for long primitives. As I have said earlier, Coding questions are important part of any Java interview, and from that recursion and bitwise operations are most popular. Questions like, How to Swap two numbers without temp variable or How to find if a number is positive or negative are some of such questions, which you see now and then in various Java interviews. In this Java tutorial, we will see, How to count number of set bits in a number, for those who don't know what is set bit, it's bit with value 1. For example 2, which is binary 0010 has just one set bit. On the other hand 10, which is 1010 in binary has two set bit or number of one's. In most of cases, Interviewer will ask you to write a Java method without using API. In this article, we will see couple of ways to calculate number of set bit in a number on Java program.

Wednesday, June 11, 2014

Is Java Compiled or Interpreted Programming language?

One of the first question a graduate C or C++ programmer, who has just started learning Java ask is, whether Java is a compiled language or an interpreted one? On academic courses or during college, students learn a lot of languages e.g. VB, C, C++ and they happily categories them as either compiled or interpreted, but with Java it's tricky. It's not clear whether Java is compiled or interpreted, because it neither generate machine language code after compiling source file,  neither interpreted source file to execute instruction line by line. In order to answer this question you need to fist know that Java is a platform independent language? Which means you can run a Java program to any platform, which includes hardware + operating system, without any modification. Knowing how Java achieves platform independence is key to answer this question. If anyone ask this question during interview, then your answer should be both i.e. Java is both compiled and interpreted programming language. Java code is written in .java files (also known as source file), which is compiled by javac, a Java compiler into class files. Unlike C or C++ compiler, Java compiler doesn't generate native code. These class files contains byte-code, which is different than machine or native code. Java virtual machine or JVM interprets byte codes during execution of Java program. So, you can see it's both compiled and interpreted language, but this answer is incomplete until you mention about JIT (Just in time compiler) which does another round of compilation to produce native code, which can directly be executed by corresponding platform. We will learn about how JIT works in next section.

Monday, June 9, 2014

SynchronousQueue Example in Java - Produer Consumer Solution

SynchronousQueue is special kind of BlockingQueue in which each insert operation must wait for a corresponding remove operation by another thread, and vice versa. When you call put() method on SynchronousQueue it blocks until another thread is there to take that element out of the Queue. Similarly, if a thread tries to remove an element and no element is currently present, that thread is blocked until another thread puts an element into the queue. You can correlated SynchronousQueue with athletes (threads) running with Olympic torch, they run with torch (object need to be passed) and passes it to other athlete waiting at other end. If you pay attention to the name, you will also understand that it is named SynchronousQueue with a reason, it passes data synchronously to other thread; it wait for the other party to take the data instead of just putting data and returning (asynchronous operation). If you are familiar with CSP and Ada, then you know that synchronous queues are similar to rendezvous channels. They are well suited for hand-off designs, in which an object running in one thread must sync up with an object running in another thread in order to hand it some information, event, or task. In earlier multi-threading tutorials we have learned how to solve producer consumer problem using wait and notify, and BlockingQueue and in this tutorial we will learn how to implement producer consumer design pattern using synchronous queue. This class also supports an optional fairness policy for ordering waiting producer and consumer threads. By default, this ordering is not guaranteed. However, a queue constructed with fairness property set to true grants threads access in FIFO order.

Friday, June 6, 2014

Exception in thread "main" java.lang.ExceptionInInitializerError in Java Program

JVM throws java.lang.ExceptionInInitializerError, when there is an Exception inside static initializer block. If you know about static variable in Java, then you may know that they are initialized at the time of class loading. If there is an Exception during that initialization of static variables, you will see ExceptionInInitializerError in Java. This could be any exception e.g. java.lang.ArrayIndexOutOfBound or java.lang.NullPointerException. Java developers often confused with this error because, they think that they have not defined any static initializer block, then how come they are getting ExceptionInInitializerError; well, by default Java combines all static variable initialization inside a static initializer block and initialize them in the order they are declared in source file. If suppose a variable ABC is declared at line 1, used at line 2 but initialized at line 3, then code at line 2 will throw java.lang.NullPointerException, which will be wrapped by JVM in ExceptionInInitializerError, and if that code happens to be executed by main thread then you will see "Exception in thread "main" java.lang.ExceptionInInitializerError" in your console or log file. In a large application with huge log files sometime this error got unnoticed, and programmers get alerted by dreaded java.lang.NoClassDefFoundError. Unfortunately this error comes when client class tries to use the class, which was not loaded because of ExceptionInInitializerError . Since class loading was failed earlier, JVM is now throwing NoClassDefFoundError. Sometime this misleads Java developer, and they start looking at classpath, path and java.library.path for missing class, and confused them with hell not finding any anomalies.  If you are investigating cause of NoClassDefFoundError, it's always a better idea to check your application log files for ExceptionInInitializerError before looking at CLASSPATH. In this article, we will see an example code, which generates exception during static initialization and results in "Exception in thread "main" java.lang.ExceptionInInitializerError". In later part, we will see how to fix this error.

Tuesday, June 3, 2014

2 Examples to read Zip Files in Java, ZipFile vs ZipInputStream

ZIP format is one of the most popular compression mechanism in computer world. A Zip file may contains multiples files or folder in compressed format.  Java API provides extensive support to read Zip files, all classes related to zip file processing are located in java.util.zip package. One of the  most common task related to zip archive is to read a Zip file and display what entries it contains, and then extract them in a folder. In this tutorial we will learn how to do this task in Java. There are two ways you can iterate over all items in a given zip archive, you can use either java.util.zip.ZipFile or java.util.zip.ZipInputStream. Since a Zip file contains several items, each of them has header field containing size of items in number of bytes. Which means you can iterate all entries without actually decompressing the zip file. ZipFile class accepts a java.io.File or String file name, it opens a ZIP file for reading and UTF-8 charset is used to decode the entry names and comments. Main benefit of using ZipFile over ZipInputStream is that it uses random access to iterate over different entries, while ZipInputStream is sequential, because it works  with stream, due to which it's not able to move positions freely. It has to read and decompress all zip data in order to reach EOF for each entry and read header of next entry. That's why its better to use ZipFile class over ZipInputStream for iterating over all entries from archive.  We will learn more about how to use read Zip file in Java, by following an example. By the way, code should work with zip file created by any zip utility e.g. WinZip, WinRAR or any other tool, .ZIP format permits multiple compression algorithms.. I have tested with Winzip in Windows 8, but it should work with zip file created by any tool.