Hello guys, if you are looking for an answer of popular Java interview question, how HashMap works in Java? or How HashMap works internally in Java then you have come to the right place. In this article, I will not just answer those question but also many related questions like How get() and put() method works in Java? what role equals() and hashcode() play in HashMap, How HashMap resize itself, and why key object of HashMap should be Immutable in Java. Let's start with the basics first. HashMap in Java works on hashing principles. It is a data structure that allows us to store object and retrieve it in constant time O(1) provided we know the key. Also this is one of my most popular article with more than 6 million views and I have now updated it to include latest information like how HashMap now uses a balanced tree instead of linked list for storing collision objects and new diagrams on HashMap working which provide visual explanations.
Wednesday, July 16, 2025
Difference between fail-safe vs fail-fast Iterator in Java? Example
The difference between fail-safe and fail-fast Iterator is becoming favorite core java interview questions day by day, the reason it touches concurrency a bit, and the interviewee can go deep on it to ask how fail-safe or fail-fast behavior is implemented. In this article, we will see what are fail-safe and fail-fast iterators in java and the differences between fail-fast and fail-safe iterators. The concept of the fail-safe iterator is relatively new in Java and was first introduced with Concurrent Collections in Java 5 like ConcurrentHashMap and CopyOnWriteArrayList.
Difference between List and Set in Java Collection? Example
What is the difference between List and Set in Java is a very popular Java collection interview question and an important fundamental concept to remember while using the Collections class in Java. Both List and Set are two of the most important Collection classes Java Program use along with various Map implementations. The basic feature of List and Set are abstracted in the List and Set interface in Java and then various implementations of List and Set adds specific features on top of that e.g. ArrayList in Java is a List implementation backed by Array while LinkedList is another List implementation that works like linked list data-structure.
Difference between ArrayList and Vector in Java
ArrayList and Vector are two of the most used classes on the java collection package and the difference between Vector and ArrayList is one of the most frequently asked java interview questions on first-round or phone interviews. Though it’s quite a simple question in my opinion but knowledge of when to use Vector over ArrayList or does matter if you are working on a project. In this article, we will some point-based differences between Vector and ArrayList in Java and trying to understand the concept behind those differences.
Tuesday, July 15, 2025
What is difference between HashMap and Hashtable in Java?
HashMap vs Hashtable in Java
Though both Hashtable and HashMap are data-structure based upon hashing and implementation of Map interface, the main difference between them is that HashMap is not thread-safe but Hashtable is thread-safe. This means you cannot use HashMap in a multi-threaded Java application without external synchronization. Another difference is HashMap allows one null key and null values but Hashtable doesn't allow null key or values. Also, the thread-safety of the hash table is achieved using internal synchronization, which makes it slower than HashMap.
Though both Hashtable and HashMap are data-structure based upon hashing and implementation of Map interface, the main difference between them is that HashMap is not thread-safe but Hashtable is thread-safe. This means you cannot use HashMap in a multi-threaded Java application without external synchronization. Another difference is HashMap allows one null key and null values but Hashtable doesn't allow null key or values. Also, the thread-safety of the hash table is achieved using internal synchronization, which makes it slower than HashMap.
Difference between LinkedList and ArrayList in Java
LinkedList and ArrayList both implement List Interface but how they work internally is where the differences lie. The main difference between ArrayList and LinkedList is that ArrayList is implemented using a resizable array while LinkedList is implemented using doubly LinkedList. ArrayList is more popular among Java programmers than LinkedList as there are few scenarios on which LinkedList is a suitable collection than ArrayList. In this article, we will see some differences between LinkedList and ArrayList and try to find out when and where to use LinkedList over ArrayList.
Difference between TreeSet, LinkedHashSet and HashSet in Java with Example
TreeSet, LinkedHashSet, and HashSet all are
implementation of the Set interface and by virtue of that, they follow the contract of Set interface i.e. they do not allow duplicate elements.
Despite being from the same type of hierarchy, there are a lot of differences between them;
which is important to understand, so that you can choose the most appropriate Set implementation based upon
your requirement. By the way difference between TreeSet and HashSet or LinkedHashSet is also
one of the popular Java Collection interview questions, not as popular as Hashtable vs HashMap or ArrayList vs Vector but still
appears in various Java interviews.
Difference between PriorityQueue and TreeSet in Java? Example
The PriorityQueue and TreeSet collection classes have a lot of similarities e.g. both provide O(log(N)) time complexity for adding, removing, and searching elements, both are non-synchronized and you can get elements from both PriorityQueue and TreeSet in sorted order, but there is a fundamental difference between them, TreeSet is a Set and doesn't allow a duplicate element, while PriorityQueue is a queue and doesn't have such restriction. It can contain multiple elements with equal values and in that case head of the queue will be arbitrarily chosen from them.
Difference between Synchronized and Concurrent Collections in Java? Answer
Synchronized vs Concurrent Collections
Though both Synchronized and Concurrent Collection classes provide thread-safety, the differences between them come in performance, scalability, and how they achieve thread-safety. Synchronized collections like synchronized HashMap, Hashtable, HashSet, Vector, and synchronized ArrayList are much slower than their concurrent counterparts like ConcurrentHashMap, CopyOnWriteArrayList, and CopyOnWriteHashSet. The main reason for this slowness is locking; synchronized collections lock the whole collection e.g. whole Map or List while concurrent collection never locks the whole Map or List.
Though both Synchronized and Concurrent Collection classes provide thread-safety, the differences between them come in performance, scalability, and how they achieve thread-safety. Synchronized collections like synchronized HashMap, Hashtable, HashSet, Vector, and synchronized ArrayList are much slower than their concurrent counterparts like ConcurrentHashMap, CopyOnWriteArrayList, and CopyOnWriteHashSet. The main reason for this slowness is locking; synchronized collections lock the whole collection e.g. whole Map or List while concurrent collection never locks the whole Map or List.
How to choose the Right Collection Class in Java? List, Set, Map, and Queue Example
The Java collection framework offers implementation of different data
structure like an array, list, set, map, queue, tree, etc and the choice
really depends upon the situation and properties of the different data
structure. For example, if your requirement is fast search with index then you
can use
ArrayList
and if you want to store key-value pairs then you would consider using hash
table data structure and there are a couple of implementation of hash table
data structure in Java, like HashMap,
Hashtable,
LinkedHashMap,
TreeMap, and
ConcurrentHashMap. Now, which one will you choose? If you don't know or confused don't worry, I will give you a set of rules and use cases which will help you choose the right Collection type in Java depending upon scenario.
Monday, July 14, 2025
Difference between HashMap, LinkedHashMap and TreeMap in Java with Example
Hello guys, if you are wondering what is difference between HashMap, TreeMap, and LinkedHashMap in Java and when to use them then you are at the right place. In past, I have shared frequently asked HashMap Interview questions and ConcurrentHashMAp Interview questions and today, I Will answer this question in detail. The java.util.Map is one of the most important interfaces from the Java Collection Framework. It provides hash table data structure functionality by its implementations like HashMap, Hashtable, LinkedHashMap, and a little bit of sorting with the TreeMap. So if you are looking to store key-value pairs in the Java program, you have a wide range of choices available depending upon your requirement. The main difference between LinkedHashMap, TreeMap, and HashMap comes in their internal implementation and specific features, which a Java programmer should know to use them effectively.
How to get Key From Value in Hashtable, HashMap in Java? Example
It's not easy to get key from the value in Hashtable or HashMap, as compared to getting value from key because HashMap or Hashtable doesn't enforce one to one mapping between key and value inside Map in Java. in fact, Map allows the same value to be mapped to multiple keys inside HashMap, Hashtable, or any other Map implementation. What you have in your kitty is Hashtable.containsValue(String value) or Hashtable.containsKey(String key) to check whether key or value exists in HashMap or not, but sometimes we want to retrieve a value from Map corresponding to any key and there is no API method to do in Map.
Difference between HashMap and IdentityHashMap in Java? Example
Hello guys, if you are wondering what is differnece between an HashMap and IdentiyHashMap in Java then you are at right place. IdentityHashMap in Java was added in Java 1.4 but still, it's one of those lesser-known classes in Java. The main difference between IdentityHashMap and HashMap in Java is that IdentityHashMap is a special implementation of Map interface which doesn't use equals() and hashCode() method for comparing objects unlike other implementations of Map e.g. HashMap. Instead, IdentityHashMap uses the equality operator "==" to compare keys and values in Java which makes it faster compared to HashMap and suitable where you need reference equality check and instead of logical equality.
What is difference between ArrayList and ArrayList<?> in Java?- Raw Type vs Wildcard Example Tutorial
One of my readers asked me about the difference between ArrayList vs ArrayList< in Java?>, which was actually asked to him in a recent Java development interview. The key difference between them is that ArrayList is not using Generics while ArrayList is a generic ArrayList but they look very similar. If a method accepts ArrayList or ArrayList<?> as a parameter then it can accept any type of ArrayList like ArrayList of String, Integer, Date, or Object, but if you look closely you will find that one is raw type while the other is using an unbounded wildcard. What difference that could make? Well, that makes a significant difference because ArrayList with raw type is not type-safe but ArrayList<?> with the unbounded wildcard is type-safe.
How to Filter Stream and Collections in Java 8? Example Tutorial
Java 8 provides excellent features to support the filtering of elements in Java Collections. Prior to Java 8, the only better way to filter elements is by using a foreach loop or iterating over Collection using the Iterator and selecting the required object, leaving out rest. Though that approach work, it was very difficult to run them in parallel and take advantage of multiple CPUs available in modern-day servers. Java 8 provides Streams, which not only makes it easy to run any operation parallel but also supports lazy loading and lazy evaluation, which means as soon as the filtering condition is satisfied, it stooped doing work, doesn't matter how many objects the collection contains.
Top 25 Java Collection Framework Interview Questions Answers for Freshers and Experienced Programmers
Interview questions from the Collection package or framework are most common in any Core Java Interview yet a tricky one. Together Collection and multithreading make any Java interview tough to crack and having a good understanding of Collection and threads will help you to excel in Java interviews. I thought about writing interview questions on the Java collection framework and important classes like ArrayList, HashMap, Hashtable, and newly added concurrent collections e.g. ConcurrentHashMap when I first wrote 10 multi-threading Interview questions but somehow this article got delayed. Though I have shared several questions individually in between.
How to Convert Collection to String in Java - Spring Framework Example
How to convert Collection to String in Java
Many times we need to convert any Collection like Set or List into String like comma-separated or any other delimiter delimited String. Though this is quite a trivial job for a Java programmer as you just need to Iterate through the loop and create a big String where individual String are separated by a delimiter, you still need to handle cases like the last element should not have a delimiter or at a bare minimum, you need to test that code.
How does Java HashMap or LinkedHahsMap handles collisions?
Prior to Java 8, HashMap and all other hash table based Map implementation classes in Java handle collision by chaining, i.e. they use linked list to store map entries which ended in the same bucket due to a collision. If a key end up in the same bucket location where entry is already stored then this entry is just added at the head of the linked list there. In the worst case this degrades the performance of the get() method of HashMap to O(n) from O(1). In order to address this issue in the case of frequent HashMap collisions, Java8 has started using a balanced tree instead of a linked list for storing collided entries. This also means that in the worst case you will get a performance boost from O(n) to O(log n).
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.
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.
Labels:
core java
,
error and exception
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.
Labels:
core java
,
debugging
,
error and 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).
Labels:
coding
,
core java
,
java collection tutorial
,
Java Programming Tutorials
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.
Labels:
core java
,
Eclipse
,
error and exception
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.
Labels:
core 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.
Labels:
android
,
best of javarevisited
,
core java
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.
Labels:
best of javarevisited
,
core java
,
interview questions
,
programming
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.
Labels:
best of javarevisited
,
core java
,
J2EE
,
online resources
5 Entertaining Posts from StackOverFlow - Must Read
StackOverFlow is great place to look for help, learn and participate, but it's also a great place to taste some real entertainment, contributed by programmers from all over the world. Though, due to strict policies of stackoverflow.com, most of the entertaining post either are either gets closed or deleted, some of them remained to entertain programming community. Being a regular reader of StackOverFlow from long time, I have found couple of threads which are truly amazing, and has lot's of funny and entertaining content. Here I am going to share 5 of my favorite StackOverFlow posts, which I suggest you to read, if you get bored or you have some time to kill. By the way, don't forget to leave comments and let us know which is your favorite funny and entertaining threads in StackOverFlow.
Labels:
best of javarevisited
,
fun
,
programmers
,
programming
Wednesday, July 9, 2025
5 Things Programmers Can Buy in Amazon Prime Day 2025 [Best Deals]
Hello guys, many of my friends and colleagues used to wait until November to buy books, gadgets, and other computer items to get the huge discount offered on Black Friday and Cyber Monday deals, but you don't need to wait that long. Amazon is bringing Black Friday to the summer with its annual Prime Day offers. The Amazon Prime day is nothing but a one-day (precisely one and half-day and this time full two-day) shopping extravaganza, where you will get huge discounts on thousands of Amazon products including books, games, gadgets, and other computer and electronics items. So, if you are looking to buy a new laptop, a new smartphone, or some fitness gadgets and watch then this is an awesome opportunity.
Labels:
best of javarevisited
,
books
,
general
,
programming
Tomcat – java.lang.OutOfMemoryError: PermGen space Cause and Solution
Tomcat web server often suffers from java.lang.OutOfMemoryError: PermGen space whenever you deploy and un-deploy your web application a couple of times. No matter you are using tomcat6, tomcat7, or using bundled tomcat in Netbeans or Eclipse you will face this error now and then while developing web application on tomcat server. I thought about this article after writing 2 Solution of OutOfMemoryError in Java. I have touched this issue there but then I thought to write a separate tutorial for tomcat outofmemoryerror because I am getting this error too frequently.
Labels:
core java
,
error and exception
,
jsp-servlet
How to fix java.lang.classcastexception cannot be cast to in Java - cause and solution
As name suggests ClassCastException in Java
comes when we try to type cast an object and object is not of the type we are
trying to cast into. In fact ClassCastException in Java is
one of most common exception in Java along with java.lang.OutOfMemoryError
and ClassNotFoundException
in Java before Generics was introduced in Java 5 to avoid frequent
instances of java.lang.classcastexception cannot be cast to while
working with Collection classes like ArrayList
and HashMap,
which were not type-safe before Java 5. Though we can minimize and avoid java.lang.ClassCastException in Java by
using Generics and writing type-safe
parameterized classes and method, its good to know real cause of ClassCastException and How to
solve it.
Labels:
core java
,
error and exception
,
programming
How to Fix java.lang.OutOfMemoryError: GC overhead limit exceeded ? Example Solution
The java.lang.OutOfMemoryError: GC overhead limit exceeded is another type of OutOfMemoryError in Java which comes when JVM spent too much time doing garbage collection without any success. For example, if almost 98% of CPU for a Java process is busy doing GC and reclaims very less amount of Java heap space around 2%, then JVM throws "java.lang.OutOfMemoryError: GC overhead limit exceeded" error. Though, the definition of 98% CPU time may vary between different Garbage collectors and different JVM versions.
Labels:
core java
,
error and exception
,
garbage collection
,
JVM Internals
What is Assertion in Java - Java Assertion Tutorial Example
Java Assertion or assert keyword in Java is a little unknown and not many programmers are familiar with this and it's been rarely used especially if you have not written a unit test using JUnit which extensively uses Java assertion to compare test result. JUnit itself is the biggest manifestation of what assertion in Java can do and believe me by using assertion along with Exception you can write robust code. Assertion not only improves the stability of code but also help you to become a better programmer by forcing you to think about different scenario while writing production-quality code and improving your think through ability.
Labels:
core java
,
Java Assertion
What is the use of java.lang.Class in Java? Example
java.lang.Class is one of the most important classes in java but mostly overlooked by Java developers. It is very useful in the sense that it provides several utility methods like getClass(), forName() which is used to find and load a class, you might have used to load Oracle or MySQL drivers. It also provides methods like Class.newInstance() which is the backbone of reflection and allows you to create an instance of a class without using a new() operator. The class has no public constructor and its instance is created by JVM when a class is loaded.
Labels:
core java
,
Java basics
Java Mistake 1 - Using float and double for monetary or financial calculation Example
Java is considered a very safe programming language compared to C and C++ as it doesn't have free() and malloc() to directly do memory allocation and deallocation, You don't need to worry about array overrun in Java as they are bounded and there is NO pointer arithmetic in Java. Still, there are some sharp edges in the Java programming language that you need to be aware of while writing enterprise applications. Many of us make a subtle mistake in Java which looks correct in the first place but turns out to be buggy when looked at carefully. In this series of java articles, I will be sharing some common Java mistakes programmers make while programming applications in Java.
Labels:
best practices
,
core java
Top 10 EJB Interview Question and Answer asked in Java J2EE Interviews
10 EJB Interview Questions and Answer from my collection of interview questions. I have been sharing interview questions on various topics like Singleton interview questions, serialization interview questions, and most recently Spring interview questions. No doubt these questions are very important for performing better in J2EE and EJB interviews but also they open a new path for learning as you may find some concepts new even while revising your knowledge in EJB. EJB interviews have always been tough because its difficult to find people who have hands-on experience on Enterprise Java Beans (EJB) and most of the guys either have worked only on sample projects and are not aware of critical functionalities like distributed transaction management, container-managed persistence, and various other services which EJB provides.
Labels:
core java
,
jsp-servlet
,
servlet interview questions
How to get and set default Character encoding or Charset in Java? Example
Default Character encoding in Java or charset is the character encoding used by JVM to convert bytes into Strings or characters when you don't define java system property "file.encoding". Java gets character encoding by calling System.getProperty("file.encoding","UTF-8") at the time of JVM start-up. So if Java doesn't get any file.encoding attribute it uses "UTF-8" character encoding for all practical purpose e.g. on String.getBytes() or Charset.defaultCharSet().
Labels:
core java
Monday, July 7, 2025
Difference between Class, Instance and Local variables in Java? Example
There are a lot of differences between instance variable, class variable, and local variable in Java, and knowing them will help you to write correct and bug-free Java programs. Java is a full-featured programming language and provides different kinds of variables like static variables also called Class variable since it belongs to whole Class, non-static also called instance variable and local variables which vary in scope and value. Thank god Java doesn't have any register variable or auto scope like C Programming language, otherwise it would have so much detail to remember. static variables are a common source of error in may multi-threaded java program and does require a bit of carefulness while using it. On the other hand instance, the variable and the local variable have less sharing visibility than a static variable.
Labels:
core java
,
object oriented programming
What is the Use of Interface in Java and Object Oriented Programming? [Answer]
Many times, I have seen questions like why should we use an interface in Java? If we can not define any concrete methods inside the interface the what is the user of the interface? Or even more common, What is the real use of the interface in Java? I can understand beginners asking this question when they just see the name of the method inside the interface and nothing else. It takes time to realize real goodness or actual use of interface or abstraction in Java or any object-oriented programming. One reason for this is a lack of experience in really modeling something real in the program using object-oriented analysis and design. In this article, I will try to answer this question and give you a couple of reasons to use the interface in your code. If you have a good understanding of Object-oriented basics like Polymorphism, then you know that it allows you to write flexible code.
Labels:
interface
,
java
,
object oriented programming
,
programming
5 Benefits of using interface in Java and Object Oriented Programming
Interface in Java is a simple concept but many programmers fail to realize
their actual use, including me. When I started learning Java programming, I
learned interface is something where you can declare functions but cannot
define them. To me, they were useless at that time because there was no code
to do anything. It took me years to realize how useful an interface can
be. They are not intended to do things but they are actually facilitators.
They provide abstraction and give the flexibility to change your program in the future. That's why it's very important for a Java programmer to understand the benefits of interfaces and realize how and when to use them in code.
Labels:
interface
,
java
,
object oriented programming
,
programming
Difference between Abstraction and Encapsulation in Java? OOP Question Answer
Both Abstraction and Encapsulation are two of the four basic OOP concepts which allow you to model real-world things into objects so that you can implement them in your program and code. Many beginners get confused between Abstraction and Encapsulation because they both look very similar. If you ask someone what is Abstraction, he will tell that it's an OOP concept which focuses on relevant information by hiding unnecessary detail, and when you ask about Encapsulation, many will tell that it's another OOP concept which hides data from the outside world. The definitions are not wrong as both Abstraction and Encapsulation do hide something, but the key difference is on intent.
Difference between Association, Composition and Aggregation in Java, UML and Object Oriented Programming
In Object-oriented programming, one object is related to another to use functionality and service provided by that object. This relationship between two objects is known as the association in object-oriented general software design and is depicted by an arrow in Unified Modelling Language or UML. Both Composition and Aggregation are the forms of association between two objects, but there is a subtle difference between composition and aggregation, which is also reflected by their UML notation. We refer to the association between two objects as Composition when one class owns other classes and other classes can not meaningfully exist, when the owner is destroyed.
Labels:
core java
,
design
,
object oriented programming
,
programming
Why Default or No Argument Constructor is Important in Java Class? Answer
Almost all Java developers know that compiler adds a default constructor or better known as a no-argument constructor in every Java class, but many of them forget that it only does when you don't provide any other constructor. This means it becomes the developers' responsibility to add a no-argument constructor if he is adding an explicit constructor. Now, Why it's important to provide a default constructor in Java, What happens if your class doesn't have a no-argument constructor? Well, this is how it's asked in many Java interviews, most commonly as part of Spring and Hibernate interviews.
Labels:
core java
,
object oriented programming
What is Type Casting in Java? Casting one Class to other class or interface Example
Type casting in Java is to cast one type, a class or interface, into another type i.e. another class or interface. Since Java is an Object-oriented programming language and supports both Inheritance and Polymorphism, It’s easy that Super class reference variable is pointing to SubClass objects but the catch here is that there is no way for Java compiler to know that a Superclass variable is pointing to SubClass object. This means you can not call a method that is declared in the subclass. In order to do that, you first need to cast the Object back into its original type. This is called type casting in Java. You can type cast both primitive and reference type in Java. The concept of casting will be clearer when you will see an example of type casting in the next section.
Labels:
coding
,
core java
,
object oriented programming
What is Constructor in Java with Example – Constructor Chaining and Overloading
What
is constructor in Java
Constructor in Java is a block of code which is executed at the time of
Object creation. But other than getting called, Constructor is entirely
different than methods and has some specific properties like name of the constructor
must be same as name of Class. Constructor also can not have any return type,
constructor’s are automatically chained by using this
keyword and super. Since Constructor is used to create object, object
initialization code is normally hosted in Constructor. Similar to the method you
can also overload the constructor in Java.
Labels:
core java
,
object oriented programming
What is Object in Java and Object Oriented Programming? Example Tutorial
Object in Java
Object in Java programming language or any other Object-oriented
programming language like C++ is the core of the OOPS concept and that's why the name.
Class
and Object along with Inheritance,
Polymorphism,
Abstraction
and Encapsulation
form the basis of any Object-oriented programming language e.g. Java. Objects are
instances of Class, Class defines blueprints and Objects are things that are
created based upon that blueprint. Object is also known as instances in Java,
e.g. When we say an instance of String class, we actually mean an Object of
String class. The object has state and behavior in Java.
Labels:
coding
,
core java
,
object oriented programming
,
programming
Open Closed Design Principle in Java - Benefits and Example
Great Example of Open Closed Design Principle
I am a big fan of design pattern articles and love to read articles on design patterns and recently wrote about decorator design pattern in Java, Observer pattern, static factory pattern and Singleton pattern. Today I come across this good article on open closed design patterns, what I like most is there example and clear way of explanation, first example is true value and it will help you understand open closed principle very quickly and second example is also not bad.
Labels:
core java
,
object oriented programming
How to use Class in Java Programming - Example
When I first about Class in Java I just thought what is this Class in Java and from that date to now Whenever we talk about java its really incomplete without classes, every one who are little bit familiar with java knows it’s purely object oriented language means every thing we discuss in java as object .so its very important for learner or anyone who is keen to know about java should know about java class then only they can move forward on java world.
In this article we will see what Java Class, Example of Class in Java is and what makes a Java Class including members, field and method.
Labels:
core java
,
object oriented programming
What is Inheritance in Java and OOP Tutorial - Example
Inheritance in Java is an Object oriented or OOPS
concepts, which allows to emulate real world Inheritance behavior, Inheritance
allows code reuse in Object oriented programming language e.g. Java. Along with
Abstraction,
Polymorphism
and Encapsulation,
Inheritance forms basis of Object-oriented programming. Inheritance is
implemented using extends keyword in Java and When one
Class extends another Class it inherit all non
private members including fields and methods. Inheritance in Java can be
best understand in terms of Parent and Child class,
also known as Super class and Sub class in Java programming language.
Labels:
core java
,
object oriented programming
,
programming
What is polymorphism in Java? Method overloading or overriding?
What is Polymorphism in Java
Polymorphism is an important Object oriented concept and is widely used in Java and other programming languages. Polymorphism in java is supported along with other concepts like Abstraction, Encapsulation, and Inheritance. Few words on the historical side; Polymorphism word comes from ancient Greek where poly means much so polymorphic are something which can take many forms. In this Java Polymorphism tutorial, we will see what is Polymorphism in Java, How Polymorphism has been implemented in Java e.g method overloading and overriding, why should we use Polymorphism and how can we take advantage of it polymorphism while writing code in Java. Along the way, we will also see a real-world example of using Polymorphism in Java.
Labels:
core java
,
object oriented programming
Can we declare a class Static in Java? Top Level and Nested static class Example
The answer to this question is both Yes and No, depending on whether you are talking about a top-level class or a nested class in Java. You cannot make a top-level class static in Java, the compiler will not allow it, but you can make a nested class static in Java. A top-level class is a class that is not inside another class. It may or may not be public like you can have more than one class in a Java source file and only needs to be public, whose name must be the same as the name of the file, rest of the class or interface on that file may or may not be public. On the other hand, a nested class is a class inside a top-level class. It is also known as the inner class or member class in Java.
Law of Demeter in Java - Principle of least Knowledge - Real life Example
The Law of Demeter also known as the principle of least knowledge is a coding principle, which says that a module should not know about the inner details of the objects it manipulates. If a code depends upon the internal details of a particular object, there is a good chance that it will break as soon as the internal of that object changes. Since Encapsulation is all about hiding internal details of an object and exposing only operations, it also asserts the Law of Demeter. One mistake many Java programmer makes it exposing internal detail of object using getter methods and this is where the principle of least knowledge alerts you.
Labels:
coding
,
core java
,
design patterns
,
object oriented programming
What is interface in Java with Example - Tutorial
What is an interface in Java?
Interface in java is a core part of the Java programming language and one of the ways to achieve abstraction in Java along with the abstract class. Even though the interface is a fundamental object-oriented concept; Many Java programmers think of Interface in Java as an advanced concept and refrain from using the interface from early in a programming career. At a very basic level interface in java is a keyword but same time it is an object-oriented term to define contracts and abstraction, This contract is followed by any implementation of Interface in Java. Since multiple inheritances are not allowed in Java, the interface is the only way to implement multiple inheritances at the Type level.
Interface in java is a core part of the Java programming language and one of the ways to achieve abstraction in Java along with the abstract class. Even though the interface is a fundamental object-oriented concept; Many Java programmers think of Interface in Java as an advanced concept and refrain from using the interface from early in a programming career. At a very basic level interface in java is a keyword but same time it is an object-oriented term to define contracts and abstraction, This contract is followed by any implementation of Interface in Java. Since multiple inheritances are not allowed in Java, the interface is the only way to implement multiple inheritances at the Type level.
Labels:
core java
,
object oriented programming
Saturday, July 5, 2025
Top 10 Courses to Crack System Design Interview in 2025 - Best of Lot
Hello guys, if you are preparing for System Design Interviews and looking for best resources then you have come to the right place. Earlier, I have shared best System design book, courses, websites, and System design interview questions and in this article, I am going to share in-depth System design courses from Educative.io, a text based online learning platform for developers and engineers. These are the best online courses to prepare for System Design Interviews in 2025. If you have been doing Software development then you know that System
design is one of the most important skill for developers and managers.
Labels:
courses
,
educative
,
System Design
4 Steps to Prepare for System Design Interviews in 2025? [The Ultimate Guide]
Hello guys, if you are preparing for Software Engineer Interviews, or Software developer interview then you may know that how difficult it is to prepare for them because of System Design interviews, given its open ended nature and vastness but at the same time you cannot ignore it. In Software Engineering world, if you are applying for a Senior Engineer / Lead / Architect / or a more senior role, System Design is the most sought-after skill, and hence one of the most important rounds in the whole process. If you mess this up, nothing else would matter. If you get it right though, you’re looking at a raise of at least tens of thousands of dollars annually.
Labels:
best of javarevisited
,
System Design
How to System Design Trade Position Aggregator? [Solution]
Hello guys, it's been a long since I shared object-oriented design and
system design questions in this blog. It was almost 7 to 8 years when I last
blogged about how to solve vending machine design problems in Java and Twitter System Design question? Actually, I had ideas for lots of such design questions at that time, but
because of the lengthy nature of these kinds of posts and the amount of time
they take, they just sit on my list of drafts. I thought to take them out
and publish then slowly improve on them instead of publishing the perfect
post for the first time, and today, I am excited to share one of such
problems, how to design a trade position aggregator in Java. This
program is like portfolio management software that monitors your risk and
exposure in real-time based on trades.
Friday, July 4, 2025
Review - Is ByteByteGo System Design Interview Course by Alex Xu Really Worth it in 2025?
Hello guys, if you are preparing for System Design Interview in 2025 then you
may have most likely come across names like ByteByteGo, Alex Xu or System Design Interview - An Insider Guide by Alex Xu, and if you are wondering what they are or you know about them
but thinking whether ByteByteGo is worth it or not in 2025? then you have come to
the right place. Yes,
ByteByteGo
is indeed worth considering for your System Design Interview preparation.
because its created by Alex Xu, an expert with FAANG interview experience and platform offers in-depth coverage of system design topics. The author's use of
diagrams to explain concepts in detail enhances the learning
experience and most importantly Alex Xu regularly and new content and update old ones,.
Labels:
ByteByteGo
,
course review
,
System Design
Thursday, July 3, 2025
How to Remove Duplicates from Array without Using Java Collection API? Example
This is a coding question recently asked to one of my readers in a Java Technical interview on investment bank. The question was to remove duplicates from an integer array without using any collection API classes like Set, HashSet, TreeSet or LinkedHashSet, which can make this task trivial. In general, if you need to do this for any project work, I suggest better using the Set interface, particularly LinkedHashSet, because that also keeps the order on which elements are inserted into Set. Why Set? because it doesn't allow duplicates and if you insert duplicate the add() method of Set interface will return false.
How to find smallest number from int array in Java, Python, JavaScript and Golang? [Solved]
This is the second part on this array interview question. In the first part, I have showed you how to find the largest element in array, and in this part, you will learn how to find the smallest number from an integer array. We will solve this problem on Java programming language but you are free to solve in any other programming language like Python or JavaScript. Most interviewer doesn't care much about which programming language you are solving the question, if you can provide working solution. This one is also a popular Java programming exercise which is taught in school and colleges and give in homework to teach programming to kids and engineering graduates.
Labels:
Array
,
Coding problems
,
data structure and algorithm
How to Find Multiple Missing Integers in Given Array of Numbers with Duplicates in Java?
Hello guys, It's been a long time since I have discussed any coding or algorithm interview questions, so I thought to revisit one of the most popular array-based coding problems of finding missing numbers in a given array of integers. You might have heard or seen this problem before on your programming job interviews and you might already know how to solve this problem. But, there are a lot of different versions of this problem with increasing difficulty levels which interviewers normally use to confuse candidates and further test their ability to adapt to frequent changes, which is key to surviving in the ever-changing software development world.
Difference between a List and Array in Java? ArrayList vs Array Example
Hello there, if you are wondering what is the difference between a list and an array, or particularly an ArrayList and an Array in Java then you have come to the right place. Earlier, I have shared the best data structure and algorithm courses and in this article, I will explain to you the differences and similarities between a list and an array in Java. Both array and ArrayList are two important data structures in Java and frequently used in Java programs. Even though ArrayList is internally backed by an array, knowing the difference between an array and an ArrayList in Java is critical for becoming a good Java developer. If you know the similarity and differences, you can judiciously decide when to use an array over an ArrayList or vice-versa.
How to Find all Pairs in Array of Integers Whose sum is Equal to a Given Number in Java? Solution Example
Practicing coding problems are very important to do well in any programming interview. You should at your best on data structures like an array, linked list, and string to clear any programming interview and believe me, you can not do this in one day or one week. It's rather a long process of learning through coding, and that's where these small coding problems help. Today, we are going to look at another interesting programming question from the array; write a program to find all pairs of integers whose sum is equal to a given number. For example, if the input integer array is {2, 6, 3, 9, 11} and the given sum is 9, the output should be {6,3}.
Labels:
Array
,
core java
,
data structure and algorithm
,
interview questions
,
programming
How to Create and Initialize Anonymous Array in Java? Example
Anonymous arrays in Java is an Array without any name, just like Anonymous inner classes and policy of using Anonymous array is just create, initialize and use it, Since it doesn't have any name you can not reuse it. The anonymous array was a good way to implement variable argument methods before Java introduced varargs in Java5. You had the liberty to create an array of any length and pass that to a method that operates on an anonymous array. Classical example of such variable argument method is aggregate function like sum(), avg(), min(), max() etc.
Labels:
Array
,
core java
,
data structure and algorithm
Can You Make an Array or ArrayList Volatile in Java?
This is one of the many interesting multi-threading questions I have shared in my post 50 multi-threading interview questions. Yes, you can make an array volatile in Java, there is no problem with that, neither compiler will flag any error not JVM will throw any exception but the tricky part is why you want to make an array volatile and what is the effect of making an array volatile in Java? In order to answer this question, you must be familiar with both volatile modifier and Java memory model, otherwise, it would be difficult to answer, and that's why it's also one of the trick questions from Java interviews. Before answering this question in detail, let's first revise what is a volatile keyword in Java and what kind of guarantee it provides in the context of multithreading and concurrency.
Labels:
Array
,
Java multithreading Tutorials
Difference between Linked List and Array in Java? Example
Array and linked lists are two fundamental data structures in the programming world. Almost all programs use Array in some form or other, which makes it increasingly important to learn array and linked list. The difference between the linked list and array data structure is also a popular data structure question, frequently asked in the various programming job interviews. This makes it even more important to learn and understand the difference between an array and a linked list. Well, there are a lot of differences between these two starting from how they store data, to how you retrieve data from them.
Labels:
Array
,
coding
,
core java
,
core java interview question
,
data structure and algorithm
,
programming
How to merge two sorted arrays in Java? Example Tutorial
Hello guys, if you want to learn how to merge two sorted arrays in Java then you have come to the right place. Earlier, I have shown you how to sort arrays in Java, and in this article, I will show you how to merge two sorted arrays in Java. Btw, if you are a complete beginner then Firstly, you need to know what an array is before going about solving this problem about sorted array. An array is a data structure in Java that holds values of the same type with its length specified right from creation time. This means you can create an integer array like int[] to store integer value. Think of a container, like a crate of eggs or coke, where number of places are fixed and you cannot change once you created it.
Labels:
Array
,
Coding problems
,
core java
How to check if a given linked list is a palindrome in Java? Example [Solved]
Hello guys, if you are wondering how to check if a given linked list is a
palindrome in Java then you have come to the right place. In the past, I
have shared how to check if a given String is palindrome or a given number is a palindrome, and in this article, I will teach you how to check if a linked list is a
palindrome. But before that, let's revise what is a palindrome? A palindrome
is a phrase, word or number, or other sequence of characters that reads the
same backward ad forward. Meaning that It gives you the same thing when read
forward or backward. For example, Mary, Army, Madam, racecar, 1-2-3-2-1,
noon, level, Hannah, civic, etc.
Labels:
Coding problems
,
data structure and algorithm
,
linked list
Subscribe to:
Posts
(
Atom
)