Monday, July 14, 2025

Difference between HashMap and HashSet in Java

HashMap vs HashSet is the most frequently asked question during any core java interview and the interview is not said completed until they will not cover the Collection Framework and multi-threading interview and collections are uncompleted without Covering Hash Set and HashMap.
Both HashMap and HashSet are part of the collection framework which allows us to work with a collection of objects. Collection Framework has its own interfaces and implementation classes. Basically, a collection is divided into Set Interface, List, and Queue Interfaces.

Difference between EnumMap and HashMap in Java? Example

HashMap vs EnumMap in Java
What is the difference between EnumMap and HashMap in Java is the latest Java collection interview question which has been asked to a couple of my friends? This is one of the tricky Java questions, especially if you are not very much familiar with EnumMap in Java, which is not uncommon, given you can use it with only Enum keys. The main difference between EnumMap and HashMap is that EnumMap is a specialized Map implementation exclusively for Enum as key. Using Enum as a key allows doing some implementation level optimization for high performance which is generally not possible with other objects as key.

Difference between ConcurrentHashMap, Hashtable and Synchronized Map in Java

ConcurrentHashMap vs Hashtable vs Synchronized Map
Though all three collection classes are thread-safe and can be used in multi-threaded, concurrent Java application, there is a significant difference between them, which arise from the fact that how they achieve their thread-safety. Hashtable is a legacy class from JDK 1.1 itself, which uses synchronized methods to achieve thread safety. All methods of Hashtable are synchronized which makes them quite slow due to contention if a number of thread increases. Synchronized Map is also not very different than Hashtable and provides similar performance in concurrent Java programs. The only difference between Hashtable and Synchronized Map is that later is not a legacy and you can wrap any Map to create it's synchronized version by using Collections.synchronizedMap() method.

How to Iterate through ConcurrentHashMap and print all keys and values in Java? Example

Suppose you have a ConcurrentHashMap of String and Integer and you want to print all keys and values, how do you do that? This is a common, day-to-day programming task for Java programmers and there are many ways to do it. The Map interface provides several view methods e.g. keySet(), values(), and entrySet() to retrieve all keys, values, and all key and value pairs as entries. You can use respective methods to print all keys, all values, or all key values pairs. For printing, you also have multiple choices like you can either use enhanced for loop or Iterator, though later also provide you the facility to remove key-value pairs while printing if needed.

Saturday, July 12, 2025

Enhanced For Loop Example and Puzzle in Java

From Java 5 onwards, we have a for-each loop for iterating over collection and array in Java. For each loop allows you to traverse over collection without keeping track of index like traditional for loop, or calling hasNext() method in while loop using Iterator or ListIterator. For-each loop indeed simplified iteration over any Collection or array in Java, but not every Java programmer is aware of some useful details of the for-each loop, which we will see in this tutorial. Unlike other popular items from Java 5 release alias Generics, Autoboxing, and variable arguments, Java developers tend to use for-each loop more often than any other feature, but when asked about how does advanced foreach loop works or what is a basic requirement of using a Collection in the for-each loop, not everyone can answer.

JUnit4 Annotations : Test Examples and Tutorial

JUnit4 Annotations are a single big change from JUnit 3 to JUnit 4 which is introduced in Java 5. With annotations creating and running a JUnit test becomes easier and more readable, but you can only take full advantage of JUnit4 if you know the correct meaning of annotations used on this version and how to use them while writing tests. In this
Junit tutorial we will not only understand the meaning of those annotations but also we will see examples of JUnit4 annotations. By the way, this is my first post in unit testing but if you are new here than you may like post 10 tips to write better code comments and 10 Object-oriented design principles for Programmer as well.

JUnit Testing Tips - Constructor is Called Before Executing Test Methods? Example

Even though almost all Java programmers either use JUnit or TestNG for their unit testing need along with some mock object generation libraries e.g. Mockito, but not everyone spends time and effort to learn subtle details of these testing libraries, at least not in proportion to any popular framework like Spring or Hibernate. In this blog post, I am sharing one of such detail, which has puzzled me a couple of years ago. At that time, though I had been using JUnit for a significant time, I wasn't aware that code written inside the constructor of the Test class is executed before each test method.

How to Fix Exception in thread "main" java.lang.NoClassDefFoundError: Running Java from Command line

The "Exception in thread "main" java.lang.NoClassDefFoundError: helloworldapp/HelloWorldApp" error comes when you are trying to run the HelloWorldApp Java program from the command line but either .class file is not there or Java is not able to find the class file due to incorrect classpath settings. The name of the class could be different in each case, it depends upon which class you are passing to java command for running from the command prompt. Another interesting thing to remember is that this error only comes in Java version less than or equal to Java 6 like Java 1.5 or Java 1.4, if you are running in JDK 7 or Java 8 instead of this you will see "Error: could not able to find or load class HelloWorldApp". Technically, both errors come due to some reason and their solution is also exactly the same.

How to fix java.io.NotSerializableException: org.apache.log4j.Logger Error in Java? Example

java.io.NotSerializableException: org.apache.log4j.Logger error says that an instance of org.apache.lo4j.Logger is not Serializable. This error comes when we use log4j for logging in Java and create Logger in a Serializable class e.g. any domain class or POJO which we want to store in HttpSession or want to serialize it. As we know from 10 Java Serialization interview question that, if you have a non serializable class as member in a Serializable class, it will throw java.io.NotSerializableException Exception.

Binary Search vs Contains Performance in Java List - Example

There are two ways to search an element in a List class, by using contains() method or by using Collections.binarySearch() method. There are two versions of binarySearch() method, one which takes a List and Comparator and other which takes a List and Comparable. This method searches the specified list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method) prior to making this call. If List is not sorted, then results are undefined. If the List contains multiple elements equal to the specified object, there is no guarantee which one will be returned. This method runs in log(n) time for a "random access" list (which provides near-constant-time positional access).

How to Fix Eclipse No Java Virtual Machine was found Windows JRE JDK 64 32 bit Error? Example

One of my readers was installing Eclipse in his Windows 7 x86 machine and emailed me about this error "A java Runtime Environment (JRE) or Java Development kit (JDK) must be available in order to run Eclipse. No Java virtual machine was found". Before getting into details and trying to find root cause and solution of Eclipse Java Virtual Machine not found error, let's see some background about Eclipse. Eclipse is a popular Java IDE, which assists on coding, debugging and running Java program, but the key point is, Eclipse itself need Java to launch and run.

Private in Java: Why should you always keep fields and methods private? Example

Making members private in Java is one of best coding practice. Private members (both fields and methods) are only accessible inside the class they are declared or inside inner classes. private keyword is one of four access modifier  provided by Java and its a most restrictive among all four e.g. public, default(package), protected and private. Though there is no access modifier called package, rather its a default access level provided by Java. In this Java tutorial we will see why should we always make members of class by default as private and answer to one of popular Java interview question can override private methods in Java.

Friday, July 11, 2025

Introduction of How Android Works for Java Programmers

Android development is a popular buzz in the Java programming world. It's Android, which keeps Java at the forefront of the last couple of years. Now, How important is it to understand or learn Android for Java programmers? Well, it depends on, if you like application development and wants to reach a mass, Android offers that opportunity to you. Millions of Android phones are available and they keep increasing, with pace, much higher than iPhone or iOS. What all this means is, it does make a lot of sense to learn Android programming for Java programmers, and this article is about that, but this is also one of the good reasons to learn Java programming. This tutorial will give you a basic idea of How Android works? not detailed but a good overview.

10 Essential UTF-8 and UTF-16 Character Encoding Concepts Every Programmer Should Learn

Hello guys, if you want to learn about character encoding, particularly UTF-18 and UTF-16, and looking for a good resource then you have come to the right place. In this article, I am going to discuss 10 important points about UTF-8 and UTF-16 character encoding which I believe every programmer should learn. This is one of the fundamental topics to which many programmers don't pay attention unless they face issues related to character encoding. Knowing how a character is stored and how they are represented in such a way what computer can understand is very important in this age of globalization and internationalization where you need to store and work through data that contains characters from multiple languages. 

Top 5 Blogs Java EE developers should follow

One reason for Java's great success as a programming language is that it has dominated the Enterprise space. Earlier J2EE used to be the popular platform, but now we have a more modern and improved Java EE platform or Jakarta EE. Java Platform, Enterprise Edition 7 provides new features that include enhanced HTML5 support, increases developer productivity, and further improves how enterprise demands can be met. One of the biggest advantages of Java EE 7 is the reduction of boilerplate code.