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

5:59 PM 33 Comments A+ a-

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

7:10 PM 1 Comments A+ a-

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

6:21 PM 4 Comments A+ a-

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

9:20 PM 3 Comments A+ a-

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

7:41 PM 2 Comments A+ a-

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++) 



Java program to convert String into Integer without Integer.parseInt()

12:12 PM 1 Comments A+ a-

Although Java SDK provides you with convenient methods to convert the compatible data from one data types to another, but sometimes in interviews and other coding competitions you are also supposed to know how to do those conversions without those built-in methods provided by Java SDK itself. In one such case, one of the most common thing in your java code is to convert the string representation of any number back to native int or Integer data type in Java. Although there is a simple method Integer.parseInt(String num) that you can use to get the string num in int format, but in case you need to do that stuff manually, this post will show you how to do that.

Logic building and approach

We will be first reading the string backwards character by character looking for the digit characters only. Till we keep getting the digit characters, we will use those to formulate our number by using the digits and increment the factor by 10 in each step.
We are simply ignoring the non-digit characters here or otherwise in we want, we can convert each character to its number representation, but I don't think that's what we need. And finally, we will also take care of negative numbers as well. For that we will check for the "-" in the very first place in the String input, if it is "-" then we will make the number negative.

Java Program to Manually convert string to int without Integer.parseInt() method

Below is the simple Java method that takes a String str as input and return the int representation of its digits only. 
For example:-
"1263*67%" will return 126367
"a76dsb6l7" will return 76617
"-78fjkd7439" will return -78439
"289289" will return 289289

public int stringToInt(String str) {
  int number = 0, factor = 1; 
  boolean negative = false;
  for (int i = str.length() - 1;i >= 0;i--) {
   //check if the very first character has '-', then the result must be negative
   if((i == 0) && (str.charAt(i) == '-')) {
    negative = true;
   //if the string has any non-number characters, continue with the next character ignoring the current one
   else if("0123456789".indexOf( str.charAt(i) ) == -1) {
   number+= (str.charAt(i) - '0') * factor;
   factor*= 10;
   return -number;
  return number;

There might be many other methods to achieve this as well. For instance, we could have used the static methods of Character class such as isDigit() to check for whether the characters are digits or not. In fact, this whole program could have been done using the static methods of Character class. You may want to give it a try!

Java program to reverse a string word by word

9:04 PM 4 Comments A+ a-

Program to reverse a String word by word in Java

String based programming questions are among the most asked questions in the Java interviews for the freshers as well as the experienced Java developers and Software engineers. And reversing a string word by word or characters by characters is very likely to be asked in any Java technical interview. In this post, I will be writing a program for the former i.e. for reversing a Java String word by word
For example:- 
Input String: Code In Java
Output String: Java In Code

There might be many approaches for solving this and you may want to choose based on your liking and its simplicity. 

Below is a Java program to reverse a String word by word.

public class ReverseString {

 public static void main(String[] args) {
  //Input String
  String str = "Code in Java - Programming in Java Tutorials for beginners";
  //Approach 1 : Using String Array
  String[] reverseArray = str.split(" ");
  //String to store the reversed string
  String reverseString1 = "";
  //reading each word from the reverseArray and creating the reverseString1
  for(int i = reverseArray.length-1;i >= 0;i--)
   reverseString1+= reverseArray[i] + " ";   
  System.out.println( reverseString1 );
  //Approach 2: Using StringBuilder
  StringBuilder revString = new StringBuilder();
  //String to store the reversed string
  String reverseString2 = "";
  for (int i = 0; i< reverseArray.length;i++) {
   revString.append( reverseArray[ reverseArray.length - 1 - i ]).append(' ');
  //creating String from the StringBuilder object
  reverseString2 = revString.toString();
  System.out.println( reverseString2 );
  //There might be many other approaches to this as well. Please share the same in comments.


Java Program to Format the String to Phone Number Format with dashes

11:58 PM 0 Comments A+ a-

Java Program to format the given input string to phone number format with dashes

Below is a coding challenge question I recently attempted in some competition. Suppose we are given a string that might contain some undesired characters apart from the digits. We are supposed to convert it into a phone number format with dashes with grouping of 3 digits. In case, only 4 digits are left in the end after grouping other numbers in a group of 3, then the numbers should be grouped in 2. In case 5 digits are left in the end, the digits should be grouped in 3 and 2. 
For example: "89437438843921" should be converted into 894-374-388-439-21
and "7836473097338" should be converted into 783-647-309-73-38
and "483974937434" should be converted into 483-974-937-434
And in case there are some alphabets and special characters, we should ignore them and remove from the output string.

Java Program to convert a given String to Phone number format with dashes:-

public class PhoneNumberFormat {
 public String formatToPhoneNumberFormat(String S) {
  StringBuilder filterOutJunk = new StringBuilder();
  int digitCount = 0;
  for (int i = 0;i < S.length();i++) {
  //if the input contains less than 2 digits, return null
  if(digitCount < 2)
   return null;
  //now the filterOutJunk contains only the clean string containing digits only
  filterOutJunk = new StringBuilder(filterOutJunk.toString());
  //start inserting the dashes after 3rd digit
  int insertDashes = 3;
  while (insertDashes < filterOutJunk.length())
   //insert dashes after 3 digits
      filterOutJunk.insert(insertDashes, "-");
      //but if we are left with only four digits in the end
      //enter dashes after 2 digits (2 + 1 = 3 for the fact that dash also takes one place)
      if(insertDashes == (filterOutJunk.length() - 5))
       insertDashes = insertDashes + 3;
       insertDashes = insertDashes + 4;
  return filterOutJunk.toString();
 public static void main(String[] args) {
  PhoneNumberFormat t = new PhoneNumberFormat();
  //Hard coded input for testing purpose. Take it from user.
  //Check for maximum input length of 100.
  String input = "47983"; 
  String formatted = t.formatToPhoneNumberFormat(input);


Please try out this on your own first and then refer this in case you get stuck somewhere. This will help you learn. And in case you find out this code not working properly for any given input string, please do let me know in comments.