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 
 */

Wednesday, 20 May 2015

Program: Write a program to reverse a number.

Below program shows how to reverse a number using numeric operations.

package in.blogspot.java2bigdata;
 
public class NumberReverse {
 
    public int reverseNumber(int number){
         
        int reverse = 0;
        while(number != 0){
            reverse = (reverse*10)+(number%10);
            number = number/10;
        }
        return reverse;
    }
     
    public static void main(String a[]){
        NumberReverse reverseNum = new NumberReverse();
        System.out.println("Result: "+reverseNum .reverseNumber(212015));
    }
}


// Output:
//Result:510212

Prgram:Factorial of a number.
Program:The leap year rule.

Instance Control Flow In a Class

In my previous article I discussed about 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 class object .

At the time of creating an object the following sequence of events will be performed automatically by JVM.

1. Identification of instance members from top to bottom.
2. Execution of instance variable assignments and instance blocks from top to bottom.
3. Execution of constructor.


Output:

0
First instance block
Second instance block
InstaceFlow constructor
main() method......

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

At the time of creating an object the following sequence of events will be performed automatically[2].

At first all instance members of the class are identified (just identified , no assignment of variables and execution of instance blocks is done), observe [3] to [8] .

After identification variable assignment and execution of instace blocks starts from top to bottom so value 5 is assigned to int firstNumber[9] , 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  “First instance Block”[12] is displayed on console. After it the second instance block is executed and “Second instace Block” is printed[13], now the secondNumber is initialized[14]. Finally constructor is being executed [15]. (Generally object initialization done in constructors). then main () method next statement will be executed[16].

Note: Instance control flow is not one time activity for every object creation it will be executed but
static control flow is one time activity and it will be executed at the time of class loading.

I will be discussing more about constructors in my up coming post.

Saturday, 16 May 2015

Factorial Of A Number

In this program we will find factorial of 5(which means 5! = 5*4*3*2*1 and the result will be 120).

package in.blogspot.java2bigdata
public class Factorial
{
public static void main(String args[])
{
int number = 5;
int fact = a;
for(int i=a-1;i>=1;i--)
fact = fact * i;
System.out.println("Factorial : "+ fact);
}
}

/********** OUTPUT ***********
Factorial : 120 */
//5! = 5*4*3*2*1 = 120

Friday, 15 May 2015

javac and java commands

javac: we can use this command to compile a single or group of java program (.java) files.

java : we can use this command to run/ execute a java class (.class ) file



javac command options listed in below screenshot.


java command options listed in below screenshot.




Increment and Decrement Operators

  • Increment and Decrement Operators are Unary Operators(Unary Operator Operates on One Operand).
  • Increment Operator is Used to Increment Value of variable by 1 (default).
  • Decrement Operator is used to decrement value of Variable by 1 (default).
Types of increment and decrement operators.

1.  Pre Increment / Pre Decrement Operator

2.  Post Increment / Post Decrement Operator

Syntax:

++ Increment operator : increments a value by 1
-- Decrement operator : decrements a value by 1


Pre-Increment Operator:

“++” is written before Variable name.

Value is Incremented First and then incremented value is used in expression.

Post-Increment Operator:

“++” is written afterVariable name.
Increment Value of Variable After Assigning.




Thursday, 14 May 2015

The Leap Year Rule

This is the algorithm to use when working out if a year is a leap-year or not...

IF the year MOD 400 equals 0
THEN its a leap year
OR IF the year MOD 4 equals 0
AND the year MOD 100 does not equal 0
THEN its a leap year


The code to implement the above goes something like this:

public static boolean isLeapYear(int year) {

    boolean leapYear = false;

    if (((year % 400) == 0) || (((year % 4) == 0) && ((year % 100) != 0))) {
      leapYear = true;
    }

    return leapYear;
  }


30 Eclipse plugins

As I was surfing on eclipse.org, I found this link which contains a selection of plugins. I've already tried someone which are very interesting. So, do like me : enhance your Eclipse!

http://www.ajaxline.com/best-eclipse-plugins


Static control flow in Parent and Child relationship

In my previous article I discussed about static control flow in a class  and let see what will happen when a class loads into JVM on static members with parent & child relationship.

JVM follows below steps to read static members in a class.

1. Identification of static members form Parent to Child.
2. Execution of static variables assignment and static blocks from Parent to Child.
3.Execution of child main() method.


Output:
0
parent static block
0
child static block
child second static block
2
child main() method......

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

At first all static members of the class are identified form Parent to Child(just identified , no assignment of variables and execution of static blocks is done), observe [1] to [11] .

After identification variable assignment and execution of static blocks starts from Parent to Child so value 10 is assigned to int firstNumber[12] , the next static 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 static block and the next statement  “parent static block”[15] is displayed on console. After the secondNumber is initialized[16] then numberOne is initilaized[17], the next static 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 static block and the next statement  “child static block”[20] is displayed on console.

After it the second static block is executed and “child second static block” is printed[21], now the numberTwo is initialized[22]. Next the child main method is executed [23] to [25].

Tuesday, 12 May 2015

Method Signature

In Java method signature consist of name of the method followed by parameters and return type is not part of method signature.


public static void main(String[] args)

It's method signature is main(String[] args)


Monday, 11 May 2015

Break statement in Java

The break statement has two forms: labeled and unlabeled.

Unlabeled Break statement :This form of break statement is used to jump out of the loop when specific condition occurs. This form of break statement is also used in switch statement.

break statement can be used in the following cases.

1. inside switch to stop fall-through. (Unlabeled )
2. Inside loops to break loop based on some condition. (Unlabeled )
3.Inside labeled blocks to break block execution based on some condition. (Labeled )

Examples:

package in.blogspot.java2bigdata;
public class LabelTest {
  
   public static void main(String[] args) {
    int x = 10;
    Label1:{
     System.out.println("label one");
     if(x==10)
      break Label1;
    }
     
 }
}
  

package in.blogspot.java2bigdata;
public class LoopTest {
  
   public static void main(String[] args) {
  
    for(int loopNumber= 1;loopNumber<10;loopNumber++){
     if(loopNumber==9)
      break;
     System.out.println(loopNumber);
    }
     
 }
}

switch statement example Click here.

If we are using any where else we will get compile time error: break can not be used outside of a loop or a switch.

All Possible Combinations of Features and Modifiers



The modifiers transient and volatile are applicable for only variables.
The modifier native is applicable for only methods.

Saturday, 9 May 2015

Java Source file

In this post we will see java source file structure.

A java program can contain any number of classes but at most one class can be declared as public.


If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

Thursday, 7 May 2015

Data types in Java

Data Type represents how much memory has to allocate for a particular identifier by JVM.
In java we have eight primitive datatypes which are based on Range(boundary of a data type) and Size(represents memory limit). Based on these range and size we will define an identifier with corresponding primitive type.



If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

Wednesday, 6 May 2015

Theme of the blog

Hadoop is an open-source Java framework for distributed processing of large amounts of data. Hadoop is based on MapReduce programming model published by Google. As you browse through the web, there is a better chance that you are touching Hadoop or MapReduce model in some way.

The beauty of open-source is that the framework is open for anyone to use and modify it to their own requirement with enough commitment. But, the big challenge in adopting Hadoop or in fact any other open-source framework is the lack of documentation. Even if it's there, it might be sparse or stale. And, sometimes no documentation is better than incorrect or outdated documentation.

As I journey through learning Hadoop, I will blog tips and tricks for the development, debugging and usage of Hadoop and JAVA. Feel free to comment on the blog entries for any corrections or any better way of doing things






What is Hadoop ?

In this article I’ll briefly discuss what Hadoop is and why it is needed.

Definition – “Hadoop is an open source software project that enables the distributed processing of large amount of data sets across clusters of commodity servers.”

Before breaking this definition further down, we can easily understand from the above definition that it is a solution for large scale distributed computing. So let us first discuss the limitations of traditional large scale computation. We will then be able to appreciate the power of Hadoop.

Today we live in a Data-Driven world. Data is everywhere and in huge numbers. We need a mechanism to not only store such huge amount of data but also analyse it to make sense out of it.

The disk storage capacity has increased considerably over the period of time. With distributed computing, it is possible to store such huge data across hundreds of computers, but the bottle neck is how to analyse the data. As most of the analysis tasks require the data to be copied from all the sources into the compute nodes. This brings along with it many challenges such as synchronization issues, load balancing and hardware failures. The programmer then has to spend more time designing for failure rather than spending time on the actual problem itself.

Well then, what is the solution? It is Hadoop! It takes care of all the issues such as data synchronization and hardware failures. Additionally it provides a scalable and cost effective solution.

Hadoop is based on papers published by Google in 2003 and 2004 (on Google File System and Google Map Reduce). There are two main components of Hadoop :-

    HDFS – Hadoop distributed file system
    MapReduce – Programming model in which a task is broken down into small pieces where each piece is run on a single node of the cluster in parallel with other pieces.
    New release has YARN - a resource-management platform responsible for managing compute resources in clusters and using them for scheduling of users' applications

We will revisit the definition we provided at the start and try to break it down.

“Hadoop is an open source software project that enables the distributed processing of large amount of data sets across clusters of commodity servers”

Open source – Hadoop is a free Java based programming framework. It is part of the Apache project sponsored by the Apache Software Foundation.

Distributed processing – Hadoop uses MapReduce as its programming model for analysis.

Large amount of data – Hadoop is capable of handling files that are gigabytes or terabytes in size.

Cluster of commodity servers – Hadoop is highly fault tolerant system. Therefore it doesn’t require highly sophisticated hardware. It can run on commonly available hardware.

This post just provides the overview of Hadoop. There are many other components in the ecosystem other that HDFS and MapReduce such as Pig, Hive, HBase, Flume, Oozie, Sqoop etc.

We will cover HDFS and MapReduce in subsequent post.





References :-

    http://www-01.ibm.com/software/data/infosphere/hadoop/
    Hadoop – The Definitive Guide (Tom White)


If you know anyone who has started learning Hadoop, why not help them out! Just share this post with them. Thanks for studying today!...

Top level class modifiers in Java

-- Top level classes can only have

1.  publilc

2.  default/package

3.  abstarct

4.  final

5.  strictfp

If we are using any other modifier we will get compile time error. 

Example:

private class Test
{
public static void main(String args[]){
int i=0;
System.out.println("Test"+i);
}
}

>javac Test.java
Test.java:1: modifier private not allowed here
private class Test

but For the inner classes the following modifiers  are aslo allowed.
 private, protected, and static.

If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

Separators

Separators are used to inform the Java compiler of how things are grouped in the code. For example, items in a list are separated by commas much like lists of items in a sentence. The most commonly used separator in Java is the semicolon. As you have seen, it is used to terminate statements.


Symbol
Name
Purpose
;
Semicolon
Terminates statements.
,
Comma
Separates consecutive identifiers in a variable
declaration.
Also used to chain statements together inside a for statement.
{ }
Braces
Used to contain the values of automatically initialized arrays.
Also used to define a block of code, for classes, methods, and local scopes.
( )
Parentheses
Used to contain lists of parameters in method definition and invocation.
Also used for defining precedence in expressions, containing expressions in control statements.
Also used for surrounding cast types.
[ ]
Brackets
Used to declare array types.
Also used when differencing array values.
.
Period
Used to separate package names from sub packages and classes Also used to separate a variable or method from a reference variable.




If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...