Why Dependency Injection is a Best Practice?

As a Java programmer, you've likely encountered the term "Dependency Injection" (DI) in your development journey. Dependency Injection is more than just a buzzword; it's a design principle that can significantly improve your code's quality, maintainability, and testability. In this article, we'll delve deep into the world of Dependency Injection, exploring why it's considered a best practice, and I will also showcase practical examples of Dependency injection using popular frameworks like Spring and Google Guice. You can use those examples to learn how to write code using Dependency Injection in Java. 

15+ Spring Framework Quizzes for Java Programmers (Free)

Hello guys, ever since I have started creating practice test on Udemy a lot of people ask me if I can practice a few questions as quiz in my blog here for free. I though its a great idea because it allows my readers to not just see the questions but also practice it and that's why I am creating this kind of quizzes. If you guys like it then I will probably create many more. Any way, preparing for IT certification like Oracle's Java certification or VMware's Spring Certification required a lot of hard-work. I have seen many experienced Java developers failing these certifications and losing money and time due to overconfidence and lack of preparation. A structured and complete certification preparation involves reading books, joining course and doing practice questions

How to print pyramid pattern of stars and numbers in Java? Example

Hello guys, printing patterns of stars and numbers is a common programming exercises and is often asked during coding interviews as well. If you are learning to program or preparing for coding interviews, knowing how to print a pattern can really help. You can print the Pyramid pattern of stars or numbers using loops and print methods in Java. There are two print methods you need to know, System.out.print() and System.out.println(), the difference between print() and println() is that println adds a new line character at the end i.e. it appends \n automatically. which means the next time you write something will begin at the new line. On the other hand, if you use print() then the text is appended to the same line.

How to Find Prime Factors of Integer Numbers in Java - Factorization Algorithm Example

One of the common homework/tasks in programming courses is about Prime Factorization. You are asked to write a program to find prime factors of a given integer number. The prime factors of a number are all of the prime numbers that will exactly divide the given number. For example, prime factors of 35 are 7 and 5, both are prime in themselves and exactly divide 35. The last time I did this exercise was when I was in college, and it was something like, writing a program that asks the user for an integer input and then displays that number's prime factorization on the command line.  

How to Count number of Set bits or 1's of Integer in Java? Example

There are multiple ways to count the number of 1's or set bits in an integer number in Java. You can use a bitwise and bit shift operator on your own, or, you can use Java API to count the number of set bits. Java 1.5 added two utility methods called bitCount(int i) which returns a number of 1's in your integer number, java.lang.Long class has a similar bitCount(long number) for long primitives. As I have said earlier, Coding questions are an important part of any Java interview, and from that recursion and bitwise operations are most popular. 

How to Add Two Integer Numbers without using Plus + or ++ Arithmetic Operator in Java - Recursion example

In this article, we will take a look at another interview question about adding two numbers, but without using the + or ++ operator. The interview starts with a simple statement, Can you write a function to add two numbers (integers) without using + or plus arithmetic operator in Java? If you are good at maths, it wouldn’t take more than a second to say that, we can use subtraction or - operator to add two numbers because a-(-b)== a+b. Well, that’s correct, but the real question starts when the interviewer quickly points out that, you can not use any arithmetic operator including +,-,*,/++, or --

How to Check if Integer Number is Power of Two in Java - 3 examples

How to check if an integer number is a power of 2 in Java is one of the popular programming interview questions and has been asked in many interviews. Surprisingly, this problem which looks simple enough to answer doesn't turn out that simple if for many developers. Many Java programmers, both freshers and less experienced,  struggle to write code for a function, which can check if the number is the power of 2 or not. 

Java Program to find factorial of number in Java - Example Tutorial

How to find the factorial of a number in Java in both recursive and iterative ways is a common Java interview question mostly asked at the fresher level. It’s not just popular in Java interviews but also in other programming languages like C or C++. It's also famous  In our last article we have seen how to check if a number is prime or not and in this Java programming tutorial, we will see a simple Java program to find the factorial of a number in Java by using recursion and iteration. The same program can also be used to print factorial of any number or print a range of factorial as well.

How to choose a Collection class in Java? Flowchart Example

One of the key skill of a Java programmer is his mastery over Collection framework, he must know when to use which collection class in Java. He must remember that Map is for key value pair, which List and Set is for storing values only. He should know that List is ordered collection, which allows duplicate but Set is unordered but doesn't allow duplicates. He should also be able to choose between Sorted Set, Map and other collection class which provides ordering e.g. LinkedHashMap and LinkedHashSet. To your surprise this is not at all a difficult task, all you need to remember is virtue of different collection class in Java. This article, help you to choose right collection class depending upon your requirement, by simply going through a flow chart and selecting collection where your requirement and their properties matches. 

How to Check If Number is Even or Odd without using Modulus or Remainder Operator? Example

Write a Java program to find if a number is odd or even is one of the basic programming exercises, and anyone will be happy to see this in actual Java Interviews, wouldn't you? By the way, did I said easy, well there is a little twist there, you need to check odd and even without using modulus (%) or remainder operator in Java. Since many programmers, especially freshers are familiar with % operators, this nice little trick does put them into thinking mode, which is what the interviewer wants. This question is on a similar level of checking if a number is a palindrome or not if you have practiced such questions, it would be easy to find a solution.

Java Program to print Prime numbers in Java - Example Tutorial and Code

How to print Prime numbers in Java or how to check if a number is prime or not is classical Java programming questions, mostly taught in Java programming courses. A number is called a prime number if it's not divisible by any number other than 1 or itself and you can use this logic to check whether a number is prime or not. This program is slightly difficult than printing even or odd numbers which is relatively easier than Java exercises. This Simple Java program prints prime numbers starting from 1 to 100 or any specified number. It also has a method that checks if a number is prime or not.

Java Program to Find Sum of Digits in a Number using Recursion? Example

Recently this question to ask was one of my readers, which inspired me to write this tutorial. There was a usual check to solve this problem using both recursion and iteration. To be frank, calculating the sum of digits of an integral number is not difficult, but I have still seen quite a few programmers fumbles, even after providing hints in terms of division and modulus operator. The key point here is to know how to use division and modulus operators in Java. This kind of exercise including reversing a number, where you need to find digits from a number, use division operator to remove right, and use modulus operator or % to get rightmost digits.

Difference in @RunWith vs @ExtendWith Annotations in JUnit - Java

Hello guys, if you have written any unit test in Java then you must have come across JUnit and Mockito. JUnit is the most popular and widely-used testing framework in the Java ecosystem, enabling developers to write and execute unit tests for their Java applications. While writing tests, JUnit provides various annotations to facilitate different functionalities. Two of these annotations, @RunWith and @ExtendWith, play a crucial role in customizing the test execution process. In this article, we will explore the key differences between these two annotations and illustrate their usage through a Java program. This one is also one of the popular JUnit Interview question which I have also included in my earlier article about 20 Most asked JUnit Interview Questions for Java developers, if you haven't read it yet then you can also read it to learn more about JUnit and unit testing in Java. 

Java Program to Reverse an Integer Number - Example tutorial

How to reverse a number in Java without using any API or write a simple Java program to reverse a number is common programming questions asked on fresher level software engineer interviews. Reversing a number is also popular homework question on many Java programming courses in schools, colleges, and training institutes. I personally feel java program to reverse number is good programming exercise for someone who is just started learning to program in Java or any other programming language because of its simplicity and a little bit of trickiness which shows how to use operators for programming purposes rather than arithmetic purpose.

3 ways to Find First Non Repeated Character in a String - Java Programming Problem Example

Write a Java program to find the first non-repeated character in a String is a common question on coding tests. Since String is a popular topic in various programming interviews, It's better to prepare well with some well-known questions like reversing String using recursion, or checking if a String is a palindrome or not. This question is also in the same league. Before jumping into the solution, let's first understand this question. You need to write a function, which will accept a String and return first non-repeated character, for example in the world "hello", except 'l' all are non-repeated, but 'h' is the first non-repeated character.

How to Count Number of Words in String ? Java Coding Exercise Example

The string is very popular among the Interviewer, and you are bound to see some questions on any programming interview, Java Interviews are no exception. Questions based on Java fundamentals like why String is Immutable in Java to questions based on coding skills e.g. reverse String using recursion in Java, String has always troubled candidates. In this article, we will see a similar question, how to count the number of words in Java String. Before jumping to the solution, just read below to make sure what a word means here. It's a sequence of one or more non-space characters.

How to Reverse String in Java Using Iteration and Recursion - Example

How to reverse String in Java is a popular core java interview question and asked on all levels from junior to senior java programming jobs. since Java has rich API most java programmer answer this question by using StringBuffer reverse() method which easily reverses a String in Java and its right way if you are programming in Java but the most interview doesn't stop there and they ask the interviewee to reverse String in Java without using StringBuffer or they will ask you to write an iterative reverse function which reverses string in Java.

Top 20 String Algorithm Questions from Coding Interviews

In this article, we are going to see the top 20 String based coding interview question and their solution to help programmers better prepare for interviews. The string is one of the most important data structures and available in almost every programming language like Java, C, C++, Python, Perl, and Ruby. Though there implement differ the essence remains the same like String is NULL terminated character array in C but String is an object in Java, again backed by character array. The string is also available on weekly typed languages like Python and Perl.  This is why you will always find some String based coding questions on programming interviews.

How to check if two String are Anagram in Java - Program Example

Write a Java program to check if two String is an anagram of each other, is another good coding question asked at fresher level Java Interviews. This question is on a similar level of finding the middle element of LinkedList in one pass and swapping two numbers without using the temp variable. By the way, two String is called anagram, if they contain the same characters but on different order e.g. army and mary, stop and pots, etc. Anagrams are actually a mix-up of characters in String. If you are familiar with String API, i.e. java.lang.String then you can easily solve this problem.

How to delete a directory with files in Java - Example

Deleting an empty directory is easy in Java, just use the delete() method of java.io.File class, but deleting a directory with files is unfortunately not easy. You just can't delete a folder if it contains files or sub folders. Calling delete() method on a File instance representing a non-empty directory will just return false without removing the directory. In order to delete this folder, you need to delete all files and subdirectories inside this folder. This may seem cumbersome, but unfortunately, there is no method that can delete a directory with files in Java, not even on Java 7 Files and Paths class.

How to resolve java.lang.ClassNotFoundException in Java? Example

What is ClassNotFoundException in Java
ClassNotFoundException is one of Java nightmare every Java developer face in there day to day life. java.lang.NoClassDefFoundError and java.lang.ClassNotFoundException are two errors  which occurs by and now and chew up of your precious time while finding and fixing root cause. From the name java.lang.ClassNotFoundException looks quite simple but underlying cause of it is always different and which classifies it as an environmental issue. In this java tutorial, we will see what is ClassNotFoundException in java, what is real cause of it, and how to fix it along with some more frequent and infamous examples of java.lang.ClassNotFoundException in Java or J2EE, Don’t mistake this exception with NoClassDefFoundError in Java which is also due to incorrect classpath in Java. 

9 Maven Concepts and Tools Every Java Developers Should Know

The Apache Maven is an essential tool for Java developers. It makes their life easy by allowing them to create a Java project faster by using a standard directory structure. It also helps them to download project dependency automatically. Not only that, but Maven also downloads transitive dependencies that relieve Java developers from the big headache of keep check of different versions of dependent libraries. For example, if your application is dependent on the Spring framework, but Spring is dependent on Log4j then you also need to download the correct version of Log4j JAR files for the Spring MVC framework, Maven does this automatically for you.

Where and How to download Spring Framework JAR file (Spring 5.0 or Spring 4.0) without Maven, Gradle

One of the easiest and oldest ways to run a Java program which depends on an external library or framework is to download dependency JAR files, put them on the classpath and then run the program by creating a Main class with the main() method. This is simple but not as easy as you think, there are many challenges down the road e.g. you need to find the right version of JAR files and their dependencies e.g. Spring might have a dependency on other third-party libraries like Log4j. So, when the build tool like Maven and Gradle comes, everybody stopped downloading the JAR file manually.

Tibco Tutorial : Http Interface for Tibco RV Issues Troubleshooting and TIBCO RV Alternatives

This is another post of my tibco tutorial series , if you want to read more about tibco rv or tibco ems please read there. in this post I am sharing you great tool to solve tibco rv related problems and a great interface to analyze your Tibco RVD activities. until i know this I mostly used netstat command to figure out which topics are subscribed by my tibco RVD but after since I know about this I had helped me a lot.

FIX protocol Tutorial: Futures and Options

Hello guys, its been a long time since I shared any FIX protocol tutorial, I think almost 12 years but today is the day. If you are using FIX Protocol to create derivative trading systems in Java and want to learn about Futures, Options and how they are supported in FIX Protocol then you have come to the right place. In the past, I have shared FIX Protocol tutorials as well as many FIX Protocol questions and in this article, I will talk about Futures, Options and how FXI Protocol support their trading. The FIX Protocol, widely used in financial markets, plays a crucial role in electronic trading, including futures and options. Futures and options are derivatives that enable traders and investors to speculate on the price movement of various financial instruments. This tutorial will provide a comprehensive overview of futures and options trading and how the FIX Protocol supports these activities.

What is Atomic Operation and Variable in Java? AtomicInteger Counter Example

Hello guys, if you're wondering what is atomic operator in Java and how Atomic variable works then you have come to the right place. Earlier, I have shared difference between atomic, volatile and synchronized in Java and in this article, I will explain What is Atomic operator in Java, What are atomic variables and how to use them. In Java, the reading and writing of 32-bit or smaller quantities are guaranteed to be atomic. By atomic we mean each action takes place in one step and cannot be interrupted. Thus, when we have multithreaded applications, the read and write operations are thread-safe and need not be made synchronized.

Role based Access control using Spring Security and MVC, Mapping LDAP Groups to Authorities for Authorization

Authentication and Authorization is an integral part of any Java enterprise or web application. Since most of the company uses LDAP Active directory for authentication, authorization, and Role-based access control (RBAC), it's good to know How to implement Role-based access control using Spring MVC and Spring Security. This is the second part of my articles on using Spring Security for authentication and authorization in Spring MVC based Java application. In the last part, we have learned about doing LDAP authentication against Windows active directory, and in this Spring Security tutorial, we will learn How to map LDAP groups to authorities for implementing Role-based access control or authorization.

Top 12 Locking, Synchronization and Multithreading Interview Questions for 5 to 7 Years Experienced Java Programmers [2023]

Hello guys, if you are an experienced Java developer say 3 to 5 years or 5 to 7 years experience and  preparing for Java Interviews then you very well know that Locking, Synchronization, ConcurrentHashMap, volatile and atomic, compare and swap (CAS), Executor Service, Stream API, and Multithreading in general are quite important and as an experienced Java developer you should be ready for them. In the past, I have shared 50+ Java Multithreading questions, 12 concurrency questions, 21 HashMap questions, and 10 ConcurrentHashMap questions and in this article, I am going to share 10 of my favorite question on Locking, Synchronization and Inter thread communication in Java. If you have been doing Java Interviews then its highly likely that you have already seen this problem but if you haven't you should definitely prepare them.

What is happens-before in Java Concurrency? An example

A couple of days ago, one of my readers messaged me on LinkedIn about a Java interview question he has recently faced - what is the happens-before relationship in Java concurrency? What is the benefit of it, and how exactly it works? He kind of has some ideas about that its related to the Java Memory Model and provides some sort of visibility guaranteed but couldn't explain with conviction to his interviewer, particularly with a code example and was a bit disappointed. He then asked me if I can write an article about it. I said you should have read the Java concurrency in Practice book or join the Java Concurrency in Practice Bundle course by Heinz Kabutz before the interview, that would have helped, but nonetheless, I liked the idea to just provide a quick overview of what is the happens-before relationship between threads in Java.

Top 5 Free Java Multithreading Courses to Learn in 2023 - Best of Lot

Hello guys, if you want to learn multithreading and concurrency in Java and looking for best free resources like online courses and tutorials then you have come to the right place. Earlier, I have shared best free Java Courses and best free Spring Framework courses and today, I will share best free online courses to learn Multithreading and Concurrency in Java. Multithreading is one of the important skill for Java programmers as companies are always in hunt of Java programmer who are good at multithreading and concurrency but at the same time its very hard topic to master. Acquiring solid multithreading and concurrency skill require a lot of hard worked and years of experience but you can speed up by joining best Java multithreading courses and learning from expert.

Top 15 Java Multithreading, Concurrency Interview Questions Answers asked in Investment banks

Multi-threading and concurrency questions are an essential part of any Java interview. If you are going for any Java interview on any Investment bank like Barclays, Citibank, Morgan Stanley, etc for the Cash Equities Front Office Java Developer position, you can expect a lot of multi-threading interview questions on your way. Multi-threading and concurrency are favorite topics on Investment banking interviews,  especially on electronic trading development jobs and they grill candidate on many tricky java thread interview questions. They just want to ensure that the guy has a solid knowledge of multi-threading and concurrent programming in Java because most of them are in the business of performance which provides them a competitive advantage and it's hard to write correct and robust concurrent code.

How to avoid deadlock in Java? Example Tutorial and Tips

How to avoid deadlock in Java? Is one of the popular Java interview question and flavor of the season for multi-threading, asked mostly at a senior level with lots of follow up questions. Even though the problem looks very basic but most of the Java developers get stuck once you start going deep. Interview questions start with, "What is a deadlock?" The answer is simple when two or more threads are waiting for each other to release the resource they need (lock) and get stuck for infinite time, the situation is called deadlock. It will only happen in the case of multitasking or multi-threading.

Top 50 Java Thread and Concurrency Interview Questions Answers for 2 to 5 Years Experienced

You go to any Java interview, senior or junior, experience or freshers,  you are bound to see a couple of questions from the thread, concurrency, and multi-threading. In fact, this built-in concurrency support is one of the strongest points of the Java programming language and helped it to gain popularity among the enterprise world and programmers equally. Most of the lucrative Java developer position demands excellent core Java multi-threading skills and experience in developing, debugging, and tuning high-performance low latency concurrent Java applications. This is the reason, it is one of the most important topics in Java interviews. Multithreading and concurrency are also hard to master the concept and only good developers with solid experience can effectively deal with concurrency issues.

Inter Thread Communication in Java using wait() and notify() - Example Tutorial

Wait and notify methods in Java are used for inter-thread communication i.e. if one thread wants to tell something to another thread, it uses notify() and notifyAll() method of java.lang.Object. A classical example of the wait and notify method is a Producer-Consumer design pattern, where One thread produces and put something on the shared bucket, and then tell the other thread that there is an item for your interest in a shared object, consumer thread than pick than item and do his job, without the wait() and notify(), consumer thread needs to be busy checking, even if there is no change in the state of the shared object.

How to use Lock in Java? ReentrantLock Example Tutorial

Many Java programmers confused themselves like hell while writing multi-threaded Java programs like where to synchronized? Which Lock to use? What Lock to use etc. I often receive a request to explain how to use Locks and ReentrantLock in Java, so I thought to write a simple Java program, which is multi-threaded and uses a rather new Lock interface and ReentrantLock to lock critical section. Remember Lock is your tool to guard shared resources which can be anything like a database, File system, a Prime number Generator, or a Message processor. Before using Locks in the Java program, it’s also better to learn some basics. Lock is an interface from java.util.concurrent package. It was introduced in JDK 1.5 release as an alternative to the synchronized keyword.

Difference between Executor, ExecutorService and Executers class in Java

All three classes Executor, ExecutorService, and Executors are part of Java's Executor framework which provides thread pool facilities to Java applications. Since the creation and management of Threads are expensive and the operating system also imposes restrictions on how many Threads an application can spawn, it's a good idea is to use a pool of threads to execute tasks in parallel, instead of creating a new thread every time a request comes in. This not only improves the response time of the application but also prevent resource exhaustion errors like "java.lang.OutOfMemoryError: unable to create new native thread".

Difference between @Transactional and @EnableTransactionManagement in Spring Boot

Any enterprise program that deals with data storage and retrieval must incorporate transaction management. Annotations like @Transactional and @EnableTransactionManagement in Spring make it simpler to manage transactions. Although both of these annotations support transaction management, there are some important distinctions between them that programmers must be aware of in order to use them properly. The distinctions between @Transactional and @EnableTransactionManagement in Spring will be covered in this post, along with examples to guide your decision-making.

What is CyclicBarrier in Java? How and When to use CyclicBarrier with Example? Tutorial

What is CyclicBarrier in Java
CyclicBarrier in Java is a synchronizer introduced in JDK 5 on java.util.Concurrent package along with other concurrent utility like Counting Semaphore, BlockingQueue, ConcurrentHashMap, etc. CyclicBarrier is similar to CountDownLatch which we have seen in the last article  What is CountDownLatch in Java and allows multiple threads to wait for each other (barrier) before proceeding. The difference between CountDownLatch and CyclicBarrier is also a very popular multi-threading interview question in Java. CyclicBarrier is a natural requirement for a concurrent program because it can be used to perform the final part of the task once individual tasks are completed.

Is "Java Concurrency in Practice" still Valid in the Era of Java 21?

Hello guys, one of my reader Shobhit asked this question on my blog post about 12 must-reads advanced Java books for intermediate programmers - part 1. I really like the question and thought that many Java programmers might have the same doubt whenever someone recommends them to read Java Concurrency in Practice. When this book came first in 2006, Java world was still not sure of about new concurrency changes made in Java 1.5, I think the first big attempt to improve Java's built-in support for multi-threading and concurrency. Many Java programmers were even not aware of new tools introduced in the API like CountDownLatch, CyclicBarrier, ConcurrentHashMap, and much more. The book offered them the seamless introduction of those tools and how they can use them to write high-performance concurrent Java applications.

Difference between atomic, volatile and synchronized in Java? [ with Example ]

Hello guys, a lot of people are asking me about the volatile, synchronized, and volatile variables in Java concurrency. After answering them individually on Facebook and LinkedIn, I thought to write this article. In this Java multi-threading tutorial, we will learn about the difference between atomic, volatile, and synchronized variables in Java. Though there are a lot of articles, posts, books, courses, and tutorials already exist on Java concurrency and synchronization, where different people have tried to explain concurrency concepts, but unfortunately, multi-threading and concurrency concepts are still hard to grasp, especially the volatile variables.

How Thread, Code and Data Works in Multi-threading Program in Java?

There are certain things, which you don't learn in academics or training class, you develop those understanding after few years of work experience, and then you realize, it was very basic, how come I had missed that all those years. Understanding of how a multi-threaded Java program executes is one of such things. You definitely have heard about threads, how to start a thread, how to stop a thread, definitions like its independent path of execution, all funky libraries to deal with inter-thread communication, yet when it comes to debugging a multithreaded Java program, you struggle.

How Volatile in Java works? Example of volatile keyword in Java

What is a volatile variable in Java and when to use the volatile variable in Java is a famous multi-threading interview question in Java interviews? Though many programmers know what is a volatile variable they fail on the second part i.e. were to use volatile variables in Java as it's not common to have a clear understanding and hands-on on volatile variables in Java. In this tutorial, we will address this gap by providing a simple example of the volatile variable in Java and discussing when to use the volatile variable in Java. Anyway,  the volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache the value of this variable and always read it from the main memory.

Top 5 Java Multithreading and Concurrency Courses for Experienced Programmers in 2023 - Best Of Lot

If you are a Java developer and looking for some awesome resources e.g. books and courses to improve your multi-threading and concurrency skills in Java then you have come to the right place. In the past, I have shared books and tutorials on Java Concurrency and Multithreading, and in this article, I am going to talk about some of the best free and paid courses to learn multithreading and concurrency in Java. You can join these free courses to improve your understanding of Java Concurrency and Multithreading. It's one of the most important skills for Java developers as almost all the companies who interview Java developers pay particular attention to their knowledge and experience in this area.

How to create Thread Pool in Java using Executor Framework - Example Tutorial

Java 1.5 introduced a Thread pool in Java in the form of an Executor framework, which allows Java programmers to decouple submission of a task to the execution of the task. If you are doing server-side programming in Java then the Thread pool is an important concept to maintain scalability, robustness, and stability of the system. For those, who are not familiar with thread pool in Java or the concept of thread pool here is a one-liner, Thread pool in Java is a pool of worker threads, which is ready to perform any task given to them, mostly in the form of implementation of Runnable or Callable interface.

How to use Callable and Future in Java? Example Tutorial

A callable interface was added in Java 5 to complement the existing Runnable interface, which is used to wrap a task and pass it to a Thread or thread pool for asynchronous execution. Callable actually represents an asynchronous computation, whose value is available via a Future object. All the code which needs to be executed asynchronously goes into the call() method. Callable is also a single abstract method type (SAM type), so it can be used along with lambda expression on Java 8. Both Callable and Future are parametric types and can be used to wrap classes like Integer, String, or anything else.

How to use wait, notify and notifyAll in Java - Producer Consumer Example

You can use wait, notify, and notifyAll methods to communicate between threads in Java. For example, if you have two threads running in your programs like Producer and Consumer then the producer thread can communicate to the consumer that it can start consuming now because there are items to consume in the queue. Similarly, a consumer thread can tell the producer that it can also start putting items now because there is some space in the queue, which is created as a result of consumption. A thread can use the wait() method to pause and do nothing depending upon some condition. For example, in the producer-consumer problem, the producer thread should wait if the queue is full and the consumer thread should wait if the queue is empty.

How to use Lock and Condition variable in Java? Producer Consumer Problem Example Tutorial

You can also solve the producer-consumer problem by using a new lock interface and condition variable instead of using the synchronized keyword and wait and notify methods.  The lock provides an alternate way to achieve mutual exclusion and synchronization in Java. The advantage of a Lock over a synchronized keyword is well known, explicit locking is much more granular and powerful than a synchronized keyword, for example, the scope of a lock can range from one method to another but the scope of a synchronized keyword cannot go beyond one method. Condition variables are instance of java.util.concurrent.locks.Condition class, which provides inter-thread communication methods similar to wait, notify and notifyAll e.g. await(), signal(), and signalAll().

What is compound assignment operator +=, -=, *= and /= in Java? Example Tutorial

Many Java programmers think that a += b is just a shortcut of a = a + b, which is only half correct. Though it expands exactly like that and in many cases it produce same result, especially when type of both variable is same e.g. both being int or long, but you will see real difference when you try to add to integer types which are different e.g. long and int, short and int, short and long etc. What many programmer miss there is type casting. Compound statement provides you implicit cast, which often goes unnoticed. Which means a += b actually translates into a = (type of a) (a + b). I have asked this question a couple of times while interviewing Java developers, and most of the time, developer who are Oracle Java Certified got it right than others. 

How to use SynchronousQueue in Java? Prouder Consumer Example

SynchronousQueue is a special kind of BlockingQueue in which each inserts operation must wait for a corresponding remove operation by another thread and vice versa. When you call to put() method on SynchronousQueue it blocks until another thread is there to take that element out of the Queue. Similarly, if a thread tries to remove an element and no element is currently present, that thread is blocked until another thread puts an element into the queue. You can correlate SynchronousQueue with athletes (threads) running with Olympic torch, they run with a torch (object need to be passed) and passes it to other athlete waiting at another end.

What is volatile modifier or field in Java? Example Tutorial

The volatile modifier has always been an interesting and tricky topic for many Java programmers. I still feel that it's one of the most underutilized modifiers in Java, which can do a lot of good if understood and applied correctly, after all, it provides a lock-free way to achieve synchronization in Java. If a field is shared between multiple threads and one of them changes its value i.e. one thread reads from the field which is written by other threads, then, by using a volatile modifier, you can synchronize access to this field. The volatile modifier in Java provides visibility and ordering guarantees without any locking.

How to use Future and FutureTask in Java Concurrency with Example

Future and FutureTask in Java allows you to write asynchronous code. The Future is a general concurrency abstraction, also known as a promise, which promises to return a result in the future. In asynchronous programming, the main thread doesn't wait for any task to be finished, rather it hands over the task to workers and moves on. One way of asynchronous processing is by using callback methods. The Future class in Java is another way to write asynchronous code.

How to create thread safe Singleton in Java - Java Singleton Example

Thread safe Singleton means a Singleton class that returns exactly the same instance even if exposed to multiple threads. Singleton in Java has been a classical design pattern like Factory method pattern, or Decorator design pattern and has been used a lot even inside JDK like java.lang.Runtime is an example of Singleton class. Singleton pattern ensures that exactly one instance of the class will remain in the Java program at any time. In our last post, 10 Interview questions on Singleton in Java we have discussed many different questions asked on Singleton pattern, One of them was writing Thread safe singleton in Java.

How to Stop a Thread in Java? Code Example

The thread is one of the important Classes in Java and multithreading is the most widely used feature, but there is no clear way to stop Thread in Java. Earlier there was a stop method that exists in Thread Class but Java deprecated that method citing some safety reasons. By default, a Thread stops when the execution of run() method finishes either normally or due to any Exception. In this article, we will How to Stop Thread in Java by using a boolean State variable or flag.

What is ReentrantLock in Java? Difference between synchronized vs ReentrantLock with Example

ReentrantLock in Java is added on java.util.concurrent package in Java 1.5 along with other concurrent utilities like CountDownLatch, Executors, and CyclicBarrier. ReentrantLock is one of the most useful additions in Java concurrency package and several of concurrent collection classes from java.util.concurrent package is written using ReentrantLock, including ConcurrentHashMap, see How ConcurrentHashMap works in Java for more details. Two key feature of ReentrantLock, which provides more control on lock acquisition is trying to get a lock with the ability to interrupt, and a timeout on waiting for a lock, these are key for writing responsive and scalable systems in Java.

The Ultimate Guide of Synchronization in Java - Examples

Multithreading and synchronization are a very important topic for any Java programmer. Good knowledge of multithreading, synchronization, and thread-safety can put you in front of other developers, at the same time, it's not easy to master this concept. In fact, writing correct concurrent code is one of the hardest things, even in Java, which has several inbuilt synchronization utilities. In this Java synchronization tutorial we will learn what is meaning of Synchronization in Java, Why do we need Synchronization in Java, What is java synchronized keyword, examples of using Java synchronized method and blocks, What can happen in multithreading code in absence of synchronized constructs, tips to avoid mistakes, while locking critical section in Java and some of the important points about synchronization in Java.

How to use Counting Semaphore in Concurrent Java Application? Example Tutorial

Counting Semaphore in Java is a synchronizer that allows imposing a bound on the resource is added in Java 5 along with other popular concurrent utilities like CountDownLatch, CyclicBarrier, and Exchanger, etc. Counting Semaphore in Java maintains a specified number of pass or permits, In order to access a shared resource, Current Thread must acquire a permit. If a permit is already exhausted by other threads than it can wait until a permit is available due to the release of permits from different threads. This concurrency utility can be very useful to implement a producer-consumer design pattern or implement bounded pool or resources like Thread Pool, DB Connection pool, etc.

Prefer TimeUnit Sleep over Thread.Sleep - Java Coding Tips Example

What is TimeUnit in Java
in Java is a class on java.util.concurrent package, introduced in Java 5 along with CountDownLatch, CyclicBarrier, Semaphore, and several other concurrent utilities. TimeUnit provides a human-readable version of the Thread.sleep() method which can be used in place of the former. For a long time Thread's sleep() method is a standard way to pause a Thread in Java and almost every Java programmer is familiar with that. In fact, the sleep method itself is very popular and has appeared on many Java interviews. The difference between wait and sleep is one of the tough Java questions to answer. 

Why wait, notify, and notifyAll methods are called from synchronized block or method in Java?

Most of the Java developers know that wait(), notify(), and notifyAll() methods of object class must have to be called inside synchronized method or synchronized block in Java but how many times we thought why? Recently this question was asked to in Java interview to one of my friend, he pondered for a moment and replied that if we don't call wait() or notify() method from synchronized context we will receive IllegalMonitorStateException in Java. He was right in terms of the behavior of language but as per him, the interviewer was not completely satisfied with the answer and wanted to explain to him more about it.

Difference between start and run method in Thread? Example

Why to do one call start method of the thread if start() calls run() in turn" or "What is the difference by calling start() over run() method in java thread" are two widely popular beginner level multi-threading interview question. When a Java programmer start learning Thread, the first thing he learns is to implement thread either overriding run() method of Thread class or implementing Runnable interface and then calling start() method on the thread, but with some experience, he finds that start() method calls run() method internally either by looking API documentation or just poking around, but many of us just don’t care at that time until it been asked in Java Interview.

How to find size, Default, Maximum and Minimum values of Primitive Data Types in Java? Example Tutorial

Well, this is absolute beginner post in Java and Why I am writing this? because of a question, which actually confused me? Do you know what is the size of boolean variable in Java? Does it take 1 byte(8 bits) or just 1 bit? My memory was saying 1 byte but my logic was saying 1 bit, because it only holds two values, true and false, which can be represented by using 1 bit, by 0 and 1. This make me to go back to my core Java book and recall all default values. By the way, you don't need to go book always, as you can check default value, maximum and minimum of any data-type by running a Java programe and printing there value.

What is CountDownLatch in Java - Concurrency Example Tutorial

What is CountDownLatch in Java
CountDownLatch in Java is a kind of synchronizer which allows one Thread to wait for one or more Threads before starts processing. This is a very crucial requirement and often needed in server-side core Java applications and having this functionality built-in as CountDownLatch greatly simplifies the development. CountDownLatch in Java is introduced on Java 5 along with other concurrent utilities like CyclicBarrier, Semaphore, ConcurrentHashMap, and BlockingQueue in java.util.concurrent package. 

Difference between transient and volatile keyword in Java? example

Surprisingly "Difference between transient and volatile keyword in Java" has asked many times on various java interviews. volatile and transient are two completely different keywords from different areas of Java programming language. the transient keyword is used during serialization of Java object while volatile is related to the visibility of variables modified by multiple threads during concurrent programming. The only similarity between volatile and transient is that they are less used or uncommon keywords and not as popular as public, static, or final.

Avoid Mixing static and non static synchronized method - Java mistake 2 Example

Using a static and non-static synchronized method for protecting shared resources is another Java mistake we are going to discuss in this part of our series “learning from mistakes in Java”. In the last article, we have seen why double and float should not be used for monetary calculation, In this tutorial, we will find out why using static and non-static synchronized methods together for protecting the same shared resource is not advisable.  I have seen some times Java programmers mix static synchronized method and instance synchronized method to protect the same shared resource.

How to Get & Print current Thread stack trace in Java - Debugging Tutorial Example

The stack trace is very useful while debugging or troubleshooting any issue in Java. Thankfully Java provides a couple of ways to get a current stack trace of a Thread in Java, which can be really handy in debugging. When I was new to Java programming and didn’t know how to remote debug a Java application, I used to put debug code as patch release, which uses classpath to pick debug code for printing stack trace and shows how a particular method is get called and that sometimes provide a vital clue on missing or incorrect argument.

What is Race Condition in Java Multithreading? Examples

Race condition in Java is a type of concurrency bug or issue that is introduced in your program because of parallel execution of your program by multiple threads at the same time, Since Java is a multi-threaded programming language hence the risk of Race condition is higher in Java which demands a clear understanding of what causes a race condition and how to avoid that. Anyway, Race conditions are just one of the hazards or risks presented by the use of multi-threading in Java just like deadlock in Java. Race conditions occur when two threads operate on the same object without proper synchronization and their operation interleaves on each other.

How to check if a thread holds lock on a particular object in Java? Example

Think about a scenario where you would have to find at the run time whether a Java thread has a lock on a particular object e.g. find out whether thread NewsReader has a lock on a NewsPaper object or not? If these questions came in any core java interview then I would automatically assume that there could be at least two answers one is the hard-earned raw answer which programmer would like to figure out based on fundamentals and the other could be some rarely used API calls that are available in Java, by the way, this is actually asked to me in an interview of one of the biggest global Investment bank.

What is blocking methods in Java and how do deal with it? Example

Blocking methods in Java are those methods that block the executing thread until their operation is finished. A famous example of the blocking method is the InputStream read() method which blocks until all data from InputStream has been read completely. A correct understanding of blocking methods is required if you are serious about Java programming especially in the early days because if not used carefully blocking method can freeze GUIs, hung your program, and become non-responsive for a longer duration of time. In this post, we will see What is Blocking methods in Java, Examples of Blocking methods and Some best practices around blocking methods, and how to use blocking methods in Java.

Producer Consumer Design Pattern with Blocking Queue Example in Java

The Producer-Consumer Design pattern is a classic concurrency or threading pattern which reduces coupling between Producer and Consumer by separating Identification of work with Execution of Work. In producer-consumer design pattern, a shared queue is used to control the flow and this separation allows you to code producer and consumer separately. It also addresses the issue of different timing requirements to produce items or consuming items. by using producer-consumer patterns both Producer and Consumer Thread can work with different speeds.

Difference between Executor Framework and Fork Join Pool in Java?

Java 5 added Executor Framework to provide an out-of-box thread pool to Java programmers and Java 7 added ForkJoinPool an implementation of ExecutorService which specifically designed to execute ForkJoinTask. The Executor Framework provides several classes e.g. Executor, ExecutorService, and Executors for execution and creating thread pools. It also provides several built-in, ready to use thread pools like a pool of fixed threads, cached thread pool which can expand itself, spawn new threads if required due to heavy load.

Top 5 Difference Between Callable and Runnable Interface in Java

The difference between Callable and Runnable is one of the most frequently asked multi-threading and concurrency interview questions in the Java world. I remember it was 2007 when I first heard about the Callable interface and that too on a telephonic interview. Till then, I was happy using Runnable to implement threads and just started paying attention to Java 1.5, as most of the applications by then using Java 1.4. That one interview question encouraged me to learn more about several other useful features introduced in Java 5 concurrency library like CountDownLatch, CyclicBarrier, Semaphore, Atomic variables, and Thread pool. This is one of the reasons I always encourage Java developers to give/take regular interviews, just to update your knowledge.

Top 10 Eclipse Code Templates Java programmer should know

Every Java programmer wants to code fast and this is important because Java is more verbose than some of the cool scripting languages e.g. Python. Eclipse Code templates can help you to write faster code in Eclipse. If you used correctly Eclipse code template can generate all kinds of boilerplate code for you. Eclipse IDE comes with some frequently used Eclipse code templates e.g. sysout which is faster way to generate System.out.println() statements. Surprisingly, not every single Java programmer working in Eclipse is familiar with this cool feature which can save tons of times writing boilerplate code related to Exception handling, logging and frequently used test code e.g. writing main method. 

ThreadLocal in Java - Example Program and Tutorial

ThreadLocal in Java is another way to achieve thread-safety apart from writing immutable classes. If you have been writing multi-threaded or concurrent code in Java then you must be familiar with the cost of synchronization or locking which can greatly affect the Scalability of application, but there is no choice other than synchronizing if you are sharing objects between multiple threads. ThreadLocal in Java is a different way to achieve thread-safety, it doesn't address synchronization requirement, instead, it eliminates sharing by providing an explicit copy of Object to each thread. Since Object is no more shared there is no requirement of Synchronization which can improve scalability and performance of the application.

Top 5 Books to Learn Concurrent Programming and Multithreading in Java - Best, Must Read (2023)

Books are essential to learning something new, and despite being in the electronic age, where books have lost some shine to the internet and blogs, I still read and recommend them to get complete and authoritative knowledge on any topic, like concurrent programming. In this article, I will share five best books to learn concurrent programming in Java. These books cover basics, starting from how to create and start a thread, parallel programming, concurrency design patterns, an advantage of concurrency and of course pitfalls, issues, and problems introduced due to multithreading. Learning concurrent programming is a difficult task, not even in Java but also in other languages like C++ or modern days JVM languages like Groovy, Scala, Closure, and JRuby.

How to reverse an ArrayList in place in Java? Example [Solved]

You can reverse an ArrayList in place in Java by using the same algorithm we have used to reverse an array in place in Java. If you have already solved that problem then It's a no-brainer because ArrayList is nothing but a dynamic array, which can resize itself. All elements of an array are stored in the internal array itself. By the way, if you need to reverse an ArrayList then you should be using the Collections.reverse() method provided by the Java Collection framework. It's a generic method, so you can not only reverse an ArrayList but also Vector, LinkedList, CopyOnWriteArrayList, or any other List implementation.

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. 

16 Examples of ArrayList in Java - Tutorial

Most of the Java interview questions on ArrayList asked freshers or Java developers with 1 to 2 years experience is just simply how to do tasks like how to sort ArrayList in Java, How to sort ArrayList in ascending and descending order, how to sort ArrayList on reverse order, how to search elements, how to remove an element using iterator etc. Since, I have written lots of Java tutorials on ArrayList, covering many general-purpose tasks like how to create an object of ArrayList and initialize to how to sort ArrayList in ascending and descending order, etc. 

6 Ways to convert ArrayList to String in Java - Example Tutorial

Many times we need elements stored in ArrayList in a single String object, but in different format than toString() method of ArrayList provides. At times, you may need them separated by comma, other times by by a tab or new line character. How do you convert your ArrayList to String in Java? Well, even though standard JDK doesn't provide any utility method to do that, there are numerous way to do that out-of-the-box, I mean, without you writing your own method to do that conversion. In the past, I showed you how to convert a Collection to String in Java and in this article, we will take a look at some of them, but beware many of the methods require third party library, which means an extra dependency in your build path. If you don't mind that than you could save lot of time reusing tried and tested code. 

How to remove objects from ArrayList using Iterator in Java? Example Tutorial

It's tricky to remove objects from ArrayList in Java while you are not iterating over it, especially if you are new to Java programming.  Although, you can use any of the overloaded remove(object obc) and remove (int index) method to remove objects directly or at any index. But, things get tricky, when you are iterating over ArrayList. If you use the remove() method from ArrayList then it will throw ConcurrentModificationException, even if you are running your code from single thread. The reason is that, Iterator checks for any modification during iteration using modCount and if it sees a modification e.g. add or remove which happens outside Iterator, it throws ConcurrentModificationException

How to empty an ArrayList in Java? clear() vs removeAll() method Example Tutorial

Many times we want to reset an ArrayList for the reusing purpose, by resetting we mean clearing it or removing all elements. There are two ways to reset an ArrayList in Java, by using the clear() method or calling removeAll(). If your ArrayList is small enough like it contains only 10 or 100 elements then you can use any of these two methods without worrying too much, but, if you have a huge list of lots of objects like an ArrayList containing 10M entries, then the choice of clear() vs removeAll() can make a huge difference in the performance of your Java application.

4 Ways to Loop or Iterate over ArrayList in Java? Iterator, ListItreator, for loop and Enhanced foreach Example

Looping ArrayList in Java or Iteration over ArrayList is very similar to a looping Map in Java. In order to loop ArrayList in Java, we can use either foreach loop, simple for loop, or Java Iterator from ArrayList. We have already touched iterating ArrayList in 10 Example of ArrayList in Java and we will see here in detail. We are going to see examples of all three approaches in this ArrayList tutorial and find out which one is clean and the best method of looping ArrayList in Java. Before start writing an example for loop in ArrayList let's think about why do we need to iterate, traverse or loop an ArrayList if it’s based on the index and backed by Array.