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

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.

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

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.