HashSet vs TreeSet in Java? Similarities and Differences

HashSet and TreeSet both implement same interface i.e  java.util.Set interface and they possess the quality of Set interface means duplicate elements are not allowed. Both HashSet and TreeSet are used for to store unique elements, but HashSet doesn't care about any order and TreeSet keeps a thing in order. Ordering or sorting on TreeSet can be customized by using Comparator interface, by default TreeSet uses elements natural order for sorting, which is defined by compareTo() method of java.lang.Comparable interface. What is the difference between HashSet and TreeSet is is also one the frequently asked Java interview question, So you should know about similarities and difference between them? It also helps you to understand when to use both TreeSet and HashSet and what are the scenario when we should use this sets. Let's go through the similarities and difference between HashSet and TreeSet in Java.

How to join two threads in Java? Thread.join() example

You can join two threads in Java by using join() method from java.lang.Thread class. Why do you join threads? because you want one thread to wait for another before starts processing. It's like a relay race where the second runner waits until the first runner comes and hand over the flag to him. Remember, unlike sleep(), join() is not a static method so you need an object of java.lang.Thread class to call this method. Now, who calls and who wants and which thread dies? for example, if you have two threads in your program main thread and T1 which you have created. Now if your main thread executes this line T1.join() (main thread execute whatever you have written in the main method) then main thread will wait for T1 thread to finish its execution. The immediate effect of this call would be that main thread will stop processing immediately and will not start until T1 thread has finished. So, what will happen if T1 is not yet started and there is no one to start T1 thread? Well,  then you have a deadlock but if it's already finished then main thread will start again, provided it get the CPU back.

OCAJP 7 or OCAJP 8? Which Java Certification should I take?

Java certification is a great way to learn and master the Java programming language, do well on the interview and get recognition in the job, but the most common reason for doing Java certification is to find a job. After Oracle's acquisition and dividing the old SCJP exam into two exams OCAJP and OCPJP, it has become really confusing for many developers to decide which Java certification exam they should take. Since technologies change fast and Java is no exception, it's just a year when Java 8 was released, and now people are talking about Java 9. In general, it is better to go with the latest version of a certification, which is currently available i.e., the Java 8 version. But in the case of Java certifications, it's not that simple.

How to calculate Maximum and minimum in Java? Beginner Tutorial

Today's programming exercise for a beginner is to write a Java program to take input from the user and find out maximum and minimum number and print them into the console. The purpose of this article is to teach you how to get input from a user in Java and how to use java.lang.Math class to perform some mathematical operation e.g. max, min or average. You can use Scanner class, added in Java 1.5 to read user input from the console. Scanner needs an InputStream to read data and because you are reading from the console, you can pass, which is InputStream for Eclipse console, or command prompt, depending upon what you are using. This class also helps you to convert user input into requiring data type e.g. if a user enters numbers then you must convert then into int data type and store them into int variable as shown in our example. You can use nextInt() method to read user input as Integer.

How to stop a thread in Java? Example

Today we're going to learn about how to stop a thread in Java. It's easy to start a thread in Java because you have a start() method but it's difficult to stop the thread because there is no working stop() method. Well, there was a stop() method in Thread class, when Java was first released but that was deprecated later. In today's Java version, You can stop a thread by using a boolean volatile variable.  If you remember, threads in Java start execution from run() method and stop, when it comes out of run() method, either normally or due to any exception. You can leverage this property to stop the thread. All you need to do is  create a boolean variable e.g. bExit or bStop. Your thread should check its value every iteration and comes out of the loop and subsequently from run() method if bExit is true. 

How to search an element inside LinkedList in Java? Example

You can search an element inside LinkedList in Java by using indexOf() and lastIndexOf() methods. Though LinkedList doesn't support random search like ArrayList, you can still go through the list, check each element and find out whether its interested element or not. Since java.util.LinkedList is an implementation of doubly linked list, these two methods are quite handy to search from either ends e.g. indexOf() method start search from head and return an element's position while lastIndexOf() starts the search from tail. Though the position is not relative to ends, they are always calculated from head. You can also use these two methods to find out duplicate elements. If an element is appeared twice in linked list then indexOf() and lastIndexOf() method will return different positions for that because it will be found at different position from head and tail. For unique elements, both these methods will return the same position.

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver [Solution]

Problem : You are getting java.lang.ClassNotFoundException: com.mysql.jdbc.Driver error while connecting to MySQL database from Java Program. You may be running your Java application directly from command prompt, shell script, ANT or Eclipse.

Cause : In order to connect to MySQL database, you need JDBC driver for MySQL. A class which implements java.sql.Driver interface for MySQL. Every vendor is responsible to implement this class for their databases. This driver implementation is provided by MySQL as MySQL java connector library. There is a class called com.mysql.jdbc.Driver which implements this interface.

'javac' is not recognized as an internal or external command

'javac' is not recognized as an internal or external command, operable program or batch file error comes when you try to compile a Java source file using javac command e.g. javac but your PATH is not set properly. It means that javac.exe executable file, which exists in bin directory of JDK installation folder is not added to PATH environment variable. You need to add JAVA_HOME/bin folder in your machine's PATH to solve this error. You cannot compile and run Java program until your add Java into your system's PATH variable. Here is how this error looks like in command prompt of windows machine :

How to use Final keyword in Java? Examples

You can use the final keyword with variables, methods and classes in Java. You can use the final modifier with variables to make them constant. A final variable is initialized only once in its lifetime, once initialized you cannot change its value. Though you can initialize the final variable at the time you declare them or you can initialize them at constructor if they are blank final variable. A static final variable, also known as constant must be initialized in the same line. You can also use the final modifier with methods to prevent method overriding. In Java, you cannot override final methods. This is usually done to signal that method is complete and it's not designed for extension. It is also done to prevent someone deliberately or accidentally changing core logic of method by overriding it e.g. in template design pattern, the method which keeps the algorithm, also known as template method should be final because the outline of the algorithm should be changed by child classes.

How to parse String to long in Java? Example

You can parse a String literal containing valid long value into a long primitive type using parseLong() and valueOf() method of java.lang.Long class of JDK. Though there are couple of difference between valueOf() and parseLong() method e.g. valueOf() method return a Long object while parseLong() method return a Long object, but given we have autoboxing in Java, both method can used for parsing String to create long values. In the last article, you have learned how to convert a Long value to String in Java and in this tutorial, you will learn opposite, i.e. how to parse a String to a long value in Java. As I said, there are the couple of ways to do it, but the most important method is parseLong(). This method is responsible for parsing input String and creating primitive long value corresponding to input String. It does input validation and throws NumberFormatException if you pass String which is not valid long value e.g. alphanumeric String, String containing characters other than +, - and numbers, long values which are out of range, lonely + or - character etc.

How to convert long to String in Java? Example

There are three main ways to convert a long value to 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 method to convert a long data type into String object. It's not very different than from how you convert an int to String in Java. Same method applies here as well. String concatenation seems the easiest way of converting a long variable to String, but others are also convenient.  If you look Java code for valueOf() method from java.lang.String class you will realize that it actually calls the toString() method of java.lang.Long class for conversion, which means there is only one method where logic of converting primitive long to String is written. Nevertheless, if you are not converting long in loop all method will perform same, but if you have to convert large number of long values to String then directly using Long.toString() method can be quite useful. 

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

What is difference between hard link and soft link in UNIX?

There are two types of links in UNIX system, hard link and soft links, also known as symbolic link or symlink. Though both points to some other source, there are a lot of difference between them. hard link is direct pointer to the inode of the original file. If you compare the original file with the hard link there won't be any differences between them. On other hand, a soft link is a file that have the information to point to another file or inode. That inode points to the data in the disk. Hard links are much more restrictive than soft links and that's why they are used rarely. Also not all file systems supports hard links but UNIX does. Earlier Windows file system doesn't support soft links but from Windows 2000 onward they are supporting it, both Windows Vista and Windows 7 support links now. MS DOS operating system doesn't support neither hard link nor soft link. You can use ln command in UNIX to create, update and remove soft links. I often use links for build and release management purpose e.g. our application never points to hard-coded file or directory instead it points to links which is updated on every release.

Difference between Type 1, 2, 3 and 4 JDBC Driver in Java?

One of the oldest Java interview question is what is the difference between different types of JDBC drivers e.g. what is the difference between type 1, type 2, type 3 or type 4 drivers? Sometimes also asked as how do you choose between different JDBC driver? When to use type 3 over type 4 driver etc. It's 2015 now and I doubt anyone is using JDBC driver other than type 4 for connecting to database, but let's see how to answer this question when you face it during the interview. The difference between different types of JDBC driver comes from the fact how they work, which is basically driven by two factors, portability, and performance. Type 1 JDBC driver is the poorest in terms of portability and performance while type 4 JDBC driver is highly portable and gives the best performance. You will learn more differences between different JDBC drivers as we go along.

How to use PriorityQueue in Java? An Example

PriorityQueue is another data structure from Java Collection framework, added in Java SE 5. This class implements Queue interface and provides a sorted element from the head of the queue. Though it provides sorting, it's little different with other Sorted collections e.g. TreeSet or TreeMap, which also allows you to iterate over all elements, in priority queue there is no guarantee on iteration. The only guaranteed PriorityQueue gives is that lowest or highest priority element will be on 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 append text to existing File in Java? Example

In the last tutorial, you have learned about 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 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. This means you can write new content at the end of the file. One of the common examples of appending text to file is logging but for that you don't need to write your own logger, there are several good logging library available in Java world e.g. Log4j, SLF4j, Logbak and even java.util.logging is good enough.