Saturday, September 30, 2023

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. 

Friday, September 29, 2023

10 Example of List in Java

Hello guys,  Java, as a versatile and widely used programming language, offers a plethora of data structures to developers. One of them is List which is also fundamental component in Java's collection framework, play a pivotal role in managing and manipulating sequences of elements. In the past, I have shared 10 Examples of HashMap in Java and In this article, we'll delve into Java lists, exploring their features and providing ten illustrative examples to deepen your understanding. List are also a popular topic from Java interviews with questions like difference between ArrayList and LinkedList which have been asked to me almost 10 times in past 20 years. 

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. 

Thursday, September 28, 2023

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 Class and Record in Java?

Hello guys, when it comes to defining data structures in Java, two primary options are at your disposal: records and classes. Each has its unique characteristics and use cases, and understanding the differences between them is crucial for making the right design choices in your Java applications. This has now also become a popular Java interview question and asked to one of my reader recently as well.  Java classes have been the cornerstone of object-oriented programming for years, offering full customization and flexibility. They allow you to define complex objects with custom behavior, encapsulation, and fine-grained control over state changes.

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

Wednesday, September 27, 2023

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. 

Tuesday, September 26, 2023

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.

Monday, September 25, 2023

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. 

Sunday, September 24, 2023

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. 

Saturday, September 23, 2023

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.

Friday, September 22, 2023

10 Common Coding Mistakes Every Java Developers Should be aware of

Hello guys, Java is a versatile and powerful programming language, but it's not immune to common coding mistakes that developers may inadvertently make. These errors can lead to unexpected behavior, performance issues, and even security vulnerabilities. In this article, I am going to share 10 such common coding mistakes Java developers often encounter, provide examples of each mistake, explain why they are problematic, and offer solutions to correct them. I strongly recommend every Java developer whether he is beginner, intermediate or senior developer to go through the list once so that you are aware of these mistakes. If you have been coding in Java then most likely you would have also made the same mistake, if you do, let us know in comments so that we all can learn from each other. 

Difference between class and ID selector in jQuery

 In jQuery, class and ID selectors are used to select and manipulate elements in the Document Object Model (DOM) based on their attributes. However, they have distinct differences in terms of how they select elements and their application:


Class Selector ($(".class-name")):


Syntax: To select elements by their class, you use the .class-name syntax, where class-name is the name of the CSS class you want to target.


Selection: Class selectors select all elements that have a specific CSS class applied to them. This means that if multiple elements share the same class, all of them will be selected.


Usage: Class selectors are typically used when you want to apply the same behavior or style to multiple elements with a common class.


Example:


javascript

Copy code

// Select all elements with the class "button"

$(".button").click(function() {

    // Perform some action

});

ID Selector ($("#element-id")):


Syntax: To select elements by their ID, you use the #element-id syntax, where element-id is the unique ID assigned to the element you want to target.


Selection: ID selectors select a single element with the specified ID. IDs must be unique within a web page, so there should be only one element with a given ID.


Usage: ID selectors are used when you want to target a specific element on the page for a unique operation or manipulation.


Example:


javascript

Copy code

// Select the element with the ID "header"

$("#header").addClass("highlight");

Key Differences:


Uniqueness: Class selectors can select multiple elements with the same class, while ID selectors target a single, unique element with a specific ID.


Performance: ID selectors are generally faster than class selectors because they exploit the uniqueness of IDs, making the search more efficient.


Applicability: Use class selectors when you want to apply a behavior or style to multiple elements with a shared class. Use ID selectors when you need to interact with or manipulate a specific, unique element.


CSS Specificity: In terms of CSS specificity, IDs have higher specificity than classes. This means that rules applied to IDs will override rules applied to classes, which can be important for styling.


In summary, understanding the differences between class and ID selectors in jQuery is essential for efficiently selecting and manipulating elements in your web applications. Select classes when you want to work with multiple elements sharing the same class, and use IDs when you need to interact with a unique element on the page.


main difference between class and Id selector in jQuery is that class selector starts with dot (.) while ID selector starts with pound (#) e.g.


$(".articles") will select all elements which has class articles applied on them


$(#article) will only select the element with id article, remember a webpage cannot have elements with duplicate id, which means on id can only be used by one element. 


Though jQuery allows you to select elements using many differnt ways, finding elmeent using tag name is the most common one e.g. $("p") can be used to find all paragraph text or $("li") can be used to find all list tags in the page, but sometime you need to little bit of flexibility. 


1) ID Selector is fastest selector in jQuery.

2) ID's should be unique on the page, when you have multiple elements with same ID's, jQuery selects only the first one. That's because it doesn't have to bother looking for others as there isn't supposed to be any more - that might explain the weird behaviour you're experiencing.


3) ID selector always return a single element but class selector can return more than one elements. This happens becasue ID is uninuqe in a page and cannot be shared between elements but class can be shared between multiple elements. 


4) Query searches for elements from right to left then walks up the DOM tree to see if they match the next selector going left..


Top 10 Java Code Analysis Tools

 Top 10 Java Code Analysis Tools


Efficient and error-free coding practices are vital for the success of any software project. However, even experienced Java developers can inadvertently introduce bugs, security vulnerabilities, or code smells into their applications. To address this, Java code analysis tools come to the rescue. These tools help identify potential issues, enforce coding standards, and improve overall code quality. In this article, we'll delve into the top 10 Java code analysis tools that can significantly enhance your development process.


1. Maven Dependency Analysis:


Maven Dependency Analysis is a part of Apache Maven, a widely used build automation and project management tool. It helps identify and manage dependencies in your project. By analyzing dependencies, you can ensure that your application uses the correct versions of libraries, eliminating potential conflicts.


2. Maven Enforcer Plugin:


The Maven Enforcer Plugin ensures that your project follows specific rules and constraints defined in your Maven build. It helps enforce best practices, such as specifying minimum Java versions, banning certain dependencies, or controlling version ranges, thereby maintaining consistency across your codebase.


3. JSLint Maven Plugin:


JSLint Maven Plugin is a valuable tool for frontend developers working with JavaScript within a Java project. It checks JavaScript code against coding standards and reports any deviations. This ensures that your JavaScript code aligns with best practices and maintains quality.


4. Maven Duplicate Finder Plugin:


The Maven Duplicate Finder Plugin identifies duplicate code in your project, helping to eliminate redundancy and maintain code clarity. It can detect code clones, reducing the chances of bugs propagating throughout your codebase.


5. Checkstyle:


Checkstyle is a popular code analysis tool that enforces coding standards and style guidelines. It supports various coding styles, including Google, Sun, and custom configurations. Checkstyle helps you maintain a consistent coding style throughout your project, making the code more readable and maintainable.


6. PMD:


PMD (Programming Mistake Detector) is a static code analysis tool that detects potential issues, such as code complexity, unused variables, and suboptimal code constructs. PMD provides valuable insights to help developers refactor and optimize their code for better performance and maintainability.


7. FindBugs:


FindBugs is another static code analysis tool that focuses on identifying common bugs and code defects in Java applications. It scans your code for issues like null pointer exceptions, resource leaks, and more, providing actionable recommendations for improvement.


8. Cobertura:


Cobertura is a code coverage analysis tool for Java. It helps you assess the quality of your test suite by identifying areas of code that are not adequately covered by tests. By using Cobertura, you can ensure that your tests exercise your code comprehensively.


9. CodeNarc:


CodeNarc is a static analysis tool specifically designed for Groovy, a dynamic language that runs on the Java Virtual Machine (JVM). It enforces coding standards and identifies potential issues in Groovy codebases, promoting clean and maintainable code.


10. SonarQube:


SonarQube is a comprehensive code analysis platform that supports multiple programming languages, including Java. It provides a centralized dashboard for analyzing code quality, identifying issues, and tracking code smells and vulnerabilities. SonarQube integrates with popular build tools and IDEs, making it a powerful tool for continuous code improvement.


List of Code Analysis Tools:


Maven Dependency Analysis

Maven Enforcer Plugin

JSLint Maven Plugin

Maven Duplicate Finder Plugin

Checkstyle

PMD

FindBugs

Cobertura

CodeNarc

SonarQube

In conclusion, Java code analysis tools are indispensable for maintaining high-quality code, improving codebase maintainability, and ensuring that your software projects are robust and reliable. By integrating these tools into your development process, you can catch issues early, enforce coding standards, and deliver software that meets the highest quality standards. Whether you're a solo developer or part of a large team, leveraging these tools can significantly enhance your Java development workflow.

What is the difference between a trait and an abstract class?

 What is the difference between a trait and an abstract class?

--------------------------------------------------------------

The first difference is that a class can only extend one other class, but an unlimited number of traits.

While traits only support type parameters, abstract classes can have constructor parameters.

Also, abstract classes are interoperable with Java, while traits are only interoperable with Java if they do not contain any implementation.



    A class can inherit from multiple traits but only one abstract class.

    Abstract classes can have constructor parameters as well as type parameters. Traits can have only type parameters. For example, you cant say trait t(i: Int) {}; the i parameter is illegal.

    Abstract classes are fully interoperable with Java. You can call them from Java code without any wrappers. Traits are fully interoperable only if they do not contain any implementation code.


trait Car {

  val brand: String

}


trait Shiny{

  val shineRefraction: Int 

}


trait Miles{

  val miles: Int

}


class BMW extends Car with Shiny with Miles{

  val brand = "BMW"

  val shineRefraction = 12

  val miles = 500

}


In the realm of object-oriented programming, both traits and abstract classes play essential roles in structuring code and promoting code reusability. However, they have distinct characteristics and use cases that set them apart. In this article, we will explore the key differences between a trait and an abstract class in the Scala programming language.


1. Inheritance Limitations:

One of the fundamental differences between traits and abstract classes lies in their inheritance model. In Scala, a class can extend only one other class, whether it's a concrete class or an abstract class. On the other hand, Scala allows a class to mix in (inherit from) an unlimited number of traits. This trait-based approach provides a flexible mechanism for combining various pieces of functionality in a single class.


2. Constructor Parameters:

Abstract classes and traits also differ in their support for constructor parameters. Abstract classes can have both constructor parameters and type parameters. This means you can pass values to an abstract class when creating an instance. In contrast, traits can only have type parameters; they cannot accept constructor parameters. Attempting to define a trait with constructor parameters is not allowed in Scala.


3. Interoperability with Java:

Scala is often used in conjunction with Java, and interoperability with Java is an essential consideration. Abstract classes have a clear advantage in this regard. They are fully interoperable with Java, meaning you can call them from Java code without any additional wrappers or modifications. Traits, on the other hand, are fully interoperable with Java only if they do not contain any implementation code. If a trait includes concrete method implementations, it becomes less straightforward to use from Java code.


Here's a quick example to illustrate these differences:


scala

Copy code

trait Car {

  val brand: String

}


trait Shiny {

  val shineRefraction: Int

}


trait Miles {

  val miles: Int

}


class BMW extends Car with Shiny with Miles {

  val brand = "BMW"

  val shineRefraction = 12

  val miles = 500

}

In this example, the BMW class inherits from multiple traits (Car, Shiny, and Miles) to combine their functionalities. Traits provide a workaround for Scala's lack of support for multiple inheritance, making it possible to mix in various traits to create a rich class hierarchy.


In summary, traits and abstract classes serve different purposes in Scala. Traits offer a flexible way to mix in multiple sets of behaviors into a class, making up for Scala's limitation on multiple inheritance. Abstract classes, on the other hand, provide constructor parameter support and seamless interoperability with Java. The choice between traits and abstract classes depends on the specific needs of your application and the desired characteristics of your class hierarchy.

In short, traits is Scala's work around for multiple inheritance feature which is not supported in Java. 

Top 10 excuse for not doing Unit testing and Code reviews

 Top 10 excuse for not doing Unit testing and Code reviews

------------------------------------------------------------

If you have been doing software development for couple of years, then you definitely know advantages of code review and unit test, but you do agree that, though it is widely regarded and accepted as best practice, it not always used as much.



Top 10 Excuses for Avoiding Unit Testing and Code Reviews


While unit testing and code reviews are widely recognized as best practices in software development, the reality is that they are not always embraced as fervently as they should be. Despite their numerous benefits, developers and teams often find themselves making excuses to avoid or delay these essential activities. Here are the top 10 excuses for not prioritizing unit testing and code reviews:


1. Tight Schedules and Timely Delivery:

"We acknowledge the benefits of unit testing and code reviews, but our project timelines are so tight that we can't afford the extra time required for these activities."


2. QA's Responsibility:

"We are paid to write code, and QA is responsible for testing it. Why should we do their job?"


3. Trust in QA's Expertise:

"Our QA team is exceptionally skilled at finding bugs. We have confidence in their ability to catch issues without the need for extensive testing on our part."


4. Post-Release Code Reviews:

"Let's focus on getting the release out the door first. We can always conduct code reviews after the software is deployed. The business has been waiting for this for a long time."


5. Fear of Conflict:

"Code reviews can sometimes lead to conflicts, especially when dealing with developers with strong egos. It's easier to skip them to maintain a harmonious atmosphere."


6. Time Constraints vs. Testing:

"I would love to write unit tests for all my classes, but it will take twice as long to complete this feature. Do you want me to prioritize writing tests over delivering features?"


7. Planned But Delayed Testing:

"Unit testing is on our roadmap, and we intend to revisit it once we have some breathing room in our schedule. Right now, we're swamped with other tasks."


8. Build Speed Concerns:

"Unit tests can slow down our build process significantly. Our agile team relies on a fast build environment, and we can't afford the delay."


9. Monthly Code Reviews:

"I enjoy code reviews, but I wish they were a regular occurrence, at least once a month. It's hard to keep up the momentum when they're infrequent."


10. Code Reviews for Inattentive Programmers:

"Code reviews are more for those developers who don't pay attention while coding. Since we take care to write quality code, we believe they're not necessary for us."


In conclusion, while these excuses may be tempting in the face of tight deadlines, conflicting priorities, and ego considerations, the benefits of unit testing and code reviews cannot be overstated. Embracing these practices leads to better code quality, fewer bugs, improved collaboration, and ultimately, more robust software. It's essential for development teams to recognize the value of these practices and prioritize them in their software development lifecycle. After all, the long-term benefits far outweigh the short-term challenges.


That's all folks, let me know what is your excuse of not doing of code review?


Top 5 Frequently Asked HR Interview Questions in Job Interviews



HR interviews are a standard part of the job application process, and you've likely encountered some seemingly straightforward yet surprisingly tricky questions during these interviews. While some may dismiss these questions as overly simplistic or cliché, they serve a vital purpose in the hiring process. In this article, we'll explore five of the most commonly asked HR interview questions, delve into their significance, and discuss why they continue to be an integral part of job interviews.


1. What Are Your Strengths and Weaknesses?


This classic question often elicits prepared responses from candidates, but its value lies beyond the rehearsed answers. HR professionals use this question to gauge a candidate's honesty, self-awareness, and preparation. While a response like "I work too hard" may come across as scripted, a more genuine answer, such as admitting to occasional emotional decision-making, reveals a candidate's courage and authenticity. Depending on the role, this information can provide insights into a candidate's suitability for the job.


2. Why Are You Looking to Leave Your Current Job?


The question about why you're leaving your current job serves as a window into your motivations and professionalism. It's not just about money; it's about understanding what drives you. Are you seeking new challenges, a better work environment, or improved work-life balance? The way you address this question demonstrates your diplomacy and honesty, without necessarily being negative about your current employer. HR professionals want to assess your seriousness and commitment to the job application.


3. Where Do You See Yourself in 5 Years?


While the classic humorous response is tempting, this question probes your ambition and long-term goals. It allows employers to identify candidates who align with the company's growth trajectory. Some candidates are more ambitious and forward-thinking, while others may seek stability and a balanced work-life scenario. A diverse team requires individuals with varying perspectives on their career trajectories.


4. Why Do You Want to Join Our Company?


This question delves into your knowledge of the company and your reasons for wanting to be a part of it. A generic response focused solely on salary and benefits may not leave a favorable impression. A thoughtful answer, highlighting your interest in the company's products, values, or unique opportunities, demonstrates your genuine enthusiasm for the role. HR professionals are looking for candidates who are genuinely excited about the company and its mission.


5. If You Described Yourself as a Biscuit, What Sort of Biscuit Would You Be?


While seemingly whimsical, this question assesses your ability to think creatively and respond under unexpected circumstances. There isn't a right or wrong answer here; rather, it's an opportunity to showcase your creativity and adaptability. Responding with a playful but tasteful answer can leave a positive impression, demonstrating your ability to handle unconventional questions with a touch of humor. For example, you can say that "Ummm, tasty and expensive"


In conclusion, these commonly asked HR interview questions, often dismissed as cliché, play a vital role in evaluating candidates beyond their technical skills. They provide insights into qualities like honesty, diplomacy, ambition, enthusiasm, and adaptability, which are essential in today's dynamic workplace. So, while you may encounter these questions frequently, remember that your responses reveal more about you than meets the eye, and they can significantly influence the outcome of your job interview. 

10 Websites to Learn Programming Online for FREE

 10 Websites to Learn Programming Online for FREE

--------------------------------------------------

If you are interested in the Internet and computer and You want to learn programming but do not know where to start?Or feel that time is over and you will not be able to learn programming,The following educational sites list will help you Start learning programming in an easy interactive way.

1-FreeCodeCamp

Is a free site that teaches you programming,Created by Quincy Larson in 2014,Includes a set of tutorials at :HTML-CSS-Js-React.js-Databases-mongoDB.There is also a chat forum with students to solve technical problems.

 Advantages :


      *Get experience by coding for FREE

      *Build projects

      *Earn FREE certifications

2-CodeAcademy

Is an educational company aiming to give different tint to teach,It also provides thousands of courses : JavaScript->HTML-CSS-PHP-Python-Ruby-jQuery .It has a team of more than 60 members Contains designers, technicians and experts.Who work to provide the finest lessons,To millions of individuals around the world.

Advantages :

    *An interactive platform for more than 24 million people sharing experience

    *The user is rewarded with badges when the exercises are finished

3-Coursera

Is an institution that offers a range of free lessons offered by a group of accredited teachers in the finest American universities.Foundations by Andrew Ng & Daphne Koller, a team of computing experts.

Advantages :

       *Obtain certified certificates

       *Learn in the least possible time

       *Source open to all

4-SoloLearn

Is a site that allows you to learn a host of famous programming languages ¹¹such as Python 3, Java, C++, and SQL.In an interactive way that relies on combining lessons with exercises .

Advantages :

      *Learning by doing

      *You decide when to learn     

      *Competition from all over the world

5-Edx

Is an educational platform that contains hundreds of free and open source tutorials .A large and qualified team is available to provide the necessary knowledge in programming languages.

Advantages :

        *Courses in various magazines

        *Supported by Harvard University

        *Introducing new techniques to better education

6-KhanAcademy

Is a reliable teaching source that works to spread knowledge in various fields of mathematics, physics, and computers Gives you the ability to learn js-> java->Html-Databases From a team of different peoples of the world.This site was launched in 2006 by SALMAN KHAN Which worked to enlarge the site to become a global site.

Advantages :

       *Content is also available in other languages

       *There are lessons supported by videos

       *The lessons are free and accessible

7-Udacity

Is an institution that offers free courses in various technical journals such as artificial intelligence and machine teaching As well as programming in various languages ¹¹and aims to develop the skills of students by integrating lessons with exercises .

Advantages :

        *The best place to start learning to code

        *The information is checked before submission

        *Free courses from big companies like Google 

Udemy


Pluralsight


Educative


That's all about some of the best websites to learn Programming online for FREE.

How to read a line from File in Java?

 How to read a line from File in Java?

--------------------------------------

You can read a file line by line using both BufferedReader and Scanner in Java, but if you want to read a specific line in file then its not directly supported in Java. In Java 8, you can also use readAllLines() from File method for reading a file line by line in Java 8. 



Solution



Advantages :


Disadvantages :



That's all about how to read a line in Java. You can either read whole file line by line using BufferedReader.readLine() method, or you can use Scanner.nextLine() method for same job. IF you want to read a specific line from file in Java then your only choice is using RandomAccessFile, which provides a file pointer to move around.

Difference between Maven and Gradle in Java

 


Difference between Maven and Gradle in Java

---------------------------------------------

Maven is a build automation tool mostly for Java projects. It's a great tool, but it has one important drawback that has motivated the creation of similar tools, like Gradle and SBT. That weakness is its verbosity of configuration. Maven gets all project build parameters from pom.xml, an XML file that can get very long.


I think Gradle solves this problem more elegantly, where you can inject common dependencies rather than inherit them.

This tends to give better control and flexibility.

It seems analogous to composition (Gradle) vs. inheritance (Maven) ;-)


Is there a way to specify only select elements to include from a parent POM?

It's not possible, in Maven. But why would you need that? All elements defined in jcabi-parent POM are "optional". When you inherit our pom.xml and don't use them, they won't get into your project.


Further Learning


Thanks for reading this article so far. If you find this article useful then please share with your friends and colleagues. If you have any questions or feedback then please drop a note.

10 Skills You can Learn to become a Senior Developer in 2020

 10 Skills You can Learn to become a Senior Developer in 2020

-------------------------------------------------------------

Nobody likes to be in the same place for year and that's also true for junior develoeprs and software engineers. They also want to grow and become Senior pro but many of them don't know what it takes to become a senior developer which companies sought after. In this article, I am going to share some of the essential skills required to beocme a senior software engineer. There is a good chance that you already have many of these skills but not upto the level required to be considered as senior pro, in that case just work on those and level up those skills.



1. Containers


2. Cloud


3. Algorithms


4. Data Structures


5. Concurrency


6. Database


7. Problem Solving


8. Scripting


9. Agile Methodology


10. Automation




That's all about some of the essential skills for programmers who wants to become a senior developer in 2020.



Further Learning


Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any questions or feedback then please drop a note.

Top 10 Tools for REST API Development and Testing

 Top 10 Tools for REST API Development and Testing

--------------------------------------------------

Hello guys, it's been long time since I have shared useful tools. So, today, I am going to write about 10 essential tools for REST API development and Testing. These are the tools which will help you in every stage of your REST based project like design, development, testing, and documentation.


Without wasting anymore of your time, here is my list of 10 useful tools every REST developer should learn



1. Postman

Postman is the most essential tool for API development and testing. It allows you to interact with any REST API by sending differnet kinds of HTTP request like GET, POST, DELETE etc. You can then see the response and also view response headers and codes. It also allows you to send query paramter, customize request headers and much more. You can also use different Authentication method like BASIC authentication to interact with secure REST API. Postman is avaialble both as a desktop application (Postman App) as well as Chrome extension. If your work involves interacting with REST API, it make sense to learn Postman. Its very useful testing REST API as well.


2. cURL

This is a Linux utility or command which can also be used as a great tool to interact with REST APIs from command line. The cURL command allows you to send both GET and POST request and also populate differnet request headers. You can also send authentication credential to interact with secure API. If you love to work in Linux command line then this a great tool to learn.


3. RESTAssured



4. Swagger



5. Burp

Debugging with HTTP Debuggers using Burp as a proxy



6. WireShark

Debugging with packet sniffers using Wireshark



7. RAML


8. JMeter

Using Loader to do load, soak and stress testing



9. SoapUI

This is another intersting tool which you can use 



10. Apiary

Using Apiary for designing, documenting and stubbing out your API



That's all about some of the useful tools for REST API developers. A good knowledge of these tools are essential for buiilding real-world REST API. These tools will help you in designing, testing, and even on documentation of your REST API and RESTful Web Services.Thanks for reading this article so far. If you like these REST API tools then plese share with your friends and colleagues. If you have any questions or feedback then please drop a note.

Perl Interview Questions and Answers

 Perl Interview Questions and Answers

-------------------------------------

What do variable sigils indicate in Perl 5?

What's the difference between accessing an array element with $items[$index] and @items[$index]?

What's the difference between == and eq?

What do you get if you evaluate a hash in list context?

How do you look up keywords in the Perl documentation?

What is the difference between a function and a method in Perl 5?

When does Perl 5 reclaim the memory used by a variable?

How do you ensure that the default scope of a variable is lexical?

How do you load and import symbols from a Perl 5 module?

What governs how Perl 5 loads modules How can you influence the list of directories from which perl attempts to load modules?

How do you look up error messages in the Perl 5 documentation? (Award bonus points for knowing how to enable explanations of all error messages encountered.)

What happens when you pass an array into a function?

How do you pass one or more distinct arrays into a function?

What is the difference, on the caller side, between return; and return undef;?

Where do tests go in a standard CPAN distribution?

How do you run tests in a standard CPAN distribution?

What command do you use to install new distributions from the CPAN?

Why would you use the three-argument form of the open builtin?

How do you detect (and report) errors from system calls such as open? (Award bonus points for knowing how to enable automatic detection and reporting of errors.)

How do you throw an exception in Perl 5?

How do you catch an exception in Perl 5?

What is the difference between reading a file with for and with while?

How do you handle parameters within a method or function in Perl 5?

What do parentheses around the variable name in my ($value) = @_; mean, and what would happen if you removed them?

Is new a builtin function/keyword?

How do you read the documentation of a core library? A CPAN module?

How do you access only the values of a Perl 5 hash?



That's all about some good Perl Interview Questions and Answers. If you are starting to learn Perl, this list is a good way to measure your skills. A good Perl developer should be able to answer all of these questions without much difficulty and with little bit of study and practice. You can also read a good text on Perl to learn more about these questions e.g. Modern Perl.

Graphs Interview Questions


----------------------------

    Breadth first search in a graph

    Number of clusters of 1s OR Number of Islands

    Topological Sorting of a Directed Acyclic Graph.

    Minimum number of trials to reach from source word to destination word

    Friend Circles Problem-> Graph Theory

    Dijkstra's Shortest Path algorithm

    Bellman-Ford Algorithm

14 Multithreading best practices in Java for Experienced Developers

Hello guys, if you are doing Java development then you know how important your multithreading and concurrency skills are. They are often the deciding factor in your selection or non-selection and that's why its very important to continuously improve your Java concurrency and multithreading knowledge. In the past, I have shared 50+ thread interview questions and today's article, I am going to share 15 best multithreading practices which experienced Java developer should know and follow. 










1) Given meaningful name to your threads and thread pool


I can't emphasize this. When dumping threads of a running JVM or during debugging, default thread pool naming scheme is pool-N-thread-M, where N stands for pool sequence number (every time you create a new thread pool, global N counter is incremented) and M is a thread sequence number within a pool. For example pool-2-thread-3 means third thread in second pool created in the JVM lifecycle. See: Executors.defaultThreadFactory(). Not very descriptive. JDK makes it slightly complex to properly name threads because naming strategy is hidden inside ThreadFactory. Luckily Guava has a helper class for that:

import com.google.common.util.concurrent.ThreadFactoryBuilder;


final ThreadFactory threadFactory = new ThreadFactoryBuilder()

        .setNameFormat("Orders-%d")

        .setDaemon(true)

        .build();

final ExecutorService executorService = Executors.newFixedThreadPool(10, threadFactory);

By default thread pools create non-daemon threads, decide whether this suits you or not.


Let's go through each of these multithreading best practices with examples to illustrate their importance:


2) Minimize inter thread communication and data sharing

Inter-thread communication and data sharing can lead to complex synchronization issues. Minimizing such communication reduces the risk of deadlocks and race conditions. Consider using thread-local variables when possible to avoid sharing data between threads.


Example:


public class ThreadLocalExample {

    private static ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);


    public static void main(String[] args) {

        threadLocal.set(42);

        int result = threadLocal.get(); // Each thread has its own value

    }

}

3) Minimize locking by reducing the scope of synchronized

To avoid contention and improve performance, synchronize only the critical sections of your code, reducing the scope of synchronization.


Example:

public class SynchronizationExample {

    private int count = 0;

    private Object lock = new Object();


    public void increment() {

        synchronized (lock) {

            count++;

        }

    }

}

4) Use Immutable objects

Immutable objects are thread-safe by design because they cannot be modified once created. Use them to avoid the need for synchronization when dealing with shared data.


Example:


public final class ImmutableExample {

    private final int value;


    public ImmutableExample(int value) {

        this.value = value;

    }


    public int getValue() {

        return value;

    }

}

5) Avoid Static variables

Static variables can be shared among all threads, leading to concurrency issues. Minimize their use and prefer instance variables when necessary.


Example:


public class StaticVariableExample {

    private static int sharedCount = 0;


    public synchronized static void increment() {

        sharedCount++;

    }

}

6) Use MDC Context for Logging

Logging frameworks like Log4j and Logback provide tools like Mapped Diagnostic Context (MDC) to associate context information with log entries for each thread.


Example (Logback MDC):


import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.slf4j.MDC;


public class LoggingExample {

    private static final Logger logger = LoggerFactory.getLogger(LoggingExample.class);


    public static void main(String[] args) {

        MDC.put("user", "john_doe");

        logger.info("User logged in.");

        MDC.clear();

    }

}


7) Always remove ThreadLocal once done

When using ThreadLocal, it's essential to remove the value associated with the current thread once you're done with it to prevent memory leaks.


Example:


public class ThreadLocalExample {

    private static ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);


    public static void main(String[] args) {

        threadLocal.set(42);

        int result = threadLocal.get();

        threadLocal.remove(); // Remove the value when done

    }

}


8) Use Lock Stripping (e.g., ReadWriteLock)

Lock stripping techniques, like ReadWriteLock, allow multiple threads to read concurrently while ensuring exclusive access for writes.


Example:


import java.util.concurrent.locks.ReadWriteLock;

import java.util.concurrent.locks.ReentrantReadWriteLock;


public class ReadWriteLockExample {

    private ReadWriteLock lock = new ReentrantReadWriteLock();

    private int data;


    public int readData() {

        lock.readLock().lock();

        try {

            return data;

        } finally {

            lock.readLock().unlock();

        }

    }


    public void writeData(int newData) {

        lock.writeLock().lock();

        try {

            data = newData;

        } finally {

            lock.writeLock().unlock();

        }

    }

}


9) Use volatile

The volatile keyword ensures that reads and writes to a variable are directly performed on the main memory, preventing thread-local caching of the variable.


Example:

public class VolatileExample {

    private volatile boolean flag = false;


    public void toggleFlag() {

        flag = !flag;

    }

}


10) Use atomic integers for counters:

Atomic integer classes, such as AtomicInteger, provide thread-safe operations for common tasks like incrementing counters.


Example:

import java.util.concurrent.atomic.AtomicInteger;


public class AtomicIntegerExample {

    private AtomicInteger counter = new AtomicInteger(0);


    public void increment() {

        counter.incrementAndGet();

    }


    public int getCount() {

        return counter.get();

    }

}

11) Use BlockingQueue for Producer-Consumer design:

BlockingQueue provides a thread-safe way to implement the Producer-Consumer pattern, ensuring proper synchronization between producers and consumers.


Example:

import java.util.concurrent.ArrayBlockingQueue;

import java.util.concurrent.BlockingQueue;


public class ProducerConsumerExample {

    private BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);


    public void produce(int item) throws InterruptedException {

        queue.put(item);

    }


    public int consume() throws InterruptedException {

        return queue.take();

    }

}

12) Use Disruptor for fast inter-thread communication:

The Disruptor pattern is designed for high-performance, low-latency inter-thread communication. It offers a ring buffer-based approach for handling data flow between threads efficiently.


13) Minimize context switching of threads:

Reducing context switching, where a CPU switches between threads, improves performance. Minimize unnecessary thread creation and ensure efficient use of existing threads.


14) Use Busy Spin to keep cached data in CPU L1:

Busy spinning is a technique where a thread repeatedly checks for a condition to become true instead of yielding its execution. It can be used when waiting times are short to keep data in CPU caches and reduce latency.


15) Use thread-safety:

Always design your classes and components with thread-safety in mind. Understand the thread-safety guarantees of libraries and frameworks you use and follow best practices to ensure your code is robust in a multi-threaded environment.


In conclusion, these best practices help you write efficient and robust multi-threaded Java applications. By minimizing inter-thread communication, using thread-safe constructs, and following these guidelines, you can avoid common pitfalls and create reliable concurrent systems.