Disclosure: This article may contain affiliate links. When you purchase, we may earn a commission.

How to format numbers in Java? - NumberFormat Example

You can use java.util.text.NumberFormat class and its method setGroupingUsed(true) and setGroupingSize(3) to group numbers and add a comma between them. Most numbers that are used to represent monetary value e.g. price, amount, etc require a comma to be added to improve readability and follow conventions. For example, if your variable is storing 1 million dollars then you would like to see it as 1,000,000 rather than 1000000. Clearly, the first one is more readable than the second one. Of course, you can further format to add currency based upon locale, but this tutorial is not about that. 

What is fail safe and fail fast Iterator in Java?

Java Collections supports two types of Iterator, fail-safe and fail fast. The main distinction between a fail-fast and fail-safe Iterator is whether or not the underlying collection can be modified while it begins iterated. If you have used Collection like ArrayList then you know that when you iterate over them, no other thread should modify the collection. If the Iterator detects any structural change after iteration has begun e.g adding or removing a new element then it throws ConcurrentModificationException,  this is known as fail-fast behavior and these iterators are called fail-fast iterator because they fail as soon as they detect any modification. 

How to convert ByteBuffer to String in Java [Example]

You can easily convert ByteBuffer to String in Java if you know how to convert byte array to String. Why? because it's very easy to convert ByteBuffer to a byte array and vice versa. All you need to do is call the ByteBuffer.array() method, it will return you the byte array used by java.nio.ByteBuffer class, later you can easily create String from that byte array. Though always remember to provide correct character encoding while converting byte array to String.

How to convert long to String in Java? Example

There are three main ways to convert a long value to a String in Java e.g. by using Long.toString(long value) method, by using String.valueOf(long), and by concatenating with an empty String. You can use any of these methods to convert a long data type into a String object. It's not very different from how you convert an int to String in Java. The same method applies here as well. String concatenation seems the easiest way of converting a long variable to a String, but others are also convenient.  

How to append text to existing File in Java? Example

In the last tutorial, you have learned how to write data to a file in Java, and in this tutorial, you will learn how to append text to a file in Java. What is the difference between simply writing to a file vs appending data to a file? In the case of writing to a file, a program can start writing from the start but in the case of appending text, you start writing from the end of the file. You can append text into an existing file in Java by opening a file using FileWriter class in append mode. You can do this by using a special constructor provided by FileWriter class, which accepts a file and a boolean, which if passed as true then open the file in append mode. 

How to add element at first and last position of linked list in Java?

LinkedList class in java.util package provides the addFirst() method to add an element at the start of the linked list (also known as head)  and addLast() method to add an element at the end of the linked list, also known as the tail of the linked list. Java's LinkedList class is an implementation of a doubly linked list data structure but it also implements java.util.Deque interface and these two methods came from that interface, which means they are only available from Java 1.6 onward. addFirst() method insert the specified element at the beginning of the linked list and addLast() method insert the specified element at the end of the linked list.

How to convert String to double in Java with Example

There are three ways to convert a String to double value in Java, Double.parseDouble() method, Double.valueOf() method and by using new Double() constructor and then storing the resulting object into a primitive double field, autoboxing in Java will convert a Double object to the double primitive in no time. Out of all these methods, the core method is parseDouble() which is specially designed to parse a String containing floating-point value into the Double object. Rest of the methods e.g. valueOf() and constructor uses parseDouble() internally. This method will throw NullPointerException if the string you are passing is null and NumberFormatException if String is not containing a valid double value e.g. containing alphabetic characters.

How to get first and last elements form ArrayList in Java

There are times when you need to get the first or last element of an ArrayList. One of the common scenarios where you need the first and last element of a list is supposed you have a sorted list and want to get the highest and lowest element? How do you get that? The first element is your lowest and the last element is your highest, provided ArrayList is sorted in ascending order. If it's opposite then the first element would be the maximum and the last element would be the minimum. This is quite easy to do in ArrayList because the first element is stored at index 0 and the last element is on index, size - 1. 

Difference between Abstraction and Polymorphism in Java and OOP [Answer]

Abstraction and Polymorphism are very closely related and understanding the difference between them is not as easy as it looks. Their operating model is also very similar and based upon the relationship of parent and child classes. In fact, Polymorphism needs the great support of Abstraction to power itself, without Abstraction you cannot leverage the power of Polymorphism. Let's understand this by what Abstraction and Polymorphism provide to an object-oriented program. Abstraction is a concept to simplify the structure of your code. Abstraction allows you to view things in more general terms rather than looking at them as they are at the moment, which gives your code flexibility to deal with the changes coming in the future.

Difference between synchronized ArrayList and CopyOnWriteArrayList in Java?

What is the difference between a CopyOnWriteArrayList and a Synchronized ArrayList is one of the popular Java interview questions, particularly for beginners with 1 or 2 years of experienced programmers. Though both synchronized ArrayList and CopyOnWriteArrayList provide you thread-safety and you can use both of them when your list is shared between multiple threads, there is a subtle difference between them, Synchronized ArrayList is a synchronized collection while CopyOnWriteArrayList is a concurrent collection. What does this mean? It means is that CopyOnWriteArrayList is designed keeping concurrency in mind and it is more scalable than synchronized ArrayList if the list is primarily used for reading. 

4 ways to concatenate Strings in Java [Example and Performance]

When we think about String Concatenation in Java, what comes to our mind is the + operator, one of the easiest ways to join two String or a String, and a numeric in Java. Since Java doesn't support operator overloading, it's pretty special for String to have behavior. But in truth, it is the worst way of concatenating String in Java. When you concatenate two String using + operator e.g. "" + 101, one of the popular ways to convert int to String, compiler internally translates that to StringBuilder append call, which results in the allocation of temporary objects. 

java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject [Solved]

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject error means that your Java program needed a class called org.apache.xmlbeans.XmlObject but JVM is not able to find that in your application's CLASSPATH. You can see the actual cause of this error is "java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject". The most probable reason for this error could be a missing JAR file. In order to solve this error, you need to first find out which JAR file this class belongs. If you look at the error message it's clearly saying that it's from xmlbeans package, it means this class belongs to XMLBeans library.

How to use PriorityQueue in Java? An Example

PriorityQueue is another data structure from the Java Collection framework, added in Java SE 5. This class implements the Queue interface and provides a sorted element from the head of the queue. Though it provides sorting, it's a little different from other Sorted collections e.g. TreeSet or TreeMap, which also allows you to iterate over all elements, in the priority queue, there is no guarantee on iteration. The only guaranteed PriorityQueue gives is that the lowest or highest priority element will be at the head of the queue. So when you call remove() or poll() method, you will get this element, and next on priority will acquire the head spot. Like other collection classes which provide sorting, PriorityQueue also uses Comparable and Comparator interface for priority.

2 Ways to Read a Text File in Java? BufferredReader and Scanner Examples

You can read a text file in Java 6 by using BufferedReader or Scanner class. Both classes provide convenient methods to read a text file line by line e.g. Scanner provides nextLine() method and BufferedReader provides readLine() method. If you are reading a binary file, you can use FileInputStream. By the way, when you are reading text data, you also need to provide character encoding, if you don't then the platform's default character encoding is used. In Java IO, streams like InputStream are used to read bytes, and Readers like FileReader are used to read character data.

How to Synchronize HashMap in Java with Example

HashMap is not synchronized, which means you cannot use it on multi-threaded Java programs without external synchronization. In another word, if you share one instance of HashMap between multiple threads, each is either adding, removing or updating entries then it's possible that HashMap loses its structure and not behave as expected. If you have read my earlier article about HashMap, you know that during re-sizing its possible that HashMap exposed to multiple threads, may end up in an infinite loop. 

How to parse String to Date in Java using JodaTime Example

In this Java tutorial, we will learn how to parse String to Date using Joda-Time library, for example, we will convert date String "04-12-2014" to java.util.Date object which represents this date. Before Java 8 introduced its new Date and Time API,  Joda was only reliable, safe and easy way to deal with date and time intricacies in Java. Java's own Date and Time was not that great, starting from JDK 1.1 when they made java.util.Date a mutable object and when they introduced Calendar in Java 1.2. It is one of the most criticized feature of Java on communities along with checked exception and object cloning

Right way to Compare String Objects in Java [Example]

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 objects to check if they are the same, i.e. contains the 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 the == operator. It is one area in which almost every Java programmer has made mistakes sometimes by comparing two String variables using the == operator. 

How to Convert Byte array to String in Java with Example

There are multiple ways to convert a byte array to String in Java but the most straightforward way is to use the String constructor which accepts a byte array i.e. new String(byte []) , but the key thing to remember is character encoding. Since bytes are binary data but String is character data, it's very important to know the original character encoding of the text from which byte array has created. If you use a different character encoding, you will not get the original String back. For example, if you have read that byte array from a file which was encoded in "ISO-8859-1" and you have not provided any character encoding while converting byte array to String using new String() constructor then it's not guaranteed that you will get the same text back? Why? because new String() by default uses platform's default encoding (e.g. Linux machine where your JVM is running), which could be different than "ISO-8859-1".

2 Ways to Print Custom String Value of Java Enum

We all know that how powerful the enumeration type in Java is, and one of the main strengths 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 the log file and other times for storing log into the database.  By default, when you print an enum constant, it prints its literal value e.g. if the name of the enum instance is RED, then it will print RED. This is also the value that is returned by the name() method of java.lang.Enum class. But, there are situations when we want a custom String value for an enum constant. 

How to break from a nested loop in Java? [Example]

There are situations we need to be nested loops in Java, one loop containing another loop like 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 like printing the 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 loops. 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 the nested loop in Java. 

Difference between instance and Object in Java

In Java or other object-oriented programming languages, 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 things or different? Why we sometimes use object and sometimes instances if they are the 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. 

How To Convert Map to List in Java with Example

Before converting a Map to a List in Java,  we should be very clear about these data structures which are widely used in Java. So let's begin with Map. What is Map? Map is an Interface in Java which store key and value object. It's a Java representation of a popular hash table data structure that allows you to search an existing element in O(1) time, at the same time also makes insertion and removal easier.  We use a key object to retrieve the value object by using hashing functionality provided by Map. As we have seen in how the get method of HashMap works, In Java, the equals() and hashcode() methods are an integral part of storing and retrieving objects from it. The map allows duplicate values but no duplicate keys.

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

We often need to convert a floating-point number into an 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 a 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 the nearest integer. The right way to convert a double value to a long in Java really depends on what you want to do with the floating-point value. 

How to reverse ArrayList in Java with Example

You can reverse ArrayList in Java by using the reverse() method of java.util.Collections class. This is one of the many utility methods provided by the Collections class e.g. sort() method for sorting ArrayList. The Collections.reverse() method also accepts a List, so you not only can reverse ArrayList but also any other implementation of List interface e.g. LinkedList or Vector or even a custom implementation. This method has a time complexity of O(n) i.e. it runs on linear time because it uses ListIterator of the given list.  It reverses the order of an element in the specified list. 

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.

How to create User Defined Exception class in Java

Java has very good support for handling Errors and Exceptions, It has a well-defined Exception hierarchy and language level support to throw and catch Exceptions and deal with them. Java Programmers often deal with built-in exceptions from java.lang package and several others which are already defined in JDK API like 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, like IndexOutOfBoundException, ArithmeticException, IOException, and java.lang.ArrayIndexOutOfBoundsException , instead of creating new ones for a similar purpose.

How to Sort HashMap in Java based on Keys and Values

HashMap is not meant to keep entries in sorted order, but if you have to sort HashMap based upon keys or values, you can do that in Java. Sorting HashMap on keys is quite easy, all you need to do is to create a TreeMap by copying entries from HashMap. TreeMap is an implementation of SortedMap and keeps keys in their natural order or a custom order specified by Comparator provided while creating TreeMap. This means you can process entries of HashMap in sorted order but you cannot pass a HashMap containing mappings in a specific order, this is just not possible because HashMap doesn't guarantee any order.

How to convert String to Float in Java and vice-versa - Tutorial

There are three ways to convert a String to float primitive in Java parseFloat(), valueOf() method of Float class, and new Float() constructor. Suppose you have a String that represents a floating-point number e.g. "3.14" which is the value of PIE, you can convert it to float by using any of those three methods. Since String is one of the most prominent data types in Java, you will often find yourself converting String to Int, Double, and other data types and vice-versa. Java designer knows about that and they have made arrangement to carry out this basic task in a predictable and consistent manner. 

How to Generate Random Number between 1 to 10 - Java Example

There are many ways to generate random numbers in Java e.g. Math.random() utility function, java.util.Random class or newly introduced ThreadLocalRandom and SecureRandom, added on JDK 1.7. Each has their own pros and cons but if your requirement is simple, you can generate random numbers in Java by using Math.random() method. This method returns a pseudorandom positive double value between 0.0 and 1.0, where 0.0 is inclusive and 1.0 is exclusive. It means Math.random() always return a number greater than or equal to 0.0 and less than 1.0. 

Second Highest Salary in MySQL and SQL Server - LeetCode Solution

Write a SQL query to get the second highest salary from the Employee table.

| Id | Salary |
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |

For example, given the above Employee table, the second highest salary is 200. If there is no second highest salary, then the query should return NULL. You can write SQL query in any of your favorite databases e.g. MySQL, Microsoft SQL Server, or Oracle. You can also use database specific feature e.g. TOP, LIMIT or ROW_NUMBER to write SQL query, but you must also provide a generic solution which should work on all database. 

How to Make Executable JAR file in Eclipse IDE - Java

If you are a Java programmer then you know what is the purpose of the JAR file, but for those who are unaware, the JAR file is deliverables of Java application. Just like C and C++ applications 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 resources needed by Java application as well. There are mainly two types of the JAR file in Java:  Library JAR (normal JAR) files: JARs which are reusable libraries like Apache commons JAR file, guava.jar itself, or even JDBC drivers like ojdbc6_g.jar. There is another type as well, Executable JAR files: JARs which can be executed as standalone Java applications. 

How to calculate Sum of Digits using Recursion in Java [Example]

This is the second part of our article to solve this coding interview question,   how to find the sum of digits of an integer number in Java. In the first part, we have solved this problem without using recursion i.e. by using a while loop and in this part, we will solve it by using recursion. It's good to know different approaches to solving the same problem, this will help you to do well on coding interviews. While finding a recursive algorithm, always search for a base case, which requires special handling. Once you find the base case, you can easily code the method by delegating the rest of the processing to the method itself, i.e. by using recursion.  

How Constructor Works in Java? [Answer]

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.

3 Examples to Read FileInputStream 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 :

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 the most misunderstood and misused one. Talking about Java, almost all programmers know 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 the difference between static and non-static methods, he is probably not ready yet and needs more practice and experience. With half knowledge, making a method static can have serious repercussions, especially in today's heavily multi-threaded Java application.

How to add Zeros at the Beginning of a Number in Java [Left Padding Examples]

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 the finance domain. There are so many legacy systems out there that expect the input of a certain length, and if your input is shorter than the specified length, you got to add zeros at the beginning of the number to make them off the right length. Java has a 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 the powerful String.format() method or its 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 a Java developer, you must have a good understanding of that.

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 an environment? 

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 sorted order. This could be either natural order of keys (defined by Comparable) or 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 the only option that remains is to get the keys, sort them and then process data in that order. 

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. 

Difference between StringBuilder and StringBuffer in Java [Answer]

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. 

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

Why Abstract class is Important in Java? [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.

Difference between String literal and New String object in Java

The String class or java.lang.String is a special class in Java API and has so many special behaviors which are not obvious to many programmers. In order to master Java, the first step is to master the 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 questions is what is the difference between String literal and String object in Java

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 languages 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.

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.

How to use Modulo , Modulus, or Remainder Operator in Java? [Example]

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 the modulo operator. It is denoted by the % (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 the 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. 

Difference between Polymorphism and Inheritance in Java and OOP [Answer]

Programmers often confused among different object-oriented concepts e.g. between Composition and Inheritance, between abstraction and encapsulation, and sometimes between Polymorphism and Inheritance. In this article, we will explore the third one, Polymorphism vs Inheritance. Like in the real world, Inheritance is used to define the relationship between two classes. It's similar to the Father-Son relationship. In object-oriented programming, we have a Parent class (also known as the superclass) and a Child class (also known as the subclass). Similar to the real world, a Child inherits Parents' qualities, like its attributes, methods, and code. 

5 Difference between Iterator and ListIterator in Java?

The Iterator is the standard way to traverse a collection in Java. You can use Iterator to traverse a List, Set, Map, Stack, Queue, or any Collection, but you might not know that there is another way to traverse over List in Java? Yes, it's called the ListIterator. There are many differences between Iterator and ListIterator in Java, but the most significant of them is that Iterator only allows you to traverse in one direction, I mean forward, you have just got a next() method to get the next element, there is no previous() method to get the previous element. 

How to Print Array with elements in Java? [Solution + Example]

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 a one-dimensional array and use deepToString() method if you want to print a two-dimensional array. Have you tried printing arrays 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 the 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.

HelloWorld Program in Java with Example

First of all, welcome to the exciting world of Java programming. If you are ready to write your first Java program i.e. HelloWorld in Java, it means you already crossed major hurdles to start Java programming, in terms of installing JDK and setting PATH for Java. If you haven't done so then you can follow those tutorials to install JDK in Windows 7 and 8 and setting PATH for Java. Before we start writing HelloWorld in Java, few notes about editors. Many Java beginners insist or try to use Eclipse or Netbeans IDE from the very start of the first program, which is not a good idea. 

Difference between GenericServlet vs HttpServlet in Servlet JSP - J2EE question

Difference between GenericServlet and HttpServlet is one of the classic Servlet Interview Question, asked on many Servlet and JSP Interviews on 2 to 4 years experience developers. Since both GenericServlet and HttpServlet form the basis of Servlets its important to know What are they and What is main difference between them. From common sense and there names, its obvious that GenericServlet is a generic and protocol-independent implementation of Servlet interface while HttpServlet implements HTTP protocol specifics. If you are working in Java web application or J2EE projects, you are most likely to deal with HttpServlet all time as HTTP is main communication protocol of web. In this Servlet JSP article we will outline some important difference between HttpServlet and GenericServlet which is worth knowing and remembering.

How to Remove Duplicates from ArrayList in Java [Example]

ArrayList is the most popular implementation of the List interface from Java's Collection framework, but it allows duplicates. Though there is another collection called Set which is primarily designed to store unique elements, there are situations when you receive a List like ArrayList in your code and you need to ensure that it doesn't contain any duplicate before processing. Since with ArrayList you cannot guarantee uniqueness, there is no other choice but to remove repeated elements from ArrayList. 

10 AWT Swing Interview Questions Answers in Java

AWT and Swing Interview Questions are part of any Java interviews which involves GUI development work. Since AWT(Abstract Windows Toolkit) and Swing offers most popular Java GUI solutions, Yes, JavaFX  has still lot of path to cover in terms of popularity and usability of Swing. In Investment banking, where Java rules on server side application development, Swing was heavily used in GUI development couple of years back. Now trends is shifting towards C# for GUI development due to couple of reasons e.g. good Swing developers are not easy to be found as compared to C# developers. By the way there are still many development work is going on Swing. One of the reason Swing developers are high in demand is because Swing is quickly becoming a niche technology.

How to convert ArrayList to String in Java - Spring Example

Some time we need to convert ArrayList to String in Java programming language in order to pass that String to stored procedure, any method or any other program. Unfortunately Java collection framework doesn't provide any direct utility method to convert ArrayList to String in Java. But Spring framework which is famous for dependency Injection and its IOC container also provides API with common utilities like method to convert Collection to String in Java. You can convert ArrayList to String using Spring Framework's StringUtils class. StringUtils class provide three methods to convert any collection e.g. ArrayList to String in Java, as shown below:

How to iterate over HashSet in Java - loop or traverse Example

Iterating over HashSet in Java
Java program to Iterate over HashSet in Java with ExampleIn our last Java collection tutorial, we have seen How to iterate over ArrayList in Java and in this tutorial we will see How to iterate over HashSet in Java. There are two ways to iterate, loop or traverse over HashSet in Java, first using advanced for-each loop added on Java 5 and second using Iterator which is a more conventional way of iterating over HashSet in Java. Now questions are When should you use for loop and when Iterator is an appropriate option. Well I usually use for loop If I only read from HashSet and doesn't remove any element, while Iterator is preferred approach. You should not remove elements from HashSet while iterating over it in for loop, Use Iterator to do that.

Difference between RuntimeException and checked Exception in Java

RuntimeException vs Checked Exception in Java
Java Exceptions are divided into two categories RuntimeException also known as unchecked Exception and checked Exception. Main difference between RuntimeException and checked Exception is that It is mandatory to provide try-catch or try finally block to handle checked Exception and failure to do so will result in a compile-time error, while in the case of RuntimeException this is not mandatory. The difference between checked and unchecked exception is one of the a most popular question on Java interview for 2 to years experienced developer especially related to Exception concepts.

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?

Java 7 Improved Exception Handling - Multiple Catch block

Java 7 in many ways improved exception handling. Two of the feature of Java 7 which improves exception handling are the ability to catch the multiple exceptions in one catch block and closing resources automatically using Automatic resource management block. Java has long been criticized for its verbose exception handling code, mandatory to handle checked Exceptions in Java. Programmers always complained that it clutters the code and reduced readability. Java 7 somehow reduces this pain by improving the Exception handling feature e.g. multiple catches and ARM blocks. In this Java 7 tutorial, we will see how to catch multiple exceptions in one catch block using JDK7.

How to format Date in Java - SimpleDateFormat Example

SimpleDateFormat in Java is used to format Date in Java. You can format date on any String format based upon various attribute available in SimpleDateFormat class e.g. mm, dd, YY etc. You can also put timezone information in formatted Date using Z attribute of DateFormat class. SimpleDateFormat is sub class of DateFormat and provide format() and parse() method to convert Date to and from String in Java. Worth noting is that SimpleDateFormat is not thread-safe and should not be shared with others. Avoid using static SimpleDateFormat in Java classes. If you want to share SimpleDateFormat or want to make it thread-safe, you can use ThreadLocal variable in Java to avoid sharing SimpleDateFormat among multiple threads. parse() method of SimpleDateFormat throws ParseException if String input is not a valid date or can not be parsed into mentioned format.

Difference between URL, URI and URN - Interview Question

All three URI, URL, and URN are used to identify any resource or name on the internet, but there is a subtle difference between them. URI is the superset of both URL and URN. By the way, the main difference between URL and URI is protocol to retrieve the resource. URL always include a network protocol e.g. HTTP, HTTPS, FTP etc to retrieve a resource from its location. While URI, in case of URN just uniquely identifies the resource e.g. ISBN numbers which are a good example of URN is used to identify any book uniquely. In this article, we will briefly see what is URI, URL, and URN and then see the main difference between URI, URL, and URN.

How to traverse iterate or loop ArrayList in Java

How to Loop ArrayList in Java
Iterating, traversing or Looping ArrayList in Java means accessing every object stored in ArrayList and performing some operations like printing them. There are many ways to iterate, traverse or Loop ArrayList in Java e.g. advanced for loop, traditional for loop with size(), By using Iterator and ListIterator along with while loop etc. All the method of Looping List in Java also applicable to ArrayList because ArrayList is an essentially List. In next section we will see a code example of Looping ArrayList in Java.

How to use Java Enum in Switch Case Statement - Exampel Tutorial

Java Enum in Switch Case Statement
Yesterday, someone ask me Can we use Java Enum in Switch case? Obviously, he was learning Enum and not aware that How powerful Enum in Java is. Yes, You can use Enum in Switch case statement in Java like int primitive. If you are familiar with enum int pattern, where integers represent enum values prior to Java 5 then you already knows how to  use the Switch case with Enum. Using Java Enum in the Switch case is pretty straightforward, Just use Enum reference variable in Switch and Enum constants or instances in CASE statement. In this Java tutorial we will see one example of How to use Enum in Switch statement in Java. By the way Enum is feature rich in Java, Enum can implement interface in Java, Enum can override method in Java, Enum can have constructor in Java and Enum is full functional Type like class or interface.

Difference between Array vs ArrayList in Java

What is the difference between Array and ArrayList is quite a common question among beginners especially those who started coding in C and C++ and prefer to use Array? Both Array and Array List are used to store elements, which can be either primitive or objects in case of Array and only objects in case of ArrayList in Java. The main difference between Array vs ArrayList in Java is the static nature of the Array and the dynamic nature of ArrayList. Once created you can not change the size of Array but ArrayList can re-size itself when needed. Another notable difference between ArrayList and Array is that Array is part of core Java programming and has special syntax and semantics support in Java, While ArrayList is part of the Collection framework along with other popular classes like Vector, Hashtable, HashMap or LinkedList.

What is CopyOnWriteArrayList in Java - Example Tutorial

CopyOnWriteArrayList vs Array List in Java
CopyOnWriteArrayList is a concurrent Collection class introduced in Java 5 Concurrency API along with its popular cousin ConcurrentHashMap in Java. CopyOnWriteArrayList implements List interface like ArrayList, Vector, and LinkedList but its a thread-safe collection and it achieves its thread-safety in a slightly different way than Vector or other thread-safe collection class. As the name suggests CopyOnWriteArrayList creates a copy of underlying ArrayList with every mutation operation e.g. add, remove, or when you set values. That's why it is only suitable for a small list of values which are read frequently but modified rarely e.g. a list of configurations.

Difference between Error vs Exception in Java - Interview question

Both Error and Exception are derived from java.lang.Throwable in Java but main difference between Error and Exception is kind of error they represent. java.lang.Error represent errors which are generally can not be handled and usually refer catastrophic failure e.g. running out of System resources, some examples of Error in Java are java.lang.OutOfMemoryError or Java.lang.NoClassDefFoundError and java.lang.UnSupportedClassVersionError. On the other hand java.lang.Exception represent errors which can be catch and dealt e.g. IOException which comes while performing I/O operations i.e. reading files and directories.

Java program to get SubList from ArrayList - Example

Sometimes we need subList from ArrayList in Java. For example, we have an ArrayList of 10 objects and we only need 5 objects or we need an object from index 2 to 6, these are called subList in Java. Java collection API provides a method to get SubList from ArrayList. In this Java tutorial, we will see an example of getting SubList from ArrayList in Java. In this program, we have an ArrayList which contains 4 String objects. Later we call ArrayList.subList() method to get part of that List.

What Java developer Should Know about Object and java.lang.Object

Java is an object oriented programming language and core of Java API is java.lang.Object class. In order to work properly in Java platform its important to learn fundamentals of Object in Java e.g. What is an Object in Java and How to use Object in Java. There are two meanings of Object in Java one which is used to refer object of Object oriented programming language or OOPS and other is java.lang.Object class. Every class in Java which explicitly doesn’t extend any class, implicitly extends java.lang.Object class. Crucial methods like finalize and wait and notify are declared in Object class, which is source of one of the java questions Why wait and notify are declared in Object class and not on java.lang.Thread class.

Difference between Serializable vs Externalizable in Java - Interview Question

Serializable vs Externalizable
What is the difference between Serializable and Externalizable in Java is famous core Java interview questions and for some of them its one of those difficult Java question, which no one wants to see in Java interview. I was in that category until I explored How Serialization works in Java and find out more about the Serialization process. What makes Serialization questions tricky is, Serialization as a persistence mechanism is not very popular. Many programmers prefer databases, memory-mapped files, or simple text files over Serialization. But Serialization has a distinguished advantage over these mechanisms.

Difference between transient vs volatile variable or modifier in Java

transient vs volatile modifier in Java
What is the difference between transient and volatile variables or modifiers in Java is one of the most common Serialization Interview Questions in Java. Though volatile variables are not related to Serialization at all, this question is mostly asked in conjunction with other Serialization questions. Both transient and volatile modifiers are completely different from each other. In fact, this question is as popular as Serializable vs Externalizable in Java. The main difference between transient vs volatile variables is that transient variables are not serialized during the Serialization process in Java while volatile variables are used to provide alternative synchronization in Java. 

20 EJB 3.0 Interview Questions and Answers - Java J2EE

EJB interview questions are core part of any Java J2EE interview. As EJB forms business layer for modern J2EE enterprise application, Good knowledge of EJB is expected from J2EE programmer. Purpose of these EJB interview questions is to give an Idea about what kind of questions you can expect on J2EE and EJB interviews. EJB was always tough for Java programmer because of heavy weight architecture comprised with many interfaces e.g. home interface, remote interface, local interface, bean class etc. It take too much time and knowledge to implement and use EJB in your Java web and enterprise application forget about challenges posed by application servers like WebLogic or IBM WebSphere.

Autoboxing, Enum, Generics, Varargs methods - Java 5 Features Quick Overview

What is Autoboxing, Generics, Enum and Varargs method in Java 5
Java 5 introduces Autoboxing, Generics, varargs and Enum along with several other features and improvement. It's been few years when Java programming language was enhanced with these features but still Java programmer thing Autoboxing, Enum, Generics or Variable arguments as an advanced feature and afraid to learn them. They are very much part of Java fundamentals just like Abstraction, Inheritance, Encapsulation and Polymorphism are part of Object oriented programming concepts. It's important to understand what are these feature and How to use them, even if you don't use them in your code, you may have to work on someone else code which is written in Java 5 and uses Generics Collection, Autoboxing quite frequently. In this Java 5 tutorial, we will see the brief overview of Java 5 features like Generics, Enum, Autoboxing and unboxing and variable arguments methods along with examples and explanations.

JDOM Example : Reading and Parsing XML with SAX parser in Java

XML parsing with JDOM parser
JDOM is an open source library which allow XML parsing and reading in Java program. JDOM is designed by using Java programming technique and customized for Java programmers, so that Java programmer with  very little knowledge of XML documents can use JDOM to read XML files. Unlike DOM Parser of Java API , which uses Factory design pattern to create instance of parser e.g DocumentBuilderFactory and DocumentBuilder, as seen in our last example of parsing XML documents in Java, JDOM uses new() operator to create its parser instances. In fact JDOM is very easy to understand and most of the time its self explanatory. 

What is Struts Action Class in Java J2EE - How to use

What is Action class in Struts
Struts in java is a framework, used to make web application its is based on Model View Controller or MVC design Pattern where Model represent the internal state and action used to change the state view represent presentation component and a controller is responsible for receiving the request from the client and decide which business logic should be called. Basically, Struts have different classes to represent this Model, View, and Controller we call them as Action, Action Form, and Action Servlet. So

Model – Action classes
View - Action form classes
Controller – Action Servlet classes

In this article, we are focusing on the Model layer of struts framework. Action class is used to provide an interface to application model layer.  What is Action class and how to use Action class is also a popular Struts interview Question asked in various J2EE interviews.

How to Override Equals, HashCode and CompareTo method in Java

Though modern IDE like Eclipse, IntelliJ or Netbeans allows you to generate equals, hashCode and compareTo methods for your value classes, it's equally important, you know how to do that by hand. By overriding equals and hashcode method by yourself, you know how they work, what kind of errors you can get, and most importantly, it's expected form you, as a Java programmer in any core Java interview. More often, you would see a coding question in Java, which ask you to override equals(), hashcode(), compare() and compareTo() methods for a value class. 

Difference between Comparator and Comparable in Java - Interview Question

Comparator and Comparable are two interfaces in Java API, which is used to compare two objects in Java. Though both are used for comparison there are some differences between them, a major difference between Comparable and Comparator is that the former is used to define the natural ordering of objects e.g. lexicographic order for java.lang.String, while later is used to define any alternative ordering for an object.  The main usage of java.lang.Comparable and java.util.Comparator interface is for sorting a list of objects in Java.

How to Iterate over Java Enum : values() Example

Enum Values() Example
In this Java programming tutorial, we will learn how to iterate over enum in Java. Since Enums are a collection of a finite number of well-known objects, often we need to iterate over them. Enums are also final in Java and have a private constructor, which means you can not create enum instances once declared. Iteration over Enum is extremely simple, provided you know about the implicit values() method, which is a static method, provided by java.lang.Enum. Since every enum in Java extends java.lang.Enum, they all get this implicit values() method. Actually there are couple of them, e.g. valueOf(), name(), ordinal() etc. This method returns enum constants in the order they are declared in the Enum class. Even the ordinal() method returns the same order.

How to Split String in Java using Regular Expression

String class provides split() method to split String in Java, based upon any delimiter, e.g. comma, colon, space or any arbitrary method. split() method splits the string based on delimiter provided, and return a String array, which contains individual Strings. Actually, split() method takes a regular expression, which in simplest case can be a single word. split() is also overloaded method in java.lang.String class and its overloaded version take a limit parameter which is used to control how many times the pattern will be applied during the splitting process. if this limit is positive n, then the pattern will be applied at most n-1 times, if it's negative or zero then split operation is applied any number of times.

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.

Difference between Deep and Shallow Copy in Java Object Cloning

Shallow copy and deep copy is related with cloning process so before go into the deep of shallow and deep copy we need to understand what is clone in java. Clone is nothing but the process of copying one object to produce the exact object, which is not guaranteed. We all know in Java object is referred by reference we can not copy one object directly to another object. So we have a cloning process to achieve this objective. Now one question arises in mind why we need this process so the answer is whenever we need a local copy of the object to modify the object in some method but not in the method caller.  

How to Create File and Directory in Java with Example

Many beginners confused with the fact that the same class is used to create both file and directories in Java. I agree, this is not very intuitive and junior developers probably start looking for a class called, which doesn't exist. On the other hand, creating file and directories are simple in Java, as provides methods like createNewFile() and mkdir() to create new file and directory in Java. These methods 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. 

Best Way to Compare Two Strings in Java Alphabetically with Example

There are multiple ways to compare two strings alphabetically in Java e.g. == operator, equals() method or compareTo() method, but which one is the best way to check if two strings are equal or not? Programmers often confused between == operator and equals() method, and think that comparing strings using == operator should be faster than equals() method, and end up using that. Though they are not completely wrong, they often missed the point that == operator is designed to compare object equality, not String equality, which is actually defined in equals()method and compare Strings alphabetically. When you compare two strings using the == operator, it may or may not return true, especially if you are expecting result based on contents. It will only return true if both reference variables are pointing to the same objects, like in the case of interned string or String literals. Otherwise, it will return false, even if the content of String remain same.