Thursday, August 28, 2014

Quicksort Sorting Algorithm in Java

Quicksort algorithm is one of the most used sorting algorithm, especially to sort large list and most of the programming languages, library have implemented it in one or another way. In Java, Arrays.sort() method sorts primitive data types using double pivot Quicksort algorithm, authored by Joshua Bloach and others. This implementation provides better performance for lot of data sets, where traditional quicksort algorithm reduced into quadratic performance. This method also uses MergeSort, another good sorting algorithm, to sort objects. QuickSort implementations are also available in C++ STL library. Have you ever thought why quicksort is so popular? because on average it is one of the fastest sorting algorithm we have. On average quicksort is a O(n log n) algorithm, while it's worst case is O(n^2), which is much better comparing with Bubble Sort or Insertion Sort. It's also one of the popular algorithm interview question, so as a programmer you must know how QuickSort works as well as how to implement Quicksort in Java or any other programming language. One of the most important thing interviewer look in your quicksort implementation is choice of pivot and whether you are sorting in place or not. In "in-place" sorting, actual sorting takes place in same array and no additional space is needed. Due to this reason, quicksort is very efficient in sorting large list of numbers, as no additional memory is required, a very space efficient sorting algorithm. Quicksort is also one of the naturally recursive algorithm and serves a good exercise for Java programmers to master art of recursion.

Tuesday, August 26, 2014

2 Examples to Convert Byte[] array to String in Java

Converting a byte array to String seems easy but what is difficult is, doing it correctly. Many programmers make mistake of ignoring character encoding whenever bytes are converted into a String or char or vice versa. As a programmer, we all know that computer's only understand binary data i.e. 0 and 1. All things we see and use e.g. images, text files, movies, or any other multi-media is stored in form of bytes, but what is more important is process of encoding or decoding bytes to character. Data conversion is an important topic on any programming interview, and because of trickiness of character encoding, this questions is one of the most popular String Interview question on Java Interviews. While reading a String from input source e.g. XML files, HTTP request, network port, or database, you must pay attention on which character encoding (e.g. UTF-8, UTF-16, and ISO 8859-1) they are encoded. If you will not use the same character encoding while converting bytes to String, you would end up with a corrupt String which may contain totally incorrect values. You might have seen ?, square brackets after converting byte[] to String, those are because of values your current character encoding is not supporting, and just showing some garbage values.

Tuesday, August 19, 2014

15 Java NIO, Socket, and Networking Interview Questions Answers

Networking and Socket Programming is one of the important area of Java programming language, especially for those programmers, who are working in client server based applications. Knowledge of important protocols e.g. TCP and UDP in detail is very important, especially if you are in business of writing high frequency trading application, which communicate via FIX Protocol or native exchange protocol. In this article, we will some of the frequently asked questions on networking and socket programming, mostly based around TCP IP protocol. This article is kinda light on NIO though, as it doesn't include questions from multiplexing, selectors, ByteBuffer and FileChannel but it does include classical questions like difference between IO and NIO. Main focus of this post is to make Java developer familiar with low level parts e.g. how TCP and UDP protocol works, socket options and writing multi-threaded servers in Java. Questions discussed here is not really tied up with Java programming language, and can be used in any programming language, which allows programmers to write client-server applications. By the way, If you are going for interview on Investment banks for core Java developer role, you better prepare well on Java NIO, Socket Programming, TCP, UDP and Networking along with other popular topics e.g. multi-threadingCollections API and Garbage Collection tuning. You can also contribute any question, which is asked to you or related to socket programming and networking and can be useful for Java interviews.

Thursday, August 14, 2014

Bubble Sort Algorithm in Java with Example

Bubble Sort is the first sorting algorithm I learned during my college day, and after so many years it's the one I remember by heart. It's kind of weird that one of the most popular sorting algorithm is also one of the worst performing sorting algorithm. Bubble sort's average case performance is in O(n^2), which means as the size array grows, the time it take to sort that array increases quadratic. Due to this reason, bubble sort is not used in production code, instead quick sort and merge sort are preferred over it. In fact, Java's own Arrays.sort() method, which is the easiest way to sort an array in Java also uses two pivot quicksort to sort primitive array and stable mergesort algorithm to sort object arrays. The reason or slow performance of this algorithm is excessive comparison and swapping, since it compare each element of array to another and swaps if it is on right side. Due to quadratic performance, bubble sort is best suited for small, almost sorted list e.g. {1, 2, 4, 3, 5} , where it just need to do one swapping. Ironically, best case performance of bubble sort, which is O(n) beats quicksort's best case performance of O(NlogN). Someone may argue that why teaching an algorithm which that poor performance, why not teach insertion or selection sort which is as easy as bubble sort, and performs better. IMHO, easiness of algorithm depends upon programmer as much as on algorithm itself. Many programmer will find insertion sort easier than bubble sort but again there will be a lot many who will find bubble sort easier to remember, including myself. This is true, despite many of them have used insertion sort unknowingly in real life, e.g. sorting playing cards in hand. Another reason for learning this sorting algorithm is for comparative analysis, how you improve algorithms, how you come up with different algorithms for same problems. In short, despite of all its shortcomings, bubble sort is still the most popular algorithm. In this tutorial, we will learn how bubble sort works, complexity and performance of bubble sort algorithm,  implementation and source code in Java and a step by step example of bubble sort.

Tuesday, August 12, 2014

How to find all Pairs in Array of Integers whose Sum is equal to a given Number

Practising coding problems are very important to do well in any programming interview. You should at your best on data-structures like array, linked list, and string to clear any programming interview, and believe me you can not do this in one day or one week. It's rather long process of learning through coding, and that's where these small coding problems helps. Today, we are going to look at another interesting programming question from array; write a program to find all pairs of integers whose sum is equal to a given number. For example if input integer array is {2, 6, 3, 9, 11} and given sum is 9, output should be {6,3}. Sounds simple? may be, but this exactly question has appeared in technical interview at Amazon, Microsoft, Facebook and couple of other fortune five tech companies in past. Many of you might already heard about this question and some of you may already know the solution of this problem as well, but it's not enough to know just the answer. In a programming interview, many things matter apart from correct solution. For example, first thing Interviewer look is whether candidate can ask right questions or not. So before jumping straight to coding, spare a second or two to think about problem and clear any doubt you may have. For example, you can ask following questions based upon problem statement given above :

Friday, August 8, 2014

Difference between getPath(), getCanonicalPath() and getAbsolutePath() of File in Java

File API is very important one in Java, it gives access of File system to Java programs. Though Java's file API is rich, there are lot of subtleties to know when you use them. One of the common query programmer's has about file path is difference between getPath(), getCanonicalPath() and getAbsolutePath() methods, why there are three methods to get file path and what happens if you call getPath() in place of getCanonicalPath(). By the way, before understanding difference between getPath(), getAbsolutePath() and getCanonicalPath() let's understand the concept behind this methods, i.e. difference between path, absolute path, and canonical path. In general, a path is way to get to a particular file or directory in a file system, it can be absolute (also known as full path) or relative e.g. relative to current location. Absolute path defines path from root of the file system e.g. C:\\ or D:\\ in Windows and from / in UNIX based operating systems e.g. Linux or Solaris. Canonical path is little bit tricky, because all canonical path is absolute, but vice-versa is not true. It actually defines a unique absolute path to the file from root of the file system. For example, C://temp/names.txt is a canonical path to names.txt in Windows, and /home/javinpaul/test/names.txt is canonical path in Linux. On the other hand, there can be many absolute path to the same file, including the canonical path which has just seen. For example another absolute path to the same file  in Windows can be C://temp/./names.txt; similarly in UNIX /home/javinpaul/test/./names.txt is another absolute path to the same file. So you can say that, absolute path may contain meta characters like . and .. to represent current and parent directory. In rest of this article, we will learn difference between getPath(), getAbsolutePath() and getCanonical() Path by looking at values it return for a particular file.

Wednesday, August 6, 2014

5 Good Books to Learn Unit testing, JUnit and TDD for Java Developers

Unit testing is very, very important thing to learn adapt. I would say this is the single most practice in my book which differentiate a good programmer with a professional programmer. It's one way you can see how disciplined a programmer is? It's also the best way to write clean code; a code which can stand test of time, a code which is flexible enough to accommodate future changes and a code which you don't afraid while changing. Despite several efforts of promoting unit testing by programming community and emphasizing unit testing by many notable programmers, it's still one of the lacking practice. In my effort to encourage developers to do unit testing, I try to make it natural rather than a special thing. I have found that it's not that programmer doesn't want to test or they don't have time, it's because they don't really know how to unit test a non-trivial code. It's easy for someone to write unit test for palindrome or prime factor program, but when it comes to write unit test for a feature you are developing which involves database connection, threads, has dependency on other module and don't have a clear entry point, programmer's lost the zeal and enthusiasm. Since user or managers doesn't care about unit tests, programmer really don't push themselves to the level they usually do to make a functional code working. How do we solve this problem? How do you develop that code sense to write unit test? How do you decompose a big feature into small units which can be independently testable? Does it sounds like I am talking about Test driven development (TDD)? Well, Yes. Even if you don't follow TDD in it's true sense, it will help you to learn many tricks and techniques to unit test your code. In this article, I am going to share 5 books, which you would love to read, which will help you to learn unit testing and master the art or writing good tests. Unit testing and JUnit is synonymous in Java world, so most of these book will teach you unit testing using JUnit. This is good, because a sound knowledge of how JUnit works, and how you can use different JUnit annotations will encourage you to write more tests.

Monday, August 4, 2014

How to Send Email from Java Program with Example

Sending Email from Java program is a common requirement. It doesn't matter whether you are working on core Java application, web application or enterprise Java EE application, you may need to send email to alert support personal with errors, or just send email to users on registration, password reset or asking them to confirm their email after registration. There are many such scenarios, where you need ability to send emails from Java program. In mature applications, you already have a module or library dealing with all king of email functionality and issues e.g. ability to send attachments, images, including signatures and other rich text formatting on emails, but if you have to code something from scratch then Java's Mail API is perfect place. In this article, we will learn how to send emails from Java application using mail API ( javax.mail ) . Before writing code, you must know some email basics e.g. you need a SMTP (Simple Mail Transfer Protocol) server. If you are running your Java application in Linux, then you should know that SMTP daemon by default listen on port 25. You can use any mail server to send emails from Java, including public email servers like GMail, Yahoo or any other provider, all you need is their SMTP server details e.g. hostname, port, connection parameters etc. You can also use SSL, TLS to securely connect and send emails, but in this example we have kept it simple and just focusing on minimum logic to send mail from Java application. In further articles, we will learn how to send mail using attachments, how to send HTML formatted email, how to attach images in emails, how to use SSL authentication to connect GMail Server and send emails etc. For now, let's understand this simple example of Java Mail API.

Friday, August 1, 2014

How to See difference between two Files in Eclipse - Text Comparision

One of the common task for every programmer is is to compare two files and find out difference between them. You would do this while comparing same file from different release version or from different environment to find out exactly what has changed. Though there are lot of good tools already exists to compare two files e.g. diff command in UNIX, Win Merge and Beyond compare in Windows, they are external tools. Beyond compare is not even free, but to be frank it's worth of money. I would like to compare two files directly from Eclipse to avoid switching to another program for a simple task. Actually, I have been using Beyond compare from long time, but I have practising to do every task ( which I can ) from Eclipse to save time by avoiding transition between multiple applications. This leads me to find out how do I compare two files in Eclipse, it could be Java source files, text files, or simply .properties or XML files. This search lead me to find the option I am going to share you with you guys here. I was very surprised that, even though I was using text comparison feature of Eclipse to see difference between local file with remote file in CVS, SVN, TFS and other source control systems in Eclipse for more than 5 to 6 years, I had missed this important feature to compare two totally unrelated files. This is a very good example of how much Java developer know about the IDE they use every day. There are many such features, and I am sure you guys can share something similar too. By using this "compare with each other option" you can just select two files and compare it right there in Eclipse itself.