HTML

Thread-safe Singleton in Java using Double Checked Locking Idiom

Singleton Pattern is one of the famous design patterns from the Gang of Four. Even though nowadays it is considered as an anti-pattern, it has served us well in the past. In Singleton pattern, a class has just one instance throughout its lifetime and that instance is shared between multiple clients. Singleton class has two responsibility, first to ensure that only instance of the class gets created and second, provide a method getInstance() so that everyone can get access to that single instance i.e. global access. One of the issue, faced by Singelton design pattern in the multi-threading program is to ensure that just one instance of the class gets created, even if multiple clients called getInstance() method same time. Many programmers solved this problem by making whole getInstance() method synchronized, which results in poor performance because every time a thread enters a synchronization method, it acquires the lock and while it's been inside the method, no other thread are allowed to enter, even if they are not creating instance and just accessing already created instance.

How to check if a key exists in HashMap Java? Use containsKey()

One of the common programming task while using HashMap in Java is to check if a given key exists in the map or not. This is supposed to be easy, right? Yes, it is easy if you know your API well, all you need to is call the containsKey() method, it returns true if given key exists in HashMap, otherwise false; but I have seen many programmer's codes like we will see in this article, which prompted me to write this blog post.

if(map.get(key) !=  null){
    System.out.println("key exits in Map");
}

This code is fragile, it will not work if you have added null values into HashMap, remember HashMap does allow null values. Many programers will test this code for some input and think that it's working fine, only to create a subtle bug in production.  It's always better to use an API method if it can do the job, many greats have advised this. Joshua Bloch even included a chapter on his classic book Effective Java, a must-read book for any Java programmer.

6 ways to convert char to String in Java - Examples

If you have a char value e.g. 'a' and you want to convert it into equivalent String e.g. "a" then you can use any of the following 6 methods to convert a primitive char value into String in Java :

1) String concatenation
2) String.valueOf()
3) Character.toString()
4) Character wrapper class + toString
5) String constructor with char array
6) String.valueOf(char [])

In this article, we will see examples of each approach and learn a little bit more about it. Actually, there is lot of overlap between each method as some of them internally calls String.valueOf(), which eventually calls to a String constructor which accepts char array and creates a String object containing primitive char value with length 1. Once you know, how they work internally, it easy to decide which one is more efficient for purpose.

60+ Java Interview Questions for Quick Revision

Java Interviews are very different than traditional software developer interviews. You can clear a Java interview without even writing a single line of code, Yes, this is true, you can become a Java developer without someone asking you to write a function in Java interview. Though, it's not the case everywhere and many companies are increasingly including coding test in their Java developer interview process, but there are many companies and start-ups where you can get a Java job without writing a single line of code. All you need to do is memorize those standard Java questions, which has been asked from ages and mostly test the theoretical knowledge of the candidate. This is great for candidates which lack hands-on coding experience, but sometimes this style of the interview can cost you good developers who are not good at interviews. Someone, who knows how to structure a complex program, knows how to model their class and objects, can write good, robust code but fail to answer questions like, Why String is Immutable? or How HashMap works in Java?

How to use BigInteger class in Java? Large Factorial Example

When you calculate factorial of a relatively higher number most of the data type in Java goes out of their limit. For example, you cannot use int or long variable to store factorial of a number greater than 50. In those scenarios where int and long are not big enough to represent an integral value, you can use java.math.BigInteger class. BigInteger variable can represent any integral number, there is no theoretical limit, but it allocates only enough memory required to hold all the bits of data it is asked to hold. There is not many time you need this class but its good to know about it and that's why I am giving one scenario which is perfectly suitable for using BigInteger class. In this article, you will learn how to calculate factorial of large number using BigInteger object. We will use same formula, we have used to calculate normal factorials as discussed in my previous post about factorials.

Top 10 Algorithm books Every Programmer Should Read

Algorithms are language agnostic and any programmer worth their salt should be able to convert them to their language of choice. Unfortunately, I have come across several programmers who are REALLY good on programming language e.g. Java, knows minor details of API and language intricacies but has very poor knowledge of algorithms. Ask them to right popular sorting algorithms e.g. quicksort and they will fall apart. Expecting them to know of about more complex algorithm e.g. String, graph, tree or greedy algorithms. Once, I have asked a very good candidate who was good in Java, multi-threading but his data structure and algorithm skill was really poor to his experience and caliber.  I asked him, why he didn't spent time brushing his algorithm and problem solving skill before coming to interview? His excuse was "those algorithms are just for interviews and never really used in practical coding. I have never used them in my 6 years of Java development career". He was right, but he failed to recognize the more long term improvement algorithm and data structure do in improving programming skill. They are tool of developing programming solving skill and coding sense, which is required to convert a user requirement into line of code also known as computer program.

How to sort HashSet in Java? Example

Somebody asked me recently, how do you sort an HashSet? For lists, we use the Collections.sort(List) method, but there is nothing for Set. If I have an HashSet then how would I go about sorting it? The answer is you cannot sort an HashSet, why? because HashSet is an unordered collection. When you insert an element in HashSet than you lose the order guarantee. You cannot do reordering or sorting in Set because it does not have random access methods (ie, .get() an element at a given index), which is basically required for sort algorithms. Though you can sort the HashSet by first converting HashSet to List and then sorting it. Also, some of Set implementation may keep the order intact e.g. LinkedHashSet maintains insertion order, which means you can sort LinkedHashSet but not HashSet. Alternatively, you can also use TreeSet to keep elements in the sorted order from the start.

Factorial in Java using Recursion and Loop

Problem : Write a program to calculate factorial of a given number in Java, using both recursion and iteration.

Solution : If you come from Maths background then you know that factorial of a number is number*(factorial of number -1). You will use this formula to calculate factorial in this  Java tutorial. Since factorial is a naturally recursive operation, it make sense to use recursion to solve this problem but its not always the best way. Iteration provides a more robust way, but don't worry you will learn how to calculate factorial with and without recursion in Java. By the way, factorial of numbers grows very quickly and even the largest integral data type in Java, long is not able to hold factorial of anything or above 50. In such cases you can use BigInteger, which has theoretically no limit and can be used to represent very large integral numbers.

Why you shouldn't use == with float and double in Java?

In this article, you are going to learn why you shouldn't use == with float and double in Java? Especially for checking loop termination condition. Java programmers often make the mistake of using floating point number in a loop and checking condition with the == operator, in the worst case this could create an infinite loop, causing your Java application to hung.


For example, following code will not work as you expect :

for(double balance = 10; balance!=0; balance-=0.1) {
   System.out.println(balance);
}

Top 10 RESTful Web Service Interview Questions for Java Developers

REST is an architectural style of developing web services which has become immensely popular in last couple of years and consequently gained lot of importance in core Java and Java EE interviews. If you are a Java web developer then you are most likely see couple of questions from web services every time you go for a Java web developer interview. One of the most frequently one is difference between REST and SOAP web services, which I have recently answered there, but there are lot many other good questions I have collected from friends and my readers, which I have not yet published. In this article, I am sharing those questions, mainly based upon REST style web services for your practice and preparation. Some of them are easy to answer and you will find them either in my blog or by doing Google but couple of them is really interesting and challenging and required real solid experience in Java web service domain to answer. I leave it to you guys for now and will probably update this post with answers in near future. If you don't find answer of any REST interview question then I suggest you to take a look at these two books, Java Programming Interview Exposed and RESTful Web Services, you will most likely find your answer there.