Pages

There are lots of programming exercise in Java, which involves printing a particular pattern in console, one of them is printing Floyd triangle in console. In Floyd triangle there are n integers in the nth row and a total of (n(n+1))/2 integers in n rows. This is one of the most simple pattern to print but helpful in learning how to create other more complex patterns. Key to develop pattern is using nested loops and methods like System.out.print() and println() appropriately. Actually pattern based programming task are originally designed to master loops in programming. A good programmer should be able to look a pattern and break into nested loops. A more formal definition of Floyd's triangle : "It's a right angled triangle of array of natural numbers, which is named after Robert Floyd. It is defined by filling the rows of the triangle with consecutive numbers, stating with 1 in the top left corner".

It looks like following pattern :

123456789101112131415

Your task is to print this table using nested loops in Java. Main point is to build the logic by yourself, this will help you a lot in the long run.

Java and null are uniquely bonded. There is hardly a Java programmer, who is not troubled by null pointer exception, it is the most infamous fact about. Even inventor of null concept has called it his billion dollar mistake, then why Java kept it? Null was there from long time and I believe Java designer knows that null creates more problem than it solves, but still they went with it. It surprise me even more because Java's design philosophy was to simplify things, that's why they didn't bothered with pointers, operator overloading and multiple inheritance of implementation, they why null. Well I really don't know the answer of that question, what I know is that, doesn't matter how much null is criticized by Java developers and open source community, we have to live with that. Instead of ruing about null it's better to learn more about it and make sure we use it correct. Why you should learn about null in Java? because If you don't pay attention to null, Java will make sure that you will suffer from dreaded java.lang.NullPointerException and you will learn your lesson hard way. Robust programming is an art and your team, customer and user will appreciate that. In my experience, one of the main reasons of NullPointerException are not enough knowledge about null in Java. Many of you already familiar with null but for those, who are not, can learn some old and new things about null keyword. Let's revisit or learn some important things about null in Java.

Do you know what is shortcut of doing static import in Eclipse? Well I didn't know before, but today I come to know that shortcut Ctrl+Shift+M (Source > Add Import) can not only be used to add missing imports but It can also help with static import in Java program. Suppose you are using lots of static variable from a utility class e.g. TimeUnit by referring them with class name, just like we refer static variable. In Eclipse IDE, you can select the whole reference variable and press Ctrl+Shift+M and it will automatically import that static element using static import in Java.
For example, if you have following code in your class, you can select TimeUnit.SECONDS and then use shortcut Ctrl+Shift+M to statically import SECONDS variable in your program, as shown in first and second screenshot.

If you are a beginner and just started learning Java, you might be thinking where exactly Java is used? You don't see many games written in Java except Minecraft, desktop tools like Adobe Acrobat, Microsoft Office are not written in Java, neither is your operating systems like Linux or Windows, so where exactly people use Java? Does it have any real-world application or not? Well, you are not alone, many programmers ask this question before starting with Java, or after picking Java is one of the programming language of choice at the graduate level. By the way, you can get a clue of where Java is used by installing Java at your desktop, Oracle says more than 3 billion devices run Java, that's a huge number, isn't it? Most major companies use Java in one way or other. Many server-side applications are written in Java to process tens of millions of requests per day, high-frequency trading applications are also written in Java e.g. LMAX trading applications, which is built over their path-breaking inter-thread communication library, Disruptor. In this article, we will see more precisely, what kind of projects are done in Java, which domain or sector Java is dominating and where exactly Java is used in real-world?

JSON is a text format is a widely used as data-interchange language because its parsing and its generation is easy for programs. It is slowly replacing XML as most powerful data interchange format, as it is lightweight, consumes less bandwidth and also platform independent. Though Java doesn't have built in support for parsing JSON files and objects, there are lot of good open source JSON libraries are available which can help you to read and write JSON object to file and URL. Two of the most popular JSON parsing libraries are Jackson and Gson. They are matured, rich and stable. Though there are couple of more libraries there like JSON simple, which we are going to use in this example. Between Jackson and Gson, later does very nice job in mapping JSON object and serialization. JSON is also used in request and response between client server communication. In this tutorial we are going to see how to read and write JSON to file using JSON.Simple library, and you will notice yourself how simple working with JSON is.

Since we don't have JSON support in JDK, we need to download this open source library. If you are using maven to download JAR and managing dependency, if not then you should, then you can just include following dependencies in your pom.xml file :

Otherwise, you have to add the newest version of json-simple-1.1.1.jar in CLASSPATH of your Java program. Also, Java 9 is coming up with built in JSON support in JDK, which will make it easier to deal with JSON format, but that will not replace existing Jackson and GSON library, which seems to be very rich with functionality.

One of the most frequently asked question on programming interviews is, write a program to find the missing number in an array in Java, C# or any other language; depending upon which language you choose. This kind of coding interview questions are not only asked in small start-ups but also on some of the biggest technical companies like Google, Amazon, Facebook, Microsoft, mostly when they visit the campus of reputed universities to hire graduates. Simplest version of this question is to find missing elements in an area of 100 integers, which contains numbers between 1 and 100. This can easily be solved by calculating the sum of the series using n(n+1)/2, and this is also one of the quickest and efficient ways, but it cannot be used if the array contains more than one missing numbers or if the array contains duplicates.

One of the oldest coding practice is to keep line width 80, Why? I believe it was to make your code more readable in the age of small monitors so that whole content can fit in screen, or it might have origin from the age of punch card, which was used to be 80 column wide; but do you think this rule make sense in 2014? We are now living in the age where most of the developers has got large monitors, which can show up-to 180 characters, doesn't this is wastage of precious monitor space? It also make your code unnecessary long, than it actually is. I first come to know about line wrapping at 80, while reading Oracle Code Conventions for the Java Programming Language, which was last revised at April 20, 1999, which under indentation says

4.1 Line Length
Avoid lines longer than 80 characters, since they're not handled well by many terminals and tools.

Note: Examples for use in documentation should have a shorter line length-generally no more than 70 characters.

I have recently come across a code snippet, where programmer was using System.exit() if application failed to acquire necessary resource after couple of retry. His reasoning was that since, application cannot function, if essential resources like database is not available or there is no disk space to write records in File system. Ok, I hear you; but System.exit() in Java Web application, which runs inside either web server or application server, which itself is Java program is not a good idea at all. Why? because invoking System.exit() kills your JVM, invoking this from Tomcat or Jetty, will not only kill your application but most likely server itself. This can be potentially dangerous, if that server also host other critical application, which is not uncommon at all. As per my experience, System.exit() calls are quite common in overly broad try-catch blocks in web application start-up code that loads environment variables, properties files, connect to MQ Series, establishes database connection, opens socket connections, etc. This is still ok, if you are writing core Java based server, where each application has their own JVM, but with web application deployed on Tomcat, JBoss, WebSphere, Weblogic or any other application server, using System.exit() is big mistake. In worst case can result in outage for lots of other critical application. On the other hand, there are ways to prevent your web application from someone else’s mistake, by enabling Security Manager. System.exit() and Runtime.exit() both goes through the security manager. Enabling Security manager will catch these calls and reduce them into an exception rather than shutting down the whole VM. It's not difficult to enable the security manager in most application servers, Tomcat, JBoss both has documented steps to enable security Manager.

I have said this before that Java Enum is very versatile and can do lot more than you normally expect from it. We have seen lot of examples of Enum in my earlier posts e.g. writing thread-safe Singleton using Enum and 10 ways to use Enum in Java. In this article, we will learn a new way to use Enum, for implementing Strategy design pattern. Strategy pattern is one of the famous pattern, which takes advantage of polymorphism, to remove switch cases and strive for open close design principle. Formally it encapsulate related algorithm, known as strategy and make them interchangeable. So your Client, also known as Context, can use different algorithm or strategy, without any modification. One of the key advantage of Strategy pattern is it's extensibility, i.e. introducing new Strategy is as easy as writing a new class and implementing Strategy interface, with Enum, instead of creating separate class, you creates a separate Enum instance, which means less number of classes and full benefit if Strategy pattern.

Many times, I have seen questions like why should we use interface in Java, if we can not define any concrete methods inside interface? Or even more common, What is the real use of interface in Java? I can understand beginners asking this question, when they just see name of the method inside interface and nothing else. It takes time to realize real goodness or actual use of interface or abstraction in Java or any object oriented programming. One reason of this is lack of experience in really modelling something real in program using object oriented analysis and design. In this article, I will try to answer this question and give you couple of reason to use interface in your code. If you have good understanding of Object oriented basics e.g. Polymorphism, then you know that it allows you to write flexible code. Interface or abstraction are key to achieve polymorphism, when a caller use interface for calling a method, he introduce flexibility and dynamism in code, as that code will work with any implementation of that interface, not just the present concrete implementation. You will never going to get this flexibility, if you use concrete classes for calling methods, we will see this in more details in next section. Also Programming for Interfaces, is also well recognized and one of the key object oriented design principle for coding. Another use of interface in Java is that, it opens new opportunities for other goodies e.g. design patterns. Lot's of design patterns are heavily relied on interfaces and Polymorphism e.g. Decorator, Composite, Proxy or Adapter pattern, all implements same interface, as there target, and because they are based on interfaces, they can be used interchangeably.

While working with memory mapped file, you may get java.io.IOException: Map failed error, which is mainly caused by Caused by: java.lang.OutOfMemoryError: Map failed error as shown below. This error usually comes while mapping a big file in memory e.g. trying to map a file greater than 1 or 2GB

batch files and shell scripts are developers best friend, they help to improve productivity a lot. They not only help you to automate boring, time consuming task but also saves lot of time doing and doing them again. Batch file also reduce chances of error, once tested and encourage re-usability by sharing them across team or people with similar needs. Though not every programmer, developer or computer user has mindset to use batch file, something it's too difficult to write, some just not able to fight with initial resistance and many of them are not even aware of batch file. As a Java programmer, you really don't need to learn these stuff, as almost everybody who use windows operating system for more than year, knows about it. Anyway knowing is not enough, main thing is adapting and taking full advantage of them, developing mentality towards scripting, automation and writing batch files. Remember, shell scripting is one of the important skill to get a programming job and more important to support application running on UNIX operating sytem in Investment banking domain. Writing batch scripts are not full blown scripting, but it's lighter form of it, It works best to train yourself and develop that scripting mentality to improve productivity. In this article, we will learn how to write a batch file in windows 8 operating system and revisit some important things about batch file.

Though both jQuery ready event and window onload event is used to perform task when page is loaded, there is subtle difference between them. jQuery document.ready method, which is not method but a jQuery event is fired, when DOM is ready i.e. all elements of DOM is available, but not necessarily all contents e.g. images and video, on the other hand JavaScript built-in window.onload event is fired when the HTML document is complete loaded, including DOM and all it's content e.g. images, audio and videos. Because of this reason, you may see that scripting code defined in jQuery $(document).ready() executes before code defined on window.onload event, especially if loading of images take long time. By the way difference between JavaScript window onload event and jQuery document.ready event is also one of the popular jQuery Interview Question, asked to both beginners and experienced web developers. In this article, we will explore some key differences between jQuery ready vs onload and will find it out when to use jQuery ready method vs window onload event.

Many Java programmers confused themselves like hell while writing multi-threaded Java programs e.g. where to synchronized? Which Lock to use? What Lock to use etc. I often receive request to explain about how to use Locks in Java, so I thought to write a simple Java program, which is multi-threaded and uses rather new Lock interface. Remember Lock is your tool to guard shared resource which can be anything e.g. database, File system, a Prime number Generator or a Message processor. Before using Locks in Java program, it’s also better to learn some basics. Lock is an interface from java.util.concurrent package. It was introduced in JDK 1.5 release as an alternative of synchronized keyword. If you have never written any multi-threading program, then I suggest first start with synchronized keyword because it’s easier to use them. Once you are familiar with working of multi-threading program e.g. How threads share data, how inter thread communication works, you can start with Lock facility. As I told you Lock is an interface, so we cannot use it directly, instead we need to use its implementation class. Thankfully Java comes with two implementation of java.util.concurrent.locks.Lock interface, ReentrantLock and ReentrantReadWriteLock, later provides two more inner implementation known as ReentrantReadWriteLock.ReadLock and ReentrantReadWriteLock.WriteLock. For our simple multi-threaded Java program's purpose ReentrantLock is enough.

For some unknown reasons many Java programmers are not very comfortable with IO package. I don't know why, but I have found them much more comfortable with java.lang and java.util than java.io. One possible reason of this could be that, writing IO code require a bit of C++ like programming, which involves doing clean-up, releasing resources once done etc. Since Java made coding a lot easier by taking care of memory management, unknowingly it also introduced bad practice of not releasing resource after use e.g. database connections, socket connection, files, directory, printers, scanners or any other scarce resource.

What's in name? "A rose by any other name would smell as sweet" is a famous quote from William Shakespeare's classic Romeo and Juliet, but sorry to say, name matter a lot in programming and coding. It's also said that code is the best document for any software, because any other document or comments can become outdated quickly, but code will always tell you truth; If code is then best document than names are most critical element of it. Every effort, small or big, invested while naming variables or methods, pays in both short term and long term. In fact, if you ask me just one coding practice to follow, It would definitely recommend giving meaningful names to your variables and methods. One reason, I push for this coding practice is because it improves readability of any algorithm or program drastically. Since every programmer spends more time reading code than writing, It would make a lot of sense to give meaningful names to your programming element. Readability is also one of the most important aspect of clean code. If you happen to read Clean code, the book by Uncle Bob, you would have seen a whole chapter on meaningful names, this just shows how important it is to name your variable, methods, classes and packages properly. Though these programming best practices are given from a Java programmer's perspective, they are equally useful in any other programming language. In fact, most of them are independent of any programming language and can be used while writing bash script, SQL stored procedures, C++ code and any other computer program. In fact you will value these practices more in case of shell script and database stored procedure because they don't have tools as smart as Java IDEs.

The year of 2014 is looking like a year of biggest software bug and vulnerabilities. Earlier this year, internet was bleeding by Heartbleed vulnerability and now it's shocked by ShellShock bug. To me it looks like even bigger than Heartbleed, just because it's a bug in Bash Shell, our own bash shell, most popular among all UNIX shells like C and K. Given most of the servers in Investment banks, Insurance companies, Clouds and e-commerce domain are Linux Servers with bash being most used shell, impact is quite large. I am sure people with Microsoft stack is smiling somewhere :), but wait, read the full article. First details of Shellshock bug emerged Wednesday last week, since then it has gone viral, both online and offline. People are busy talking about it and engineers are busy patching Servers, computers, routers, firewalls and other computing resources using vulnerable versions of bash. It has triggered patching almost everywhere. I am sure many of my readers are still puzzling with what is this ShellShock bug? For those, It's an example of an arbitrary code execution (ACE) vulnerability, which means attacker can execute their code on your vulnerable server. What this mean to you? Well if they can execute their own command they can do anything to your server and business. To start-with they can stop your servers, delete files, stole passwords and can take complete control for the machine, operating them remotely. Typically, arbitrary code execution vulnerability attacks are very sophisticated and require expert understanding of the internals of code execution, memory layout, and assembly language, which makes them very hard. Thanks to Bash ShellShock bug, now even a naive programmer can launch such kind of powerful attack to take control of vulnerable server. To give you an example, due to ShellShock vulnerability, anyone can take control of your web server by simply sending an HTTP request. This is massive, but fortunately impact is only limited to servers, where server side program pass user supplied information to Bash Shell, if your Java server doesn't do that, you are probably safe from that path of attack.

If you have worked in Oracle database ever, you would definitely have seen ORA-00904: invalid identifier error. Doesn't matter which version you are working 10g, 11g or 12g, this is one of the most common error comes while doing CRUD (Create, Read, Update, and Delete) operations in Oracle. By the way, if you are beginner, SELECT, INSERT, UPDATE and DELETE are used to perform CRUD operation in Oracle database. What do you do if you get this error while running in SQL script? Like any error, you should first pay attention to error message, what is Oracle trying to say here. Invalid identifier means the column name entered is either missing or invalid, this is one of the most common cause of this error but not the only one. Some time it come if you use names, which happened to be reserved word in Oracle database. Now how do you resolve it? We will learn in this article, by following series of examples which first reproduce this error and later suggest how to fix it.

Today one of my readers asked about what is the latest OCPJP or SCJP exams available, which prompted me to browse through Oracle's certification website. During my casual browsing, I noticed this new Java 8 certification. I said great, within six months of Java 8 release we now have Java SE 8 certification available, programmer still digesting changes from Java 8 now have a chance to be certified on latest Java 8. The certification is called, "Oracle Certified Associate, Java SE 8 Programmer - 1Z1-808" and has written for the Java SE 8 release. The format of the exam is similar to the previous certification e.g. Java SE 7 Associate and Professional exams (1Z1-803 and 1Z1-804). The exam is in beta and as per their website, exam score reports will be available in CertView approximately 11 weeks after the close of the Beta Exam. You will receive an email with instructions on how to access your beta exam results.

Writing multi-threaded and concurrent programs is not easy, not even in Java. Even senior developers, including myself, make mistakes while writing concurrent Java applications. This is also one of the trickiest area of Java programming language, where misconceptions outnumbers concepts. Considering amount of misconception an average Java programmers has about multi-threading and concurrency, I thought to start a new series about common multi-threading mistakes done by Java programmers; what is better way to learn from common real word mistakes. Learning from mistakes has another name Experience, but if you only learn from your mistakes then there is only limited things you can learn, but if you learn from other peoples mistake, you can learn much more in short span of time. Have you ever thought, Why writing multi-threaded code is difficult? IMHO, primarily reason for this is that it multi-threading makes it hard for a code to speak for itself. Programmer read code sequentially to understand how it's executed, but it is only correct if one and only one thread is executing it. That's why Single threaded code are easy to read and debug. As soon as two threads comes into picture, It become very difficult to make prediction about how your code behave, especially in the absent of any synchronization rules e.g. rules enforced by Java Memory Model. Without JMM you can not make correct prediction about your code in a multi-threaded environment, because it's possible for one thread to stop at arbitrary point and another thread at different point. Situation becomes even more tricky if those threads are sharing data between them e.g. in form of objects, a poorly written multi-threaded program can cause deadlock, race condition and responsiveness issues, which will prevent a Java application to fulfil it's promise. I hope, in this series we can learn from each other's mistake and take a step forward on writing correct multi-threaded application in Java.

One of the most common task in any Linux is creating directories, and most of us spend a lot of time creating complex directory structure in UNIX. I am sure you know about mkdir command, we have been using this command in almost every operating system e..g DOS, Windows, Linux, OS/2, Solaris or many other *NIX operating system. It is one of the basic command but as important as find, grep or chmod. mkdir stands for "make directory" and this command is literally used to create directories. Suppose, you need to create a directory tree like /opt/software/java/app/config, how are you going to create these directories? One by one right? Well, yes you can use mkdir and command to create these directories one by one as shown in below example :

Conducting Interview is not cheap and costs both time and money to a company. It take a lot of time to find the right candidate for a job from 100s resume you receive from consultants and agents. They will always tell you that this guy is a Java Guru, this one is SQL Expert and next one is the full stack developer you are looking for. If you have trust them blindly and invite all of them for face-to-face interview, you are going to be disappointed. One of the first thing you should do is to filter candidates who claims to have certain skills e.g. SQL but doesn't have them, the faster you can weed out those candidates the cheaper will be the hiring process. A phone screening interview is just for that purpose, it doesn't cost you much and also suitable for candidate, as they don't have to take off and come down to your office. It's flexible for both the parties.

Coding is an integral part of programming and we all somehow learn to code by following examples here and there. What is more difficult is to write good code. You can easily find programmers in Java, C++, Ruby or Python, but finding programmers, who are also a good coder is very difficult. Some universities have a good curriculum and practical classes to teach coding better than others, but most of these great codes are self-taught. The point is self-learning is VERY important in the field of Programming and Coding, you just cannot rely on your college and university to make you an expert programmer, you have to make that extra effort to distinguish yourself from the group. What could be best by learning coding and wisdom of programming from those who have gone through the same path?

HTML is core of web, all the page you see in internet are HTML, whether they are dynamically generated by JavaScript, JSP, PHP, ASP or any other web technology. Your browser actually parse HTML and render it for you. But what would you do, if you need to parse an HTML document and find some elements, tags, attributes or check if a particular element exists or not from Java program. If you have been in Java programming for some years, I am sure you have done some XML parsing work using parsers like DOM and SAX, but there is also good chance that you have not done any HTML parsing work. Ironically, there are few instances when you need to parse HTML document from core Java application, which doesn't include Servlet and other Java web technologies. To make the matter worse, there is no HTTP or HTML library in core JDK as well; or at least I am not aware of that. That's why when it comes to parse a HTML file, many Java programmers had to look at Google to find out how to get value of an HTML tag in Java. When I needed that I was sure that there would be an open source library which will does it for me, but didn't know that it was as wonderful and feature rich as JSoup. It not only provides support to read and parse HTML document but also allows you to extract any element form HTML file, their attribute, their CSS class in JQuery style and also allows you to modify them. You can probably do anything with HTML document using Jsoup. In this article, we will parse and HTML file and find out value of title and heading tags. We will also see example of downloading and parsing HTML from file as well as any URL or internet by parsing Google's home page in Java.

Recently I face an strange issue while using Maven in Eclipse via M2Eclipse plugin. I have created a Maven Java project in Eclipse and subsequently tried to add Spring framework as dependency, to my surprise, nothing was happening. Eclipse was not able to search dependency in Maven central repository. I was surprised because I have never faced this issue while I was using M2Eclipse plugin from long time. After some trial and error, I realized that this is my brand new workspace and I am running with Eclipse Luna, newest version of Eclipse which I had just downloaded couple days of back. My first hunch was that Eclipse might not able to connect to Internet, and to verify that I tried connecting Eclipse market place, and boom it was working fine. Then I quickly checked Maven settings in Eclipse and found that the option which is required to download and build the index was not turned on. The check box was unchecked there. To give you some background about how Eclipse search dependency on Maven remote repository, be it default Maven central or internal Nexus repository. Eclipse search artifact dependency on repository's index file. If that file is not download or not exist due to any reason, Maven's dependency search will not work in Eclipse. That's why you need to check the option "Download repository Index updates on startup". If this option is enabled then Eclipse will download repository index from configured location e.g. Maven central or Nexus and every time Eclipse will start it will just do update. You should also check the option "Do not automatically update dependencies from remote repositories", because that will download latest build every time they were pushed into Maven central repository. By the way, this error has nothing to do with Eclipse Luna. I received emails from my readers that some of them not able to add dependency in Maven project even in older versions of Eclipse e.g. Kepler and Indigo version. It is totally due to absent of artifact index file. One you enable "Download repository Index updates on startup" option and restart Eclipse, you will see that Eclipse is updating index at the bottom right corner, once this update this finish, you would be able to add dependency using Eclipse Maven GUI. In worst case, if your problem doesn't resolve even after enabling and restarting Eclipse, try re-building Index from Maven repository view in Eclipse, as shown in images attached here.

One of the important aspect of software development is maintenance, and it's proven by experience that a software which keeps visibility of its component low is more maintainable than the one who exposes its component more. You won't realize it upfront, but you will miss it badly, while redesigning your application. Since maintaining backward compatibility is must have requirement for many app, you end up patching and repeating same mistakes. You can not do much because lots of other applications are tightly integrated with your class and interfaces. Java has always put encapsulation on priority, provided support of access modifiers from very beginning. It provides three ways to control visibility of any Type e.g. class or interface, by making them public, package-private or private. What happened to protected, can't we use protected with class or interface. No you can't, you can only use two access modifier with types, protected is not a legal modifier for class and interface.

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.

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.

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-threading, Collections 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.

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.

Practising coding problems are very important to do well in any programming interview. You should at your best on data-structures like an 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 a long process of learning through coding, and that's where these small coding problems help. Today, we are going to look at another interesting programming question from the 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? maybe, but this exact question has appeared in a technical interview at Amazon, Microsoft, Facebook and couple of another fortune five tech companies in past. Many of you might already heard about this question and some of you may already know the solution to 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 a candidate can ask right questions or not. So before jumping straight to coding, spare a second or two to think about the problem and clear any doubt you may have. For example, you can ask following questions based upon problem statement given above :

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.

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.

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.

Classpath in Java is not only used to load .class files, but also can be used to load resources e.g. properties file, images, icons, thumbnails, or any binary content. Java provides API to read these resources as InputStream or URL. Suppose, you have a properties file inside config folder of your project, and you want to load that properties file, how do you do that? Similarly, you have icons and thumbnails for your web applications on icons directory of your project, how do you load them? Answer is by using java.lang.Class' getResource() and getResourceAsStream() method. These method accepts path of resource as String and returns URL and InputStream respectively. You can obtain a reference of Class by calling either getClass() method or by using class literal. If you have an object, then you can call getClass() because its a non-static method, on the other hand, if you don't have any object, you can simply use .class with name of any class e.g. Sample.class will give you reference of java.lang.Class. These methods are available from JDK 1.1 and you can even use them anywhere you have access to core Java library. If you are creating J2ME games or application, you can use these method to load icons and tiles for your game, and all other resource for your application as well.

Java 8 now allows you to add non-abstract method implementations to interfaces by utilizing the default and static keyword. Methods with default keyword are known as default methods or defender methods in Java. Before Java 8, it was virtually impossible to change an interface once published. Any change e.g. addition of a new method would have broken all clients. That's why when Java 8 decided to switch to internal iterator implementation using forEach() method, they face a daunting challenge of breaking all implementation of Iterable interface. Since backward compatibility is top priority for Java engineers, and it wasn't practical to break all clients, they came up with idea of default method.

From long time one reason for me to update to newer Java version was always bug fix and performance improvement. Apart from major changes like Generics in Java 1.5 and Lambdas in Java 8, there are so many small improvements, performance optimization which just goes under radar, one of such change is creating empty ArrayList and HashMap with size zero in JDK 1.7.0_40 update. Many Java developer doesn't even know about these changes, part of the blame lies on Java developers like me, as I hardly read release notes of minor Java updates. Some times these changes are done as part of bug fixes and other time as minor optimization, but given popularity of ArrayList and HashMap in Java application impact of this simple Java optimization is huge.

TCP and UDP are two transport layer protocols, which are extensively used on the internet for transmitting data from one host to another. Good knowledge of how TCP and UDP works is essential for any programmer. That's why the difference between TCP and UDP is one of the most popular programming interview questions. I have seen this question many times on various Java interviews, especially for server-side Java developer positions. Since FIX (Financial Information Exchange) protocol is also a TCP based protocol, several investment banks, hedge funds, and exchange solution provider looks for Java developer with good knowledge of TCP and UDP. Writing fix engines and server side components for high-speed electronic trading platforms needs capable developers with a solid understanding of fundamentals including data structure, algorithms, and networking.

One of the classical program to build programming logic is, write a program to find largest of three numbers. I am sure many of you have already done this exercise in variety of languages including C, C++, C#, JavaScript, Perl, Ruby, PHP etc. This time we will do it in Java. We will first learn the logic by understanding flowchart of largest of three numbers and then we will implement solution using ternary operator in Java. I love this program for its sheer simplicity and how it can help beginners to build logic. As always, you are not allowed to use any library function which can solve this problem directly, your main task is to build logic using primitive language tools e.g. operators. In Java, this problem is also used to teach how ternary operator works, as one of the popular version of this require you to find largest of three numbers using ternary operator.

An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 153 is an Armstrong number, since 1**3 + 5**3 + 3**3 = 153, 371 is an Armstrong number since 3**3 + 7**3 + 1**3 = 371. Along with usual beginner exercises e.g. calculating factorial, reversing string or calculating prime numbers, this is a good exercise to build programming logic. It teaches you basic programming technique of how to use operator for something which is not obvious, for example, to solve this programming challenge, we first need to check if a number is Armstrong or not, and to do this we need individual digits of the number. how do we do that? well there is a programming technique, which you might have learned while doing number palindrome exercise.

Sometimes 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, sometimes 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? The similar question is, should your package be independent and self-contained?

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.

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.

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.

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.

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.

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.

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.

One of the best thing of jQuery is there selectors, which gives jQuery enormous power to find and select DOM elements so easily. If you are coming from JavaScript background then you might love those classical methods e.g. getElementById() and getElementByName(), which has served very well in old days of JavaScript coding, but once you start using jQuery selector, which is quite similar to CSS selector, I am sure you will be forget them. Searching and selecting DOM elements using jQuery selectors are natural, intuitive and super easy. In this jQuery tutorial, you will learn how to find elements using jQuery class and ID selector.

Law of Demeter also known as principle of least knowledge is a coding principle, which says that a module should not know about the inner details of the objects it manipulates. If a code depends upon internal details of a particular object, there is good chance that it will break as soon as internal of that object changes. Since Encapsulation is all about hiding internal details of object and exposing only operations, it also assert Law of Demeter. One mistake many Java programmer makes it exposing internal detail of object using getter methods and this is where principle of least knowledge alerts you. I first come to know about this principle, while reading one of the must read programming book, Robert C. Martin's Clean code. Apart from many good thing the book teaches you, "principle of least knowledge" is one principle, which I still remember.

Singleton class is quite common among Java developers, but it poses many challenges to junior developers. One of the key challenge they face is how to keep Singleton class as Singleton? i.e. how to prevent multiple instances of a Singleton due to whatever reasons. Double checked locking of Singleton is a way to ensure only one instance of Singleton class is created through application life cycle. As name suggests, in double checked locking, code checks for an existing instance of Singleton class twice with and without locking to double ensure that no more than one instance of singleton gets created. By the way, it was broken before Java fixed its memory models issues in JDK 1.5. In this article, we will see how to write code for double checked locking of Singleton in Java, why double checked locking was broken before Java 5 and How that was fixed.

By the way this is also important from interview point of view, I have heard it’s been asked to code double checked locking of Singleton by hand on companies in both financial and service sector, and believe me it’s tricky, until you have clear understanding of what you are doing. You can also see my full list of Singleton design pattern questions to prepare well.

Serialization and SerialVersionUID is always remains a puzzle for many Java developers. I often see questions like what is this SerialVersionUID, or what will happen if I don't declare SerialVersionUID in my Serializable class? Apart from complexity involved and rare use, one more reason of these questions is Eclipse IDE's warning against absence of SerialVersionUID e.g. "The Serializable class Customer does not declare a static final SerialVersionUID field of type long". In this article, you will not only learn basics of Java SerialVersionUID but also it's effect during serialization and de-serialization process. When you declare a class as Serializable by implementing marker interface java.io.Serializable, Java runtime persist instance of that class into disk by using default Serialization mechanism, provided you have not customized the process using Externalizable interface.

If you are coming from C background than there is pleasant surprise for you, Java programming language provides implicit bound checks on Array, which means an invalid array index access is not allowed in Java and it will result in java.lang.ArrayIndexOutOfBoundsException. Array is one of the most used data structure across all programming language and it’s no different in Java. In fact Java API has used array to build several useful data structures e.g. HashMap and ArrayList. These classes also throws IndexOutOfBoundsException if invalid index is supplied to their get(int index) methods. One of the common mistakes Java programmer makes is invalid end condition on classical index based for loops.

One of the common homework/tasks in programming courses is about Prime Factorization. You are asked to write a program to find prime factors of given integer number. The prime factors of a number are all of the prime numbers that will exactly divide the given number. For example, prime factors of 35 are 7 and 5, both are prime in itself and exactly divides 35. Last time I did this exercise when I was in college, and it was something like, writing a program that asks the user for an integer input and then displays that number's prime factorization on the command line. There are variants of this program as well e.g. look at this exercise, Write a program that prompts the user to enter a positive integer and displays all its smallest factors in decreasing order. It's more or less same as the earlier mentioned version of prime factorization problem, but with a catch of displaying them in decreasing order.

Being a Java programmer and Software developer, I have learned a lot from articles titled as What Every Programmer Should Know about ..... , they tend to give a lot of useful and in-depth information about a particular topic, which otherwise is very hard to discover. In my quest of learning, I have come across some very useful articles, which I have bookmarked for reference and multiple reading. I personally think that all programmer can benefit by reading these articles, which makes me write this post and share all of these "What Every Programmer Should Know" articles with you guys. These are from my personal bookmarks. In this article, you will see classic what every programmer should know article from topics like memory, Unicode, floating point arithmetic, networking, object oriented design, time, URL Encoding, String and many more.

Can't load IA 32-bit .dll on a AMD 64-bit platform is a generic error, which comes when a 64-bit process tries to load a 32-bit dll, but when it comes its not that easy to resolve. One of my reader was getting this error tibrvnative.dll : Can't load IA 32-bit .dll on a AMD 64-bit when he was trying to install Tibco Rendezvous 8.2 on his Windows 8 HP Laptop. He was working on Java application which was dependent upon Tibco Rendezvous for inter process communication. After installing Tibco on his machine he was having hard time to run his Java application, first he was getting errors like java.lang.UnsatisfiedLinkError: no tibrvnative in java.library.path and after resolving that he was getting a new error tibrvnative.dll: Can't find dependent libraries.

PDF format is a popular format for sending receipt, email confirmation and other documentation and we often has requirement to create PDF documents using Java, mostly in JSP pages. Since most of official documentation uses PDF format now days, it becomes imperative to support PDF files. Recently I received couple of question regarding suggestion of open source Java PDF libraries, like which is the best open source PDF library in Java or should I use iText or Apache FOP in my Java application for PDF processing. These questions motivates me to write this post. In this article, I will share couple of Java based open source PDF libraries, both FREE and with some licensing fees, which you can use to generate PDF documents in Java projects.

Ever Since Java allows using String variable in switch and case statements, there are many programmers using this feature in code, which can be better written using integer and enum pattern. This was one of the popular features of JDK 7 release, including automatic resource management and multi exception catch blocks. Though I upfront didn't like this feature because of better alternative available in terms of using enumeration type, I am not totally against this feature. One reason of this is convenience and given usage of String in Java program, it's quite handy as well, but I prefer to learn more before using any new feature in production code.

When I first come to know about this feature, I had an idea that String in Switch can be implemented using equals()and hashCode() method, I was more interested on how String in Switch works in Java 7.

One more reason I was curious to know about internal working of this feature because I wanted to ask this during Java interviews, having one of such question makes interviews little more interesting. Testing was simple, you just need to write code using String variables in switch block, and then decompile the code to see, how compiler has translated them.

So what are we waiting for, Let's see how String in switch block actually works?

Cloud computing is Hot, it's the biggest IT trend of last few years and will continue to grow strong in coming future. Cloud computing provides several not-so-easy-to-ignore advantages, especially to public and small enterprises, which cannot afford to own and maintain expensive data centres. Since most of online business now days need high avaibility, scalability, and resiliency, with-in quick time, it's not possible to achieve all these by your own, and cloud computing becomes a best alternative here. Cloud service providers like Amazon Web Services (AWS) has helped several firms to remain focus on their business, without worrying for IT and infrastructure too much, this has yield big result for them.

RowSet interface is another key interface from JDBC API, which extends the ResultSet interface to provide support for the JavaBean component model. Along with convenient methods to set connection parameters e.g. setUrl(), setUsername(), setPassword() and setCommand(), it also defines getters and setters for different data types e.g. getLong() and setLong(). Another feature of RowSet is that it supports event listeners. You can attach listeners to RowSet object to listen for events, much like Observer design pattern. RowSet acts as Subject and notifies Observer on events like change in cursor location, change in row or change in the entire RowSet. There are two types of RowSet available in JDBC 4.1 API, connected and disconnected.

Are you stuck with your coding because you have a byte array and next method in chain needs an InputStream? don't worry Java has solution for that, You can use ByteArrayInputStream to convert byte array to InputStream in Java. This class takes a byte array as source and since it's a sub-class of InputStream, you can easily pass this to any method, which accepts InputStream as parameter. Though most of the API like JDBC and File API allows you to read directly from InputStream, because this allows you to process an arbitrary content with limited heap space. You should take advantage of this and directly read from InputStream instead of getting byte array and then converting them back to InputStream.

In order to make proper use of State and Strategy design Pattern in Core Java application, its important for a Java developer to clearly understand difference between them. Though both State and Strategy design patterns has similar structure, and both of them are based upon Open closed design principle, represents 'O' from SOLID design principles, they are totally different on there intent. Strategy design pattern in Java is used to encapsulate related set of algorithms to provide runtime flexibility to client. Client can choose any algorithm at runtime, without changing Context class, which uses Strategy object. Some of the popular example of Strategy pattern is writing code, which uses algorithms e.g. encryption, compression or sorting algorithm.

It's been almost a month Java 8 is released and I am sure all of you are exploring new features of JDK 8. But, before you completely delve into Java 8, it’s time to revisit some of the cool features introduced on Java 7. If you remember, Java 6 was nothing on feature, it was all about JVM changes and performance, but JDK 7 did introduced some cool features which improved developer's day to day task. Why I am writing this post now? Why I am talking about Java 1. 7, when everybody is talking about Java 8? Well I think, not all Java developers are familiar with changes introduced in JDK 7, and what time can be better to revisit earlier version than before welcoming a new version.

If you have used Hibernate with JPA and using annotation to declare your entity bean then you might have seen this confusing error called "org.hibernate.MappingException: Unknown entity". This error message is so misleading that you could easily lose anywhere between few minutes to few hours looking at wrong places. I was using Spring 3 and Hibernate 3.6 when I got this error,which occurs when addEntity() method was executed. I checked everything, from Spring configuration file applicationContext.xml, Hibernate config file, my Entity class and DAO class to see whether my Entity class is annotated or not, but I was still getting this error message. After some goggling I eventually find that, it was an incorrect import which was causing this error.

Before going to explain specific difference between FileInputStream and FileReader in Java, I would like to state fundamental difference between an InputStream and a Reader in Java, and when to use InputStream and when to go for Reader. Actually, Both InputStream and Reader are abstractions to read data from source, which can be either file or socket, but main difference between them is, InputStreamis used to read binary data, while Reader is used to read text data, precisely Unicode characters. So what is difference between binary and text data? well everything you read is essentially bytes, but to convert a byte to text, you need a character encoding scheme. Reader classes uses character encoding to decode bytes and return characters to caller.

From Java 5 onwards, we have a for-each loop for iterating over collection and array in Java. For each loop allows you to traverse over collection without keeping track of index like traditional for loop, or calling hasNext() method in while loop using Iterator or ListIterator. For-each loop indeed simplified iteration over any Collection or array in Java, but not every Java programmer is aware of some useful details of for-each loop, which we will see in this tutorial. Unlike other popular items from Java 5 release alias Generics, Autoboxing and variable arguments, Java developers tend to use for-each loop more often than any other feature, but when asked about how does advanced foreach loop works or what is basic requirement of using a Collection in for-each loop, not everyone can answer. This small tutorial and example aims to bridge that gap by going through some interesting foreach loop puzzles. So, without any further delay let's see our first puzzle on Java 5 for-each loop.

If you are working in Hibernate framework, then you know that one of the key feature of Hibernate is "lazy initialization", which allows framework to lazily initialize dependencies, relationship or association lazily from database on need basis. For example, if you are dealing with User object, which has relationship with Permission object like one user can have multiple permissions, then Hibernate may choose not to initialize the collection which holds all permissions at the time it initialized User object and instead returns a proxy object. At this point, if you close your session and letter tries to access an attribute from Permission object, you will get "org.hibernate.LazyInitializationException: could not initialize proxy - no Session in Hibernate".