Saturday, September 30, 2023

10 Exception handling Best Practices in Java Programming

Exception handling is an important part of writing robust Java applications. It’s a non-functional requirement for any application, to gracefully handle any erroneous condition like resource not available, invalid input, null input, and so on. Java provides several exception handling features, in built-in the language itself in form of try, catch, and finally keywordJava programming language also allows you to create new exceptions and throw them using  throw and throws keyword. In reality, Exception handling is more than knowing the syntax. Writing a robust code is an art more than science, and here we will discuss few Java best practices related to Exception handling.

How to Fix Exception in thread "main" java.lang.ExceptionInInitializerError in Java Program? Example

JVM throws java.lang.ExceptionInInitializerError, when there is an Exception inside static initializer block. If you know about static variables in Java, then you may know that they are initialized at the time of class loading. If there is an Exception during that initialization of static variables, you will see ExceptionInInitializerError in Java. This could be any exception e.g. java.lang.ArrayIndexOutOfBound or java.lang.NullPointerException. Java developers are often confused with this error because they think that they have not defined any static initializer block, then how come they are getting ExceptionInInitializerError; well, by default Java combines all static variable initialization inside a static initializer block and initialize them in the order they are declared in the source file.

How to fix java.io.FileNotFoundException: (Access is denied)? Example

Earlier my impression was that java.io.FileNotFoundException: (Access is denied) comes when you try to read a text or binary file for which you don't have permission from the Java program but this can also come while you are using the jar command. jar command internally uses java.util.zip.ZipFile class to open any jar or war file which can throw java.io.FileNotFoundException: (Access is denied). I was trying to see the contents of the war file which was created using a recent build when I stumble upon this error, see the exact command below:

test@dev454:war-store/target jar -tvf maven-eclipse-web-demo
java.io.FileNotFoundException: maven-eclipse-web-demo (Access is denied)
        at java.util.zip.ZipFile.open(Native Method)
        at java.util.zip.ZipFile.<init>(ZipFile.java:127)
        at java.util.zip.ZipFile.<init>(ZipFile.java:88)
        at sun.tools.jar.Main.list(Main.java:979)
        at sun.tools.jar.Main.run(Main.java:224)
        at sun.tools.jar.Main.main(Main.java:1149)

How to resolve java.lang.UnsupportedClassVersionError:Unsupported major.minor version 49.0 to 65 with example

The java.lang.UnsupportedClassVersionError  is a quite common error after NoClassDefFoundError or ClassNotFoundException they all seems to related to class files but they all are different and there cause and resolution are different. In this java tutorial, we will see what is UnsupportedClassVersionError in Java? Why UnsupportedClassVersionError comes in Java? What are a class file format and version numbers associated with it and finally how to resolve UnsupportedClassVersionError in Java? 

How to fix java.lang.NoSuchMethodError: main Exception in thread "main" in Java? Example

How to solve java.lang.NoSuchMethodError: main Exception in thread "main"
java.lang.NoSucMethodError comes when Java code tries to call a method that does not exist on a class, this could be either static or non-static method. a most common manifestation of java.lang.NoSuchMethodError is running a class that doesn't have the main method in Java. In this article, we will see what is "java.lang.NoSuchMethodError: main Exception in thread "main"", Why does java.lang.NoSuchMethodError comes and how to solve java.lang.NoSuchMethodError in Java.

Friday, September 29, 2023

Polymorphism and Inheritance Example in Java

Hello guys, If you are new to Java or Object oriented programming and wondering what is Polymorphism and Inheritance and what are their use then you have come to the right place. Polymorphism and Inheritance are two fundamental concepts in object-oriented programming that allow for flexibility and reusability of code. In Java, these concepts are closely related and often go hand in hand. Java Programming provides a couple of way to implement Inheritance like extending a class or implementing an interface. Similarly they provide overloading and overriding for Polymorphism. In the past, I have shared 40 object oriented questions as well as 23 design patterns and In this article, we'll explore these concepts with a practical example.

Thursday, September 28, 2023

How to deal with NullPointerException in Java with Examples - java.lang.NullPointerException Guide

The java.lang.NullPointerException or NullPointerException in Java is probably the first error or exception you will face in Java. It is a true nightmare for beginners in Java but pretty easy to solve once you get familiar with Exception handling in Java. What makes NullPointerException a little bit tricky to solve is its name which has a pointer in itself and Java does not support pointers like C++ or C, just like you don't have multiple inheritances in Java. As a Java developer with 20 years of experience, I have solved countless amount of NullPointerException and now I have developed a coding and debugging sense through which I can spot what causing a particular NullPointerException and how to fix it. 

Fixing java.net.BindException: Cannot assign requested address: JVM_Bind in Tomcat, Jetty

One of the most dreaded errors in Java-based client server-based applications is a networking-related error, e.g. java.net.BindException: Cannot assign requested address: JVM_Bind. I have faced this issue while working with web servers like Tomcat, Jetty, and Weblogic before, but yesterday it came again when one of my colleagues faced this issue in Windows. As soon as Java programmers see java.net.BindException, they come to the conclusion that it's an issue with two processes listening on the same port and often mistook it for Java.net.BindException: Address already in use: JVM_Bind:8080, which is slightly different than this.

How to Fix java.net.ConnectException: Connection refused: connect in Java

java.net.ConnectException: Connection refused: connect is one of the most common networking exceptions in Java. This error comes when you are working with client-server architecture and trying to make a TCP connection from the client to the server. Though this is not as cryptic as java.lang.OutOfMemoryError: Java heap space or java.lang.UnsupportedClassVersionError, it’s still a frequent problem in distributed Java applications. java.net.ConnectException: Connection refused: connect also comes in the case of RMI (Remote Method Invocation) because RMI also uses TCP-IP protocol underneath. While writing client socket code in Java, You should always provide proper handling of this exception

How to solve java.util.NoSuchElementException in Java? Example

How to fix java.util.NoSuchElementException in Java

java.util.NoSuchElementException is a RuntimeException that can be thrown by different classes in Java like Iterator, Enumerator, Scanner, or StringTokenizer. All of those classes have a method to fetch the next element or next tokens if the underlying data structure doesn't have any element Java throws "java.util.NoSuchElementException". The most common example of this is iterating over hashmap without checking if there is an element or not and that's why it's advised to use hashNext() before calling next() on Iterator. In this Java tutorial we will what causes NoSuchElementException in Java and how to avoid it completely.

How to fix java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory

java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory or "Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory" exception comes when you don't apache commons-logging-1.1.1.jar in your Classpath. I have faced this exception many times while using open-source frameworks like Struts, Spring, and Displaytag which uses a commons-logging framework for logging. commons-logging is not an actual java logging framework but provides a wrapper so that you can use log4j, java logging, or any other Java logging framework.

Top 10 DevOps Certifications for Experienced IT Professionals in 2024

Hello guys, DevOps, a combination of software development and IT operations, has become a widely adopted approach in the modern software industry. It emphasizes collaboration, automation, and continuous integration and delivery to streamline software development and deployment processes. To excel in the field of DevOps, professionals can pursue certifications that validate their knowledge and skills in various DevOps practices and tools. In the past, I have shared best Cloud Computing Certifications and best Certification for Java developers and in this article, we will explore the top 10 DevOps certifications for 2024 that can help bridge the gap between development and operations.

Wednesday, September 27, 2023

[Solved] How to find and Print Armstrong number between 0 and 9999 in Java? Example

An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 153 is an Armstrong number, since 1**3 + 5**3 + 3**3 = 153, 371 is an Armstrong number since 3**3 + 7**3 + 1**3 = 371. Along with usual beginner exercises like calculating factorial, reversing a string, or calculating prime numbers, this is a good exercise to build programming logic. It teaches you basic programming techniques of how to use the operator for something which is not obvious.

Java Program to Multiply Two Matrices - Matrix Multiplication Example

How to write a Java program to multiply two matrices in Java is a very good programming exercise to get familiar with the two-dimensional array in Java. this example teaches about how to multiply arrays, how to access elements from a multi-dimensional array, how to pass them to a function etc. Since the matrix is a natural representation of a multi-dimensional array in Java, they are often used to illustrate real word matrix exercises e.g. the calculating sum of two matrices or calculating the difference of two matrices, etc. It's also one of the popular Matrix based coding problems you can find on coding interviews. 

[Solved] How to Implement Binary Search in Java without Recursion? Iterative Algorithm Example Tutorial

Hey Java programmers, if you want to implement a binary search in Java, and looking for both iterative and recursive binary search algorithms then you have come to the right place. Earlier, I have shared the free courses to learn Data Structure and algorithms in Java, and today, I am going to teach you an important algorithm.  In computer science, a binary search or half-interval search is a divide and conquer algorithm which locates the position of an item in a sorted array. Binary search works by comparing an input value to the middle element of the array. The comparison determines whether the element equals the input, less than the input or greater. 

Top 20 Amazon and Google Programming Interview Questions for Software Developers

Hello, In this article I am going to sharing some frequently asked programming job interviews from technical giants and startups. If you are going for a programming job interview with Microsoft, Google, or Amazon, you better be prepared for all kinds of questions. These companies are known to ask tough questions, tricky puzzles, and lots of data structure and algorithm questions. Since it's hard to prepare all these in a short time, it makes sense to at least have a good idea of frequently asked programming questions in Microsoft, Google, or Amazon.

How to find the largest and smallest number in given Array in Java? Example Tutorial

Hello guys, today I am going to discuss one of the frequently asked programming interview questions to find the largest and smallest number from an integer array. This question is commonly asked on telephonic interviews and the first round for screening candidates. This coding problem is in the same league of other frequently asked algorithmic questions like Fibonacci, Palindrome, Prime, and Power of two checks. They are easy but you will find them difficult during the interview because of the pressure, particularly if you have not solved them before. Sometimes even if you have solved the problem one time, you tend to do mistakes because you haven't understood them properly. So, always take your time to understand the question.

What are AtomicInteger and AtomicLong in Java? How it works? compareAndSet() Example Tutorial

Concurrency is a fundamental aspect of modern software development, and Java provides a variety of tools and classes to help developers manage shared resources and coordinate the behavior of multiple threads. Among these tools one is atomic variables, which ensure that certain operations on shared data are performed atomically, I mean in one shot, without the need for explicit synchronization. In the past I talked about difference between atomic, synchronized, and volatile in Java and In this article, we'll explore atomic variables in Java, with a focus on AtomicInteger and AtomicLong, and explain how they work and how to use them effectively in Java. 

How to Implement Stack data structure in Java? Example Tutorial

The stack is one of the popular data structures which supports LIFO (Last In First OUT) operation. Due to the LIFO advantage, you can use a stack data structure to convert a recursive algorithm to an iterative one. The stack data structure is very easy to implement using an array or linked list, but you don't have to implement it on your own because Java already provides a Stack implementation in java.util.Stack class. This class is a subclass of the Vector class and you should use it whenever you need Stack for your production code, there is no point in inventing the wheel again when the focus is on developing your application.

How to check if a given Number is Binary in Java? [Solved] Example

Today we will take a look at another simple programming exercise, write a program to check if a number is binary in Java. A number is said to be binary if it only contains either 0 or 1, for example, 1010 is a binary number but 1234 is not. You can not any library method to solve this problem, you need to write a function to check if the given number is binary, you can use basic constructs of Java programming language e.g. operators, keywords, control statements, etc. If you are a regular reader of Javarevisited, then you know that I love to share simple programming problems here.

How to find Middle Element of Linked List in Java in Single Pass

ow do you find the middle element of LinkedList in one pass is a programming question often asked Java and non-Java programmers in telephonic Interview. This question is similar to checking palindrome or calculating the factorial, where the Interviewer sometimes also asks to write code. In order to answer this question candidate must be familiar with the LinkedList data structure i.e. In the case of the singly LinkedList, each node of Linked List contains data and pointer, which is the address of the next Linked List and the last element of Singly Linked List points towards the null. Since in order to find the middle element of the Linked List you need to find the length of the linked list, which is counting elements till the end i.e. until you find the last element of the Linked List.

How to find the 3rd (Kth) Node from end of linked list in Java? Fast and Slow Pointer Example [Solved]

Hello guys, the problem to find the 3rd element from the end in a singly linked list or Kth node from the tail is one of the tricky but frequently asked linked list problems in Programming job interviews. I know you can easily solve this problem by moving from tail to head or in the reverse direction but the main challenge here is to solve the problem in just one pass. That means, you can not traverse the linked list again and you cannot traverse backward because it's a singly linked list. So what do you think? Isn't this problem challenging? Well, I did struggle when I saw this problem very first time but once you understand the logic and some tricks to solve a linked list based problem like Recursion then it would be easy for you, and that's what you will learn in this article.

How to Remove a character from String in Java ? Recursion Example [Solved]

Hello guys, if you are wondering how to remove a given character from a String in Java then you have come to the right place. In the past, we have solved many common String coding problems like String anagram check, String Palindrome check, and String permutation and in this article, you will learn how to remove a given character from a String in Java. Basically, you need to write a program to remove a given character from String in Java. Your program must remove all occurrences of a given character. For example, if given String is "aaaaa" and String to remove is "a" then the output should be an empty String. Similarly, if input String is "abc" and character to remove is "b" then your program must return "ac" as output. 

How to Print Pyramid Pattern of Alphabet Characters in Java? Example Tutorial [Solved]

In earlier programming tutorials, I have taught you how to print a pyramid pattern of stars and numbers in Java, and in this tutorial, you will learn the printing pyramid patterns of alphabets. If you understand the logic of previous programs then this one won't be difficult for you because we will use the same logic of printing rows and columns using the nested loop in Java. Actually, a pyramid pattern is nothing but a matrix where you need to print rows and columns. Though, you need to learn where to print those values and when to move to the next row.

Tuesday, September 26, 2023

What is LongAdder, AtomicLong, and LongAccumulator in Java? How it works? Example Tutorial

Hello guys, Concurrency in Java can be a challenging aspect of software development. As applications become more multithreaded and concurrent, Java developers often face issues related to thread safety, contention, and performance bottlenecks. To address these concerns, Java provides various tools and classes, one of which is LongAdder. In this article, we will explore what LongAdder is, when to use it, how to use it, and some best practices. You will be surprised to see how useful this little unknown class can be when multiple threads need to atomically update a shared counter like running count. 

How to calculate large factorial using BigInteger in Java? Example Tutorial

Factorial of numbers greater than or equal to 13 cannot be found using primitive int data type as shown in our earlier factorial solution due to overflow. These factorials are too large to fit in an int variable, whose maximum value is just 2147483647 (2^31 -1). Even if we use the long data type, factorials greater than or equal to 21 will generate an overflow. To find the factorial of anything above 21, you need to use the BigInteger class from java.math package.  As the name suggests, BigInteger class is designed to hold a really large integer value, something which is even bigger than the maximum value of long primitive like 2^63 -1 or 9223372036854775807L.

[Solved] How to find Largest Prime Factor of a Number in Java? Example

Hello guys, one of the common programming kata to learn coding is to write a program to find the largest prime factor of a number. Earlier, we have solved how to check if number is prime or not and in this article, we will calculate prime factors of a given number in Java.  Like any other programming problem, you need to build the logic to solve this problem. Before solving the problem, let's revise the concept of number theory. Prime factors of a positive integer are the prime numbers that divide the number exactly i.e. without any remainder, and prime factorization is the process of finding all prime numbers when multiplied together to make the original number.

3 ways to swap two Numbers without using Temp or Third Variable in Java?

How to swap two numbers without using temp or third variable is a common interview question not just on Java interviews but also on C and C++ interviews. It is also a good programming question for freshers. This question was asked to me long back and didn't have any idea about how to approach this question without using temp or third variable, maybe lack of knowledge on bitwise operators in Java or maybe it didn't click at that time. Given some time and trial error, I eventually come out with a solution with just an arithmetic operator but the interviewer kept asking about other approaches of swapping two variables without using temp or third variable.

Java 8 Compute(), ComputeIfAbsent() and ComputeIfPresent() Example Tutorial

Hello guys, if you have been doing Java development then you know that Java 8 brings a lot of changes not just on programming language part by introducing Lambda expression, default methods on interface, static method on interface but also on API  and SDK part like Stream API and new Date and Time API. But while those bigger changes get lot of coverage many small changes but very useful in day to day programming task doesn't get enough mention and many Java programmers are unaware of those. One of such enhancement was addition of compute(), computeIfAbsent(), and computeIfPresent() method in java.util.Map interface. Adding  a new method on an existing interface was not possible before Java 8 but new feature like default and static method on interface made it possible and Java designers take full advantage of these two feature to enhance and improve existing interface like Collection and Map. 

Monday, September 25, 2023

How to Find Largest and Smallest of N numbers without using Array in Java? Example

One of the common programming questions is, how do you find the largest and smallest number in N numbers without using arrays in Java? Can you write a program to solve this problem? Well, it's very similar to the problem we have seen before, find the largest and smallest of 3 integers. You can use the same approach and generalize it for N numbers. All you need to do is start with largest as Integer.MIN_VALUE and smallest number as Integer.MAX_VALUE and loop through N numbers. At each iteration, compare the number with the largest and smallest number, if the current number is larger than the largest then it's a new largest, and if the current number is smaller than the smallest then it's a new smallest number.

How to Remove Duplicate Characters from String in Java? Example

This week's coding exercise is to remove duplicate characters from String in Java. For example, if the given String is "aaaaaa" then the output should be "a", because the rest of the "a" are duplicates. Similarly, if the input is "abcd" then the output should also be "abcd" because there is no duplicate character in this String.  By the way, you can not use any third-party library or Java API method to solve this problem, you need to develop your own logic or algorithm and then write code to implement that algorithm. This is one of the interesting problems from Java coding interviews and you can use this program to weed out Java programmers who cannot write code.

How to generate Prime numbers in Java? Sieve of Eratosthenes Algorithm Example

Hello guys, I have said many times that a good knowledge of Data Structure and Algorithms is the first step towards becoming a better programmer and that's why I share a lot of Data structure and Algorithm stuff in this blog. To continue the tradition, I am going to share an interesting algorithm today, The Sieve of Eratosthenes algorithm, which can be used to generate prime numbers up to a given number. There are many occasions when you need to generate all prime numbers up to a specified integer and one algorithm which is most often used to generate prime numbers is the Sieve of Eratosthenes Algorithm. Surprisingly, not many developers know about this algorithm, particularly Java programmers, which is mainly because of not doing enough competitive programming.

Fibonacci Series in Java using Recursion and Iteration - Example Tutorial

Printing Fibonacci Series In Java or writing a program to generate Fibonacci number is one of the interesting coding problems, used to teach college kids recursion, an important concept where function calls itself. It is also used a lot as coding problems while interviewing graduate programmers, as it presents lots of interesting follow-up questions as well. In the Fibonacci series, the next number is equal to the sum of the previous two numbers. First two numbers of series are always 1 and 1, third number becomes 1 + 1 = 2, subsequently fourth number becomes 2 + 1 = 3. So a Fibonacci series looks like 1, 1, 2, 3, 5, 8, 11, 19, and so on, as shown in the image as well.

Quicksort Sorting Algorithm in Java - In Place Example and Explanation

Quicksort algorithm is one of the most used sorting algorithms, especially to sort the large lists, and most of the programming languages, libraries have implemented it in one or another way. In Java, Arrays.sort() method sorts primitive data types using a double-pivot Quicksort algorithm, authored by Joshua Bloch and others. This implementation provides better performance for a lot of data sets, where traditional quicksort algorithms reduced into quadratic performance. This method also uses MergeSort, another good sorting algorithm, to sort objects. Quicksort implementations are also available in the C++ STL library.

How to Find Multiple Missing Integers in Given Array of Numbers with Duplicates in Java?

Hello guys, It's been a long time since I have discussed any coding or algorithm interview questions, so I thought to revisit one of the most popular array-based coding problems of finding missing numbers in a given array of integers. You might have heard or seen this problem before on your programming job interviews and you might already know how to solve this problem. But, there are a lot of different versions of this problem with increasing difficulty levels which interviewers normally use to confuse candidates and further test their ability to adapt to frequent changes, which is key to surviving in the ever-changing software development world.

Top 30 Linked List Algorithm Questions from Programming/Coding Interviews

The linked list is one of the most common and essential data structure and that's why you would frequently find linked list based coding questions on interviews. The range of questions can be from simple questions like finding the length of a linked list to very difficult like merging two sorted linked lists. Nevertheless, the point is that you should be familiar with linked list data structure and must know how to perform basics task in the linked list e.g. adding or removing nodes from a linked list, traversing order linked list and implementing linked list in your choice of programming language like Java, C++, C, or Python.

How to Print Fibonacci Series in Java without Recursion - Coding Problem for Beginners

Fibonacci series is a great example of Dynamic Programming, Recursion, and how the use of Recursion can result in a clear and concise solution. That's why whenever asked about writing a Java program to get Fibonacci numbers or print the Fibonacci series of certain numbers, it's quite natural for programmers to resort to recursion. The interviewer often challenged this practice by asking candidates to implement the Fibonacci series without using recursion. Yes, you read it right, you can't use recursion and this is what you will learn in this article. If you have attended your programming classes regularly then you may know that many recursive algorithms also have their iterative counterpart which uses loops instead of recursion or calling itself. We will take advantage of that concept to devise a solution to this problem.

Sunday, September 24, 2023

3 ways to sort an ArrayList in Java without using sort() method - Example Tutorial

Hello guys, you can sort an ArrayList in Java without using the sort() method from the Collections class or the List interfaces' sort() method by implementing your own sorting algorithm. You can use any sorting algorithm like bubble sort, insertion sort, selection sort, quicksort, or merge sort to sort your ArrayList without using sort() method from Collection API. In the past, I have even showed multiple examples of sorting List in Java in both increasing and decreasing order. We have even seen example of sorting List in custom order using Comparator and in this article I will show you multiple way to sort an ArrayList without using Java Collection API. 

How to fix class file has wrong version 61.0, should be 53.0 error in Spring Boot? [Solved]

Hello guys, The "class file has wrong version" error typically occurs when you're trying to run a Java application compiled with a higher Java version than the one supported by your current Java runtime environment. In this case, the error message suggests that the class file was compiled with Java version 17 (version 61.0) but is being executed on a Java runtime that only supports version 9 (version 53.0). This error commonly asked when you try to use Spring Framework 6 or Spring Boot 3 in your project which is not running on Java 16 or Java 17.  The error also manifest in different messages like "“Java class file has wrong version 61.0” or "“Java class file has wrong version 62.0”. 

2 Ways to check If String is Palindrome in Java? Recursion and Loop Example Tutorial

A String is said to be Palindrome if it is equal to itself in reverse order. You can use this logic to check if String is Palindrome or not. There are two common ways to find if a given String is Palindrome or not in Java, first by using for loop, also known as an iterative algorithm, and second by using recursion, also known as a recursive algorithm. The crux of this problem lies in how do you reverse String in Java? because once you have the String in reverse order, the problem is reduced to just comparing itself with the reversed String. If both are equal then the given String is Palindrome otherwise it's not. Also whether your solution is iterative or recursive will also determine by implementing this logic.

How to Convert Fahrenheit to Celsius in Java with Example

In this Java tutorial, you will learn how to write a program to convert Fahrenheit to Celsius in Java. Fahrenheit is a thermodynamic temperature scale, where the freezing point of water is 32 degrees Fahrenheit (°F) and the boiling point of water is 212°F (at standard atmospheric pressure). This puts the boiling and freezing points of water exactly 180 degrees apart. Therefore, a degree on the Fahrenheit scale is 1/180 of the interval between the freezing point and the boiling point of water. Absolute zero is defined as -459.67°F. If you know, in the Celsius scale, the freezing point of water is at 0ºC and the boiling point of water is at 100ºC. By using these facts, you can easily deduce a formula to convert Fahrenheit temperature into Celsius.

How to print 1 to 100 without using loop in Java? Example Solution

This is one of the interesting problems  I have seen in coding interviews for beginners. The program has a surprise element by saying that you need to print 1 to 100 without using a loop e.g. for, forEach, or enhanced for loop. This brings out some innovative solutions from candidates which tell a lot about their approach, knowledge, and attitude. I remember, asking this question during campus recruitment to at least 5 candidates. The first one took 5 minutes to think and then come up with the brute force way where he just copies pasted 100 System.out.println() and printed numbers 1 to 100 but when we asked to improve that, he couldn't do that. Unfortunately, he didn't think that recursion can replace an iterative algorithm without using a loop.

How to Convert Binary Number to Decimal in Java - Algorithm Example Tutorial

Problem: Write a Java program to convert a binary number into the decimal format, without using any library method which can directly solve the problem. You are free to use basic Java functions through e.g. those defined in java.lang and all kinds of Java operators e.g. arithmetic and logical operator, bitwise and bitshift operator, and relational operators.

Solution: Let's first revise some theory of the number system, which is required to convert a number from binary to decimal format. There are four kinds of number systems binary, octal, decimal, and hexadecimal. Binary is base 2 and that's why any number is represented using only two-digit, 0, and 1 also known as bits.

Double Checked Locking on Singleton Class in Java - Example

Singleton class is quite common among Java developers, but it poses many challenges to junior developers. One of the key challenges they face is how to keep Singleton class as Singleton? i.e. how to prevent multiple instances of a Singleton due to whatever reasons. Double-checked locking of Singleton is a way to ensure only one instance of Singleton class is created through an application life cycle. As the name suggests, in double-checked locking, code checks for an existing instance of Singleton class twice with and without locking to double ensure that no more than one instance of singleton gets created.

How to check if a number is a palindrome or not in Java - Example

How to check if a number is a palindrome or not is a variant of popular String interview question how to check if a String is a palindrome or not. A number is said to be a palindrome if the number itself is equal to the reverse of number e.g. 313 is a palindrome because the reverse of this number is also 313. On the other hand, 123 is not a palindrome because the reverse of 123 is 321 which is not equal to 123, i.e. original number. In order to check if a number is a palindrome or not we can reuse the logic of How to reverse a number in Java.

How to Count Occurrences of a Character in String - Java Programming Example

Write a program to count the number of occurrences of a character in String is one of the common programming interview questions not just in Java but also in other programming languages like C or C++.  As String is a very popular topic in programming interviews and there are a lot of good programming exercises on String like "count number of vowels or consonants in String", "count number of characters in String", How to reverse String in Java using recursion or without using StringBuffer, etc, it becomes extremely important to have a solid knowledge of String in Java or any other programming language. Though, this question is mostly used to test the candidate's coding ability i.e. whether he can convert logic to code or not.

How to Find Missing Number on Integer Array of 1 to 100 - BitSet Example

One of the most frequently asked questions on programming interviews are, write a program to find the missing number in an array in Java, C#, or any other language; depending upon which language you choose. This kind of coding interview questions are not only asked in small start-ups but also on some of the biggest technology companies like Google, Amazon, Facebook, Microsoft, mostly when they visit the campus of reputed universities to hire graduates. The simplest version of this question is to find missing elements in an area of 100 integers, which contains numbers between 1 and 100. 

How to calculate area of Triangle in Java - Example Solution

Calculate the area of Triangle in Java
Write a Java program to calculate Area of Triangle, accept input from User, and display output in Console is one of the frequently asked homework questions. This is not a tough programming exercise but a good exercise for beginners and anyone who has started working in Java. For calculating the area of a triangle using the formula 1/2(base*height), you need to use arithmetic operators. By doing this kind of exercise you will understand how arithmetic operators work in Java, subtle details which affect calculation like precedence and associativity of the operator, etc.

How to get User input from Console and command line in Java - Example Tutorial Code

How to get input from users in Java from the command line or console is one of the common thing, everyone started learning Java looks for. It’s the second most popular way of starting programming after HelloWorld in Java. There are so many ways to get input from Users in Java including command line and Graphical user interface. For beginners simpler the example, better it is. first and foremost way of getting input from user is String[] passed to main method in Java but that only work for one time requirement and its not interactive. Another way of getting input from User is involving IO classes like InputStream to read from console or command line which can be little complicated for true beginner.

Saturday, September 23, 2023

How to debug Servlet, JSP based Java Web Application in Eclipse with Tomcat

One of my reader was struggling with debugging a Java web application, containing Servlet and JSP in Eclipse with Tomcat. While helping him, I realized that I have not written anything about debugging a Java web application in Eclipse yet. Even though, I have wrote articles about debugging tips and remote debugging in Eclipse, I have never touched the topic of debugging Servlet and JSP in Eclipse or any other IDE, which are two pillars of Java web applications. To fill that gap, I am starting a series of articles where we'll first learn how to setup Eclipse with Tomcat to debug Java web application and then learn some tips and tricks to effective debug Servlet and JSP. 

How to Find All Permutations of String in Java using Recursion? Solution Example

How to find all permutations of a String using recursion is one of the tricky coding questions from programming job interviews. I have first seen this question in my college exam when we were asked to code the solution using C or C++ language. Since then I have seen this question many times at various written tests and Java interviews for a junior developer position. It does not only serve as a good question to check whether the candidate understands recursion but also its one of the better java programming exercise for beginners.

How to find duplicate words in Java String? [Solution Example]

Problem:  Write a Java program to print the duplicate words from a given statement e.g. if the given String is "Java and JavaScript are totally different, JavaScript follows Java" then your program should print "Java" and "JavaScript" because those two are 2 duplicate words from given String. You need to consider all cases e.g. given String can be null, empty, may or may not contain any duplicate words, but for simplicity, you can assume that sentence will always be in English and only use ASCII characters, alphabets, and numerals, no special character.

Bubble Sort Algorithm in Java with Example

Bubble Sort is the first sorting algorithm I learned during my college day, and after so many years it's the one I remember by heart. It's kind of weird that one of the most popular sorting algorithms is also one of the worst-performing sorting algorithms. Bubble sort's average-case performance is in O(n^2), which means as the size array grows, the time it takes to sort that array increases quadratically. Due to this reason, bubble sort is not used in production code, instead quick sort and merge sort are preferred over it. In fact, Java's own Arrays.sort() method, which is the easiest way to sort an array in Java also uses two pivot quicksort to sort primitive arrays and a stable mergesort algorithm to sort object arrays.

How to Find Largest of Three Integers in Java - Algorithm, Logic Example

One of the classical programs to build programming logic is, write a program to find the largest of three numbers. I am sure many of you have already done this exercise in a variety of languages including C, C++, C#, JavaScript, Perl, Ruby, PHP, etc. This time we will do it in Java. We will first learn the logic by understanding the flowchart of the largest of three numbers and then we will implement a solution using the ternary operator in Java. I love this program for its sheer simplicity and how it can help beginners to build logic. As always, you are not allowed to use any library function which can solve this problem directly, your main task is to build logic using primitive language tools e.g. operators.

3 ways to parse String to float in Java? Examples

float and double are two data type which is used to store floating-point values in Java and we often need to convert String to float in Java and sometimes even a Float object or float primitive to String. One thing, which is worth remembering about floating-point numbers in Java is that they are approximate values, a float value 100.1f may hold the actual value of 100.099998, which will be clear when we have seen examples of converting float to String and vice-versa. By the way, It's easy to parse String to float and vice-versa, as rich Java API provides several ways of doing it.

Friday, September 22, 2023

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. 

Thursday, September 21, 2023

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. 

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. 

Wednesday, September 20, 2023

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 between @RunWith vs @ExtendWith Annotations in JUnit - Java Unit Testing Example

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.

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.

Tuesday, September 19, 2023

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.

Monday, September 18, 2023

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.

Sunday, September 17, 2023

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.

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

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