Tuesday 17 November 2015

SQOOP is not supporting HIVE external tables at the moment

Sqoop does not support creating Hive external tables. Instead you might:

Step 1: import data from mysql to hive table.

sqoop import --connect jdbc:mysql://localhost/ --username training --password training --table --hive-import --hive-table -m 1 --fields-terminated-by ','

Step 2: In hive change the table type from Managed to External.

Alter table <Table-name> SET TBLPROPERTIES('EXTERNAL'='TRUE')

refer SQOOP-816

Monday 16 November 2015

Shell scripting to check the memory space in unix

This script will check for the memory space usages for the filesystem.

#!/bin/bash
##################################################
# Author: java2bigdata                           #
# Description:  check the memory space in unix   #
##################################################
# Total memory space details

echo "Memory Space Details"
free -t -m | grep "Total" | awk '{ print "Total Memory space : "$2 " MB";
print "Used Memory Space : "$3" MB";
print "Free Memory : "$4" MB";
}'

echo "Swap memory Details"
free -t -m | grep "Swap" | awk '{ print "Total Swap space : "$2 " MB";
print "Used Swap Space : "$3" MB";
print "Free Swap : "$4" MB";

}'

Delete Files Older Than 2 years on Linux Click here
Shell Scripting Routines  Click here



Delete Files Older Than 2 years on Linux

The logic helps in the automatic deletion of unnecessary files that keep on getting accumulated in the server without manual intervention .

//To delete the Cost* folders older than 2years under /usr/test/reports:

find /usr/test/reports -maxdepth 0 -type f -name Cost* -mtime +730 -exec rm '{}' '+'; > log.txt

//The above script deletes all the files as per the mentioned criteria and also creates a log for them and stores it in log.txt We can also use the :/ instead of + .The only difference is :/ deletes each file when found but + deletes all the files at once at the end.

//To delete all the files under /usr/test/reports older than 2 years:

find /usr/test/reports -maxdepth 0 -type f -mtime +730 -exec rm {} \;

//To delete all the files under /usr/test/reports older than 2 years(including sub directories):

find /usr/test/reports -type f -mtime +730 -exec rm {} \;

Note:-The statements mentioned after // are the comments for the script.

shell Scripting Routines Click here


Sunday 15 November 2015

Checking Disk Space using Java program

With this code you can check Disk Space.

/** To Check the Disk Space **/
package in.blogspot.java2bigdata;

import java.io.File;
public class DiskSpaceCheck {
public DiskSpaceCheck() {
File file = new File("E:");
System.out.println("E:");
System.out.println("Total:  " + file.getTotalSpace());
System.out.println("Free:   " + file.getFreeSpace());
System.out.println("Usable: " + file.getUsableSpace());
file = new File("E://movie");
System.out.println("E://movie");
System.out.println("Total:  " + file.getTotalSpace());
System.out.println("Free:   " + file.getFreeSpace());
System.out.println("Usable: " + file.getUsableSpace());
file = new File("/");
System.out.println("n/");
System.out.println("Total:  " + file.getTotalSpace());
System.out.println("Free:   " + file.getFreeSpace());
System.out.println("Usable: " + file.getUsableSpace());
}
public static void main(String[] args) {
new DiskSpaceCheck();
}
}

Java Program to List Contents of Directory in Hadoop (HDFS)

Saturday 14 November 2015

Shell scripting routines

  Most programming languages have a set of "best practices" that should be followed when writing code in that language. Based on my experience i have decided to mention some of generic routines in shell scripting.

Here is my list of best routines for shell scripting :

1. Use functions
2. Document your functions
3. Use shift to read function arguments
4. Declare your variables
5. Quote all parameter expansions
6. Use arrays where appropriate
7. Use "$@" to refer to all arguments
8. Use uppercase variable names for environment variables only
9. Prefer shell builtins over external programs

Basic shell scripting.......

==============================================================================
Variables:
==============================================================================
variable="value"
variable=`unix command`

index=1

==============================================================================
Incrementing a numeric variable:
==============================================================================
index++

==============================================================================
Arrays:
==============================================================================
variable[1]="value"
variable[2]=`unix command`

==============================================================================
Print to console:
==============================================================================
echo "Prining my first line.."
echo $variableName

echo ${variable[${index}]}


==============================================================================
Generating a unique Nubmer/Name:
==============================================================================
date +%Y%m%d%H%M

How to add a new column to a table in Hive

Use the following command to add a new column to a table in Hive

    ALTER TABLE students ADD COLUMNS (new_col INT);

How to copy a table in Hive to another table or create temp table?


If you want to store results of a query in a table in Hive then

    Create a schema of the temp table using command CREATE TABLE ..

    Execute the following command

INSERT OVERWRITE TABLE temp_tablename SELECT * FROM table_name limit 10

How to create output in gzip files in Hadoop Hive ?

How to create output in gzip files in Hadoop Hive

Sometimes its required to output hive results in gzip files  to reduce the file size so that the files can be transferred over network.
To do this, run the following commands in hive before running the query. The following code sets these options and then runs the hive query. The output of this hive query will be stored in gzip files.

set mapred.output.compress=true;
set hive.exec.compress.output=true;
set mapred.output.compression.codec=org.apache.hadoop.io.compress.GzipCodec;
set io.compression.codecs=org.apache.hadoop.io.compress.GzipCodec;
INSERT OVERWRITE DIRECTORY 'hive_out' select * from tables limit 10000;


Java Program to List Contents of Directory in Hadoop (HDFS)

Java Program to List Contents of Directory in Hadoop (HDFS)

How to list out the files and sub directories in the specified directory in Hadoop HDFS using java program?

The following java program prints the contents (files and directories) of a given directory(/user/hadoop) in HDFS:

/*Java Program to Print Contents of HDFS Directory*/
package in.blogspot.java2bigdata;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;

public class ListDirectoryContents {
  public static void main(String[] args) throws IOException, URISyntaxException
  {
    //1. Get the Configuration instance
    Configuration configuration = new Configuration();
    //2. Get the instance of the HDFS
    FileSystem hdfs = FileSystem.get(new URI("hdfs://localhost:54310"), configuration);
    //3. Get the metadata of the desired directory
    FileStatus[] fileStatus = hdfs.listStatus(new Path("hdfs://localhost:54310/user/hadoop"));
    //4. Using FileUtil, getting the Paths for all the FileStatus
    Path[] paths = FileUtil.stat2Paths(fileStatus);
    //5. Iterate through the directory and display the files in it
    System.out.println("***** Contents of the Directory *****");
    for(Path path : paths)
    {
      System.out.println(path);
    }
  }
}

In the above program, hdfs://localhost:54310 is the namenode URI.

Java program which can list all files in a given directory

 With this code you can list all files in a given directory:

package in.blogspot.java2bigdata;

import java.io.File;
 
public class ListFiles 
{
 
 public static void main(String[] args) 
{
   // Directory path here
  String path = "."; 
 
  String files;
  File folder = new File(path);
  File[] listOfFiles = folder.listFiles(); 
 
  for (int i = 0; i < listOfFiles.length; i++) 
  {
    if (listOfFiles[i].isFile()) 
   {
   files = listOfFiles[i].getName();
   System.out.println(files);
      }
  }
}
}

If you want to list only .txt files for example, Use this code:

package in.blogspot.java2bigdata;

import java.io.File;
 
public class ListTxtFiles 
{
 
 public static void main(String[] args) 
{
 
  // Directory path here
  String path = "."; 
 
  String files;
  File folder = new File(path);
  File[] listOfFiles = folder.listFiles(); 
 
  for (int i = 0; i < listOfFiles.length; i++) 
  {
 
   if (listOfFiles[i].isFile()) 
   {
   files = listOfFiles[i].getName();
       if (files.endsWith(".txt") || files.endsWith(".TXT"))
       {
          System.out.println(files);
        }
     }
  }
}
}

You can modify the .txt or .TXT to be whatever file extension you wish.

Friday 2 October 2015

Basic puzzle in java programming #1

In this program the below scenario will be implemented.

Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the string unchanged. Note: use .equals() to compare 2 strings.

notString("hi") ? "not hi"
notString("a") ? "not a"
notString("not bad") ? "not bad"

 /* Program to print
 * "hi" to "not hi"
 *  "String to not String"
 */

package in.blogspot.java2bigdata;

public class addNotToString {
 public String notString(String str) {
    if (str.length() >= 3 && str.substring(0, 3).equals("not")) {
      return str;
    }
    
    return "not " + str;
  }
 public static void main(String[] args){
  addNotToString word = new addNotToString();
  
  System.out.println(word.notString("Hi"));
  System.out.println(word.notString("good"));
  System.out.println(word.notString("not good"));
  System.out.println(word.notString("is not"));
  
 }

 }


click here for star pattern in java programming #1
click here for star pattern in java programming #2

Star pattern in java programming #3

In the program the following star pattern will be printed.

Diamond pattern:


Click here for Star pattern in java programming #1

Click here for Star pattern in java programming #2

This program will accept a number as input. The loops are used to build a diamond pattern of *.

/* 
* Diamond star pattern
**/
package com.blogspot.java2bigdata;

import java.io.*;
import java.lang.*;
import java.util.*;
 
class DiamondPattern{
      static public int ReadInteger()
      {
            try
            {
                  String inpString = "";
                  InputStreamReader input = new InputStreamReader(System.in);
                  BufferedReader reader = new BufferedReader(input);
                  String s = reader.readLine();
                  return Integer.parseInt(s);
            }
            catch (Exception e)
            {
                  e.printStackTrace();
            }
            return -1;
      }
 
      public static void main(String[] args)
      {
            System.out.println("Enter the number till you want a star (*) diamond pattern.");
            
            int n = ReadInteger();
           
            System.out.println("\nHere is the Diamond of Stars\n");
 
            for (int i = 1; i <= n; i++)
            {
                  for (int j = 0; j < (n - i); j++)
                        System.out.print(" ");
                  for (int j = 1; j <= i; j++)
                        System.out.print("*");
                  for (int k = 1; k < i; k++)
                        System.out.print("*");
                  System.out.println();
            }
 
            for (int i = n - 1; i >= 1; i--)
            {
                  for (int j = 0; j < (n - i); j++)
                        System.out.print(" ");
                  for (int j = 1; j <= i; j++)
                        System.out.print("*");
                  for (int k = 1; k < i; k++)
                        System.out.print("*");
                  System.out.println();
            }
 
            System.out.println();
      }
}

Output:


Thursday 1 October 2015

Star pattern in java programming #2

In the program the following star pattern will be printed.

 Click here for Star pattern in java programming #1

Output:

* * * * * * * * *
   * * * * * * * *
      * * * * * * *
         * * * * * *
            * * * * *
               * * * *
                  * * *
                     * *
                        *


/* Star pattern
 * 
 * */

package in.blogspot.java2bigdata;

import java.util.Scanner;  
    
public class StarPattern {  
       public static void main(String[] args)  
       {  
            int number; 
            System.out.println("Enter the number till you want a star pattern");  
            Scanner scan = new Scanner(System.in);  
            number = scan.nextInt();  
    
            label:     for(int i=0; i<number; i++)  
                 {  
                      for(int k=i; k>0; k--)  
                     {  
                           System.out.print(" ");  
                      }  
                      for(int j=0; j<number-i; j++)  
                      {  
                           System.out.print("*");  
                      }  
                     //for jump to next line  
                      System.out.println("");  
                 }  
       }  
  } 

At first, we get the number where we want to print the star pattern from the user with the use of Scanner class and store that number in variable number then we make a loop which starts from 0 till number-1.

Inside of that loop there is another loop which is used for giving spaces from left side equal to the line number.

There is one more loop inside the first loop which takes values from 0 to number-1 and used for printing stars and then there is a println statement which is used for going to the next line.



Wednesday 30 September 2015

Star pattern in java programming

In the program the following star pattern will be printed.

out put:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *

/*     star pattern
 *  *
*  *
*  **
*  ***
*  ****
*  *****
*  ******
*  *******
*  ********
* */

package in.blogspot.java2bigdata;

  import java.util.Scanner;  
    
  class StarPattern
  {  
       public static void main(String[] args)  
       {  
           int n;  
            System.out.println("Enter the number till you want a star pattern");  
            Scanner scan = new Scanner(System.in);  
            n = scan.nextInt();  
    
            label:     for(int i=0; i<n; i++)  
                 {  
                      for(int j=0; j<n; j++)  
                      {  
                           if(j>i)  
                           {  
                                System.out.println();  
                                continue label;  
                           }  
                           else  
                           {  
                                System.out.print("*");  
                           }  
                      }  
                 }  
      }  
 } 

At first, we get the number where we want to print the star pattern from the user with the use of Scanner class and store that number in variable n then we make a loop which starts from 0 till n-1.

Inside of that loop there is another loop from 0 to n-1 and we jump from the inner loop if we get a number greater than the outer loop value with the use of continue because we only want stars equal to outer loops in a single line.


Arrays's different outputs

In this post, you will get to know what are different outputs come while initializing an array.

Arrays in Java
Array creation



Tuesday 16 June 2015

Reverse Number using Java

This program prints reverse of a number i.e. if the input is 4321 then output will be 1234.

/*
  Reverse Number using Java
 
*/
package in.blogspot.java2bigdata 
public class ReverseNumberDemo {
 
        public static void main(String[] args) {
               
                int number = 4321;
                int reversedNumber = 0;
                int temp = 0;
               
                while(number > 0){
                       
                        //use modulus operator to strip off the last digit
                        temp = number%10;
                       
                        //create the reversed number
                        reversedNumber = reversedNumber * 10 + temp;
                        number = number/10;
                         
                }
               
                //output the reversed number
                System.out.println("Reversed Number is: " + reversedNumber);
        }
}
 
/*
Output of this Number Reverse program would be
Reversed Number is: 1234
*/

Monday 15 June 2015

What is a Java Literal ?

Literals:  Any constant value which can be assigned to the variable is called literal.Literals represent numerical (integer or floating-point), character, boolean or string values.

Example:
int literal = 100;
here the value 100 considered as a literal,int is datatype and literal is identifier.



Integral Literals: For the integral data types (byte, short, int and long) we can specify literal value in the following ways.

1. Decimal literals: Allowed digits are 0 to 9.
 Example:  int x=10;

Tuesday 9 June 2015

Array Creation

In previous post, we learned more about Array Declarations. In this blog post, I will discuss Array Creation.

Array in java is an object hence we can create by using new keyword.

int[] arr = new int[5];


For every array type corresponding classes are available but these classes are part of java language and not available to the programmer level.



Rule 1: At the time of array creation compulsory we should specify the size otherwise we will get compile time error.

Example:
int[] a=new int[3];
int[] a=new int[];    //C.E:array dimension missing

Rule 2: It is legal to have an array with size zero in java.
Example:
int[] a=new int[0];
System.out.println(a.length); //0

Rule 3: If we are taking array size with -ve int value then we will get runtime exception saying NegativeArraySizeException.

Example:
int[] a=new int[-3];//R.E:NegativeArraySizeException

Rule 4: The allowed data types to specify array size are byte, short, char, int. By mistake if we are using any other type we will get compile time error.

Examples:
int[] a=new int['a'];//(valid)
byte b=10;
int[] a=new int[b];//(valid)
short s=20;
int[] a=new int[s];//(valid)
int[] a=new int[10l];//C.E:possible loss of precision//(invalid)
int[] a=new int[10.5];//C.E:possible loss of precision//(invalid)

Rule 5:  The maximum allowed array size in java is maximum value of int size [2147483647].

Examples:
int[] a1=new int[2147483647];(valid)
int[] a2=new int[2147483648]; //C.E:integer number too large: 2147483648(invalid)

Sunday 31 May 2015

Arrays in Java

In this section, you'll learn what arrays are, and how to declare them.

Introduction:

So far, you have been working with variables that hold only one value. The integer variables you have set up have held only one number, and the string variables just one long string of text.

int number0 = 0,number1= 1,number2= 2,..........................;
String one = "One",two = "Two",.....................;

let's assume we have hundred's of int variables and we have been declared hundred's of variables in our program.If we think of readability and maintenance of code then how hard it will be ,because of this sun people introduced array concept.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.

Example:
 int number0 = 0,number1= 1,number2= 2,........int nightyNine = 99;
or 
int[] numbers = new int[100];
numbers[0]=1;
numbers[1]=2;
numbers[99]=100;

An array is a flexible structure for storing a sequence of values all of the same type.

Saturday 30 May 2015

How to create a JAR file in Java

The Java™ Archive (JAR) file format enables you to bundle multiple files into a single archive file. Typically a JAR file contains the class files and auxiliary resources associated with applets and applications.

Usage: jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...

Options:
    -c  create new archive
    -t  list table of contents for archive
    -x  extract named (or all) files from archive
    -u  update existing archive
    -v  generate verbose output on standard output
    -f  specify archive file name
    -m  include manifest information from specified manifest file
    -e  specify application entry point for stand-alone application
        bundled into an executable jar file
    -0  store only; use no ZIP compression
    -M  do not create a manifest file for the entries
    -i  generate index information for the specified jar files
    -C  change to the specified directory and include the following file

If any file is a directory then it is processed recursively.
The manifest file name, the archive file name and the entry point name are specified in the same order as the 'm', 'f' and 'e' flags.

jar cvf  <jar-file>  <input-files>

Options :

Thursday 28 May 2015

Instance Control Flow In Parent And Child Relationship:

In my previous article I discussed about instace control flow in a class , static control flow in a class and static control flow in parent and child relationship. let see what will happen at the time of creating child class object.

Whenever we are creating child class object the following sequence of events will be executed automatically.

1) Identification of instance members from Parent to Child.
2) Execution of instance variable assignments and instance block only in Parent class.
3) Execution of Parent class constructor.
4) Execution of instance variable assignments and instance blocks in Child class.
5) Execution of Child class constructor.


I know the above program is bit confusing, I will try to elaborate more

At the time creating child object the following sequence of events will be performed automatically.

At first all instance members of parent and child are identified (just identified , no assignment of variables and execution of instance blocks is done), observe [1] to [11] .

After identification,variable assignment and execution of instace blocks starts only in parent class so value 5 is assigned to int firstNumber[12] , the next instance block is executed here firstMethod() method is called ,  observe  firstMethod() is trying to print secondNumber which is not yet initialized so the default value “0” is printed, now control flows back to instace block and the next statement  “Parent first instance Block”[15] is displayed on console. Now the secondNumber is initialized[16]. Next parent class constructor is executed [17].

Now,variable assignment and execution of instace blocks starts in child class so value 1 is assigned to int numberOne[18] , the next instance block is executed here secondMethod() method is called ,  observe  secondMethod() is trying to print numberTwo which is not yet initialized so the default value “0” is printed, now control flows back to instace block and the next statement  "Child first instance Block”[21] is displayed on console.

After it the second child instance block is executed and “Child Second instace block ” is printed[22], now the numberTwo is initialized[23]. Finally child constructor is being executed [24]. (Generally object initialization done in constructors). then main () method next statement will be executed[25].


// Instance control flow in Parent and Child relaitonship
package in.blogspot.java2bigdata;
/**
 * 
 *  @author Mahendhar E 
 */
public class ParentInstanceFlow {

 int firstNumber=5;
 {
  firstMethod();
  System.out.println("Parent first instance block");
 }
 ParentInstanceFlow()
 {
  System.out.println("parent class constructor");
 }
 public static void main(String[] args)
 {
  ParentInstanceFlow p=new ParentInstanceFlow();
  System.out.println("parent class main method");
 }
 public void firstMethod()
 {
  System.out.println(secondNumber);
 }
 int secondNumber=10;
}
class ChildInstanceFlow extends ParentInstanceFlow
{
 int numberOne=1;
 {
  secondMethod();
  System.out.println("Child first instance block");
 }
 ChildInstanceFlow()
 {
  System.out.println("Child class constructor");
 }
 public static void main(String[] args)
 {
  ChildInstanceFlow c=new ChildInstanceFlow();
  System.out.println("Child class main method");
 }
 public void secondMethod()
 {
  System.out.println(numberTwo);
 }
 {
  System.out.println("Child second instance block");
 }
 int numberTwo=2;
}



Output:
0
Parent first instance block
parent class constructor
0
Child first instance block
Child second instance block
Child class constructor
Child class main method


Tuesday 26 May 2015

Java Comments

Comments are those lines which will be skipped while compilation.
i.e. The JVM ignore the comments.

Java supports three types of comments
// single line comment.To comment a single line it is used
/*---*/ multiline comment.To comment more than one line.
/**--*/ Documentation comment. Used to produce a HTML document for your program.

Example Click here


Sunday 24 May 2015

Hadoop -1.0.4.tar.gz Directory Structure :

In this post we will see Hadoop-1.0.4 tar.gz directory structure in pictorial representation.


/bin directory contains some scripts used to launch Hadoop DFS and Hadoop Map/Reduce daemons.

/conf directory contains some configuration files for Hadoop.

I will be updating Hadoop-2.7.0 directory structure in upcoming post.


Saturday 23 May 2015

Using Command Line Arguments In Java

In this post we will learn how to pass command line arguments.

A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched.

>javac UsingArgument.java
>java UsingArgument Mahendhar

When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of Strings. In the previous example, the command-line arguments passed to the UsingArgument application in an array that contains a single String: "Mahendhar".

// Program using a commmand line arugment
/*
 *  Compilation:  javac UsingArgument.java
 *  Execution:    java UsingArgument yourname
 *
 *  Prints "Hellp, Mahendhar. How are you?" where "Mahendhar" is replaced by the
 *  command-line argument.
 *
 *  > java UsingArgument Mahendhar
 *   Output:
 *   Hello, Mahendhar. How are you?
 *  
 **/

public class UsingArgument {

    public static void main(String[] args) {
        System.out.print("Hello, ");
        System.out.print(args[0]);
        System.out.println(". How are you?");
    }

}


First Java Progarm

In this post we will learn writing our First Java Program. At first we break the process of programming in Java into three steps:

   1. Create the program by typing it into a text editor and saving it to a file named, say, HelloWorld.java.
   2. Compile it by typing "javac HelloWorld.java" in the terminal/command prompt window.
   3. Run (or execute) it by typing "java HelloWorld" in the terminal/command prompt window.

Creating a Java program.

A program is nothing more than a sequence of characters, like a sentence, a paragraph, or a poem. To create one, we need only define that sequence characters using a text editor in the same way as we do for e-mail. HelloWorld.java is an example program. Type these character into your text editor and save it into a file named HelloWorld.java.


 public class HelloWorld { 
       public static void main(String[] args) { 
          System.out.println("Hello, World");
       }
    }

Compiling a Java program.

 A compiler is an application that translates programs from the Java language to a language more suitable for executing on the computer. It takes a text file with the .java extension as input (your program) and produces a file with a .class extension (the computer-language version). To compile HelloWorld.java type the boldfaced text below at the terminal. (I use the > symbol to denote the command prompt, but it may appear different depending on your system.)

> javac HelloWorld.java

Executing a Java program. 

Once you compile your program, you can run it. This is the exciting part, where the computer follows your instructions. To run the HelloWorld program, type the following at the command prompt/terminal:

>java HelloWorld

If all goes well, you should see the following response

Hello Word



/*************************************************************************
 *  Compilation:  javac HelloWorld.java
 *  Execution:    java HelloWorld
 *
 *  Prints "Hello, World". By tradition, this is everyone's first program.
 *
 *  Output:
 *  Hello World
 *
 *************************************************************************/

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello, World");
    }

}


Friday 22 May 2015

Program: Armstrong Number in Java

If sum of each digits's cube is equal to original number then that number is called as Armstrong Number

Example: 153 = (1*1*1) + (5*5*5) + (3*3*3)


Please follow below Steps to check if number is armstrong number or not using java :

i.   Take Reminder of number
ii.  Cube the reminder and add it to Sum
iii. Retrieve pending number to be evaluate and set it to Number
iv.  Perform above checks until number is greater than 0.


// Example: 153 = (1*1*1) + (5*5*5) + (3*3*3)
package in.blogspot.java2bigdata;  
  
/** 
 * 
 * @author Mahendhar E 
 */  
public class ArmStrong {  
  
    protected void checkArmStrongNumber(int number) {  
        int sum = 0, reminder = 0;  
        int original = number;  
  
        while (number > 0) {  
            //take reminder  
            reminder = number % 10;  
  
            //cube the reminder and add it to sum  
            sum = sum + reminder * reminder * reminder;  
  
            //retrieve pending number to be eveluated  
            number = number / 10;  
        }  
  
        if (original == sum) {  
            System.out.println("Number " + original + " is armstrong");  
        } else {  
            System.out.println("Number " + original + " is not armstrong");  
        }  
    }  
  
    public static void main(String[] args) {  
        ArmStrong armStrong = new ArmStrong();  
        armStrong.checkArmStrongNumber(153);  
        armStrong.checkArmStrongNumber(154);  
    }  
}


output:
/**
 *
 * Number 153 is armstrong  
 * Number 154 is not armstrong 
 */