HTML

How to Synchronize ArrayList in Java with Example

ArrayList is a very useful Collection in Java, I guess most used one as well but it is not synchronized. What this mean? It means you cannot share an instance of ArrayList between multiple threads if they are not just reading from it but also writing or updating elements. So how can we synchronize ArrayList? Well, we'll come to that in a second but did you thought why ArrayList is not synchronized in the first place? Since multi-threading is a core strength of Java and almost all Java programs have more than one thread, why Java designer does not make it easy for ArrayList to be used in such environment? The answer lies in performance, there is performance cost associated with synchronization and making ArrayList synchronized would have made it slower. So, they definitely thought about it and left ArrayList as non-synchronized to keep it fast, but at the same time they have provided easy ways to make it synchronized and this is what we are going to learn in this tutorial.

How to break from nested loop in Java

There are situations we need to be nested loops in Java, one loop containing another loop e.g. to implement many O(n^2) or quadratic algorithms e.g. bubble sort, insertion sort, selection sort, and searching in a two-dimensional array. There are a couple of more situations where you need nesting looping e.g.  printing pascal triangle and printing those star structures exercises from school days. Sometimes depending upon some condition we also like to come out of both inner and outer loop. For example, while searching a number in a two-dimensional array, once you find the number, you want to come out of both loops. The question is how can you break from nested loop in Java. You all know about break right? you have seen a break in switch statements, or terminating for, while and do-while loop, but not many Java developer know but there is a feature called labeled break, which you can use to break from nested loop.

Strategy Pattern in Java with Example

Can you tell me any design pattern which you have used recently in your project, except Singleton? This is one of the popular questions from various Java interviews in recent years. I think, this actually motivated many Java programmers to explore more design patterns and actually look at original 23 patterns introduced by GOF. Strategy pattern is one of the useful patterns you can mention while answering such question. It's very popular and there are lots of real world scenario where Strategy pattern is very handy. Many programmers ask me what is the best way to learn design pattern, I say you first need to find how other people use it and for that you need to look at the open source libraries you use in your daily task. JDK API is one such library I use on daily basis and that's why when I explore new algorithms, design pattern, I first search JDK for their usage.

2 Ways to Print Custom String Value of Java Enum

We all know that how powerful enumeration type in Java is, and one of the main strength of enum is that they can implement an interface, they can have an instance variable and you can also override any method inside enum instance. In Java programs, we often need to convert Enum to String type, sometimes just to print values in log file and other time for storing log into database.  By default, when you print an enum constant, it print its literal value e.g. if name of enum instance is RED, then it will print RED. This is also the value which is returned by name() method of java.lang.Enum class. But, there are situations when we want a custom String value for enum constant. For example, I want to print Red instead of RED when I convert Enum to String. How do you do that? Well, there are two ways you can achieve this, first by overriding toString() method for each enum constant and second by using an instance variable to hold custom String value. You can provide custom value while creating Enum constants and later you can call that method which returns custom  String value. In this article, we will see example of these two ways.

How to Find Missing Number in a Sorted Array in Java

Today's coding problem is not very new, it's age old classic from programming interviews. You have a sorted array containing n - 1 unique numbers starting from 0 to n - 1. There is only one number missing in this range and you need to find that out. I mean you need to write a Java method to find the missing number and print it's value in the console. Some of you might have seen this question before, but if you have not been asked this question before, what is the first approach comes into your mind to solve this question? Since only one number is missing, many programmers come up with the approach of iterating over the array and comparing each element with the expected one e.g. first element should be 0, the second element should be 1 and so on. Though this will sort the problem, it will costs you O(n) time. What can you do to improve performance? The key here has we have sorted the array, do you think our earlier solution is taking full advantage of this knowledge, well it is but not fully. What it is doing is performing linear search which is costing O(n), but if you do binary search, which of course need a sorted array, we can reduce the time taken in the range of O(logN). Since numbers are in the range from 0 to n - 1 and are sorted, the first number till the missing one should be same as their indexes. I mean if 0 is not missing, then it must be in the first index i.e. at 0. If you generalize this, you will find out that if the missing number is k then all numbers less than k are located in an array with indexes same as their value. Also number k + 1 will be located at index k, and number k + 2 will be located at index k + 1. What does this mean? Well, it means that missing number is the first cell whose value is not same as its index. So our problem reduces to search in an array to find the first cell, whose value is not same as its index. You can easily find out this by using binary search algorithm in O(logN) time. Our function implements this logic to find the missing integer in a sorted array in Java. You can use this solution to find missing number in array of numbers 1-1000 or 1 -100.

Right way to Compare String in Java

The String is a special class in Java, so is String comparison. When I say comparing String variables, it can be either to compare two String object to check if they are same, i.e. contains same characters or compare them alphabetically to check which comes first or second. In this article, we are going to talk about the right way of comparing String variables, but what is the wrong way? The wrong way is to compare String using == operator. It is one area in which almost every Java programmer  has made mistakes sometimes by comparing two String variable using == operator. Many Java developers are exposed to string comparison very early in their Java journey,  It's often required in their first few programming assignments e.g. write a program to print hello if the user enters "John".  When you first start with String in Java, you create an object using String literal syntax e.g. name = "John" and then compare using == operator, you will get the right answer, but if you take same String as user input, you will not get the correct answer.  Why? because equality operator compares references i.e. if two reference variable points to the same object in the heap then it returns true, otherwise, it returns false.

How to convert String to Date Example in Java Multithreading

Data type conversion is one of the most common tasks in programming and a good programmer must know how to convert one type to another type. There are many times when you will be required to convert a String to java.util.Date object mostly in different format e.g. dd-MM-yy or yyyy-MM-dd or simply yyyy MM dd. For example, client pass dates as String to Server or sometimes we read Date related data from CSV file. Java provides API for parsing String to date using DateFormat class, though Java's Date and Time API is severely criticized, it is also the most used Date and Time format solution. Though Joda Date and Time API is always there and now Java 8 also got new date and time API, many of us don't have the luxury to use it in production. Many enterprise application is still running on Java 5 and Java 6, forget about JDK 7 or 8.

Difference between instance and Object in Java

In Java or other object oriented programming language, we often use Object and instance word interchangeably, but sometimes it confuses beginners like hell. I have been often asked several times, whether object and instance are the same thing or different? Why we sometimes use object and sometimes instance if they are same thing etc? This gives me the idea to write a little bit about it. I will mostly talk about Java conventions perspective. Just like we use word function in C or C++  for a block of code, which can be called by its same, but in Java, we refer them as methods. In Java functions are known as methods, similarly, objects are known as instances in Java. You have a class, which represent a blueprint of a real world thing e.g. Car, and object represents a real world car e.g. your car, my car, a red car or a blue car. They are also known as instances of the car.

How to create User Defined Exception class in Java

Java has the very good support of handling Error and Exception, It has a well-defined Exception hierarchy and language level support to throw and catch Exception and deal with them. Java Programmers often deals with built-in exceptions from java.lang package and several others which are already defined in JDK API e.g. NullPointerException. If you have read Effective Java, you may remember the advice of Joshua Bloch regarding Exception. According to him, you should try to reuse the Exception classes provided in the JDK, e.g., IndexOutOfBoundException, ArithmeticException, IOException, and java.lang.ArrayIndexOutOfBoundsException , instead of creating new ones for a similar purpose. But there are cases when a user-defined, the custom exception provides a better opportunity to deal with special cases.

How to test if an Array contains a value in Java - Linear Search

One of the common coding question from Java interviews is how to test if an Array contains a certain value or not? This is a simple question but sometimes interview pressure makes candidates nervous. Since array in Java doesn't have any inbuilt method for search, interviewer prefers to ask this question, to see how a candidate deals with such situation. If you have good knowledge of Java API then you will immediately come to know that there are alternatives available e.g. binary search of Arrays class or taking advantage of ArrayList contains method by first converting your array to ArrayList. If you come up with those solutions, Interviewer will surely ask you to write down a method to search an element in an array without using any library method. You can easily solve this question if you know linear search or binary search algorithm.

How to Convert a Double to Long in Java - Example Tutorial

We often need to convert a floating point number into integral number e.g. a double or float value 234.50d to long value 234L or 235L. There are a couple of ways to convert a double value to long value in Java e.g. you can simply cast a double value to long or you can wrap a double value into a Double object and call it's longValue() method, or using Math.round() method to round floating point value to a nearest integer. Te right way to convert a double value to a long in Java really depends on upon what you want to do with the floating point value. If you just want to truncate the double value to remove zero and take an integer value, you can simply cast double to long. If you have Double object instead of the double primitive type then you can also Double.longValue() method, this doesn't do anything but just cast the double primitive wrapped inside the Double object to long.

Modulo or Remainder Operator in Java

Modulo Operator is one of the fundamental operators in Java. It's a binary operator i.e. it requires two operands. In a division operation, the remainder is returned by using modulo operator. It is denoted by % (percentage) sign. For example 5%2 will return 1 because if you divide 5 with 2, the remainder will be 1. For a programmer it's very important to know how to use this operator, they are very important to build logic. For example, in many cases like reversing a number or checking if a number is a palindrome, you can use modulus operator with 10 to get the last digit, for example, 101%10 will return 1 or 1234%10 will return 4, the last digit. It is one of a rather less used arithmetic operators in comparison of +, -, * and /. One of the important points about the remainder operator which is not known by many Java programmer is that it can also be used with floating point numbers.

How to declare and Initialize two dimensional Array in Java with Example

An array of more than one dimension is known as multi-dimensional array. Two of the most common examples of multi-dimensional arrays are two and three dimensional array, known as 2D and 3D array, anything above is rare. I have never seen 4 dimensional arrays, even 3D arrays are not that common. Now question comes, when do use multi-dimensional array? Any real life example? Well, 2D arrays are very common on platform games like Super Mario Bros to represent screen or terrain; 2D arrays can also be used to represent structures like spreadsheet, or to draw board games like Chess, which requires 8x8 board, Checkers and  Tic-Tac-Toe, which requires 3 rows and 3 columns. Another popular application of multi-dimensional arrays are in matrix manipulation. For example to represent a 3x3 matrix you need a two dimensional array of 3 one dimensional array each containing 3 elements.

2 Examples to Add Zeros at the Beginning of a Number in Java (Padding)

How do you left pad an integer value with zeroes in Java when converting to a string? This is a common requirement if you are working in finance domain. There are so many legacy systems out there which expect the input of certain length, and if your input is shorter than specified length, you got to add zeros at the beginning of number to make them off right length. Java has rich API and thankfully neither converting an integer to String is difficult nor formatting String to add leading zeros. In fact, there are multiple ways to add zeros at the start of a number or numeric String, you can either use powerful String.format() method or it's close cousin printf() method, or you can go back to DecimalFormat class if you are still working in JDK 4. Formatting, in general, is a very useful concept and as Java developer, you must have a good understanding of that.

How to use Static Method in Java with Example

Static methods are one of the important programming concepts in any programming language but unfortunately it is also most misunderstood and misused one. Talking about Java, almost all programmers knows that. static methods belong to the class and non-static methods belong to the objects of the class, but hardly all of them understand what it means. That's why this is one of the popular weed out questions on programming interviews. If a Java programmer doesn't know difference between static and non-static method, he is probably not ready yet, and needs more practice and experience. With half knowledge, making a method static can have serious repercussion , especially in today's heavily multi-threaded Java application. Today, one of my reader message me this question on my Facebook account of Javarevisited, which prompted me to to write this tutorial cum discussion post to give a good explanation or example to clarify the concept. What you have learned is totally find, all we do here is to elaborate your learning by understanding key differences between static methods and instance methods in Java.

Insertion Sort in Java with Example

Insertion sort is next simple sorting algorithm after Bubble Sort. You may not have realized but you must have used insertion sort in a lot of places in your life. One of the best examples of insertion sort is, how you sort your hand in playing cards. We pick one card from the deck, we assume it's sorted, and then we insert subsequent card in their proper position. For example, if our first card is Jack, and our next card Queen then we put that after Jack. Now if next card is King, we put it after the queen, and if we get 9, we put it before jack. So if you look closely, insertion sort is a perfect sorting algorithm to insert a new value into the already sorted list. That's why best-case complexity of insertion sort is O(n), in which case you insert a new number in the already sorted list of integers. Another thing to keep in mind is the size of the list, insertion sort is very good for small list or array, but not so for a large list, where QuickSort, MergeSort, and HeapSort rules.

How to Convert Array to String in Java with Example

Array and String are very closely related, not with anything else but with popularity. Many times we need to convert an array to String or create an array from String, but unfortunately, there is no direct way of doing this in Java. Though you can convert an array to String by simply calling their toString() method, you will not get any meaningful value.  If you convert an integer array to String, you will get something like I@4fee225 due to the default implementation of toString() method from java.lang.Object class. First, I show the type of the array and content after @ is hash code value in hexadecimal. How valuable is that? This is not what I want to see, I was interested in contents rather than hashcode. Fortunately, Java provides a utility class called java.util.Arrays, which provides several utility methods for arrays in Java.

How to Read, Write XLSX File in Java - Apach POI Example

No matter how Microsoft is doing in comparison with Google, Microsoft Office is still the most used application in software world. Other alternatives like OpenOffice and LiberOffice have failed to take off to challenge MS Office. What this mean to a Java application developer? Because of huge popularity of MS office products you often need to support Microsoft office format such as word, Excel, PowerPoint and additionally Adobe PDF. If you are using JSP Servlet, display tag library automatically provides Excel, Word and PDF support. Since JDK doesn't provide direct API to read and write Microsoft Excel and Word document, you have to rely on third party library to do your job. Fortunately there are couple of open source library exists to read and write Microsoft Office XLS and XLSX file format, Apache POI is the best one. It is widely used, has strong community support and it is feature rich.

Why Constructor is Important in Java

In simple word, Constructor is a method like a block of code which is called by Java runtime during object creation using new() operator. Constructor are special in the sense that they have the same name as the Class they are part of. They are also special in a sense that they are called by JVM automatically when you create an object. Have you ever thought about Why do you need a constructor? What benefits it provide? One reason is to initialize your object with default or initial state since default values for primitives may not be what you are looking for. One more reason you create constructor is to inform the world about dependencies, a class needs to do its job. Anyone by looking at your constructors should be able to figure out, what he needs in order to use this class.  For example, following class OrderProcessor needs a Queue and Database to function properly.

Right way to check if String is empty in Java

What do you most of us do while using String in Java? checking whether String is null or empty right? I am sure you know a couple of ways to test whether String is empty or not, but do you know the right way to do it? When we talk about Strings in Java, we can imagine them as arrays of characters, and they are, but in Java, they also object. An empty Java String is considered as the not null String that contains zero characters, meaning its length is 0. However, a Java String that might only contain the white-space character is not considered as empty, it is considered to contain one character and its length is equal to 1. One of the most popular way of checking whether String is empty or not is String class' isEmpty() method, this looks perfect right, it's readable and returns boolean if String is empty otherwise returns false, but the problem is you can not call this method without checking whether String is null or not. In another word, this is not null safe and it will throw NullPointerException if String is null.

Top 10 Java 8 Tutorials - Best of Lot, Must Read

It's almost six months since Java 8 has released and there are so many Java 8 tutorials are written by Oracle, bloggers, and other peoples, but which should you read? Which tutorials are worth of your time? Actually, this question is asked to me by one of my reader called John, he was asking me about some good Java 8 tutorials, which he can read to start with. This encouraged me to take a look at some of the the Java 8 tutorials available on the internet and form a list of best. I have just used three criterion, content, language and length. Because tutorials complement books, they should not be like the book. They should be small enough to complete in few hours and complete enough to give useful information. I also like tutorials, which discusses practical problems and examples.

What is difference between UNION vs UNION ALL in SQL?

Though both UNION and UNION ALL is used to combine results of two SELECT queries, the main difference between them is that UNION doesn't include duplicate record but UNION ALL does. Another difference between them is that UNION ALL is faster than UNION but may look slow because it returns more data which takes more time to travel via the network. The difference between UNION and UNION ALL is one of the tricky SQL questions, especially for developers, who has not used this useful keyword ever. Since UNION clause is not as common as a SELECT clause in SQL, it's usually asked in a telephonic round of programming interviews to check whether the candidate is comfortable with SQL or not. It's in the same league of questions like clustered vs non-clustered index or  primary vs unique keyUNION is very different than other SQL commands because it operates on data rather than columns.

HelloWorld - My First jQuery Program

What is jQuery
jQuery is nothing but JavaScript library that comes with rich functionalities. It's small and faster than many JavaScript code written by an average web developer. By using jQuery we can write less code and do more things, its makes web developer's task very easy. In simple word, jQuery is a collection of several useful methods, which can be used to accomplish many common tasks in JavaScript. A couple of lines of jQuery code can do things which need too many JavaScript lines to accomplish. The true power of jQuery comes from it's CSS-like selector, which allows it to select any element from DOM and modify, update or manipulate it. You can use jQuery to do cool animations like fade in or fade out. You can also change CSS class of a component dynamically e.g. making a component active or inactive. I have used this technique to implement tabbed UI in HTML. I can vouch for jQuery that once you start using it, you will never go back to plain old JavaScript, it's clear, concise and powerful. You will even regret why you are not using jQuery before.

4 Examples to Sort Array in Java

You can use Arrays.sort() method to sort both primitive and object array in Java. This method sorts given array into ascending order, which is the numeric order for primitives and defined by compareTo() or compare() method for objects. For primitive arrays e.g. int,  short, character, float, double or long this method uses  dual-pivot Quicksort sorting algorithm implemented by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch (author of Effective Java) . This algorithm offers O(n log(n)) performance on many data sets that cause other quicksort algorithms to degrade into their worst quadratic performance e.g. O(n^2) and is typically faster than traditional (one-pivot) Quicksort implementations. That's why I always said that prefer library method your own, you can get it right but the amount of exposure library method gets, you will never get for your implementations.

Difference between POST and GET Request in HTTP Protocol

HTTP Protocol supports many method to retrieve data from server or perform any operation on server e.g. upload data, delete file etc. In total, HTTP protocol supports following methods e.g. GET, POST, PUT, DELETE, HEAD, DELETE, OPTIONS and TRACE and HTTP 1.1 reserves method called CONNECT for future use.  GET and POST are two of the most common HTTP methods you would heard or work in web. Though both can be used to send and receive data from client to server, there are some important difference between GET and POST in HTTP, which will help you to understand when you should use GET vs POST while writing your client and server application. HTTP is also programming language independent, doesn't matter whether your client and server is written in Java, or client written in HTML, JavaScript and Server in Java, or client and server both written in .NET, you will use HTTP protocol. In this article, we will learn pros and cons of GET and POST method to choose, which method you should use in HTML forms, considering facts like security, speed and amount of data to transfer.

What is the difference between a Class and an Object in Java?

This article is solely for all beginner programmers, who are learning object oriented programming language e.g. Java, C++ or C# and aspire to do well on any programming interview. The difference between class and object is one of the most common questions, you would like to ask a fresher coming out from college or training institute, but you would be surprised how many beginner Java programmers struggle with this question. Class and Object are two pillars of Object Oriented Programming (OOPS) and a good understanding is a must, but when you ask this question apart from the theoretical and bookish answer that "class is a blueprint and objects are actual things created out of that blueprint", you would hardly get anything substantial. Though that answer is correct and works perfectly, it doesn't differentiate between a programmer, who has just mugged the answer, or the one who truly understand the difference between class and object.

Difference between String literal and New String object in Java

String is a special class in Java API and has so many special behaviours which is not obvious to many programmers. In order to master Java, first step is to master String class, and one way to explore is checking what kind of String related questions are asked on Java interviews. Apart from usual questions like why String is final, or  equals vs == operator, one of the most frequently asked question is what is difference between String literal and String object in Java. For example, what is the difference between String object created in following two expression :
String strObject = new String("Java");
and
String strLiteral = "Java";
Both expression gives you String object, but there is subtle difference between them. When you create String object using new() operator, it always create a new object in heap memory. On the other hand, if you create object using String literal syntax e.g. "Java", it may return an existing object from String pool (a cache of String object in Perm gen space, which is now moved to heap space in recent Java release), if it's already exists. Otherwise it will create a new string object and put in string pool for future re-use. In rest of this article, why it is one of the most important thing you should remember about String in Java.

What is array data structure in Java? Properties, Example and Tutorial

Without any doubt, an array is one of the most used data structure in all programming language, including Java. Pick up any programming language be it functional, object-oriented, imperative or even scripting languages like Python, Bash, and Perl, you will always find array. That's why it's important for any programmer to have a good understanding of  array data structure. The array is used to store elements in the contiguous memory location and many C, C++ programmer can take advantage of a pointer to work with an array. In Java, there are no pointers and arrays are also a little bit different. They are the object, they have length field which denotes how many elements array can store. Arrays are created in the special memory area called heap memory in JVM, which is also created when you start the JVM. What remains same is that you can access the array element in constant time using their index, this works almost similarly in both C, C++ and Java, they start with 0 and ends at length -1, but Java array has an extra caveat that arrays index access are subject to bound check in Java.

Top 21 Frequently Asked Java Interview Questions Answers

If you have been to couple of Java interviews then you know that there are some questions which keep repeating e.g. difference between == and equals() method and may of it's popular cousins like HashMap vs Hashtable, ArrayList vs LinkedList, difference between equals() and hashCode(), or difference between Comparator and Comparable in Java. I call them frequently asked Java interview questions, and I suggest every Java developer to make a list of them for their own reference and revision. I am sure many Java programmer already has such list of questions handy, if not this is a good time to find and make your own list. These are the questions which you simply can't afford to miss, especially at freshers level. They appear at various stage of Java interviews. Most likely you will see them on telephonic round, where Interviewer just want to filter candidates between who knows Java and who doesn't.

QuickSort Example in Java using Recursion - Sorting Algorithm Implementation

Quicksort is one of the very popular sorting algorithms in programming, often used to sort a large list of numbers. Though their are numerous algorithm available to sort list of objects, including integer, string and floating point number, quicksort is best for general purpose. It's a divide and conquer algorithm, where we divide the given array with respect to a particular element, known as 'pivot' such that the lower partition of the array are less than the pivot and upper partition elements of the array are higher than the pivot. Quicksort is also one of the best example of recursion. It's naturally recursive, because it sort the large list by dividing into smaller sub-list and then applying same algorithm on those.

Write a Program to Find Sum of Digits in Java

One of the common programming practice question thrown to beginners is to write a program to calculate the sum of digits in an integral number. For example, if the input is 123456 then output or sum of the digit is (1+2+3+4+5+6) = 21. An additional condition is you can not use any third party or library method to solve this problem. This program is not as simple as it looks and that's why it's a good exercise, you must know some basic programming techniques e.g. loops, operators, and logic formation to solve this problem. Let's see how we can solve this problem using Java programming language. In order to calculate the sum of digits, we must get digits as numbers. So your first challenge is how do you get the digits as numbers?  How do we extract 6 out of 123456?

Why Abstract class is Important in Java with Example

Abstract class is a special class in Java, it can not be instantiated and that's why can not be used directly. At first concept of abstraction, abstract class and interface all look useless to many developers, because you can not implement any method in an interface, you can not create an object of the abstract class, so why do you need them. Once they face biggest constant of software development, yes that is CHANGE, they understand how abstraction at the top level can help in writing flexible software. A key challenge while writing software (Java Programs, C++ programs) is not just to cater today's requirement but also to ensure that nurture requirement can be handled without any architectural or design change in your code. In short, your software must be flexible enough to support future changes.

5 Examples of Formatting Float or Double Numbers to String in Java

Formatting floating point numbers is a common task in software development and Java programming is no different. You often need to pretty print float and double values up-to 2 to 4 decimal places in console, GUI or JSP pages. Thankfully Java provides lots of convenient methods to format a floating point number up to certain decimal places. For example you can use method printf() to format a float or double number to a output stream. However, it does not return a String. In JDK 1.5, a new static method format() was added to the String class, which is similar to printf(), but returns a String. By the way there are numerous way to format numbers in Java, you can use either DecimalFormat class, or NumberFormat or even Formatter class to format floating point numbers in Java. Coming back to String's format method, here is a quick example of using it :
String strDouble = String.format("%.2f", 1.23456);
This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.2f, f is for floating point number, which includes both double and float data type in Java. Don't try to use "d" for double here, because that is used to format integer and stands for decimal in formatting instruction. By the way there is a catch here, format() method will also arbitrarily round the number. For example if you want to format 1.99999 up-to 2 decimal places then it will return 2.0 rather than 1.99, as shown below.

How to Compare Two Arrays in Java - String, Integer Array Example

Our task is to compare two arrays in Java and see if they are equal to each other or not. Of-course we can't compare an String array to an int array, which means two arrays are said to be equal if they are of same type, has same length, contains same elements and in same order. Now, you can write your own method for checking array equality or take advantage of Java's rich Collection API. Similar to what we have seen while printing array values in Java, java.util.Arrays class provides convenient methods for comparing array values. They take care of all four condition, I have mentioned above. In fact, Arrays class also provide deepEquals() method to compare two-dimensional array in Java. By the way it's not restricted to just two-dimensional and also valid for any multi-dimensional array.

Difference between StringBuilder and StringBuffer in Java

If you are in a hurry and heading straight to interview then I won't take much of your time, In a couple of words, the main difference between StringBuffer and StringBuilder is between four parameters, synchronization, speed, thread-safety, and availability. StringBuffer is synchronized and that's why thread-safe, but StringBuilder is not synchronized, not thread-safe and that's why fast. Regarding availability, StringBuffer is available from Java 1.0 while StringBuilder was added in Java 5. Now we can take a breath, and can continue with rest of this article. In Java, there are three classes to deal with String data type, String, StringBuffer and StringBuilder. All of three belongs to java.lang package, which is automatically imported into every Java program thus you don't need to do any import for using StringBuilder and StringBuffer.

3 Examples to Read InputStream as String in Java - JDK7, Guava and Apache Commons

Java programming language provides streams to read data from a file, a socket and from other sources e.g. byte array, but developers often find themselves puzzled with several issues e.g. how to open connection to read data, how to close connection after reading or writing into file, how to handle IOException e.g. FileNotFoundException, EOFFileException etc. They are not confident enough to say that this code will work perfectly.  Well, not everyone expect you to make that comment, but having some basics covered always helps. For example In Java, we read data from file or socket using InputStream and write data using OutputStream. Inside Java program, we often use String object to store and pass file data, that's why we need a way to convert InputStream to String in Java. As a Java developer, just keep two things in mind while reading InputStream data as String :

3 Examples to Loop Map in Java - Foreach vs Iterator

There are multiple ways to loop through Map in Java, you can either use a foreach loop or Iterator to traverse Map in Java, but always use either Set of keys or values for iteration. Since Map by default doesn't guarantee any order, any code which assumes a particular order during iteration will fail. You only want to traverse or loop through a Map, if you want to transform each mapping one by one. Now Java 8 release provides a new way to loop through Map in Java using Stream API and forEach method. For now, we will see 3 ways to loop through each element of Map. Though Map is an interface in Java, we often loop through common Map implementation like HashMap, Hashtable, TreeMap and LinkedHashMap. By the way, all the ways of traversing Map discussed in this article is pretty general and valid for any Map implementation, including proprietary and third-party Map classes.

2 Ways to sort HashMap in Java? Example

So you have a Map in your Java program and you want to process its data in sorted order. Since Map doesn't guarantee any order for its keys and values, you always end up with unsorted keys and Map. If you really need a sorted Map then think about using TreeMap, which keeps all keys in a sorted order. This could be either natural order of keys (defined by Comparable) or a custom order (defined by Comparator), which you can provide while creating an instance of TreeMap. If you don't have your data in a sorted Map then only option remains is to get the keys, sort them and then process data in that order. Since keys are unique in Map, it returns a Set of keys, which means you cannot sort them by using Collections.sort() method, which accept a List. So what to do? Well, we can convert our Set into List as shown in this example, then sort them using sort() method in any order and process them accordingly.

10 Points about Enum in Java

Apart from Class and Interface, Enumeration type or Enum is another popular type in Java programming language. Enum allows you to represent fixed number of things in a type-safe manner e.g. days of the week, days of the month, planets in solar system, buttons on remote control, keys on keyboard and suits on playing cards. Before Enum was introduced, prior to Java 1.5, integer and string constants are used to represent fixed number of things, known as enum int pattern and enum string pattern. Though they serve the purpose, they had some major drawbacks, one of them was type-safety i.e. you cannot restrict them to represent fixed number of values  e.g. an integer constant, which is representing days of the week can have value as 100, which is incorrect, given we have only 7 days in a week.

Array length vs ArrayList Size in Java

One of the confusing part in learning Java for a beginner to understand how to find the length of array and ArrayList in Java? Main reason for the confusion is an inconsistent way of calculating length between two. Calling size() method on arrays and length, or even length() on ArrayList is common programming error made by beginners. The main reason for confusion is the special handling of an array in Java.  Java native arrays have built-in length attribute but no size() method while the Java library containers, known as Collection classes e.g. ArrayList<>, Vector<>, etc,  all have a size() method. There is one more thing which adds to this confusion, that is capacity, at any point capacity of any collection class is the maximum number of elements collection can hold. the size of collection must be less than or equal to its capacity.

Java 8 Stream Examples and Tutorial

It's been a couple of weeks Java 8 has released and a lot of Java developers are trying their hands on major enhancement e.g. lambda expression, method reference, new data and time classes, and more importantly Stream API for bulk data operations. In my opinion, the best way to learn any new feature or functionality is by writing short examples, and this is what prompt me to write this article. In this Java 8 tutorial, I have shared simple examples of java.util.Stream package. Streams are one of the most important addition on JDK, it allows you to leverage other changes e.g. lambda expression, method reference, functional interface and internal iteration introduced via forEach() method. Some of the most common things we do with Streams are filtering a collection, applying map and reduce function on all elements of the collection and taking advantage of lazy evaluation, built-in parallelism via parallelStream().

How to Make Executable JAR file in Eclipse IDE - Java

If you are Java programmer then you know what is the purpose of JAR file, but for those who are unaware, JAR file is deliverables of Java application. Just like C and C++  application produce EXE files, Java produces JAR files. In other words, A JAR (Java Archive) file is a ZIP format file that bundles Java classes into a single unit, it may contain all the resource needed by Java application as well. There are mainly two types of JAR file in Java:  Library JAR (normal JAR) files: JARs which are reusable libraries e.g. Apache commons JAR file, guava.jar itself or even JDBC drivers e.g. ojdbc6_g.jar. There is another type as well, Executable JAR files: JARs which can be executed as a standalone Java applications. The main difference between normal and executable JAR file is that later contains a mainfest file, which specifies a main-class entry. When you run that JAR file, Java starts your application by reading that main-class entry, because you need the main method to execute Java programs.

Difference between Polymorphism and Inheritance in Java and OOP

Programmers often confused among different object oriented concepts e.g. between Composition and Inheritance, between abstraction and encapsulation and sometime between Polymorphism and Inheritance. In this article, we will explore third one, Polymorphism vs Inheritance. Like in real world, Inheritance is used to define the relationship between two classes. It's similar to Father-Son relationship. In object oriented programming, we have a Parent class (also known as the super class) and a Child class (also known as the subclass). Similar to the real world, Child inherits Parents qualities, e.g. it's attribute, methods and code. Inheritance is actually meant for code-reuse. A child can reuse all the codes written in Parent class, and only write code for behaviour which is different than the parent. Though it’s possible to restrict something to parent itself by using the private and final keyword in Java.On the other hand, Polymorphism is an ability of Object to behave in multiple form.

How to Find Top Two Maximum Number from Integer array in Java

In this post, I have come with another simple programming problems for Java beginners. I love to share short programming problems because they help in developing programming sense. Many people will argue against simple problems like prime numbers, palindrome, and factorial, but I really find them useful, especially for beginners. A beginner is far away to solve a complex data structure problem or even more complex problems like those appear in TopCoder or other programming sites. Programmers learn gradually and they need the joy of doing something and seeing result much quickly than any other. Small success motivates them. Anyway, here is our problem statement, you need to write a Java program to find top two maximum numbers in the given array. You can not use any sorting functions and you should iterate the array only once. Use of any kind of collection class e.g. TreeSet or LinkedHashSet is also not allowed.

How to Print Array with elements in Java?

You cannot print array elements directly in Java, you need to use Arrays.toString() or Arrays.deepToString() to print array elements. Use toString() if you want to print one-dimensional array and use deepToString() method if you want to print two-dimensional array. Have you tried printing array in Java before? What did you do? just passed an array to println() method and expecting it prints its elements? Me too, but surprisingly array despite being Object and providing a length field, doesn't seem overriding toString() method from java.lang.Object class. All it prints is type@somenumber. This is not at all useful for anyone who is interested in seeing whether an array is empty or not, if not then what elements it has etc.

Is Java a Pure Object Oriented Programming Language?

One of the oldest question related to Java is whether Java a pure object oriented language or not?Short answer is no, There are many things in Java which are not objects e.g. primitive data types e.g. boolean, char, short, int, long, float, double, different kinds of arithmetic, logical and bitwise operator e.g. +, -. *, /, &&, || etc. Few pure OO languages are Smalltalk and Eiffel. Though Java is one of the most successful Object oriented programming language, which also got some functional programming touch in Java 8 is never considered 100% or pure object-oriented programming language. If it were, all its primitives would be objects. It actually moves half-way in this direction with String (and perhaps Array), but it doesn't quite go far enough. Actually, one could argue that as String and Array aren't inheritable, that makes those parts of Java at best object-based.

2 Ways to Remove Elements/Objects From ArrayList in Java

There are two ways to remove objects from ArrayList in Java, first, by using remove() method, and second by using Iterator. ArrayList provides overloaded remove() method, one accept index of the object to be removed i.e. remove(int index), and other accept object to be removed, i.e. remove(Object obj). Rule of thumb is, If you know the index of the object, then use the first method, otherwise use the second method. By the way, you must remember to use ArrayList remove methods, only when you are not iterating over ArrayList if you are iterating then use Iterator.remove() method, failing to do so may result in ConcurrentModificationException in Java. Another gotcha can have occurred due to autoboxing. If you look closely that two remove methods, remove(int index) and remove(Object obj) are indistinguishable if you are trying to remove from an ArrayList of Integers.

Decimal to Binary Conversion in Java

This week's programming exercise is to write a program to convert a decimal number to binary in Java. It's a simple exercise for beginners who has just started learning Java programming language. Decimal numbers are base 10 numbers, which means there are exactly 10 digits to represent a number, starting from 0 to 9, on the other hand, binary number system has just two digits 0 and 1, which is known as bits. Binary numbers have lot of use in the digital world, in fact, binary is the language of computers where 0 and 1 represent true/false, on/off and becomes key for logic formation. In order to convert a decimal number into binary, we will use modules operator in Java, represented by a percentage sign (%). This is also known as a remainder operator because it returns the remainder of a division operation, for example, 5%,2 will return 1 while 7%4 will return 3.

How to Find Duplicate Characters on String - Java Programming Problems

Today's programming exercise is to write a program to find repeated characters in a String. For example, if given input to your program is "Java", it should print all duplicates characters, i.e. characters appear more than once in String and their count e.g. a = 2 because character 'a' has appeared twice in String "Java". This is also a very popular coding question on the various level of Java interviews and written test, where you need to write code. On difficulty level, this question is at par with prime numbers or Fibonacci series. I personally like this exercise because it gives beginners an opportunity to familiar with the concept of Map data structure, which allows you store mappings in the form of key and value. Since Map is heavily used in any enterprise Java application, good knowledge of this data structure is highly desirable among any level of Java programmers.

Java Program to Print Alphabets in Upper and Lower Case

One of the textbook exercise to get start with any programming language is writing a program to print alphabets in both upper and lower case. This program allows you to explore the String class in Java with toUpperCase() and toLowerCase() method but normally when you start, it's asked to do this without any API methods. This kind of exercise actually improves your understanding of programming language e.g. basic operators, data types like int and char. It's similar to your prime number, Fibonacci series, and factorial program exercise. I strongly suggest doing this textbook exercises to anyone who is just started learning a new programming language. Coming back to this program, Java has a datatype called char, which is 2-byte unsigned integer type. It is used to store characters in Java  e.g. char A = 'A'.

How to Find IP address of Localhost, Server or Your Machine

In today's Java programming tutorial, we will learn some networking basics by exploring java.net package. One of the simple Java network programming exercise, yet very useful, is to write a program to find IP address of the local host in Java. Sometimes this question also asked as find IP address of Server on which your Java program is running or find IP address of your machine using Java etc. In short, they all refer to localhost. For those who are entirely new in networking space, there are two things to identify a machine in a network, which could be LAN, WAN or The Internet. First thing is DNS name and the second thing is IP address. In Local Area Network, DNS is more generally replaced by hostname, which could be as simple as ReportingServer to ReportingServer.com or something else.

How Google Search words, Contents, Images and Videos on Internet

Though we all use Google almost more than 100 times in a day, how many of you know that How Google works? How Google find the content you are looking for? How does it even find all the website in the BIG world of Internet? How does it index URLs? There is a lot of things to know about how Google actually works. Though I know a couple of them before, I found this useful Infographic, which tells you how exactly Google Works. It all starts from Crawling and Indexing. Google has lots of programs known as Spider, which keeps crawling the web, day, and night. This is how Google picks up every new information added into the internet. As long as your website is reachable by The Internet and your Content is crawlable i.e. not prevented or secured by robot.txt, Google will crawl then and index them appropriately.

Can You Run Java Program Without Main Method?

First thing Java programmers learns is that they need a main method to run, but when they go to any Interview or college viva and asked can you run a Java program without a main method, they surprised like hell. Well, there are actually different types of execution model available in Java, for example, Applets which run on browser doesn't have main method, instead they have life-cycle methods like init(), start() and stop(), which controls their execution. Since Applet is a Java program, you can answer this question in Yes. Similarly, we have Servlet, which runs in a Servlet container, comes as bundled in a web server like Tomcat, or Jetty. Servlet also works on callback mechanism, it has methods like init(), service() and destroy(). Container calls init() if Servlet is first time loaded into memory, calls service() if there is a request to process and calls destroy() before removing it from memory.

What is the Actual Use of Interface in Java?

An interface in Java has remained a complex topic for many beginners to understand. The first thing which puzzles many programmers is the fact that you cannot define any method inside interface, it a just declaration. By rule, all method inside interface must be abstract (Well, this rule is changing in Java 8 to allow lambda expressions, now interface can have one non-abstract method, also known as a default method). So, if you can't define anything, Why we need an interface?  what's the use of an interface, if we are anyway going to write a class and override them to provide behaviour, Can't we declare those methods inside the class itself without using interface etc. Well, if you are thinking in terms of behaviour then you are really missing the point of interface.

Difference between Static and Dynamic Binding in Java

When you call a method in Java, it is resolved either at compile time or at runtime, depending upon whether it's a virtual method or a static method. When a method call is resolved at compile time, it is known as static binding, while if method invocation is resolved at runtime, it is known as Dynamic binding or Late binding. Since Java is an object-oriented programming language and by virtue of that it supports Polymorphism. Because of polymorphism, a reference variable of type Parent can hold an object of type Child, which extends Parent. Now if you call a virtual method (not private, final or static) on this object, then Compiler can not find actual method, because it could be the one, which is defined in the Parent class, or the one which Child has overridden. This call can only be resolved at runtime when the actual object is available. That's why this is known as runtime or dynamic binding.

How to find largest and smallest number from integer array - Java Solution

Good Understanding of array data structure is very important for any software developer, and to develop this understanding there are lots of programming exercise beginners can do. One of them is writing a program to find smallest and largest number in an integer array. Java programmers are no different than others, so they can do this program in Java, not just to understand array but also relational operators available in Java.  In this program, you need to write a method, yes we call the function a method in Java, which will accept an integer array and then print largest and smallest number from that array. Use of any third-party library or API method is not allowed, which means you need to do this exercise by using basic tools of Java programming language, which includes operators, control statements,  keyword and some classes from java.lang package.

This problem is also known as finding maximum and minimum numbers in an array, and technique mentioned here can be used in any other programming language as well. As a bonus point, you can also write JUnit test cases to test your method, I have not done so and relied on simple main method to test my code to show the output and keep it short, essential for any example or demo.

Btw, if you preparing for programming job interview, then don't forget to check the Cracking the Coding Interview book. It contains 150 Programming Questions and Solutions, which is more than enough for many coding interviews.

How to Convert java.util.Date to java.sql.Date - Example

There are two date classes in Java, one in java.util package and other in the java.sql package. Though both are known as Date class, there is some difference between java.util.Date and java.sql.Date e.g. Former is used whenever a Date is required in Java application while later is used to read and store DATE SQL type from the database. There is one more important difference is, java.util.Date stores both date and time values, while java.sql.date only stores date information, without any time part. As per Javadoc, java.sql.date is a thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated. See SQL date vs Util date for few more differences.

How to Create File and Directory in Java with Example

Many beginners confused with the fact that same class java.io.File is used to create both file and directory in Java. I agree, this is not very intuitive and  junior developers probably start looking for a class called java.io.Directory, which doesn't exists. On the other hand, creating file and directory are simple in Java, as java.io.File provides methods like createNewFile() and mkdir() to create new file and directory in Java. These method returns boolean, which is the result of that operation i.e. createNewFile() returns true if it successfully created file and mkdir() returns true if the directory is created successfully. There is another method called mkdirs(), which you can use if parent directory doesn't exist, it's like mkdir -p option from UNIX mkdir command. In this Java program, we will learn how to create file and directory, only if they don't exist already.

Is Java a Good language to start learning Programming?

I often receive questions like what is a good programming language to learn first, Is Java a good programming language to start with,  how good is Java as a first programming language or shall I start with Java or Python. Well, the answer to all these questions is, Java is one of the most popular programming languages and there are the lot of reasons to learn Java, starting from Job opportunity to leverage community support. In the context of starting programming or choosing Java as the first language, my biggest reason is that it's simpler to learn. The last generation of programmers grew up learning C and C++ with Java as their second or third programming language. One reason of  this could be that C and C++ were more popular in those days than Java, other was most curriculum was designed to teach C and C++. This is true, often we don't make the choice and we learn as part of our programming curriculum at school and colleges.

How to Check if Given Number is Prime in Java - With Example

One of the most common programming exercise for beginners is, write a program to check if given number is prime or not? There are many methods to check if a number is prime or not, but most common of them is trial division, which is what we will see in this tutorial. In my opinion, these kind of program is their first steps towards algorithmic understanding. You first come with a solution, which is driven by the fact that prime numbers are natural numbers, which are not divisible by any positive number other than 1 and themselves. You write a for loop to check every number, starting from 1 to given number, to see if given number is divisible by any positive number or not. This leads you to the solution. Then you find some more fact that there is no need to check till N-1, where N is the number we are checking for primeness, and checking till square root of N is enough. This reduces a lot of time, especially while checking a large number is prime or not.

How HashSet Internally Works in Java

Not many programmer know that HashSet is internally implemented using HashMap in Java, so if you know How HashMap works internally in Java, more likely you can figure out how HashSet works in Java. But, now a curious Java developer can question that, how come HashSet uses HashMap, because you need a key value pair to use with Map, while in HashSet we only store one object. Good question, isn't it? If you remember some functionality of earlier class, then you know that HashMap allows duplicate values and this property is exploited while implementing HashSet in Java. Since HashSet implements Set interface it needs to guarantee uniqueness and this is achieved by storing elements as keys with same value always. Things gets clear by checking HashSet.java from JDK source code. All you need to look at is, how elements are stored in HashSet and how they are retrieved from HashSet. Since HashSet doesn't provide any direct method for retrieving object e.g. get(Key key) from HashMap or get(int index) from List, only way to get object from HashSet is via Iterator. See here for code example of iterating over HashSet in Java. When you create an object of HashSet in Java, it internally create instance of backup Map with default initial capacity 16 and default load factor 0.75 as shown below :

Java Regular Expression to Check If String contains at least One Digit

This week's task is to write a regular expression in Java to check if a String contains any digit or not. For example, passing "abcd" to pattern should false, while passing "abcd1" to return true, because it contains at least one digit. Similarly passing "1234" should return true because it contains more than one digit. Though java.lang.String class provides a couple of methods with an inbuilt support of regular expression e.g.split method, replaceAll() and  matches method, which can be used for this purpose, but they have a drawback.  They create a new regular expression pattern object, every time you call. Since most of the time we can just reuse the pattern, we don't need to spend time on creating and compiling pattern, which is expensive compared to testing a String against the pattern.

How to Fix java.lang.OufOfMemoryError: Direct Buffer Memory

Java allows an application to access non-heap memory by using direct byte buffer. Many high-performance applications uses direct byte buffer, along with memory mapped file for high-speed IO. And, while the ByteBuffer object is small itself, it can hold a large chunk of non-heap memory, which is outside of Garbage collection scope.  Which means garbage collector can not reclaim this memory. It is often used to store large data e.g. order or static data cache. Since generally your program allocates the large buffer e.g. size of 1GB or 2GB, you get "Exception in thread "main" java.lang.OutOfMemoryError: Direct buffer memory" error, when you try to allocate memory by running following code

Why String Class is made Immutable or Final in Java - 5 Reasons

There is hardly any Java Interview, where no questions are asked from String, and Why String is Immutable in Java is I think most popular one. This question is also asked as Why String class is made final in Java or simply, Why String is final. In order to answer these questions, Java programmer must have a solid understanding of How String works, what are special features of this class and some key fundamentals. The String class is a God class in Java, It has got special features which is not available to other classes e.g. String literals are stored in pools, You can concatenate strings using + operator. Given its importance in Java programming, Java designer has made it final, which means you can not extend java.lang.String class, this also helps to make String object Immutable.

10 points about Thread in Java

Thread in Java is one of those topics which always confuse beginners but given its important and strength it provides to Java language, it's very important for every Java developer to learn and understand the fundamental concept of multi-threading and basic points about Thread in Java. I had started thread programming in Java by animating a couple of  words in Applets, that was an amazing experience to code animation, but after spending almost 10 years on developing core Java application and I am still discovering things on threading and concurrency. My first program which involves Thread had three words dropping from each corner of the screen and I was excited to see that animation driven by Java thread.

java.lang.UnsatisfiedLinkError: Library not found tibrvnative or android

When I was working in JNI and using native code, actually an in-house library,  I realized that java.lang.UnsatisfiedLinkError: Library not found comes mainly due to two reasons

1) First reason, which happens in 90% scenarios is that the library which you are using directly or indirectly (some external JAR is using native library or native dll e.g. if your Java application is using TIBCO libraries for messaging or fault tolerance then tibrv.jar uses tibrvnative.dll library and throws java.lang.UnsatisfiedLinkError: Library not found tibrvnative if that library (the dll) is not in the path. In order to fix this problem, you need to update your PATH environment variable to include native libraries binary. see last section for more details.

6 Difference between LinkedHashSet vs TreeSet vs HashSet in Java

LinkedHashSet, TreeSet, and HashSet are three of most popular implementation of Set interface in Java Collection Framework. Since they implement Set interface, they follow its contracts for not allowing duplicates. All these implementation except, TreeSet uses equals() method to check for duplicates, on the other hand TreeSet use compareTo() or compare() method for comparing objects and can break Set interface contract of unique element, if equals method is not consistent with compareTo() or compare() method. In this Java Collection tutorial, we will see the difference between LinkedHashSet vs TreeSet vs HashSet on different points e.g. speed, performance, ordering, synchronization etc. Based upon these differences we can also decide when to use LinkedHashSet vs TreeSet vs HashSet in Java.