Java Program to Find Whether the given words are Anagram or Not

Anagrams as you might already know, are the words or phrase formed by rearranging the letters of another word. For example: angel and glean or stain and satin.

Well, my description of what the anagrams are ends here as this is not an English grammar tutorial site. What I am more interested in writing out a piece of code to which we can pass the words and can get know whether the words were anagram or not. Well, this is what the solo purpose of this tutorial at least. May be you'd asked such a question somewhere someday, may be in some interview or some coding test, so I just thought to post this here. 

So, how do we proceed? Java is such a powerful programming language that using the provided library methods, you might be able to do this in no more than couple of lines of code. Great if you can! But having faced enough number of interviews to assure you of that, the interviewer in most cases, are not that interested in knowing how good you're at memorizing the method and class names but how quickly your brain can find out a solution to the given problem and your approach. So, the chances are that the Java programming interview questions that you'd be asked would expect you to solve the problem without relying much upon the library methods.
Well, we'll do it both ways and we'll just take two words as the input to our method. You can easily extend the code to include more. (var-args might be of some help!)

Using the library methods

This just makes it ridiculously easy! We will be just reading the  given strings, sorting them using Arrays.sort() and then comparing the sorted strings. If the sorted strings are equal then the words were anagrams. Simple! Because the anagrams as already stated are the words formed by rearranging the words in hand. 

Without using the library methods

Without using the library methods also does not make it any less simpler. We can just first read the two strings, check for their same lengths, take one string character by character and search the other for each characters. And if all characters are found from one string are found in another then the two strings are anagrams because they were of same length. 

So, enough of the text, now the program!

Java program to check whether the two strings are anagram or not

import java.util.Arrays;
import java.util.Scanner;

public class AnagramDemo {

 // method to check for the anagrams using built-in methods
 public static boolean isAnagram(String str1, String str2) {

  char[] charArr1 = str1.toCharArray();
  char[] charArr2 = str2.toCharArray();

  // performing sorting of string

  return Arrays.equals(charArr1, charArr2);

 // method to check for the anagrams without using library methods
 public static boolean isAnagramManual(String str1, String str2) {
  // if length itself not equal, return false.
  if (str1.length() != str2.length())
   return false;
  // else do the brainstorming!
  boolean anagram = true;

  for (int i = 0; i < str1.length(); i++) {
   if (str2.indexOf(str1.charAt(i)) == -1)
    anagram = false;

  return anagram;

 public static void main(String[] args) {

  System.out.println("First string");
  Scanner sc = new Scanner(;
  String str1 = sc.nextLine();
  System.out.println("Second string");
  String str2 = sc.nextLine();
  System.out.println("Using library methods:-");
  if (isAnagram(str1, str2))
   System.out.println(str1 + " and " + str2 + " are anagrams!");
   System.out.println(str1 + " and " + str2 + " are NOT anagrams!");

  System.out.println("WITHOUT USING LIBRARY METHODS");
  if (isAnagramManual(str1, str2))
   System.out.println("NOT ANAGRAMS");



I hope that you find it useful. In case you find any mistakes or the better way of doing it, please write in comments.
In case you have any other Java related question or problem that you want me to write code for, please let me know in comments or mail me

Program to check if Least Significant Bit for a number is set or not

In Binary number representation of a number, the rightmost bit (or digit) is called the Least Significant Bit (LSB) and the leftmost bit is called the Most Significant Bit (MSB). As we know while converting a binary representation of a number back to its decimal system representation, we calculate the decimal representation by multiplying the LSB by 20 and then increasing the power of 2 from 0 by 1 on each bit as we go from LSB to MSB.
For example: Suppose we have a binary number: 11001
It's decimal equivalent will be: 1*24 + 1*23 + 0*22 + 0*21 + 1*20 = 25
Let us take another example:
Binary number: 11100
It's decimal equivalent will be: 1*24 + 1*23 + 1*22 + 0*21 + 0*20 = 28

Thing to note from the above discussion

Sometimes in the interviews you do not get the questions directly and to even understand the question properly, you need to have a careful look at the question statement. 
Suppose, like in this case, you are asked to write a program to check if the Least Significant Bit of a number is set or not (And you can not make use of the % and / operators. 
Here in this question, if you did not get what the interviewer is expecting from you, you might end up wasting a lot of time calculating the binary equivalent of the number and then manually checking the value of its LSB. But thankfully, this is not what this questions expects you to do. Let us go back to the first section of the post where we discussed in brief about the binary to decimal conversions. The one and only thing I wanted you to notice from the above discussion is that, for even numbers, the LSB is not set and for odd, the LSB is always set. 
Now understanding this simple logic can save you a lot of efforts in your interviews and coding competitions. Now you would have understood why the examiner has denied you the use of '%' and '/' operators. So, you are basically assigned a challenge of finding whether a given number is odd or even without using the '%' and '/' operators
There might be many approaches to do that, I will just implement only one in the below Java program method. The method will simply take the input number and return true or false based on whether the LSB is set or not.

public boolean isLSBSet(int number) {

  String num = Integer.toString( number );
  int lastDigit = num.length() - 1;
  //Only for odd numbers, the Least Significant Bit will be set.
  if (num.charAt(lastDigit) == '1' || num.charAt(lastDigit) == '3'
    || num.charAt(lastDigit) == '5' || num.charAt(lastDigit) == '7'
    || num.charAt(lastDigit) == '9')
   return true;
   return false;

We thank DJ Spiess for his tip! The whole above code now can be reduced to one line.

return (number ^ (number - 1)) == 1;
So, Kudos! We now know How to check if number is even or odd without using the modulus '%' or '/' operator. Keep sharing such tips to the community and help us all learn Java in a simple and fun way! :)

Java Program to find occurrence of a pattern in String with (and without) String methods

Finding patterns in the String : The problem description

Today, I will be writing a program to print the occurrence of a String pattern in the given input String in two ways: one using the String substring() method (which will make the task very easy) and second without using the substring() method (similar but need to do the substring calculation and comparison manually).
The scenario is we have an input String of characters and we want to find the occurrences of some pattern (which will of course be the substring of the input string). 
For example:- 
Patter String: "JAVA"
Occurrence: 2

Logic for finding the pattern occurrences in the String

We will go for the simple and straightforward logic. And that is, we will be finding all the sub-strings of length equal to the length of the pattern we are looking for. And then from those list of sub-strings, we will pick sub-strings one by one and compare it against the patter string. Whenever the match happens, we will increment the occurrence count. So, the main task here seems to be just finding all the sub-strings of length L equal to the length of pattern string. The rest part is just comparison with the pattern and counting the occurrences. 

Using String substring() method

Using the String utility method substring() for finding the sub-strings makes this task extremely easy and straightforward. Below is the method that takes the input string and pattern string and return the number of occurrences of pattern in input string. 
public int countOccurenceOfPattern(String input, String pattern) {
  int inputLength = input.length();
  int patternLength = pattern.length();
  int occurrence = 0;

  // Using String methods. In this case we'll need only substring()
  for (int i = 0; i < (inputLength - patternLength); i++) {
   if ((input.substring(i, i + patternLength)).equals(pattern))

  return occurrence;

Without using the substring() method

Well, here is when we will have to do a bit of logic building and do the things manually. Well this doesn't complicate the code much and is still very straightforward. We will be creating the substrings of length L equal to length of pattern manually iterating through the two loops and comparing the each substring with the pattern string. Below is the previous method re-written to achieve the same objective without using the substring() method.
public int countOccurenceOfPattern(String input, String pattern) {
  int inputLength = input.length();
  int patternLength = pattern.length();
  int occurrence = 0;

  // Without using substring()
  // In that we will be required to do a bit of logic building ourself.
  String temp = "";

  for (int i = 0; i < (inputLength - patternLength); i++) {
   temp = "";
   for (int j = i; j < (i + patternLength); j++) {
    temp = temp + Character.toString(input.charAt(j));
   if (temp.equals(pattern))

  return occurrence;

Circular Shifting of elements in Arrays - Java program to shift array elements circularly

What do we mean by shifting the elements of an array

Many a times in our programs, we need to shift the elements of our array either to the left or to the right. For example, while dynamically adding any new element in between the existing elements of an array, we will be right shifting the elements after the inserted position. Similarly, we will do a left shift of the elements when we remove an element.

Circular Shifting in Arrays  - Right Circular Shift and Left Circular Shift

As we are now familiar with what we mean by shifting the array elements, the term circular adds a little more complexity to the otherwise a simple process of shifting elements of arrays to the left or right. 

Left Circular Shifting of Array Elements: In left circular shifting of array elements by N positions, we will take the first N elements starting from the left most side of the array and start placing them from the rear of the array in the same order as we took out them from the front of array. 
for example: 
Suppose we have an input array like this:
10, 20, 30, 40, 50
After left circular shift by 2 positions, the array would become:-
30, 40, 50, 10, 20

Right Circular Shifting of Array Elements: The Right circular shifting of arrays is exactly opposite to that of the Left circular shifting. In this we will be taking out the N elements from the rear of the array and will be inserting them to the front of the array. The below example would help us to understand this much easily.
for example:-
We have an input array: 10, 20, 30, 40, 50
After right circular shift by 2 positions: 40, 50, 10, 20, 30

Java Program to print only the unique elements from the String array without using Collections

In Java, you'll rarely be writing a program without using the arrays. As the arrays put no limitations on what type of elements you can put in them or do not provide any means to check for the duplicates, there might be some scenarios wherein you might need only the distinct elements from the array instead of all its elements.
Suppose we have an array of Strings and we need only the distinct strings out from that array. Obviously, the same task can be done conveniently using Collections API but there might be cases where you'll be just better off not requiring to put any overhead of using the Collections classes such as Sets in this case. Or if this does not convince you, knowing how to do this without using the Collections will still be worth learning if you're going to appear in some interviews or for some coding competitions. As I have repeatedly mentioned in my posts that Java programming questions on Strings are among the hot favorite for interviewers, so I'll be posting many more such String based java programming questions in my future posts.

Java Program to find only distinct elements of String Array without using Collections

public class CodeInJava {

 public static void main(String[] args) {
  //Input array
  String str[] = {"Java","Struts2","Java","Spring3","C++","Python","Java"};
  //Creating new array to store only the unique elements
  String[] uniqueArray = new String[str.length];
  //copying the first element directly to uniqueArray
  uniqueArray[0] = str[0];
  //Counter to keep track of the index to put next value at in uniqueArray
  int counter = 1;
  boolean flag = false;
  for(int i = 1;i < str.length;i++) {
   flag = false;
   for (int j = 0;j < i;j++) {
    if(uniqueArray[j] == null)
    //comparing in case-insensitive manner.
    //In case you need to find unique in case sensitive manner, use equals() only
    else if( str[i].equalsIgnoreCase( uniqueArray[j] ) )
     flag = true;
   if( !flag ) {
    uniqueArray[counter] = str[i];
  //Printing the unique elements. Counter stores the number of unique elements in the original array.
  for (int i = 0; i < counter; i++)