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.

10 Things Every Java Programmer Should Know about String

String in Java is a very special class and the most frequently used class as well. There are lot many more things to learn about String in Java than any other class, and having a good knowledge of different String functionalities makes you use it properly. Given the heavy use of Java String in almost any kind of project, it becomes even more important to know subtle detail about String. Though I have shared a lot of String related articles already here in Javarevisited, this is an effort to bring some of the String features together. 

How to Split String based on delimiter in Java? Example Tutorial

You can use the split() method of String class from JDK to split a String based on a delimiter e.g. splitting a comma-separated String on a comma, breaking a pipe-delimited String on a pipe, or splitting a pipe-delimited String on a pipe. It's very similar to earlier examples where you have learned how to split String in Java. The only point which is important to remember is little bit of knowledge of regular expression, especially when the delimiter is also a special character in regular expression e.g. pipe (|) or dot (.), as seen in how to split String by dot in Java. In those cases, you need to escape these characters e.g. instead of |, you need to pass \\| to the split method.

String replaceAll() example - How to replace all characters and substring from String

You can replace all occurrence of a single character, or a substring of a given String in Java using the replaceAll() method of java.lang.String class. This method also allows you to specify the target substring using the regular expression, which means you can use this to remove all white space from String. The replaceAll() function is a very useful, versatile, and powerful method and as a Java developer, you must know about it. Even though Java provides separate methods for replacing characters and replacing substring, you can do all that just by using this single method.

Wednesday, June 25, 2025

Why character array is better than String for Storing password in Java? Example

Why character array is better than String for storing a password in Java was a recent question asked to one of my friends in a java interview. he was interviewing for a Technical lead position and has over 6 years of experience. Both Character array and String can be used to store text data but choosing one over the other is a difficult question if you haven't faced the situation already. But as my friend said any question related to String must have a clue on a special property of Strings like immutability and he used that to convince the interviewer. here we will explore some reasons why should you use char[] for storing passwords than String.

How to Compare Two Strings Without Case Sensitivity in Java? Example

How to Compare Two Strings Without Case Sensitivity in Java

Java provides several ways to compare strings without taking case sensitivity into account. In this article, we'll explore different methods to perform case-insensitive string comparisons in Java.

Method Use Case Efficiency
equalsIgnoreCase() Checking equality High
compareToIgnoreCase() Ordering comparison High
String.CASE_INSENSITIVE_ORDER Sorting collections High
equals() + toUpperCase() Not recommended Low

1. Using equalsIgnoreCase()

The equalsIgnoreCase() method

This method is ideal for checking if two strings are equal without considering their case. It returns true if both strings contain the same characters, regardless of their case.

String str1 = "Hello";
String str2 = "hello";
boolean isEqual = str1.equalsIgnoreCase(str2); // Returns true

2. Using compareToIgnoreCase()

The compareToIgnoreCase() method

Use this method when you want to check which string is greater or smaller, or to find out their relative ordering in lexicographical or alphabetical order, without considering case.

String str1 = "Apple";
String str2 = "banana";
int result = str1.compareToIgnoreCase(str2); // Returns a negative value

3. Using String.CASE_INSENSITIVE_ORDER

The String.CASE_INSENSITIVE_ORDER comparator

This comparator is useful for sorting a list of strings in case-insensitive order.

List<String> fruits = Arrays.asList("Apple", "banana", "Cherry");
Collections.sort(fruits, String.CASE_INSENSITIVE_ORDER);
// Result: [Apple, banana, Cherry]

4. Using equals() + toUpperCase()

Combining equals() and toUpperCase()

This is a tricky way to compare two strings in Java in a case-insensitive manner. First, convert both strings to uppercase, then compare them using equals().

String str1 = "Hello";
String str2 = "hello";
boolean isEqual = str1.toUpperCase().equals(str2.toUpperCase()); // Returns true

Note: This method is not recommended as it creates new String objects, which can be inefficient for large-scale comparisons.

Conclusion

When comparing strings without case sensitivity in Java, it's generally best to use the built-in methods like equalsIgnoreCase() for equality checks and compareToIgnoreCase() for ordering comparisons. 

These methods are optimized and provide clear, readable code. For sorting collections of strings, the String.CASE_INSENSITIVE_ORDER comparator is an excellent choice.

Remember, all these methods compare strings in lexicographical order. Choose the method that best fits your specific use case to ensure efficient and accurate string comparisons in your Java applications.

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. 

Difference in String pool between Java 6 and 7? Answer

String pool in Java is a pool of String literals and interned Strings in JVM for efficient use of String objects. Since String is immutable in Java, it makes sense to cache and shares them in JVM. The String pool has gone through an important change in Java 7 release when it was relocated from PermGen space to heap space. Till Java 1.6, interned String and literals are stored in the PermGen space of JVM memory, which was a fixed size area for storing class metadata. The biggest issue of having a String pool in PermGen is the small and fixed size of PermGen space.

10 Difference between StringBuffer and StringBuilder in Java? [Answered]

Both StringBuffer and StringBuilder are two important classes in Java which represent mutable String i.e. the String object, whose value can be changed. Since String is Immutable in Java, any change or operation on String object e.g. converting it to upper or lower case, adding character, removing a character, or getting a substring, all results in a new String object. This can put a lot of pressure on the Garbage collector if your application generates lots of throws away String instances. To avoid this issue, Java designer presented initially StringBuffer class and later StringBuilder as mutable String. That's the main difference between String vs StringBuffer and StringBuilder and also one of the frequently asked Java questions for beginners.

How to Convert and Print Byte array to Hex String in Java? Example

We often need to convert byte arrays to Hex String in Java, In order to print byte array contents in a readable format. Since many cryptographic algorithms e.g. MD5 return the hash value as a byte array, In order to see and compare that byte array, you need to convert the byte array to Hex String. As we have seen, while generating MD5 checksum of File, there are multiple ways to convert byte array to Hexadecimal String in Java. You can either write your own method, or you can use an open-source library e.g. Apache commons-codec to create Hex String from a byte array in Java. Commons codec provides a utility class Hex, which contains an encodeHexString() method to create Hex String from a byte array.

StringJoiner.join() and String.join() Example in Java 8

Hello guys, joining multiple String literals or objects into one is a common programming requirement and you will often find situations where you need to convert a list of String or a Collection of String into a CSV String for your application. For a long time, JDK API has no way to join multiple String literals or objects together, which forces programmers to write hacks like looping through all String objects and manually joining them using String concatenation to create the final, joined String. Even though this approach worked, it was filled with errors and hacks like you need to be careful not to add delimiter before the first element and after the last element, which often caused issues, particularly in the case of beginners and junior Java developers.

3 ways to convert String to Boolean in Java? Examples

Hello guys, if you ar wondering how to convert a String object to boolean value in Java then don't sweat there are multiple ways to convert a String to Boolean class or boolean value in Java. For Example, ou can convert a String object to a Boolean object or boolean primitive by using the Boolean.valueOf() and Boolean.parseBoolean() method. The steps are similar rot converting to String to other data types  like String to Integer and String to Long. You can use the valueOf() method to convert String to Boolean object and parseBoolean() method to convert a given string to a boolean primitive value. 

Tuesday, June 24, 2025

Top 15 Java String interview Question Answers for 3 to 5 Years Experienced

10 Java String interviews Question answers
String interview questions in Java is one of Integral part of any Core Java or J2EE interviews. No one can deny the importance of String and how much it is used in any Java application irrespective of whether it's core Java desktop application, web application, Enterprise application or Mobile application. The string is one of the fundamentals of Java programming language and correct understanding of String class is a must for every Java programmer. What makes String interview questions in Java even more interesting is the special status of String in terms of features and privileges it has like the + operator is kind of overloaded to perform String concatenation despite the fact that Java does not support operator overloading. There is a separate String pool to store String literal etc.

How to compare two String in Java - String Comparison Example

String comparison is a common programming task and Java provides several way to compare two String in Java. String is a special class in Java, String is immutable and It’s used a lot in every single Java program starting from simple test to enterprise Java application. In this Java String compare tutorial we will see different ways to compare two String in Java and find out how they compare String and when to use equals() or compareTo() for comparison etc.

Here are four examples of comparing String in Java
1) String comparison using equals method
2) String comparison using equalsIgnoreCase method
2) String comparison using compareTo method
4) String comparison using compareToIgnoreCase method

How to Remove First and Last Character of String in Java - Example Tutorial

You can use the substring() method of java.lang.String class to remove the first or last character of String in Java. The substring() method is overloaded and provides a couple of versions that allows you to remove a character from any position in Java. Alternatively, you can convert String to StringBuffer or StringBuilder and then use its remove() method to remove the first or last character. Both StringBuffer and StringBuilder provides a convenient deleteCharAt(int index) method which removes a character from the corresponding index. You can use this method to remove both first and last characters from String in Java.

How to get first and last character of String in Java - Example

You can get the first and last character of a String using the charAt() method in Java. This method accepts an integer index and returns the corresponding character from String. Since Java String is backed by an array, their index is also zero-based, which means the first character resides at index zero, and the last character is at index, length-1, where length is the number of characters in the String. You can get the length of the String by calling the length() method. The charAt() method is not defined on java.lang.String class, but on its super interface java.lang.CharSequence, hence it will also work for StringBuffer and StringBuilder.

How to check if String is not null and empty in Java? Example

In Java, since null and empty are two different concepts, it's a little bit tricky for beginners to check if a String is both not null and not empty. A String reference variable points to null if it has not been initialized and an empty String is a String without any character or a string of zero length. Remember, a String with just whitespace may not be considered as empty String by one program but considered as empty String by others, so, depending upon your situation, you can include the logic to check for that as well. A String with just white space is also referred to as a blank String in java. In this tutorial, I will teach you a couple of right ways to test if a String is not null and not empty in Java.

When to use intern() method of String in Java? Example

The String.intern() method can be used to deal with the String duplication problem in Java. By carefully using the intern() means you can save a lot of heap memory consumed by duplicate String objects. A String object is said to be duplicated if it contains the same content as another string but occupied a different memory location e.g. str1 != str2 but str1.equals(str2) is true. Since the String object consumes a large amount of heap memory in the average Java application, it makes sense to use the intern() method to reduce duplication and take advantage of the String pool feature provided by Java. You can use the intern() method to intern a String object and store them into the String pool for further reuse.

How to split a comma separated String in Java? Regular Expression Example

You can use the String.split() function or StringTokenizer class to split a comma-separated String in Java. Since splitting a String is a very common functionality, Java designers have provided a couple of split() methods on java.lang.String class itself. These split() function takes a regular expression and split the String accordingly. In order to parse a comma-delimited String, you can just provide a "," as a delimiter and it will return an array of String containing individual values. The split() function internally uses Java's regular expression API (java.util.regex) to do its job.

Why String is Immutable or Final in Java? Explained

The string is Immutable in Java because String objects are cached in the String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client's action would affect all other clients. For example, if one client changes the value of the String "Test" to "TEST", all other clients will also see that value as explained in the first example. Since caching of String objects was important for performance reasons this risk was avoided by making the String class Immutable. At the same time, String was made final so that no one can compromise invariant of String class like Immutability, Caching, hashcode calculation, etc by extending and overriding behaviors. Another reason why the String class is immutable could die due to HashMap.

Sunday, June 22, 2025

How to Convert an Array to Comma Separated String in Java - Example Tutorial

The simplest way to convert an array to comma separated String is to create a StringBuilder, iterate through the array, and add each element of the array into StringBuilder after appending the comma. You just need Java 1.5 for that, even if you are not running on Java 5, you can use StringBuffer in place of StringBuilder. The joining of String has got even easier in JDK 8, where you have got the join() method right in the String class itself. The join() method takes a delimiter and a source, which can be an array or collection, and returns a String where each element is joined by a delimiter.

Friday, June 20, 2025

Top 10 Low Latency Tips for Experienced Java Developers

Hello guys, If you are preparing for interviews at High-Frequency Trading (HFT) firms, hedge funds, investment banks, or crypto exchanges, then one thing is guaranteed: You will be asked about low latency systems. Building such systems is a completely different ball game. It’s not just about writing clean code — it's about writing fast code that responds in microseconds. I’ve worked on low-latency Java applications that run in production under tight time constraints, and in this post, I’ll share what I’ve learned in easy Indian English, with some practical examples.

Thursday, June 12, 2025

Difference between Stack and Heap memory in Java? Example

The difference between stack and heap memory is a common programming question asked by beginners learning Java or any other programming language. Stack and heap memory are two terms programmers start hearing once they started programming but without any clear and definite explanation. Lack of knowledge of what is a heap in Java and what is stack memory in Java results in misconceptions related to stack and heap. To add to this confusion, a stack is also a data structure that is used to store elements in LIFO(Last In First Out) order and is available in Java API as java.util.Stack.

What is load-on-startup servlet element in web.xml with Example?

load-on-startup is an element that appears inside <servlet> tag in web.xml.4 years back load-on-startup was a very popular servlet interview question because not many Java J2EE developer was familiar with this element and how load-on-startup works inside a servlet container like tomcat or WebSphere. In this J2EE Tutorial, we will see what is a load on startup, how to use the load-on-startup element, and what are different values we can configure for load-On-Startup inside web.xml.

Difference between SendRedirect() and Forward() in JSP Servlet? Example

The difference between SendRedirect and forward is one of the classical interview questions asked during a java web developer interview. This is not just applicable for servlet but also for JSP in which we can use forward action or call sendRedirect() method from scriptlet. Before examining the difference between forward and SendRedirect let’s see what send Redirect method and the forward method does.

SendRedirect ():  

This method is declared in HttpServletResponse Interface.

Signature: void sendRedirect(String url)

Difference between throw and throws in Exception handling - Java Example

Difference between throw and throws keyword on Exception handling in Java is a popular core java interview question. Exception handling being an important part of Java programming language, complete knowledge of all keywords related to exception handling e.g. try, catch, finally, throw and throws is important. Main difference between throw and throws is in there usage and functionality. where throws is used in method signature to declare Exception possibly thrown by any method, throw is actually used to throw Exception in Java code, here is an example of both throw and throws keyword which makes it easy to understand difference between them.