Saturday, December 30, 2023

5 Free Data Structure and Algorithms Books in Java Programming

In the last article, I have shared some of the best data structure and algorithms books for programmers, but those were not free. After that article, I received some feedback about how about sharing free data structure and algorithm books? Fair enough, everybody loves free eBooks, courses, and PDFs, don't you? In the past, I have shared a list of free Java programming books, so I had some ideas. I did some more research on the internet and checked my collection as well. Fortunately, there are a couple of good Data Structure and Algorithm books which are available for free as a PDF download or for online reading, which is what I am going to share with you all today.

Friday, December 29, 2023

Top 5 Hibernate Books for Java Developers - Best, Must read

Hibernate is one of the most popular, open-source ORM (Object Relational Mapping) framework, which has now become a standard for developing persistence layer on Java enterprise application, along with JPA (Java Persistence API). I often receive requests to suggest which book is best to learn to hibernate or recommendation about some good books and training courses on Spring and Hibernate. This motivates me to write this article about some of the best books on Hibernate currently available on the market.

Thursday, December 28, 2023

How to sort ArrayList in Natural and Custom Order in Java - Example Tutorial

Sorting ArrayList in Java is a common task for Java developers and we have touched it while discussing in my last article 10 Examples of  ArrayList in Java and again when we discussed comparator and comparable in Java. There are multiple ways to sort ArrayList in Java for example, you an use Collections.sort() method or List.sort(), or Stream.sort() method to sort an ArrayList in Java depending upon which Java version are you using. If you want a solution irrespective of Java version then Collections.sort() is the best way because this method is available since JDK 1.1. In order to sort an ArrayList, we need to use the Collections utility class which contains an overloaded sort() method for sorting different collections and supports different comparators in Java. In this article, we will see how to sort ArrayList in the natural order of elements and then sorting ArrayList in Java with a comparator.

Monday, December 25, 2023

Top 10 Java Programming Books - Best of lot, Must Read

Hello guys, if you want to learn Java and looking for the best books to learn Java then you have come to the right place. In the past, I have shared best Java courses, websites, and even a complete Java Developer RoadMap and in this article, I am going to share best books you can read to learn Java programming in depth. These top Java programming books are some of the good books to learn Java and I would say some of them are simply the best Java books ever published. Whenever a programmer starts learning Java programming language, the first question he asks is "Which book should I refer to learn Java?", or "What is the best book to learn Java for beginners?" or "Can you tell me some good books to learn Java?" .That itself says how important Java books are for programmers especially beginners.  

Saturday, December 23, 2023

5 Must Read Books to become Software Architect or Solution Architect

I receive a lot of queries from senior Java developers, who aspire to become software architect or solution architect, like what can they do to become a software architect? Which books, resources, or certifications can help? And general queries like how much experience you need to become a software architect etc. In the past, I have been suggesting them individually about some books to read to expand their knowledge base and look at the software from architecture and design perspective, and this article is a compilation of many of such suggestions. Since a lot of books can confuse, I have only select 5 best and must-read books from the software architect's perspective.

Sunday, December 17, 2023

How to enable Spring MVC in Java Web Application? Example Tutorial

In last article, I have shared thoughts on how to enable Spring Security on Java Web application, where my reader also shown interest to know how to configure/enable Spring MVC in Java web application. Though, this is very basic information, it helps a lot to anyone who is new to String framework and want to understand then essential steps required to enable Spring MVC framework for a Java based web application. It's easy to configure Spring MVC if you have developed a simple hello word kind of program using Servlet or JSP and familiar with web application fundamentals in Java world e.g. Servlet container like Tomcat, deployment descriptor file or web.xml, Servlet or JSP itself and some essential tags on web.xml e.g. <servlet> and <servlet-mapping>, <url-pattern> etc. 

Monday, December 11, 2023

How to conditionally render view in JSP using Spring Security tag library? Example tutorial

One of the common requirement of secure Java application is to show and hide content based upon role of current user. For example, a logged in user can see his name e.g. Welcome User1 but that link is not visible to an unauthenticated user. Similarly, a user with admin role can see a lot of admin related functionality which should not be visible to a normal user e.g. add/remove users, disable users, create roles, edit roles etc. How can you achieve such condition based rendering in view? Does spring security support that? Well, the answer is Yes. Spring security provide a tag library which you can use in JSP pages to perform a lot of authentication and authorization related stuff e.g. you can access current user's name, you can access access current user's role and you can also conditionally show/hide certain section of views based upon user's role. 

Monday, December 4, 2023

How to Crack AWS Certified Solution Architect Associate Exam SAA-C03 in 2024

There is no doubt that AWS certification is precious and opens the door for a lot of opportunities, not just for system admins but also for developers and DevOps. Even though there is no substitute for knowledge and experience there are a lot of tangible and intangible benefits of AWS certifications, mainly AWS Certified Solution Architect Associate. Your certification is useless if you don't know how to work in AWS console, but if know that and still struggling to find a job then AWS certification can help you. First thing, it gives you recognition. It allows you to put AWS in your resume and LinkedIn and also get you a lot of chances as recruiters and companies prefer certified professionals over a non-certified if skill set matches.

Spring Professional Develop 2024 Certification Guide - [VMware 2V0 -72.22 FAQ]

If you are a Java developer, working in the Spring framework, and thinking to become a certified Spring professional but couldn't do it in the past due to expensive mandatory training provided by Vmware and its partners then there is good news for you. Now you can take online Spring training courses from Vmware for appearing to the Spring Professional Develop certification exam, which means, now, it's not mandatory to take expensive Spring training for Spring certifications (see here). Similar to Oracle's Java certifications, you can become a Vmware Certified Spring Professional by just buying the exam vouchers and scheduling your exam online using examlocal.com from anywhere in the world.

5 Best Java 8 and Functional Programming Books for Beginners and Experienced [UPDATED]

If you follow Java updates, you may know that Java 13 was released, and Java 14 is on the way, but I often receive emails and queries asking about some good books to learn Java 8. Since Java 8 is very different from any other JDK release, in terms of language and API enhancement, you really need an excellent book to learn fundamentals. In short, based upon my 2 years of learning and reading Java 8 books, I can say that Java SE 8 for Really Impatient is hands down the best book to learn Java 8. It covers all the essential things released in JDK 8, not just lambda expression and streams but also new Date and Time API and several other minor enhancement yet crucial features, which often go unnoticed.

Top 6 Advanced SQL Books for Experienced Programmers - Best of lot, Must read

If you an experienced programmer and know how to write SQL queries and database fundamentals but want to take your SQL and database skills to the next level then you have a come to the right place. In this blog, I have shared a lot of free SQL books and courses you can use to start your SQL journey. This is also the second article about SQL books, In the first part, I have shared some of the best SQL books which are essential to learning SQL queries and fundamentals of database like normalization, indexing, and other design stuff, if you haven't read it yet, I suggest to do it now. You will find some amazing books to start learning SQL.

How to get current logged in user in JSP and Controller using Spring Security? Example Tutorial

One of the common task while using Spring Security in a Java web application is getting the username of currently logged in user. Sometime, you need that in your controller class and sometime in JSP for view purpose, but the big question mark is how do you get the current user in Spring Security? Well, there are many ways to do it and depending upon whether you need it inside a JSP page or Controller class, you can choose them. The current user, also known as Principal in Spring Security can be obtained from the UserDetails class, which holds all details for currently logged in user. You can get this class from the SecurityContext, which in turn can be retrieved from SecurityContextHolder as shown below:

Sunday, November 26, 2023

How Request mapping or HandlerMapping works in Spring MVC? @RequestMapping Example

Hello guys, In last a couple of articles, we have learned how Spring MVC framework works and what is the role of DispatcherServlet in Spring MVC. We have briefly touched another frequently asked Spring MVC interview question, how does requests are mapped to controllers in Spring MVC? In this article, we'll expand our knowledge on that. You have learned that DispatcherServlet is the front controller in Spring MVC framework, it is the single point entry and all incoming request goes through it, but instead of processing those request it just dispatches the request to the appropriate handler methods based on the request mapping, but how does it do that?

Monday, November 20, 2023

How to secure an URL using hasRole() in Spring Security? Is it enough to hide sections of JSP to protect URL? Example?

One of the Spring security question asked to me on a recent interview was about is it enough to hide portions of JSP to protect a URL from unauthorized access in Spring security? First of all I didn't understand the question, so I ask him to clarify a bit more. He explained to me that there are different roles in his application e.g. DEVELOPER, ADMIN, TRADER, OPERATION and each role can only see the functionalities based upon their role. For example, an ADMIN has a right to add or remove new users into the system, while DEVELOPER can only see test order, but OPERATION can see all orders. 

Monday, November 13, 2023

How to show current logged in username in JSP using Spring Security? Example Tutorial

One of the common feature of secure Java web application to show the username as link on the top right corner of web application once user successfully logged in. Some application also show the logout or sign-out link like that but how do you display the current user or principal name in a JSP page secured using Spring security library? Well, Spring Security provides a small but userful JSP tag library which contains custom tags similar to JSTL, which can show a lot of useful authentication and authorization details of current user. For example, you can use <s:authetication> tag to display the current principal details including the username of currently logged in user. The tag name is authentication here and s is the prefix you specify while importing tag using taglib directive in JSP. 

Sunday, November 5, 2023

5 Ways to Update Values in ConcurrentHashMap in Java 8 - Example Tutorial

In last article, I have showed you how to update value in HashMap and today we'll learn about how to update value in a ConcurrentHashMap. Some of you may question, can we use the same technique we used to update a value in HashMap here? well, you can but you need to keep in mind the difference between an HashMap and a ConcurrentHashMap. The HashMap is only meant to be updated by one thread at a time, hence you don't need to pay any attention to thread-safety or concurrency, but ConcurrentHashMap can be updated by multiple threads at the same time, hence you need to pay special attention. 

Monday, October 30, 2023

Why Java and Spring Developers Should Learn RESTful Web Services and Microservices

More and More companies are adopting  Microservices architecture e.g. Uber and Netflix already uses it and many startups I know is choosing REST and MicroService as the standard way to build and provide their services. This is fueling the demand for programmers who can develop robust and scalable Microservices and RESTful Web Services. Since Java is one of the most popular language for developing backend, it is also benefiting from this trend. The demand for Java developers who knows Spring framework and understand how to build RESTful web services is huge and that's why it has become a key skill in Java application development job market. 

Monday, October 23, 2023

15 Example of print() and println() methods in Java

Hello guys, if you have learned Java in early 2000 then there is  good chance that you must have written your first Java code using System.out.println(). For a long time, I have no idea what that mean but I alway use it to print messages on console. When I started working in Java and preparing for Java certification then I come to know that System is a class and out is an object of PrintStream which has println() method. That was a revelation for me. I also found that Java provides a powerful set of I/O classes for handling various input and output operations. Among these, the PrintStream class stands out as a versatile tool for writing formatted text to output streams. The print()printf() and println() methods within the PrintStream class, as well as System.out.println(), are particularly useful for printing different types of data to the console or other output destinations.

Sunday, October 15, 2023

Top 6 Books to Learn and Master Programming and Coding - Must Read, Best of Lot

Coding is an integral part of Programming, and we all somehow learned to code by following examples here and there. Yes, I am talking about both self-taught programmer and Computer Science Graduates. You can learn Coding easily if you are dedicated, but what is more difficult is to write good code. You can easily find programmers in Java, C++, Ruby, or Python, but finding programmers, who are also a good coder is very difficult. Some universities have a good curriculum and practical classes to teach coding better than others, but most of these great coders are self-taught Programmers, who learned by reading books, joining online courses, and doing things on their own.

Tuesday, October 10, 2023

How to fix Eclipse - Could not reserve enough space for object heap in Java? Solution

If you are running Java program in Eclipse and ever tried playing with -Xmx parameter you know about those virtual machine initialization error e.g. "“Error occurred during initialization of VM; Could not reserve enough space for object heap”. This error usually occur when you to try to give your program, running on 32-bit JVM more than 1.4G of memory in Eclipse in Windows. It doesn't matter how much memory your machine have e.g. I have seen this error in laptops running 4GB of memory. The important thing which matter is whether JRE or JVM you are using with Eclipse is 32-bit or 64-bit. If you use 64-bit JRE in Eclipse, you can potentially allocate more than 1.4G of memory in Windows itself.

Monday, October 9, 2023

How to fix java.net.SocketException: Connection reset by peer: socket write error? [Solved]

"Exception in thread "main" java.net.SocketException: Software caused connection abort: socket write error" comes when you are writing into a connection which is already closed by your peer i.e. the other party in the connection. For example, if you are server and sending response to client but client closed its connection before you complete writing response, the write() method of DataOutputStream will throw this error. It's not necessary that this error will only come when you are using DataOutputStream, it can come even if you are just using and OutputStream or SocketOutputStream point is you are writing in a socket which is closed by other end. Here is the actual error message with stacktrace:

Sunday, October 8, 2023

2 Ways to remove whitespaces from String in Java? Example Tutorial

You can remove blanks for whitespaces from a Java String by using the trim() method of java.lang.String class of JDK API. Unlike SQL Server which have LTRIM() and RTRIM() methods to remove whitespace from String, Java doesn't have ltrim() and rtrim() methods to trim white spaces from left and right, instead it just have a trim() method which removes all spaces from String including space at the beginning and at the end. Since String is Immutable in Java, it's worth noting that this method return a new String if original String contains space either at beginning or end, otherwise it will return the same String back. 

Friday, October 6, 2023

How does Remember Me functionality works in Spring Security?

In the last article, You have learned how to enable the remember-me functionality in Spring security and today you will learn how does Remember Me work under the hood. So far, you know that remember-me functionality uses cookie to remember users and allow auto-login (without entering password again), so you might have guessed that spring security provides hooks to generate that cookie as well as process those cookie when an already signed user open the application after the break e.g. after a day or two. As long as cookie is not expired and token is valid i.e. user hasn't changed the password, he should be able to login to your application. 

Wednesday, October 4, 2023

6 ways to sort ArrayList in Java 8? List.sort() + Collections.sort() Example Tutorial

There are many ways to sort an ArrayList in Java 8; for example. you can use the old but still rocking way to sort a List by using Collections.sort() method, or you can use the newly added sort() method in the List interface in Java, or you can use the new java.util.stream API to sort a list of objects. You now have multiple choices when it comes to sort a List or Array in Java. Though, my preferred way is Collections.sort() method because it is available to all the Java versions and its easy to use and it also allows you to sort in any custom order.  The method is overloaded which gives you ability to sort a list of objects into their natural order as well allow you to supply a Comparator of your choice to sort elements into customer order. 

Tuesday, October 3, 2023

How to enable RememberMe Functionality in Spring Security

Hello guys, most of the web application has login or authentication functionality where user need to enter their username and password to access functionalities provided by application. This is great from application's perspective because functionalities are protected from anonymous user but from user's perspective he would appreciated something which would not ask him/her to enter username and password every now and then. This is what remember me functionality of Spring security does. It allow you to build a web application which can remember their user and allow them to automatically login when the restart their browser or come back another day. 

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? 

Thursday, September 28, 2023

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.

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. 

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.