Monday, July 7, 2025

What is Object in Java and Object Oriented Programming? Example Tutorial

Object in Java
Object in Java programming language or any other Object-oriented programming language like C++ is the core of the OOPS concept and that's why the name. Class and Object along with Inheritance, Polymorphism, Abstraction and Encapsulation form the basis of any Object-oriented programming language e.g. Java. Objects are instances of Class, Class defines blueprints and Objects are things that are created based upon that blueprint. Object is also known as instances in Java, e.g. When we say an instance of String class, we actually mean an Object of String class. The object has state and behavior in Java. 

Open Closed Design Principle in Java - Benefits and Example

Great Example of Open Closed Design Principle
I am a big fan of design pattern articles and love to read articles on design patterns and recently wrote about decorator design pattern in JavaObserver patternstatic factory pattern and Singleton pattern. Today I come across this good article on open closed design patterns, what I like most is there example and clear way of explanation, first example is true value and it will help you understand open closed principle very quickly and second example is also not bad.

How to use Class in Java Programming - Example

When I first about Class in Java I just thought what is this Class in Java and from that date to now Whenever we talk about java its really incomplete without classes, every one who are little bit familiar with java knows it’s purely object oriented language means every thing we discuss in java as object .so its very important for learner or anyone who is keen to know about java should know about java class then only they can move forward on java world.
In this article we will see what Java Class, Example of Class in Java is and what makes a Java Class including members, field and method.

What is Inheritance in Java and OOP Tutorial - Example

Inheritance in Java is an Object oriented or  OOPS concepts, which allows to emulate real world Inheritance behavior, Inheritance allows code reuse in Object oriented programming language e.g. Java. Along with Abstraction, Polymorphism and Encapsulation, Inheritance forms basis of Object-oriented programming. Inheritance is implemented using extends keyword in Java and When one Class extends another Class it inherit all non private members including fields and methods. Inheritance in Java can be best understand in terms of Parent and Child class, also known as Super class and Sub class in Java programming language.

What is polymorphism in Java? Method overloading or overriding?

What is Polymorphism in Java
Polymorphism is an important Object oriented concept and is widely used in Java and other programming languages.  Polymorphism in java is supported along with other concepts like Abstraction, Encapsulation, and Inheritance. Few words on the historical side; Polymorphism word comes from ancient Greek where poly means much so polymorphic are something which can take many forms. In this Java Polymorphism tutorial, we will see what is Polymorphism in Java, How Polymorphism has been implemented in Java e.g method overloading and overriding, why should we use Polymorphism and how can we take advantage of it polymorphism while writing code in Java. Along the way, we will also see a real-world example of using Polymorphism in Java

Can we declare a class Static in Java? Top Level and Nested static class Example

The answer to this question is both Yes and No, depending on whether you are talking about a top-level class or a nested class in Java. You cannot make a top-level class static in Java, the compiler will not allow it, but you can make a nested class static in Java. A top-level class is a class that is not inside another class. It may or may not be public like you can have more than one class in a Java source file and only needs to be public, whose name must be the same as the name of the file, rest of the class or interface on that file may or may not be public. On the other hand, a nested class is a class inside a top-level class. It is also known as the inner class or member class in Java.

Law of Demeter in Java - Principle of least Knowledge - Real life Example

The Law of Demeter also known as the principle of least knowledge is a coding principle, which says that a module should not know about the inner details of the objects it manipulates. If a code depends upon the internal details of a particular object, there is a good chance that it will break as soon as the internal of that object changes. Since Encapsulation is all about hiding internal details of an object and exposing only operations, it also asserts the Law of  Demeter. One mistake many Java programmer makes it exposing internal detail of object using getter methods and this is where the principle of least knowledge alerts you.

What is interface in Java with Example - Tutorial

What is an interface in Java?
Interface in java is a core part of the Java programming language and one of the ways to achieve abstraction in Java along with the abstract class. Even though the interface is a fundamental object-oriented concept; Many Java programmers think of Interface in Java as an advanced concept and refrain from using the interface from early in a programming career. At a very basic level interface in java is a keyword but same time it is an object-oriented term to define contracts and abstraction, This contract is followed by any implementation of Interface in Java. Since multiple inheritances are not allowed in Java, the interface is the only way to implement multiple inheritances at the Type level.

Saturday, July 5, 2025

Top 10 Courses to Crack System Design Interview in 2025 - Best of Lot

Hello guys, if you are preparing for System Design Interviews and looking for best resources then you have come to the right place. Earlier, I have shared best System design bookcourses, websites, and System design interview questions and in this article, I am going to share in-depth System design courses from Educative.io, a text based online learning platform for developers and engineers. These are the best online courses to prepare for System Design Interviews in 2025.  If you have been doing Software development then you know that System design is one of the most important skill for developers and managers. 

4 Steps to Prepare for System Design Interviews in 2025? [The Ultimate Guide]

Hello guys, if you are preparing for Software Engineer Interviews, or Software developer interview then you may know that how difficult it is to prepare for them because of  System Design interviews, given its open ended nature and vastness but at the same time you cannot ignore it. In Software Engineering world, if you are applying for a Senior Engineer / Lead / Architect / or a more senior role, System Design is the most sought-after skill, and hence one of the most important rounds in the whole process. If you mess this up, nothing else would matter. If you get it right though, you’re looking at a raise of at least tens of thousands of dollars annually. 

How to System Design Trade Position Aggregator? [Solution]

Hello guys, it's been a long since I shared object-oriented design and system design questions in this blog. It was almost 7 to 8 years when I last blogged about how to solve vending machine design problems in Java and Twitter System Design question? Actually, I had ideas for lots of such design questions at that time, but because of the lengthy nature of these kinds of posts and the amount of time they take, they just sit on my list of drafts. I thought to take them out and publish then slowly improve on them instead of publishing the perfect post for the first time, and today, I am excited to share one of such problems, how to design a trade position aggregator in Java. This program is like portfolio management software that monitors your risk and exposure in real-time based on trades. 

Friday, July 4, 2025

Review - Is ByteByteGo System Design Interview Course by Alex Xu Really Worth it in 2025?

Hello guys, if you are preparing for System Design Interview in 2025 then you may have most likely come across names like ByteByteGo, Alex Xu or System Design Interview - An Insider Guide by Alex Xu, and if you are wondering what they are or you know about them but thinking whether ByteByteGo is worth it or not in 2025? then you have come to the right place. Yes, ByteByteGo is indeed worth considering for your System Design Interview preparation. because its created by Alex Xu, an expert with FAANG interview experience and platform offers in-depth coverage of system design topics. The author's use of diagrams to explain concepts in detail enhances the learning experience and most importantly Alex Xu regularly and new content and update old ones,.

Thursday, July 3, 2025

How to Remove Duplicates from Array without Using Java Collection API? Example

This is a coding question recently asked to one of my readers in a Java Technical interview on investment bank. The question was to remove duplicates from an integer array without using any collection API classes like Set, HashSet, TreeSet or LinkedHashSet, which can make this task trivial. In general, if you need to do this for any project work, I suggest better using the Set interface, particularly LinkedHashSet, because that also keeps the order on which elements are inserted into Set. Why Set? because it doesn't allow duplicates and if you insert duplicate the add() method of Set interface will return false. 

How to find smallest number from int array in Java, Python, JavaScript and Golang? [Solved]

This is the second part on this array interview question. In the first part, I have showed you how to find the largest element in array, and in this part, you will learn how to find the smallest number from an integer array. We will solve this problem on Java programming language but you are free to solve in any other programming language like Python or JavaScript. Most interviewer doesn't care much about which programming language you are solving the question, if you can provide working solution. This one is also a popular Java programming exercise which is taught in school and colleges and give in homework to teach programming to kids and engineering graduates. 

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

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

Difference between a List and Array in Java? ArrayList vs Array Example

Hello there, if you are wondering what is the difference between a list and an array, or particularly an ArrayList and an Array in Java then you have come to the right place. Earlier, I have shared the best data structure and algorithm courses and in this article, I will explain to you the differences and similarities between a list and an array in Java.  Both array and ArrayList are two important data structures in Java and frequently used in Java programs. Even though ArrayList is internally backed by an array, knowing the difference between an array and an ArrayList in Java is critical for becoming a good Java developer. If you know the similarity and differences, you can judiciously decide when to use an array over an ArrayList or vice-versa. 

How to Find all Pairs in Array of Integers Whose sum is Equal to a Given Number in Java? Solution Example

Practicing coding problems are very important to do well in any programming interview. You should at your best on data structures like an array, linked list, and string to clear any programming interview and believe me, you can not do this in one day or one week. It's rather a long process of learning through coding, and that's where these small coding problems help. Today, we are going to look at another interesting programming question from the array; write a program to find all pairs of integers whose sum is equal to a given number. For example, if the input integer array is {2, 6, 3, 9, 11} and the given sum is 9, the output should be {6,3}.

How to Create and Initialize Anonymous Array in Java? Example

Anonymous arrays in Java is an Array without any name, just like Anonymous inner classes and policy of using Anonymous array is just create, initialize and use it, Since it doesn't have any name you can not reuse it. The anonymous array was a good way to implement variable argument methods before Java introduced varargs in Java5. You had the liberty to create an array of any length and pass that to a method that operates on an anonymous array. Classical example of such variable argument method is aggregate function like sum(), avg(), min(), max() etc.

Can You Make an Array or ArrayList Volatile in Java?

This is one of the many interesting multi-threading questions I have shared in my post 50 multi-threading interview questions. Yes, you can make an array volatile in Java, there is no problem with that, neither compiler will flag any error not JVM will throw any exception but the tricky part is why you want to make an array volatile and what is the effect of making an array volatile in Java? In order to answer this question, you must be familiar with both volatile modifier and Java memory model, otherwise, it would be difficult to answer, and that's why it's also one of the trick questions from Java interviews. Before answering this question in detail, let's first revise what is a volatile keyword in Java and what kind of guarantee it provides in the context of multithreading and concurrency.

Difference between Linked List and Array in Java? Example

Array and linked lists are two fundamental data structures in the programming world. Almost all programs use Array in some form or other, which makes it increasingly important to learn array and linked list. The difference between the linked list and array data structure is also a popular data structure question, frequently asked in the various programming job interviews. This makes it even more important to learn and understand the difference between an array and a linked list. Well, there are a lot of differences between these two starting from how they store data, to how you retrieve data from them.

How to merge two sorted arrays in Java? Example Tutorial

Hello guys, if you want to learn how to merge two sorted arrays in Java then you have come to the right place. Earlier, I have shown you how to sort arrays in Javaand in this article, I will show you how to merge two sorted arrays in Java. Btw, if you are a complete beginner then Firstly, you need to know what an array is before going about solving this problem about sorted array.  An array is a data structure in Java that holds values of the same type with its length specified right from creation time. This means you can create an integer array like int[] to store integer value. Think of a container, like a crate of eggs or coke, where number of places are fixed and you cannot change once you created it.

How to check if a given linked list is a palindrome in Java? Example [Solved]

Hello guys, if you are wondering how to check if a given linked list is a palindrome in Java then you have come to the right place. In the past, I have shared how to check if a given String is palindrome or a given number is a palindrome, and in this article, I will teach you how to check if a linked list is a palindrome. But before that, let's revise what is a palindrome? A palindrome is a phrase, word or number, or other sequence of characters that reads the same backward ad forward. Meaning that It gives you the same thing when read forward or backward. For example, Mary, Army, Madam, racecar, 1-2-3-2-1, noon, level, Hannah, civic, etc.

[Solved] How to reverse a Stack in Java using Recursion and Iteration? Example Tutorial

Hello guys, if you are wondering how to reveres a stack in Java then don't go anywhere. In this article, I will show you step by step how to reverse a given stack in Java. There are two ways to reverse a stack, you can use iteration or recursion. The most common way of reversing a stack is to use an auxiliary stack. First, we will pop all the elements from the stack and push them into the auxiliary stack. Once all the elements are pushed into the auxiliary stack, then it contains the elements in the reverse order and we simply print them. But, here, we will not use the auxiliary stack. We will use a recursion method to reverse a stack where recursion means calling the function itself again and again. 

[Solved] How to Implement Fibonacci Series with Memoization in Java 8? ConcurrentHashMap Caching Example

Hello guys, if you are wondering how to solve the Fibonacci series problem with memorization in Java then you have come to the right place. In the past, I have shared recursive and iterative Fibonacci series solution and in this article, I am going to show you how you can improve your solution using a technique called memorization which uses a cache to store the intermediate results. This is a very useful technique to solve Dynamic Programming problems like the Knapsack problem. The good thing about Java is that it provides rich libraries which have classes like ConcurrentHashMap which can be used as a cache to store these intermediary results instead of re-computing them. This can drastically reduce the time to calculate the Nth Fibonacci number.

Top 20 Stack and Queue Data Structure Interview Questions for 1 to 3 years Experienced

Both Stack and Queue are two of the crucial data structure which is very useful in solving a lot of problems. They are not as fundamental data structures as an array or linked lists but they offer some unique advantages in terms of how you store and access elements. Stack is commonly known as LIFO data structure because the last element you put is the first one to come out while Queue is known as FIFO data structure. The elements are retrieved from the queue in the order they were inserted. Both of these data structure has several usages and are used to solve many common problems and to implement algorithms. 

Top 25 Recursion Interview Questions Answers for Coding Interviews

Recursion is often dreaded by programmers as its very difficult for many programmers to visualize and understand, but it's a useful problem solving technique which often result in better, simpler and more concise code than their iterative solutions. That begin said, it's often difficult to come up when to use recursion to solve a coding problem. In general, you should use recursion if a problem can be broken down into sub-problems which are exactly the same as original problem. For example, finding a node in a binary tree. If you are asked to find a node with give value in a binary tree than you can solve this with recursion. Why? because you can breakdown the problem into subproblems which are exactly the same like finding a node in binary tree is same as finding the node in left subtree and right subtree.

Top 10 Matrix Coding Exercises for Programming interviews and Homework

Hello guys, if you are preparing for Coding interviews and solved 100+ data structure problems then you may know that Matrix is one of the under-rated topic for coding interviews but Matrix coding problems are not that easy to solve and  In this article, we'll see some of the popular Matrix coding problems for coding interviews. I actually learned a lot by solving Matrix related problems. I still remember the first Matrix based problem I solve was about how to multiply two matrices in Java and I learned a lot about multi-dimensional array and nested loop in Java by solving that problem. The second problem I solved was about transposing Matrix and that was also quite challenging for me at that time but helped me to further solidify my knowledge about loops and array in Java. 

How to find first recurring or duplicate character in given String? [Solved]

Hello guys, while surfing the Internet for a couple of weeks back, I come to know that this problem was asked on Google interviews, find the first recurring character in a given String. I don't know if that's true but this looks like a very simple coding problem from Google's Interview standard. If it was indeed asked, then that guy must have been very lucky. Anyway, I liked this coding problem and thought to write about it, because it's a good coding problem to check candidates' data structure and algorithms skills because it's tricky. It's tricky because it's very easy to make a mistake assuming just one recurring character in String, which you should avoid. Even if it was not asked on Google, you will potentially find this problem on various startups, and other IT companies like Infosys, TCS, Cognizant, Microsoft, and maybe Amazon

Tuesday, July 1, 2025

[Solved] How to Find maximum Product of a sub-array in Java? Example

Hello guys, if you are asked to find maximum product of a sub-array in Java and you are wondering how to solve this difficult looking coding problem then you have come to the right place. Earlier, I have shared 30 array coding problems, 30 linked list problems, and 10 dynamic programming problems and in this article, we shall be finding the maximum product of a sub-array in java. This problem has a lot to do with arrays. But first, we'll solve the problem then we talk about Array and how it operates. The problem we are to solve here is to find the maximum product of a subarray in Java

How to calculate Area and Perimeter of Square in Java Program? Example Tutorial

Hello guys, if you are looking for Java program to calculate area of Square or program to calculate perimeter of square or just learning Java and looking for programming exercises then you have come to the right place. I have share many programming exercises and homework in this blog and today, I am going to share another simple programming assignment for beginners. Yes, we ae going to write a program which will calculate the area and perimeter of a square in Java. If you don't remember, area of a square is nothing but the multiplication of side with itself or square of side, while perimeter of a square is 4 times of its side because in case of square, each side is equal. 

How to Print a left triangle star pattern in Java? Example Tutorial

Pattern based exercises are very common on Interviews as they are tricky for beginners and also offers coding practice. In the past, I have shared article on how to print pyramid pattern of stars in Java and Pyramid pattern of albhabets, and in this article, I will show you how to print left triangle star pattern in Java. There are different ways of printing different patterns, but most of them involves using loops and print methods like print() and println() to print characters like star, alphabets or numbers. If you know how to use loops and when to break from loop then you can easily solve pattern based coding problems. 

[Solved] How to check if given point is inside Triangle or not in Java? Example

One of the interesting problem from Java Programming interviews is, "write a program to check if given point lies inside a triangle or not?". You will be given co-ordinates of vertices and the point as part of problem and you need to write a function e.g. isInside() which return true if point is within the triangle and false if it is not. For example, in the triangle specified by vertices (11, 31), (21, 1), and (1, 1) the point (11, 16) are inside the triangle and point (30,17) are outside of the triangle. It's a good coding interview question if you have not heard before, just think about how do you prove if the point lies inside the triangle or not? It's not a difficult algorithm and you can think of it by just trial and error. 

How to Rotate Array to Left or Right in Java? Example - LeetCode Solution

Hello guys, rotating an array in Java is a common coding problems which are often used to teach beginners coding as well used during interviews to check candidate's programming and data structure skills. This problem may look easy but its not that easy, especially if you are not coding regular. In order to rotate an array of n elements to the right by kth index, you need to rearrange the item in such a way that the array will start from k + 1the element.  For example, with n = 7 and k = 3, the array [1, 2, 3, 4 ,5, 6, 7] is rotated to [5, 6, 7, 1, 2, 3, 4]. See, it looks like you pick the the 4th element and rotated the array in right direction. The problem becomes even more interesting when interviewer ask you to rotate the array by left or right and in place. Could you do it in-place with O(1) extra space?

How to check Perfect number in Java? Example Tutorial

Hello guys, if you are wondering how to check if a given number is a perfect number or not in Java then you have come to the right place. This is one of the interesting coding problem to solve and learn and improve your coding and programming skill. In face, I learned most of my programming by solving these kind of questions. I started with simple ones like factorial, prime number, palindrome, anagram, string permutations before I started solving tree based problems and Dynamic programming problems. These kind of exercise not only give you a chance to get familiar with the programming language constructs like data type, operators, functions, class etc, but also help to build coding sense, which is nothing but your skill to convert your logic into code. 

How to transpose a Matrix in Java? Example Tutorial

Hello guys, if you are wondering how to transpose a matrix in Java then you have come to the right place. Matrix related coding problems are great way to learn multi-dimensional array and nested loop and they are good programming exercise for beginners. In the past, I have taught you how to multiply matrices in Java and how to add/subtract matrices in Java, and in this article, I will show you how to create transpose of a given matrix in Java, but before that let's first understand what is transpose of a matrix means and how do you transpose a matrix in maths? Well, a transpose of a matrix is nothing but a matrix whose rows and columns are reversed. 

Top 10 Dynamic Programming Problems from Coding Interviews

Dynamic Programming is one of the toughest concepts to master for programmers but at the same time, it's quite important to crack any programming job interviews. Nowadays, you will find at least one Dynamic programming coding problem on every coding interview and that's where most of the programmers get stuck. They try to solve the problem using techniques like divide and conquer but ultimately fail because it's difficult to come to a solution to such problems unless you have solved a decent number of dynamic programming-based coding questions. This is very similar to system design questions which look easy but when you try to solve them you often find yourself stuck and that's why I suggest you practice as much as possible. 

How to check if a given Tree is a Binary Search Tree in Java? Example Tutorial

Hello guys, if you are preparing for a coding interview then you may know those binary tree problems are not easy to solve on coding interviews and I have seen many candidates struggling to do post-order traversal and checking if a given binary tree is a binary search tree or not. If you want to succeed in the coding interview, you need to prepare well on binary trees in general. One way to prepare better is solving common binary tree coding problems like this one, where you need to find if the given tree is BST or not. There are a lot of things that would tell us if a tree is a binary search tree. But before we get to that, we need to understand what a binary tree is.

Radix sort in Java with Example

Hello guys, in one of the interview I was asked to name any O(n) sorting algorithm. I was shocked because I only knew about QuickSort and Mergesort whose best time is O(NLogN), so I couldn't answer that question. After the interview, the first thing I did was to Google about O(n) sorting algorithm and I was surprised to find that there are many algorithms like Radix Sort and Counting Sort and Bucket Sort which can provide O(n) performance. So, I learn them and wrote articles about them like in previous article I explained about Counting Sort algorithm and in this article, I will explain Radis sort like what it is and how it works. In Radix sort, we are sorting by comparing individual digits from the last one to the first one. In essence, radix sort is like this: sort elements by the last digit. 

How to check if a String has all unique characters in Java? [Solved]

Hello guys, its been long time since I shared any interesting coding problem but the wait is over. Today, I am going to share one interesting and popular String based coding problem which you would love to solve. Today's coding challenge is to find out if a given string has all unique characters or not, for example, if given String is "Java" then your function should return false because all styles from this String are not unique. On the other hand, if the given String is "Python," then your function should return true because all characters are unique in this String. Btw, don't just jump on the solution if this is ever asked to you on Interview; instead, you should ask a couple of good questions to demonstrate your requirement gathering skill and attention for details.

5 ways to find length of String in Java - Example Tutorial

On another day, someone asked me, is there a way to find the length of String without using the length() method from java.lang.String class? I didn't ask why, because I know it might have been asked to him on Interviews. Before I explore ways to find the length of String, let's recap what does the length of String means in Java? Well, it's no different than C here, a number of characters in a String including whitespace, newlines are known as length of String. By knowing this, you can think of many approaches to calculating length e.g. getting a char array from String and counting a number of characters or many are by applying some clever tricks.

How to implement Linear Search in Java? Example Tutorial

Hello guys, earlier, I have talked about how the binary search algorithm works and shared the code to implement the binary search in Java. In that article, someone asked me about is there any other search algorithm that exists? How can you search an element in the array if it's not sorted, and you cannot use the binary search algorithm? To answer his questions, I mentioned the Linear search algorithm, which is the predecessor of binary search. Generally, it is taught before the binary search algorithm because the binary search is faster than Linear search. However, never mind, you can still learn this useful algorithm to search for an item in the array or linked list.

How to Find Square Root of a Number in Java? Example Solution

Write a program to calculate the square root of a number in Java or C++ is one of the popular coding interview questions from Programming job interviews both on tech companies like Facebook, Amazon, and investment banks like Citibank and Bank Of America, etc. The problem may look easy because you might know how to find the square root of a number but it's not. In fact, it's one of the tricky questions you would encounter in programming job interviews. The first hurdle is do you really remember how to calculate square root by hand? Many programmers don't. I know they have learned it past but when you ask them to calculate square root by hand, many won't remember the algorithm they have learned in school or college.

Counting Sort Algorithm in Java? Example Tutorial

Hello guys, in our last article, we looked at the Radix Sort in Java and in this article, we will look at the counting sort in Java. If you are thinking how they are related then let me tell you that both are O(n) sorting algorithms. Yes, its possible to sort in O(n) or linear time. If you are wondering that you have so far only learned that best sorting algorithms are Quick Sort and Merge Sort who sorts an array in O(nLogN) time then you are in for surprise. Yes, there existing O(n) sorting algorithms which are faster than both Quicksort and Merge sort like Radix Sort, Counting Sort, and Bucket Sort but they have their limitation. They are not general purpose sorting algorithm and you can use this to sort only integers and it also depends upon how big is the data set and how many different numbers are in the data set. 

3 Ways to Find Duplicate Elements in an Array - Java

There are multiple ways to find duplicate elements in an array in Java and we will see three of them in this program. The solution and logic shown in this article are generic and apply to an array of any type e.g. String array or integer array or array of any object. One of the most common ways to find duplicates is by using the brute force method, which compares each element of the array to every other element. This solution has the time complexity of O(n^2) and only exists for academic purposes. You shouldn't be using this solution in the real world.

Monday, June 30, 2025

How to sort an Array in Java? Ascending and Descending Order Example

As a Java programmer, quite often you would need to sort array in Java luckily java.util.Arrays class provides several utility methods to sort an array in Java. You can sort different types of array in Java like array of primitive data types, object or int, String, etc. Arrays are in java.util package and exposed all sorting related methods as static utility functions. you can access sort() as Arrays.sort() and just pass your array and it will sort that array object by comparing them in the order implemented in the compareTo() method if the class implements Comparable interface. 

How to loop through an Array in Java? Example Tutorial

Hello there, If you want to loop over an array in Java but not sure how to do that then you have come to the right place. Earlier, I have shared many Java array tutorials and the best Java courses for beginners, and today, I am going to teach you how to iterate over an array in Java. There are multiple ways to loop over an array in Java, like you can use a for loop, an enhanced for loop, a while loop, or a do-while loop. Since while and do-while needs a condition to terminate they often depend upon the content of the array like stop when the current element is null or even or odd etc. If you just want to iterate over an array to access each element like loop over an array and print each entry then you should use either for loop or the enhanced for loop.

How to declare and initialize a List with values in Java (ArrayList/LinkedList) - Arrays.asList() Example

Hello guys, today, I am going to share with you a useful tip to initialize a List like ArrayList or LinkedList with values, which will help you a lot while writing unit tests and prototypes. Initializing a list while declaring is very convenient for quick use, but unfortunately, Java doesn't provide any programming constructs like the collection literals of Scala, but there is a trick which you can use to declare and initialize a List at the same time. This trick is also known as initializing a List with values. I have used this trick a lot while declaring list for unit testing and writing demo programs to understand an API etc and today I'll you'll also learn that.

How to implement Skip List in Java? Example Tutorial

Hello friends, we meet again today. hope you all are excited and ready for today's journey. Today, we are gonna learn something that is not very common. It is used not very common, but, if used, it is a great strength to our time complexity reduction. So, what's the wait? Let's start! So, suppose we have a linked list with us which has 10 million records. Now, for searching a particular node, the time taken would be O(N). Where N is the size of the list. Similarly, the time taken for deletion of a Node, Insertion at a particular Node will also take O(N) time. Can we reduce it?

How to find If Linked List Contains Loop or Cycle in Java? Example Solution

Write a Java program to check if a linked list is circular or cyclic,  and how do you find if a linked list contains loop or cycles in Java are some common linked list related data structure interview questions asked in various Java Interviews. This is sometimes asked as a follow-up question of basic linked list questions like inserting an element at the beginning, middle and end of a linked list or finding the length of linked list. In order to solve linked list related algorithmic questions in Java, you need to be familiar with the concept of singly linked list, doubly linked list, and circular linked list. Until stated specifically, most questions are based on a singly linked list. For those who are not familiar with the linked list data structure, its a collection of nodes.

How to use Array in Java? Example Tutorial

The array is one of the most important data structures in any programming language, at the same time different programming languages implement and treat the array differently. Anyone who is done some programming knows the value of an array and the importance of knowing about array type, using them in their program. Together with a linked list, the array forms a set of basic data structures. Though Java offers excellent Collection API and some of the collection classes like ArrayList and  HashMap, they are internally based on the array.

Top 15 Data Structures and Algorithm Interview Questions Answers for Java Programmer

Data structures and algorithm questions are an important part of any programming job interview, be it a Java interview, a C++ interview, or any other programming language. Since data structures are core programming concepts, it's mandatory for all programmers, to know basic data structures like the stack, linked list, queue, array, tree, and graph. Though trees and graphs are on the tougher side, I still see programmers get familiar will all these. Any list of programming job interview questions is incomplete without questions from data structures and algorithms. Similarly, while going on questions from data structure you may get some programming exercise as well e.g. swapping numbers without temp variable.

Difference between Stable and Unstable Sorting Algorithm - MergeSort vs QuickSort

Recently in one interview, after some initial questions about sorting algorithms e.g. how do you write QuickSort or the difference between QuickSort and MergeSort, the interviewer asked about do you understand the difference between stable and unstable sorting algorithms? This question was new to my reader, so he says, Sorry, never heard about that. The story ended there, and Interviewer moved on to the next question but like many of us, my reader went on to find more unanswered questions and ultimately he asks me what is the meaning of a stable and unstable sorting algorithm? Some of you might be heard about it and many of you might not know about this distinction, I'll try to answer this question in this article.

Saturday, June 28, 2025

How to Count Number of Leaf Nodes in a Binary Tree in Java ? [ Iterative and Recursive Solution]

Hello guys, today I am going to talk about an interesting binary tree-based coding problem from Programming Job interviews. If you have attended a couple of technical interviews then there is a good chance that you already have seen this question about counting the number of leaf nodes in a binary tree. If you know how to solve this problem then it's well and good but if you haven't don't worry, you will learn in this article. If you follow this blog then you might know that I have discussed a lot of data structure and algorithms problems here, including array, linked list, hash table, binary tree, and binary search tree. 

6 ways to declare and initialize a two-dimensional (2D) String and Integer Array in Java - Example Tutorial

Declaring a two-dimensional array is very interesting in Java as the Java programming language provides many ways to declare a 2D array and each one of them has some special things to learn about. For example, It's possible to create a two-dimensional array in Java without specifying the second dimension, sounds crazy right? but it's possible because a two-dimensional array in Java is nothing but an array of array. You can even create a two-dimensional array where each subarray has a different length or different type, also known as a heterogeneous array in Java. This means it's possible to create a two-dimensional array with variable column length in Java.

How to implement Bucket Sort in Java? [Solved] - Example Tutorial

In recent years, one of the questions I have increasingly seen in programming job interviews is about constant time sorting algorithms like do you know any O(n) sorting algorithm? how do they work? When I first encountered this question, I had no idea whether we can sort in constant time because even some of the fastest sorting algorithms like QuickSort or MergeSort take O(N log N) time for sorting on their average case. After some research, mainly by going through the classic CLRS book and this DS and Algorithms course by Tim Buchalka and Goran Lochert on Udemy, I come to know that there indeed are some constant time or linear time sorting algorithms like bucket sort, counting sort, and radix sort, which can sort an array in O(n) time but they work with only a special set of input.

Recursive Binary Search Algorithm in Java - Example Tutorial

The binary search algorithm is one of the most famous search algorithms in computer science. It allows you to search a value in logarithmic time i.e. O(logN), which makes it ideal to search a number on a huge list. For example, in order to search a number in a list of 1 million numbers will take around 210 comparisons compared to 1 million comparisons required by the linear search algorithm. The only thing is that the list must be sorted before you can use a binary search algorithm and it must support index-based search. 

Difference between Stack and Queue Data Structure in Java? Example

Stack and Queue are two of the important data structures in the programming world and have a variety of usage. As opposed to the array and linked list, which are considered primary data structures, they are secondary data structures that can build using an array or linked list. You can use Stack to solve recursive problems and Queue can be used for ordered processing. The difference between Stack and Queue Data structure is also one of the common questions not only in Java interviews but also in C, C++, and other programming job interviews.

Difference between Comparison (QuickSort) and Non-Comparison (Counting Sort) based Sorting Algorithms? Example

For many of you, this might be a surprise that how you can sort or arrange items without comparing them with each other, but it's possible. There are some sorting algorithms that perform sorting without comparing the elements rather than making certain assumptions about the data they are going to sort. The process is known as non-comparison sorting and algorithms are known as the non-comparison-based sorting algorithms. Non-comparison sorting algorithms include Counting sort which sorts using key-value, Radix sort, which examines individual bits of keys, and Bucket Sort which examines bits of keys. 

How to implement Post Order Traversal of Binary Tree in Java - Recursion and Iteration Example

This is the third article on tree traversal. In the last couple of articles, I have shown you how to implement preorder and inorder traversal in Java, both recursively and iteratively and today, you will learn about the post-order traversal. Out of these three main tree traversal algorithms, the post-order traversal is most difficult to implement, especially the iterative version. In postorder traversal, you first visit left subtree, then right subtree and at last you print the value of root or not. So, the value of root is always printed at last in the post-order traversal.

How to Implement Binary Search Tree in Java? Example

A binary search tree or BST is a popular data structure that is used to keep elements in order. A binary search tree is a binary tree where the value of a left child is less than or equal to the parent node and the value of the right child is greater than or equal to the parent node. Since it's a binary tree, it can only have 0, 1, or two children. What makes a binary search tree special is its ability to reduce the time complexity of fundamental operations like add, remove, and search, also known as insert, delete and find. In a BST, all these operations (insert, remove, and find) can be performed in O(log(n)) time.

Friday, June 27, 2025

How to Compare Arrays in Java – Equals vs deepEquals Example

java.util.Arrays class provides equals() and deepEquals() method to compare two Arrays in Java. Both of these are overloaded methods to compare primitive arrays e.g. int, long, float, double, and Object arrays e.g. Arrays.equals(Object[], Object[]). Arrays.equals() returns true if both Arrays which it is comparing are null If both arrays pointing to the same Array Object or they must be of the same length and contains the same element in each index. In all other cases, it returns false. Arrays.equals() calls equals() method of each Object while comparing Object arrays.

Recursion in Java with Example – Programming Tutorial for Beginners

Recursion is one of the tough programming techniques to master. Many programmers working on both Java and other programming languages like C or C++ struggles to think recursively and figure out the recursive pattern in the problem statement, which makes it is one of the favorite topics of any programming interview. If you are new to Java or just started learning Java programming language and you are looking for some exercise to learn the concept of recursion then this tutorial is for you. 

3 Examples to Print Array Elements/Values in Java - toString and deepToString from Arrays

Printing array values in Java or values of an array element in Java would have been much easier if  arrays are allowed to directly prints its values whenever used inside System.out.println() or format and printf method, Similar to various classes in Java do this by overriding toString() method. Despite being an object, array in Java doesn't print any meaningful representation of its content when passed to System.out.println() or any other print methods. If you are using array in method argument or any other prominent place in code and actually interested in values of an array then you don't have much choice than for loop until Java 1.4.

Iterative QuickSort Example in Java - without Recursion

The quicksort algorithm is one of the important sorting algorithms. Similar to merge sort, quicksort also uses divide-and-conquer hence it's easy to implement a quicksort algorithm using recursion in Java, but it's slightly more difficult to write an iterative version of quicksort. That's why Interviewers are now asking to implement Quicksort without using recursion. The interview will start with something like writing a program to sort an array using a quicksort algorithm in Java and most likely you will come up with a recursive implementation of quicksort as shown here. As a  follow-up, the Interviewer will now ask you to code the same algorithm using Iteration.

4 Ways to Search Java Array to Find an Element or Object - Tutorial Example

Searching in Java Array sounds familiar? should be,  because it's one of the frequently used operations in Java programming. The array is an index-based data structure that is used to store elements but unlike Collection classes like ArrayList or HashSet which has contains() method, the array in Java doesn't have any method to check whether an element is inside an array or not. Java programming language provides several ways to search any element in the Java array

How to loop over two dimensional array in Java? Example

You can loop over a two-dimensional array in Java by using two for loops, also known as nested loop. Similarly to loop an n-dimensional array you need n loops nested into each other. Though it's not common to see an array of more than 3 dimensions and 2D arrays is what you will see in most of the places. It's one of the most useful data structures in the programming world. You can use a two-dimensional array to make finite state machine (FSM) solve state-based problems, you can use a 2D array to create board games like Chess, Sudoku, and Tic-Tac-To and you can even use a two-dimensional array to create 2D arcade games e.g. Tetris, Super Mario Bros and so on. Whatever you see on your screen is nothing but a 2D array that is populated using tiles.

2 Examples to Convert Byte[] Array to String in Java

Converting a byte array to String seems easy but what is difficult is, doing it correctly. Many programmers make the mistake of ignoring character encoding whenever bytes are converted into a String or char or vice versa. As a programmer, we all know that computer's only understand binary data i.e. 0 and 1. All things we see and use like images, text files, movies, or any other multi-media are stored in form of bytes, but what is more important is the process of encoding or decoding bytes to a character. Data conversion is an important topic in any programming interview, and because of the trickiness of character encoding, this question is one of the most popular String Interview questions on Java Interviews.

How to Fix Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: in Java? Solution

If you are coming from C background than there is a pleasant surprise for you, Java programming language provides implicit bound checks on Array, which means an invalid array index access is not allowed in Java and it will result in java.lang.ArrayIndexOutOfBoundsException. An array is one of the most used data structures across all programming language and it’s no different in Java. In fact, Java API has used an array to build several useful data structures e.g. HashMap and ArrayList. These classes also throw IndexOutOfBoundsException if an invalid index is supplied to their get(int index) methods. One of the common mistakes Java programmer makes is invalid end condition on classical index-based for loops.

Thursday, June 26, 2025

How to remove all special characters from String in Java? Example Tutorial

You can use a regular expression and replaceAll() method of java.lang.String class to remove all special characters from String. A special character is nothing but characters like - ! #, %, etc. Precisely, you need to define what is a special character for you. Once you define that you can use a regular expression to replace those characters with empty String, which is equivalent to removing all special characters from String. For example, suppose, your String contains some special characters e.g. "Awesome!!!" and you want to remove those !!! to reduce some excitement, you can use replaceAll("!", "") to get rid of all exclamation marks from String.

StringTokenizer Example in Java with Multiple Delimiters - Example Tutorial

StringTokenizer is a legacy class for splitting strings into tokens. In order to break String into tokens, you need to create a StringTokenizer object and provide a delimiter for splitting strings into tokens. You can pass multiple delimiters e.g. you can break String into tokens by, and: at the same time. If you don't provide any delimiter then by default it will use white-space. It's inferior to split() as it doesn't support regular expression, also it is not very efficient. Since it’s an obsolete class, don't expect any performance improvement either. On the hand split() has gone some major performance boost on Java 7, see here to learn more about splitting String with regular expression.

How to replace a substring in Java? String replace() method Example Tutorial

You can replace a substring using replace() method in Java. The String class provides the overloaded version of the replace() method, but you need to use the replace(CharSequence target, CharSequence replacement). This version of the replace() method replaces each substring of this string (on which you call the replace() method) that matches the literal target sequence with the specified literal replacement sequence. For example, if you call "Effective Java".replace("Effective", "Head First") then it will replace "Effective" with "Head First" in the String "Effective Java". Since String is Immutable in Java, this call will produce a new String "Head First Java".

How to check if String contains another SubString in Java? contains() and indexOf() example

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1. For example "fastfood".indexOf("food") will return 4 but "fastfood".indexOf("Pizza") will return -1. This is the easiest way to test if one String contains another substring or not.

How to check if a String is numeric in Java? Use isNumeric() or isNumber() Example

In day-to-day programming, you often need to check if a given string is numeric or not. It's also a good interview question but that's a separate topic of discussion. Even though you can use Regular expression to check if the given String is empty or not, as shown here, they are not full proof to handle all kinds of scenarios, which common third-party libraries like Apache commons-lang will handle e.g. hexadecimal and octal String. Hence, In the Java application, the simplest way to determine if a String is a number or not is by using the Apache Commons lang's isNumber() method, which checks whether the String is a valid number in Java or not.

How to split String in Java by WhiteSpace or tabs? Example Tutorial

You can split a String by whitespaces or tabs in Java by using the split() method of java.lang.String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces. Though this is not as straightforward as it seems, especially if you are not coding in Java regularly. Input String may contain leading and trailing spaces, it may contain multiple white spaces between words and words may also be separated by tabs. Your solution needs to take care of all these conditions if you just want words and no empty String.

Java String Replace Example Tutorial

This String replace example in Java will show you how to replace String in Java both at the character level and by using regular expression. Since String is final in Java every time you replace String you will get a new String object only if your actually replace anything on original String otherwise replace methods of String return same String object. String Class in Java provides 4 methods to replace String in Java. Those methods allow you to replace character from String, replace CharacterSequence from String, replace all occurrence of pattern in String or just first occurrence of any pattern in Java.

How SubString method works in Java - Memory Leak Fixed in JDK 1.7

Substring method from the String class is one of the most used methods in Java, and it's also part of an interesting String interview question e.g. How substring works in Java or sometimes asked as to how does substring creates memory leak in Java. In order to answer these questions, your knowledge of implementation details is required. Recently one of my friends was drilled on the substring method in Java during a Java interview, he was using the substring() method for a long time, and of course, all of us has used this, but what surprises him was the interviewer's obsession on Java substring, and deep-dive till the implementation level.

How to use String in switch case in Java with Example

Have you ever feel that String should be used in switch cases like int and char? JDK 7 has made an important enhancement in their support of String, now you can use String in switch and case statements, No doubt String is the most widely used type in Java, and in my opinion, they should have made this enhancement long back when they provided support for enum in java and allowed enum to be used in a switch statement. 

How to String Split Example in Java - Tutorial

Java String Split Example
I don't know how many times I needed to Split a String in Java. Splitting a delimited String is a very common operation given various data sources e.g CSV file which contains input string in the form of large String separated by the comma. Splitting is necessary and Java API has great support for it. Java provides two convenience methods to split strings first within the java.lang.String class itself: split (regex) and other in java.util.StringTokenizer. Both are capable of splitting the string by any delimiter provided to them. Since String is final in Java every split-ed String is a new String in Java.

How to convert String or char to ASCII values in Java - Example Tutorial

You can convert a character like 'A' to its corresponding ASCII value 65 by just storing it into a numeric data type like byte, int, or long as shown below :

int asciiOfA = (int) 'A';

Here casting is not necessary, simply assigning a character to an integer is enough to store the ASCII value of character into an int variable, but casting improves readability. 

Since ASCII is a 7-bit character encoding, you don't even need an integer variable to store ASCII values, byte data type in Java, which is 8 bits wide is enough to store the ASCII value of any character.  So you can also do like this :
byte asciiOfB = 'B'; // assign 66 to variable

How to format String in Java – String format Example

String format and printf Example
How to format String in Java is the most common problem developers encounter because of classic System.out.println() doesn’t support formatting of String while printing on console. For those who don’t know What is formatted String? here is a simple definition,  Formatted String is a String that not only displays contents but also displays it in a format that is widely accepted like including comma while displaying large numbers e.g. 100,000,000, etc. Displaying formatted String is one of the needs for modern GUI applications and thankfully Java has good support for formatting String and all other types like Integers, Double, and Date

How String in Switch works in Java? Example

Ever Since Java allows using String variables in switch and case statements, there are many programmers using this feature in code, which can be better written using integer and enum patterns. This was one of the popular features of the JDK 7 release, including automatic resource management and multi-exception catch blocks. Though I upfront didn't like this feature because of the better alternatives available in terms of using the enumeration type, I am not totally against this feature. One reason for this is convenience and given usage of String in Java program, it's quite handy as well, but I prefer to learn more before using any new feature in production code.