Preparing for Java Interview?

My books Grokking the Java Interview and Grokking the Spring Boot Interview can help

Download a Free Sample PDF

How to find length/size of ArrayList in Java? Example

You can use the size() method of java.util.ArrayList to find the length or size of ArrayList in Java. The size() method returns an integer equal to a number of elements present in the array list. It's different than the length of the array which is backing the ArrayList, which is called the capacity of ArrayList. When you create an object of ArrayList in Java without specifying a capacity, it is created with a default capacity which is 10. Since ArrayList is a growable array, it automatically resizes when the size (number of elements in the array list) grows beyond a threshold. 

How to remove all elements of ArrayList in Java - RemoveAll Example

There are two ways to remove all elements of an ArrayList in Java, either by using clear() or by using the removeAll() method. Both methods are defined in the java.util.List and java.util.Collection interface, hence they are available not just to ArrayList but also to Vector or LinkedList, etc. Both elements remove all objects from ArrayList but there is a subtle difference in how they do. The clear() method is straightforward, it traverses through the ArrayList and sets all indices to null, which means the ArrayList becomes empty and all elements become eligible to Garbage collection, provided there are no more references to them.

How to loop over a TreeSet in Java with Example

In our earlier articles, we have learned how to loop over ArrayList in Java and you can use the same logic to loop over a TreeSet. You can use both, enhanced for loop and Iterator to traverse over TreeSet in Java. Though worth noting is that Iterator returned by the iterator() method of TreeSet returns elements in the sorted order which is imposed by the Comparator you have provided to TreeSet at the time of instantiation. By default, if you don't provide any custom Comparator then TreeSet sorts elements in their natural order like String elements are sorted in alphabetical order and Integer elements are sorted in numeric order. When you iterate over a TreeSet the iterator follows this order.

How to Convert Vector to Array in Java? 2 Examples

In the last article, we have learned how to convert a LinkedList to an array in Java, and in today's tutorial, you will learn how to convert a Vector to an array in Java. There is a similarity between Vector and LinkedList, both implement the List interface. Even though Vector is a legacy class and exists in Java from JDK 1.1 long before the Java Collection framework was introduced, it was later retrofitted to implement the List interface. You can use the same toArray() method to convert a Vector to an array in Java. 

How to sort a LinkedList in Java? Example Tutorial

Since LinkedList implements the java.util.List interface, you can sort the LinkedList by using the Collections.sort() method, just like you sort an ArrayList. Since the LinkedList class implements the linked list data structure which doesn't provide random access based upon the index, sorting is quite expensive. In order to access any element, you need to first traverse through that element which is the O(n) operator. This method uses an efficient strategy to handle this scenario. It first copies the contents of LinkedList to an array, sorts the array, and copies it back. 

How to Convert a List to a Set in Java with Example

How to convert a List to Set in Java
Many times we need to convert one collection to another like converting a List to a Set. It's also an easy way to copy contents from one collection to other in Java, like from List to Set or Set to List. Thanks to the Collection framework in Java, copying collections from one to another is extremely easy. Since every Collection class implements a Collection interface that defines the addAll() method, which can be used to create a collection from contents of another collection.

Difference between ArrayList and HashMap in Java

Difference between ArrayList and HashMap in Java
One of the most critical differences between the HashMap and ArrayList class is that the former is the implementation of the hash table while the latter is a dynamic array that can resize itself. The HashMap and ArrayList are two of the most popular classes from the Java Collection framework. Though both are used to store objects they are completely different in their implementation, working, and usage. The main difference between ArrayList and HashMap is that ArrayList is an index-based data structure backed by an array while HashMap is a map data structure that works on hashing to retrieve stored values. 

How to sort HashSet in Java? Example

Somebody asked me recently, how do you sort a HashSet? For lists, we use the Collections.sort(List) method, but there is nothing for Set. If I have a HashSet then how would I go about sorting it? The answer is you cannot sort a HashSet, why? because HashSet is an unordered collection. When you insert an element in HashSet then you lose the order guarantee. You cannot do reordering or sorting in Set because it does not have random access methods (ie, .get() an element at a given index), which is basically required for sort algorithms.

How to declare ArrayList with values in Java? Examples

Sometimes you want to create an ArrayList with values, just like you initialize t at the time of declaration, as shown below:

int[] primes = {2, 3, 5, 7, 11, 13, 17};
or
String[] names = {"john", "Johnny", "Tom", "Harry"};

but unfortunately, ArrayList doesn't support such kind of declaration in Java. But don't worry, there is a workaround to declare an ArrayList with values e.g. String, integers, floats, or doubles by using the Arrays.asList() method, which is nothing but a shortcut to convert an Array to ArrayList.

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

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.

Difference between HashMap and LinkedHashMap in Java

Difference between LinkedHashMap and HashMap in Java
HashMap and LinkedHashMap are two of the most commonly used Map implementation in Java. The main difference between HashMap and LinkedHashMap is that LinkedHashMap maintains the insertion order of keys, the order in which keys are inserted into LinkedHashMap. On the other hand, HashMap doesn't maintain any order or keys, or values. In terms of performance, there is not much difference between HashMap and LinkedHashMap but yes LinkedHashMap has more memory footprint than HashMap to maintain doubly LinkedList which it uses to keep track of the insertion order of keys. 

Difference between TreeMap and TreeSet in Java? Answer

Difference between TreeSet and TreeMap in Java
The main difference between TreeMap and TreeSet is that TreeMap is an implementation of Map interface while TreeSet is an implementation of the Set interface. There are some similarities between both TreeMap and TreeSet and few differences as well. In this Java tutorial, we will first see similarities between TreeMap and TreeSet, and then you will learn some differences between TreeMap and TreeSet in Java. 

Difference between FileReader vs FileInputStream in Java? Answer

Even though both FileReader and FileInputStream are used to read data from a file in Java, they are quite different. The main difference between the FileReader and FileInputStream is that one reads data from a character stream while the other reads data from a byte stream. The FileReader automatically converts the raw bytes into characters by using the platform's default character encoding. This means you should use this class if you are reading from a text file that has the same character encoding as the default one. 

How to Create Read Only and Unmodifiable ArrayList in Java? Example

Read-only Collection in Java
You can create read-only Collection by using Collections.unmodifiableCollection() utility method. it returns an unmodifiable or read-only view of Collection in which you can not perform any operation which will change the collection like add(), remove() and set() either directly or while iterating using Iterator or ListIterator. It will throw UnsupportedOperationException whenever you try to modify the List. 

Difference between HashSet and TreeSet in Java

Difference between HashSet and TreeSet in Java
There are several differences between a HashSet and a TreeSet are similar to what we discussed as a difference between TreeMap and HashMap. Anyway, Set and Map are two completely different interfaces so we will revisit those differences here. Probably the most important difference between HashSet and TreeSet is the performance. HashSet is faster than TreeSet which means if you need performance use HashSet but HashSet doesn't provide any kind of ordering so if you need ordering then you need to switch to TreeSet which provides sorting of keys

How to handle click event in jQuery - Example

In the world of web development, interactivity is key to creating engaging user experiences. One fundamental aspect of interactivity is the ability to respond to user actions, such as clicks. jQuery, a fast and concise JavaScript library, has long been a favorite among developers for simplifying common tasks, including event handling.  You can handle click event in jQuery by using event handlers. You can bind event handlers to any element by using on() method or click() method. The event handler is nothing but a function containing some code which will be executed when user will click on the element. For example, if user clicks on a button then color of button might changed to show on and off behavior. All this can be implemented by handling click event in jQuery. 

Top 5 Java Main method Interview Questions with Answers

Hello Java programmers, the main() method in Java is the starting point of any standalone core Java application. JVM starts executing Java program from main method and the thread which executes main is called main thread in Java. The main method is also an important topic in Java interviews for 2 to 3 years of experienced developers. In this Java article, we will a couple of questions related to the main method in Java. Apart from Why main is static in Java, I see the following questions keep coming related to the main method:
  1. Can we overload the main method in Java? Which main method JVM will call?
  2. Can we override the main method in Java?
  3. Can we make the main final in Java?
  4. Can we make the main synchronized in Java?
  5. How to call a non static method from main in Java?

Difference between NoClassDefFoundError vs ClassNotFoundExcepiton in Java

Both NoClassDefFoundError and ClassNotFoundException are dangerous errors that come when JVM or ClassLoader not able to locate class during the class loading process. Since different ClassLoader loads classes from a different location, sometimes this issue may be caused because of incorrect CLASSPATH as well i.e. some JAR files from lib are missing or from the old version. Though looks quite similar there is a subtle difference between NoClassDefFoundError and ClassNotFoundException, NoClassDefFoundError indicates that the class was present during the time of compilation but not available when you run Java program, sometimes error on static initializer block can also result in NoClassDefFoundError.

Difference between Public, Package, Private and Protected in Java?

In Java, you have got something called an access modifier, which specifies the accessibility of class, methods, and variables. There is four access modifier in Java namely public, private, protected and the default access modifier, also known as package level modifier. The difference between these access modifiers comes in their ability to restrict access to a class, method, or variables, public is the least restrictive access modifier while private is the most restrictive access modifier, package, and protected lies in between. 

Difference between HashSet vs TreeSet in Java? [Answer]

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 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 the Comparator interface, by default TreeSet uses elements of natural order for sorting, which is defined by the compareTo() method of java.lang.Comparable interface.  What is the difference between HashSet and TreeSet is also one of the frequently asked Java interview questions, So you should know about similarities and differences between them? 

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. 

Difference between ROW_NUMBER(), RANK() and DENSE_RANK() in SQL

The main difference between ROW_NUMBER() and RANK() in SQL server is that ROW_NUMBER doesn't handle ties while RANK() does. Though both ROW_NUMBER() and RANK() are window function used for ranking row, the way they handle duplicates differentiate them. ROW_NUMBER() function assigns a unique number to each row starting from 1 and arbitrarily assign values if two rows are equal, which means it's not guaranteed that which row will get 2nd or 3rd position if they are identical. In contrast, RANK() assigns an equivalent rank to similar rows, which creates gaps between RANK. 

Difference between Method and Constructor in Java and OOP? Example

What is the difference between method and constructor in Java is a very common question in beginner-level Java interviews with 2 to 3-year experience. Since the constructor is kind of special and it has its own properties that separate it from any normal Java method, this question makes sense. The main difference between a Constructor and a Method is that you need to call the method explicitly but the constructor is called implicitly by the Java programming language during object instantiation. This is one of the special properties of constructors in Java and that's why all the object initialization code is put inside the constructor. 

What is static in Java? Example Tutorial

What is static in Java
Static in Java is related to class if a field is static means it belongs to the class, similarly static method belongs to classes and you can access both static method and field using the class name, for example,  if count field is static in Counter class than you can access it as Counter.count, of course, subject to restriction applied by access modifier like private fields are only accessible in class on which they are declared, protected fields are accessible to all classes in the same package but only accessible in subclass outside the package, you can further see private vs protected vs public for complete details on access modifier. 

Can you make an Abstract Class or Method Final in Java? Example

No, you cannot make an abstract class or method final in Java because the abstract and final are mutually exclusive concepts. An abstract class is incomplete and can only be instantiated by extending a concrete class and implementing all abstract methods, while a final class is considered complete and cannot be extended further. This means when you make an abstract class final, it cannot be extended hence it cannot be used and that's why the Java compiler throws a compile-time error when you try to make an abstract class final in Java. In short, an abstract class cannot be final in Java, using both abstract and final modifiers with a class is illegal in Java. 

What is Variable and Method Hiding in Java - Example Tutorial

If Java, if you are not careful you can possibly hide both methods and variables of the superclass. Now you must be wondering what does it mean by hiding a variable or method in Java? A field or variable is said to hide all fields with the same name in superclasses. Similarly, a static method with the same name in a subclass can hide the method of the superclass. This can lead to subtle bugs, especially if you are expecting a different method to be called. In this article, I'll show you examples of both variables and methods hiding in Java so that you can understand and avoid them in the future. Earlier, I also wrote about difference between overloading, overriding, shadowing, and hiding, it's a comprehensive post and I suggest you to read it as well if you haven't read already.  It will help you to understand these concepts in more detail. 

Difference between Abstract class and Interface in Java 8? Answer

Ever since JDK 8 has allowed concrete (non-abstract) methods on the interface like default and static methods, many of my readers have asked me how should they answer the classical abstract class vs interface questions. Earlier, an interface cannot have any concrete methods and that was the main difference between abstract class and interface but now that is not the case. In this post, I'll revisit this hugely popular Java interview question in light of Java 8 changes. This is also a popular Java interview question and knowing the difference will help you to answer this question in a real interview.

How to Fix java.lang.OutOfMemoryError: Metaspace in Java? [Solution]

Hello guys, An OutOfMemoryError related to Metaspace indicates that your Java application has exhausted the memory allocated for the Metaspace area, which is used for class metadata and method information. This error typically occurs when an application dynamically generates and loads a large number of classes or when the Metaspace size is not properly configured to handle the application's requirements.  Java class metadata (the virtual machine's internal presentation of Java class) is allocated in native memory (referred to here as metaspace). If metaspace for class metadata is exhausted, a java.lang.OutOfMemoryError exception with a detail MetaSpace is thrown. 

Java Interface Example Tutorial

Hello guys, if you are wondering what Java interface is and how to do your user interface in Java, you have come to the right place. Earlier, I have written about the actual use of the interface in Java, and in this article, I will give you an example of an interface in Java. I will also explain what an interface is and how and where you should use it. An interface is nothing but a name. As Joshua Bloch advised in the Effective Java book, the interface is great for declaring type. So, if you want to declare your own type like Employee, Order, Listener, etc., you can use the interface. 

How Constructor Chaining works in Java - Example

How to call one constructor from another constructor in Java or What is Constructor Chaining in Java is one of the tricky questions in Java interviews. Well, you can use this keyword to call one constructor from another constructor of the same class if you want to call a constructor from a based class or super class then you can use the super keyword. Calling one constructor from another is called Constructor chaining in Java. Constructors can call each other automatically or explicitly using this() and super() keywords. this() denotes a no-argument constructor of the same class and super() denotes a no argument or default constructor of the parent class. Also having multiple constructors in the same class is known as constructor overloading in Java.

5 Rules of Method Overloading and Overriding in Java? Examples

Since you can either overload or override methods in Java, it's important to know what are the rules of overloading and overriding in Java. any overloaded method or overridden method must follow rules of method overloading and method overriding to avoid compile-time error and logical runtime errors;  where you intend to override a method but the method gets overloaded. That is not uncommon and happens several times when a Java programmer tries to override equals in Java or overriding the compareTo method in Java while implementing a Comparable interface, which accepts the Object type of argument. 

Difference between Method Overloading and Overriding in Java? Answer

Overloading vs Overriding in Java
In the last couple of articles, we have seen What is method overloading and What is method overriding in Java and now we will see What is difference between overloading and overriding in Java. Overloading vs overriding is one of those frequently asked Java interview questions which can not be ignored. Overloading vs Overriding has appeared in almost every Java interview, mostly at beginner and intermediate level like 2 to 4 years experience. In fact, most of those tricky Java interview Questions came from Overloading and Overriding. 

Can You Override Private Method in Java ? Example

No, We can not override the private method in Java, just like we can not override the static method in Java. Like static methods, the private method in Java is also bonded during compile time using static binding by Type information and doesn't depend on what kind of object a particular reference variable is holding. Since method overriding works on dynamic binding, it's not possible to override the private method in Java. 

How to fix java module error "Caused by: java.lang.reflect.InaccessibleObjectException: module java.base does not "opens java.util" to unnamed module"

The error message you're seeing, (Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make field private final java.util.Comparator java.util.TreeMap.comparator accessible: module java.base does not "opens java.util" to unnamed module @6d4a82") or  java.lang.reflect.InaccessibleObjectException, is related to module system changes introduced in Java 9 and later versions. It occurs when you try to access a field, method, or class that is not accessible due to module restrictions. In this case, it appears that you're trying to access the private final java.util.Comparator field of a java.util.TreeMap, which is not accessible because the java.base module does not open java.util to unnamed modules.

Difference between Class and Interface in Java and OOP? (with Example)

It is one of the frequently asked Java questions from beginners who struggle to get the concept behind an interface. The main difference between a class and an interface lies in their usage and capabilities. An interface is the purest form of abstraction available in Java where you just define the API or contract e.g. you define run() method on the Runnable interface without worrying about how something will run, that is left to the implementor which will use a class to define how exactly to run. So an interface gives you a method name but how the behavior of that method has come from the class which implements it.

10 Essential Object Oriented Concepts for Java Developers

I have written several OOP (Object Oriented Programming) concepts tutorials in past and I was thinking to bring them together so that anyone who wants to learn OOP basics can benefit from them easily. In this article, I will share with you my collection of OOP tutorials and OOP concepts interview questions, which will not only help you to understand four pillars of Object-Oriented programming like Abstraction, Encapsulation, Inheritance, and Polymorphism but also powerful design techniques of Aggregation, Association, and Composition, along with SOLID design principles, which are key to write flexible, extensible and object-oriented software. 

Difference between Static binding vs Dynamic binding in Java? [Answer]

In order to understand the difference between static and dynamic binding in Java, it's important to first learn what is binding? Binding means the link between reference and actual code e.g. when you refer a variable it's bonded to the code where it is defined, similarly when you call a method, it's linked to the code where a method is defined. There are two types of method binding in Java, static binding and dynamic binding. When a method is called in Java it's bonded to the actual code either at compile time or runtime, when the program is actually started and objects are created. 

What is Inheritance in Java with example - Object Oriented Programming Tutorial

What is Inheritance in Java
Inheritance in Java or OOPS (Object-oriented programming) is a feature that allows coding reusability.  In other words, Inheritance self-implies inheriting or we can say acquiring something from others. Along with Abstraction, Encapsulation, and Polymorphism, Inheritance forms the backbone of Object-oriented programming and Java.  In Java, we use the term inheritance when one object acquires some property from other objects. In Java, inheritance is defined in terms of superclass and subclass. it is normally used when some object wants to use an existing feature of some class and also wants to provide some special feature, so we can say inheritance has given the advantage of reusability.

19 Java and OOP Method Overloading and Overriding Interview Questions and Answers

Method overloading and overriding are some of the tricky concepts to master and that's why it's one of the most popular topics in Java Interviews. You will often see questions like what is the difference between overloading and overriding? or can you overload methods in the same class? during the first few rounds of interviews, mostly at telephonic rounds. Since it's part of object-oriented fundamentals it's also good to know as much about these concepts as possible. In this article, I am sharing some of the basic but frequently asked questions which are solely based upon overloading and overriding concept and their implementation in Java programming language. 

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 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 create a class with methods and attributes in Java? Example Tutorial

Hello guys, we are again with new article that is on Creating Class with methods and attributes in Java. The main aim of this article is to give you idea about how to declare a class or method in Java and about different ways of declaring. In the world of Java programming, class serve as the fundamental building blocks for creating objects and defining the structure of your applications. These classes encapsulate data and behavior, allowing you to model real-world entities and implement the logic that governs their interactions.

How to convert a List to Array in Java? Example Tutorial

There is no easy way to convert an array to a list in Java, but you can easily convert a list into an array by calling the toArray() method, which List inherits from the Collection interface. If you solely rely on core JDK, then the only way to convert an array to a list is by looping over the array and populating the list one element at a time. But if you can use open source libraries like Google Guava or Apache Commons lang then there are many utility classes to convert list to array and vice-versa, as shown in this tutorial. If you are working on a Java application, you will often need to convert between list and array. 

How to search a 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 it's an interesting element or not. Since java.util.LinkedList is an implementation of a doubly-linked list, these two methods are quite handy to search from either end e.g. indexOf() method starts the search from the head and returns an element's position while lastIndexOf() starts the search from the tail. Though the position is not relative to the ends, they are always calculated from the head.

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

PriorityQueue in Java? Example Tutorial

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.

10 Examples of HashMap in Java - Programming Tutorial

The HashMap in Java is one of the most popular Collection classes among Java programmers. After my article on How HashMap works in Java, which describes the theory part of Java HashMap and becomes hugely popular among Java programmers, I thought to share how to use HashMap in Java with essential and fundamental HashMap examples, but couldn't do that earlier and it was slipped but today we are here with all the HashMap examples about getting values to checking if a key exists in Map, I am going to share everything a Java developer should know about HashMap. The HashMap is a data structure, based on hashing, which allows you to store an object as a key-value pair, an advantage of using HashMap is that you can retrieve objects on constant time i.e. O(1) if you know the key.

How to convert a Map to List in Java? HashMap to ArrayList 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 HashSet works in Java [Explained with Example]

Not many Java programmers 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 the earlier class, then you know that HashMap allows duplicate values, and this property is exploited while implementing HashSet in Java.

How get() and put() methods of HashMap works in Java? [Explained]

In this article, I am revisiting a couple of interesting questions related to the internal working of HashMap in Java, mostly asked senior Java developers, ranging from 4 to 6 and up to 8 years of experience. I did cover a lot of these questions from HashMap, ranging from thread-safety to race conditions, in my post about the internal working of Java HashMap, but I thought to revisit two of those questions, how does get and put method of HashMap or Hashtable works internally in Java and what happens if two different keys return the same hashCode, how do you return value from HashMap in that case. 

4 ways to read String from File in Java - Example

Just like there are many ways for writing String to text file, there are multiple ways to read String form File in Java. You can use FileReader, BufferedReader, Scanner, and FileInputStream to read text from file. One thing to keep in mind is character encoding. You must use correct character encoding to read text file in Java, failing to do so will result in logically incorrect value, where you don't see any exception but content you have read is completely different than file's original content. Many of the method which is used to read String by default uses platform's default character encoding but they do have overloaded version which accepts character encoding. 

How to check if a Key Object Exists in HashMap Java? containsKey() Example Tutorial

Hello Java programmers, if you have working in Java programming language or writing server side programs then you may know that one of the common programming tasks while using HashMap in Java is to check if a given key exists in the map or not. This is supposed to be easy, right? Yes, it is easy if you know JDK API well, all you need to is call the containsKey() method, it returns true if the given key exists in HashMap, otherwise false; but I have seen many programmers write code like below which is not correct, which inspired me to write this blog post.

if(map.get(key) !=  null){
    System.out.println("key exists in Map");
}

This code is fragile, it will not work if you have added null values into HashMap because HashMap does allow null values.

How to sort HashMap by values in Java 8 [using Lambdas and Stream] - Example Tutorial

In the past, I have shown you how to sort a HashMap by values in Java, but that was using traditional techniques of the pre-Java 8 world. Now the time has changed and Java has evolved into a programming language that can also do functional programming. How can you, a Java Programmer take advantage of that fact to do your day-to-day task better like how do you sort a Map by values in Java using lambda expressions and Stream API. That's what you are going to learn in this article. It will serve two purposes, first, it will tell you a new way to sort a Map by values in Java, and, second and more important it will introduce you to essential Java 8 features like Lambda Expression and Streams, which every Java Programmer should learn.

How to use ConcurrentHashSet from ConcurrentHashMap in Java 8 - Example Tutorial

There is no ConcurrentHashSet in JDK 8, but you can still create one for yourself using the ConcurrentHashMap class of java.util. Concurrent package. A new method is added into ConcurrentHashMap in JDK 8, newKeySet(), which allows you to create a concurrent hash set backed by a concurrent hash map. If you remember, whenever you get keys from the map, they are returned in a Set e.g. for the old keySet() method, because the map only has unique keys. Since the map doesn't allow duplicate keys, it can be used as a set, as long as you only care for keys or just one element. 

How to initialize HashMap with values in Java? Example

There is often a situation where you would like to create a HashMap with some pre-defined mapping, but unfortunately, Java doesn't provide map literals like Groovy or Scala to create the map with values in the same line. If you remember, we have faced the same issue with other Collection classes as well e.g. ArrayList, Vector, or LinkedList. But ArrayList is lucky because you can still use the Arrays.asList() method to create and initialize the ArrayList in just one line as shown here. But, how do you initialize the HashMap with values in Java? 

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.

Right way to check if String is empty in Java with Example

What do most of us Java Programmers do while using String in Java? Check 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 empty, it is considered to contain one character and its length is equal to 1. 

Java 8 StringJoiner Example - How to join multiple Strings with delimiter in Java?

While everyone was looking at the lambda expression and Stream API, JDK quietly sneaked some of the exciting methods on its API. There are a lot of hidden gems on JDK 8 and I have uncovered many of them already in this blog and today we'll talk about one of such gems which you can use in your day-to-day programming activities like joining much String together. The Java 8 has added a new class called StringJoiner to join Strings. The java.util.StringJoiner can be used to join any number of arbitrary String, a list of String, or an array of String in Java. You can choose any delimiter to join String like comma, pipe, colon, or semi-colon. This class also allows you to specify a prefix and suffix while joining two or more String in Java.

How to Join Multiple Strings in Java 8 - String join() Example

Hello guys, I have been writing about the new features of Java SE 8 for quite some time. Initially, my focus areas on much talked about lambda expressions and streams, but slowly I realized that Java 8 is not just about them, it's much more than that. It has many more new features and API enhancements that will help Java developers in their day-to-day job as much as lambdas and streams. One of such less talked features is the ability to join multiple String objects into one separated with any delimiter. It has added a class called StringJoiner in java.util package which we have seen earlier, but it has also added a new method on String class, the join() method, which finally allows you to join Strings in Java.

10 Points about String in Java with Examples

someone might question that why do we need another article about string in Java, haven't we had enough about the string is already written? Yes, I agree there are a lot of articles related to Java string covering topics like how to use Java String, an example of Java string, and almost everything you can do with string in Java. But, I wanted to document my experience of using String in Java and some nasty and little-known things I discovered about the Java String class, which may not be obvious to many Java developers.

How to Remove all white spaces from String in Java? From Start, End and between Words Examples

String API in Java provides several utility methods to remove white space from String in Java, from the beginning, end, and between words. White space means blank space including tab characters. One of the classic methods to remove white space from the beginning and end of a string in Java is the trim() method, which removes white space from beginning and end. While using the trim() method, the key thing to remember is that trim() returns a different String object than the older one because String is immutable in Java

3 ways to convert String to byte array in Java - Example Tutorial

Today, I am going to discuss one of the common tasks for programmers, converting a String to a byte array. You need to do that for multiple reasons like saving content to a file, sending over a network, or maybe some other reason. Suppose you have a string "abcd" and you want to convert it into a byte array, how will you do that in a Java program? Remember, String is made of the char array, so it involves a character to byte conversion, which is subject to character encoding intricacies

Java - Convert String to Boolean Example

There are two ways to convert a String to a boolean in Java, first, by using Boolean.parseBoolean() method, and second, by using Boolean.valueOf() method. The parseBoolean() method returns an equivalent boolean value of a given String, for example, if you pass "true" it will return the primitive boolean value true. Similarly, if you pass "false" it will return false. The good thing about this method is that it is case insensitive, which means if you pass "true", "TRUE", or "True" you will still get a true boolean value.

How to convert lowercase String to uppercase in Java? Example

Convert String from uppercase to lowercase in Java
Sometimes we need to convert String from lowercase to uppercase or from uppercase to lowercase e.g. before printing or storing into a database etc. String class in Java provides some utility method to perform this case conversion. You can use toUpperCase() to convert any lower case String to uppercase and toLowerCase() to convert any uppercase String to lowercase. Key thing to remember while using toUpperCase() and toLowerCase() is that they return a different string rather than modifying the same String because String is immutable in Java

How to Compare and Sort String by their length in Java? Example

One of the common programming tasks is to compare String, sometimes by their value and sometimes by their length. The natural way to compare String is the lexicographic way, which is implemented in the compareTo() method of String class, but sometimes you need to compare String by their length. You cannot use the default compareTo() method for that task, you need to write your own custom Comparator, which can compare String by length. Don't worry, It's easy to compare multiple String by their length, all you need to do is write a Comparator implementation which calculates their length using the length() method and compares them.

Difference between == and equals() method in Java? String Example

What is the difference between == and equals() method for comparing Objects in Java is one of the classical Interview Questions which appears now and then in many interviews? This question is mostly asked in conjunction with String because comparing String using == and equals() method returns different results. I have often seen along with other popular String questions like StringBuffer vs StringBuilder, Why String is final etc.  Java is a pure object-oriented language and every object has one state and location in the memory and equals () and == are related to the state and location of the object, now in this article will try to understand this concept and the difference between == and equals method in Java.

How to check String contains a text in Java? contains() and indexOf() Example

Sometimes you want to check if one String contains another String or SubString or not e.g. "HelloWorld" contains "Hello" and "World" SubString. There are many ways to check SubString in String in Java e.g. contains(), indexOf(), or matches() method of java.lang.String class. In the last article, we have seen how to use matches method of String class with a regular expression and In this article we will see example of contains() and indexOf() method to check any String or SubString in Java. 

Difference between String and StringBuffer in Java? Answer

String vs StringBuffer in Java
String and StringBuffer are two classes that are most widely used in any Java program. If I say you can not write a program without using String in Java then it would not be an exaggeration. The string is everywhere, the main method accepts a String argument, logs are String, etc. Though many Java programmers familiar with String, not many are careful while performing operations on String, Since String is final in Java; every operation like converting String into Uppercase, creating SubString,  converting String to Lowercase all result in a separate new String Object, which can take trigger frequent garbage collection and affect your application performance.

7 Examples of formatting String Java - String.format() and printf() Examples

You can format String in Java either by using the String.format() method or by using the System.printf() method, both use TextFormat class to format String input internally. Both of these methods are inspired from C-Style printf() method and formatting instructions are very similar to C e.g. %s for String, %d for numeric, %f for floating-point value, and %n for new lines, etc, but it is not exactly same as C. Some customization has been made to accommodate some Java language features. 

How to split String by comma in Java - Example Tutorial

In the earlier article, I have shown you how to split String by regular expression and now, you will learn how to split string by comma. Since CSV is a popular format for exporting data, you often need to split a comma-separated String to create an array of individual Strings. Similar to the earlier example, you can use the split() method to accomplish this task. Just pass a "," instead of "\\s+" the regular expression to remove whitespaces, as the regular expression.  The split method will return an array of String, which you can further convert to a list of String. 

5 Examples of substring() in Java

SubString in Java is a useful method from java.lang.String class, which is used to create smaller String from bigger ones. The way Substring works prior to Java 1.7 can create a subtle memory leak because both String and their substring share the same character array. This means, if you have a big String of 200MB and created a substring of 2MB from that, that could prevent 200MB String from being garbage collected. I agree this doesn't look normal and indeed was a bug, but it was like that till Java 1.6 and its various updates. 

2 ways to parse String to int in Java - Example Tutorial

Java provides Integer.parseInt() method to parse a String to an int value, but that's not the only way to convert a numeric String to int in Java. There is, in fact, a better way, which takes advantage of the parsing logic of the parseInt() method as well as caching offered by the Flyweight design pattern, which makes it more efficient and useful. Yes, you guessed it right, I am talking about the Integer.valueOf() method, which implements the Flyweight design pattern and maintains a cached pool of frequently used int values e.g. from -128 to 127

6 ways to convert char to String in Java - Example Tutorial

If you have a char value like 'a' and you want to convert it into equivalent String like "a" then you can use any of the following 6 methods to convert a primitive char value into String in Java are String concatenation,  String.valueOf(),  Character.toString() method,  Character wrapper class + toString method, String constructor with a char array, and String.valueOf(char []) method.  In this article, we will see examples of each approach and learn a little bit more about it. Actually, there is a lot of overlap between each method as some of them internally call String.valueOf(), which eventually calls to a String constructor which accepts char array and creates a String object containing primitive char value with length 1. Once you know, how they work internally, it easy to decide which one is more efficient for the purpose.

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. 

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. 

How to Make Executable JAR file in Eclipse IDE - Java Example

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. 

Difference between @GetMapping @PostMapping @PutMapping @DeleteMapping @PatchMapping

In the world of web development, the Spring Framework is widely known for its versatility and ease of use. It provides several annotations that simplify the process of handling HTTP requests and mapping them to specific methods in Spring controllers. Among these annotations, @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, and @PatchMapping are some of the most commonly used ones. In this article, we will explore each of these annotations in detail, highlighting their purposes, differences, and providing examples to better understand their usage.

How to Perform Binary Tree InOrder traversal in Java using Recursion? Example Tutorial

The InOrder traversal is one of the three popular ways to traverse a binary tree data structure, the other two being the preOrder and postOrder. During the in-order traversal algorithm, the left subtree is explored first, followed by root, and finally nodes on the right subtree. You start traversal from root then go to the left node, then again go to the left node until you reach a leaf node. At that point in time, you print the value of the node or mark it visited and move to the right subtree. Continuing the same algorithm until all nodes of the binary tree are visited. The InOrder traversal is also known as the left-node-right or left-root-right traversal or LNR traversal algorithm.

How to Remove all adjacent duplicates characters from String in java? Example Tutorial

Hello guys, if you are wondering how to remove adjacent repeated characters or duplicates from a given String in Java then you have come to the right place. In the last article, we have seen how to find duplicate characters as well as how to remove duplicate characters from String in Java, and in this article, we will take that topic to another level and remove adjacent duplicates from given String. This topic gives another perspective to removing duplicates in a word or phrase. Probably before now, you are familiar with removing duplicates from a word or phrase, or number. But this topic gives a detailed understanding of how to remove adjacent duplicates. 

How to Find Duplicate Characters in String [Java Coding Problems]

Hello guys, 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 like a = 2 because of 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 tests, where you need to write code. On the difficulty level, this question is at par with the prime numbers or Fibonacci series, which are also very popular on junior level Java programming interviews and it's expected from every programmer to know how to solve them.

How to Implement Binary Tree InOrder traversal in Java without Recursion - Example Tutorial

I have been writing about different binary tree traversal algorithms and so far we have seen both pre-order and post-order algorithms to traverse a binary tree and today you'll learn about the in-order or sorted order algorithms. This is actually the second part of implementing the inorder traversal of a binary tree in Java, in the first part, I have shown you how to solve this problem using recursion and in this part, we'll implement the inorder traversal algorithm without recursion. Now, some of you might argue, why use iteration if the recursive solution is so easy to implement? Well, that's true, but the iterative solution is often regarded better as they are not prone to StackOverFlowError. Another reason why we are discussing the iterative solution here is because of technical interviews.

How to remove duplicate characters from String in Java? [Solved]

Hello all, how are you doing? It's been a long since I have shared a coding problem from the interview. The last one I discussed was about finding the Nth Fibonacci number, one of the popular dynamic programming problems. Never mind,  today, you are going to learn about another popular coding problem.  How do you remove duplicate or repeated characters from String in Java is one of the frequently asked string-based coding problems from Interviews. This problem is very similar to removing duplicate elements from an array which we have discussed in the past here after all String is a character array in Java. If you know how to solve that problem, you should be able to solve this one as well.

10 Programming questions and exercises for Java Programmers

If you have just started learning the basics of Java programming language or are familiar with programming in either C or C++, then these Java programming questions and exercises are for you. It doesn't focus on a particular part of Java, but these coding exercises will switch you into programming mode. These are also great ways to master basic programming construct like if-else, loops like for and while break and continue with loop,   Java operators e.g., arithmetic and logical operator, recursion, methods, or functions, and standard Java API. You may also find these Java programming questions in most Java courses taught in schools, colleges, and various Java training courses.

How to Find the Largest and Smallest of Three Numbers in Java? [Solved]

Hey Java programmers, I have been sharing coding problems from interviews for quite some time and today I am going to share with you another interesting coding problem for beginners, how to find the largest and smallest of three numbers. If you are learning how to program or looking to improve your problem-solving and coding skills then these kinds of small problems are good to start with. They not only provide you an opportunity to think about how to solve a problem using basic programming constructs like conditionals (if, else, if-else, switch), loops (for, while, do-while), operators like arithmetic, the bitwise and logical operators as well as teach you how to write functions, class and create a program which you can run.

How to find median of two sorted arrays in Java? Example Tutorial

Hello friends, we meet again on our journey of Java and the ocean of knowledge. I am sure you guys must be very excited about today's lesson as today we will deep dive into something that makes everyone's head scratch, yes, we will talk about a popular coding problem. So friends, get ready to scratch your head, learn something, code a few things, and use some of your grey cells (Agatha christie fans rejoicing in the back :p). So friends, today's topic is coding and we will take on one of the most famous and difficult problems. Today we will learn how to find the median of two sorted arrays. seems easy right? Wait a bit, I will make sure you learn something new and make it a bit of a challenge :D

Fibonacci Series in Java Using Recursion

Fibonacci series in Java
Write a Java program to print the Fibonacci series up to a given number or create a simple Java program to calculate Fibonacci number is common Java questions on fresher interviews and homework. Fibonacci series is also a popular topic on various programming exercises in schools and colleges. Fibonacci series is a series of natural numbers where the next number is equivalent to the sum of the previous two numbers like fn = fn-1 + fn-2. The first two numbers of the Fibonacci series are always 1, 1. In this Java program example for the Fibonacci series, we create a function to calculate Fibonacci numbers and then print those numbers on the Java console.