Java Generate PDF file from database records

Java Generate PDF using Hibernate to read records from database

import java.util.*;
public class Student
{
	private int studentId;
	private String studentName;
	private String studentSex;
	private String studentCourseName;
	private String studentPhno;
	private int studentMarks;
	private String studentAddress;
	public Student( int studentId,String studentName, String studentSex, String studentCourseName, String studentPhno,int studentMarks, String studentAddress) {
		this.studentId=studentId;
		this.studentName=studentName;
		this.studentSex= studentSex;
		this.studentCourseName=studentCourseName;
		this.studentPhno=studentPhno;
		this.studentMarks=studentMarks;
		this.studentAddress=studentAddress;
	}
	
	
	
	@Override
	public String toString() {
		return "" + studentId + "\t\t" + studentName + "\t\t" + studentSex
				+ "\t\t" + studentCourseName + "\t\t" + studentPhno + "\t\t"
				+ studentMarks + "\t\t\t" + studentAddress ;
	}



	public int getStudentId() {
		return studentId;
	}


	public void setStudentId(int studentId) {
		this.studentId = studentId;
	}


	public String getStudentName() {
		return studentName;
	}


	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}


	public String getStudentSex() {
		return studentSex;
	}


	public void setStudentSex(String studentSex) {
		this.studentSex = studentSex;
	}


	public String getStudentCourseName() {
		return studentCourseName;
	}


	public void setStudentCourseName(String studentCourseName) {
		this.studentCourseName = studentCourseName;
	}


	public String getStudentPhno() {
		return studentPhno;
	}


	public void setStudentPhno(String studentPhno) {
		this.studentPhno = studentPhno;
	}


	public int getStudentMarks() {
		return studentMarks;
	}


	public void setStudentMarks(int studentMarks) {
		this.studentMarks = studentMarks;
	}


	public String getStudentAddress() {
		return studentAddress;
	}


	public void setStudentAddress(String studentAddress) {
		this.studentAddress = studentAddress;
	}


	public void display(){
		System.out.print(studentId+"\t\t");
		System.out.print(studentName+"\t\t");
		System.out.print(studentSex+"\t");
		System.out.print(studentCourseName+"\t\t");
		System.out.print(studentPhno+"\t\t");
		System.out.print(studentMarks+"\t\t\t");
		System.out.print(studentAddress+"\t");
		System.out.println();
		
	}
}

Hibernate.cfg.xml
<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE hibernate-configuration PUBLIC “-//Hibernate/Hibernate Configuration DTD 3.0//EN” “http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”>
<hibernate-configuration>
<session-factory>
<property name=”show_sql”>false</property>
<property name=”hbm2ddl.auto”>create</property>
<property name=”hibernate.dialect”>org.hibernate.dialect.MySQLDialect</property>
<property name=”hibernate.connection.driver_class”>com.mysql.jdbc.Driver</property>
<property name=”hibernate.connection.url”>jdbc:mysql://localhost:3306/student1?zeroDateTimeBehavior=convertToNull</property>
<property name=”hibernate.connection.username”>root</property>
<property name=”hibernate.connection.password”></property>

<mapping class=”com.santanu.arrays.Student”/>

</session-factory>
</hibernate-configuration>

public class HibernateTest {

	public static void main(String[] args) {
		Student [] student= new Student[10];
		
		student[0]= new Student(1, "Vipin", "M", "Java", "9000000001", 85, "Lucknow");
		student[1]= new Student(2, "Sohel", "M", "C++", "9000000002", 81, "Kolkata");
		student[2]= new Student(3, "Meheraj", "M", "C/C++", "9000000003", 86, "Bengalore");
		student[3]= new Student(4, "Shruti", "F", "J2ee", "9000000004", 55, "Kolkata");
		student[4]= new Student(5, "Shabbu", "M", ".Net", "9000000005", 86, "Bengaluru");
		student[5]= new Student(6, "Sharukh", "M", "Python", "9000000006", 74, "Delhi");
		student[6]= new Student(7, "Deepika", "F", "PHP", "9000000007", 67, "Chandigarh");
		student[7]= new Student(8, "Anuskha", "F", "HTML", "9000000008", 67, "Patna");
		student[8]= new Student(9, "Kejri","M", "Ruby", "9000000009", 71, "Vizag");
		student[9]= new Student(10, "Rahul", "M", "ASP", "9000000010", 51, "Bairely");
		
	    SessionFactory sf = new Configuration().configure().buildSessionFactory();
	    Session sc = sf.openSession();
	    sc.beginTransaction();
	    	  
	    System.out.println("hi");
	    for (Student x:student) {
			sc.save(x);
			}
	    System.out.println("hi");
	    sc.getTransaction().commit();
	    sc.close();
	    
		}

}
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.sql.*;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class PDFCreator {

	public static void main(String[] args) throws ClassNotFoundException, SQLException, FileNotFoundException, DocumentException,  IllegalAccessException {
	int rowno=0;
	
	Class.forName("com.mysql.jdbc.Driver");//.newInstance();
	Connection  con= DriverManager.getConnection("jdbc:mysql://localhost:3306/student1?zeroDateTimeBehavior=convertToNull", "root","") ;
	Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
	ResultSet rs = st.executeQuery("SELECT * FROM student");
	ResultSetMetaData rsmd = rs.getMetaData();
	int colno = rsmd.getColumnCount();
	while (rs.next()) {
		 rowno= rowno+1;
		
	}
	rs.first();
	System.out.println(""+rs.getString(1));
	
	Document d = new Document();
	PdfWriter.getInstance(d, new FileOutputStream("report.pdf"));
	PdfPTable pt = new PdfPTable(colno);
	d.open();
	d.add(new Paragraph("Student Record"));
	for (int i = 0; i < rowno; i++) {
		pt.addCell(""+rs.getString(1));
		pt.addCell(""+rs.getString(2));
		pt.addCell(""+rs.getString(3));
		pt.addCell(""+rs.getString(4));
		pt.addCell(""+rs.getString(5));
		pt.addCell(""+rs.getString(6));
		pt.addCell(""+rs.getString(7));
		rs.next();
	}
	
	d.add(pt);
	
	d.close();
	}

}

What is JAR File and How to create JAR File

A JAR File, stands for Java Archive file. Like ZIP file, JAR is compressed file format, which is used to share software resources required for Java Applications. For example Hibernate, Struts, Spring,etc… provide their framework implementation through multiple JAR files. Similarly you can provide Jar files to your clients, or other Teams dependent on your Classes or packages. Even JDBC driver is provided as a Jar file. A Jar file may contain
1. bunch of .class files
2. any other resource files, like images, icons,etc… required by .class files

Also note that a jar file can have multiple packages or sub packages.

How to create JAR file in Eclipse

Below are the steps involved in creating jar file in Eclipse IDE.
1. Create a Java Project
2. Add class Files
3. Build the Project, do Testing
4. Right click on Project, and Select Export

export jar file
export jar file

5. In Export Window, select java, then JAR file, then Next button.
create-jar
create-jar

6. Now Below JAR File Specification window appears. Select various options, based on your requirement.
Select or unselect appropriate checkbox to specify if you want to Export generated class files and resources or Export Java source files and resources as well.

jar-file-specification
jar-file-specification

Browse to select a location for the JAR file, which will get created.

Select or unselect, Compress the contents of the JAR file checkbox.
Select or unselect, Overwrite existing files without warning checkbox. If you unselect this checkbox, then you will be prompted to confirm the replacement of each file that will be overwritten.

In this way you can create JAR file, out of your class files, and other required resources, and distribute it.

You may also like to read:

How to Compress and Uncompress file in Java


How to create a Jar file in a Netbeans Project?
How to create Jar file, in run time, using Java program?
How to add an external Jar file to a Eclipse Project?
How to add an external jar file to a Netbeans Project?

How to create our own linked list in Java

Each node is an object of class. Node can store an int, and a reference to next Node object. Also note that you can use a complex object, as a member instead of an int.

As shown in the example, next reference of last element is null.

while loop is used to iterate thru the elements in the linked list.
Also, more methods can be added which performs adding an element, deleting an element, etc….

Below is a Program of singly linked list in Java.

class Node
{
	private int i;
	
	Node next;

	Node(int i)
	{
		this.i = i;
	}
	public void set(int i)
	{
		this.i = i;
	}
	
	public int get()
	{
		return i;
	}
	
}

public class OwnLinkedList {
	public static void main(String args[])
	{
	//create elements, and assign next element
	Node n1 = new Node(10);
		
	Node n2 = new Node(20);
	n1.next = n2;
		
	Node n3 = new Node(30);
	n2.next = n3;
		
	Node n4 = new Node(40);
	n3.next = n4;
		
	Node n5 = new Node(50);
	n4.next = n5;
	n5.next = null;
		
	Node tmp = n1;
	while(tmp.next!=null)
	{
		System.out.println(tmp.get());
		tmp = tmp.next;
	}
		
	}
}

double linked list
double linked list

Below is program on how to implement double linked list. Advantage of doubly linked list is it can be traversed in both the directions, unlike singly linked list. As shown below, each Node1 has reference to previous element, along with reference to next element. previous reference for first element is null. next reference for last element is null.

class Node1
{
	private int i;
	
	Node1 next;
	Node1 previous;

	Node1(int i)
	{
		this.i = i;
	}
	public void set(int i)
	{
		this.i = i;
	}
	
	public int get()
	{
		return i;
	}
	
}

public class OwnDLinkedList {
	public static void main(String args[])
	{
		//create elements, and assign next and previous element
		Node1 n1 = new Node1(10);
		
		n1.previous = null;
		Node1 n2 = new Node1(20);
		n1.next = n2;
		n2.previous = n1;
		
		Node1 n3 = new Node1(30);
		n2.next = n3;
		n3.previous = n2;
		
		Node1 n4 = new Node1(40);
		n3.next = n4;
		n4.previous = n3;
		
		Node1 n5 = new Node1(50);
		n4.next = n5;
		n5.previous = n4;
		n5.next = null;
		
		Node1 tmp = n1;
		while(tmp.next!=null)
		{
			System.out.println(tmp.get());
			tmp = tmp.next;
		}
		
	}
}

What is circular linked list

Below is an implementation of Circular doubly linked list. Here Head node refers to starting node, Tail node refers to last node.

Circular Linked List
Circular Linked List

public class OwnCLinkedList {
	public static void main(String args[])
	{
		Node1 n_head, n_tail;
		//create elements, and assign next and previous element
		Node1 n1 = new Node1(10);
		
		Node1 n5 = new Node1(50);
		
		n_head = n1; //set head node
		n_tail = n5; //set tail node
		
		n1.previous = n5;
		Node1 n2 = new Node1(20);
		n1.next = n2;
		n2.previous = n1;
		
		Node1 n3 = new Node1(30);
		n2.next = n3;
		n3.previous = n2;
		
		Node1 n4 = new Node1(40);
		n3.next = n4;
		n4.previous = n3;
		
		
		n4.next = n5;
		n5.previous = n4;
		n5.next = n1;
		
		Node1 tmp = n_head;
		while(tmp!=n_tail)
		{
			System.out.println(tmp.get());
			tmp = tmp.next;
		}
		
	}
}

We can make above Data structures better useful by providing methods, to add and delete Node,etc…

Similar steps can be followed to build complex data structures such as Graph

You may also like to read:
How Vector and ArrayList differ
List and Set differences
How ArrayList and LinkedList are implemented internally

What is method recursion?

A recursion is nothing but, invoking a method itself. For example, in below code snippet, the method test() calls itself.

class Abc{
public void test()
{
System.out.println("test() method");
test();
}
}

However, do not try to use above code snippet, as this will continuously gets into recursion. Programs having such endless recursion, runs until java.lang.StackOverFlowError, is being thrown. This Exception is Unchecked Exception, and is thrown when stack gets full. The reason stack gets full is, an entry is added to stack whenever a method is invoked.Continuing to add entries to stack results in overflow of stack, and java.lang.StackOverFlowError exception is thrown.

Can static method call itself recursively?

Yes, static methods can call itself recursively.

How to use method recursion, effectively?

Remember that whenever a method is called recursively, there need to be condition, which need to control it. And there need to arise a situation where this condition is satisfied.Below is program, for fibonacci, using recursion.

public class FibonacciRecursion {
	public static void main(String args[])
	{
		int i = 0, j =1;
		fib(i,j);
	}
	
	private static void fib(int x, int y)
	{
		if(x>=30)
		{
			return;
		}
		
		System.out.print(y+"  ");
		
		fib(y, x+y);
	}
}

Also note that, above recursive version is more compact compared to non recursive version of fibonacci program.

What is indirect recursion?

A method test1(), invoking test2(), test2() further invokes test1(). This is termed as indirect recursion. In the example taken there are only two methods involved, also remember that there can be more methods involved, in indirect recursion. Indirect recursion may also end up with java.lang.StackOverFlowError exception, if not used cautiously.

Below code snippet shows non recursive method, as display() invokes super.display(), and not itself.

class Abc{
public void display()
{
System.out.println("Abc.display()");
}
}

class Xyz extends Abc{
public void display()
{
super.display(); //invokes display() method of Base class
System.out.println("Xyz.display()");
}
}

You may also like to read:
When OutOfMemoryException is thrown?
Difference between checked and unchecked Exception?
Purpose of static keyword?
How to invoke Base class constructor?

Why rethrow an Exception in Java?

What is rethrowing an Exception

When an Exception is thrown from your code,
1. You can handle handle the Exception completely, by using try and catch blocks you handle the Exception, and further throw the Exception object. OR
2. Use throws with method declaration, to indicate that invokers of the method need to handle the Exception, or further throws it.

Another option we have here is a combination of above both. That is, the Exception is handled, with try, catch blocks, and further throw the Exception.

Below is an example, of the same.

class TDemo22{
	public void met2() throws Exception
	{
	try
	{
	String str="2abcd3";

	int i = Integer.parseInt(str);
	}
	catch(Exception ep)
	{
	System.out.println("Exception catching");
	throw ep;
	}
	}
}

public class NumberFormatDemo {
	public static void main(String args[])
	{
	try{
	TDemo22 td2 = new TDemo22();
	td2.met2();

	}catch(Exception e)
	{
	e.printStackTrace();
	}
	}
}

There are two different ways, an Exception can be re thrown.
1. catch an Exception, and further throw same Exception object(as shown in above example)
2. catch an Exception, and further create a new Exception object, and throw it(as shown in below example)

class MyException extends Exception{
}

class TDemo22{
	public void met2() throws Exception
	{
	try
	{
	String str="2abcd3";

	int i = Integer.parseInt(str);
	}
	catch(Exception ep)
	{
	System.out.println("Exception catching");
	throw new MyException(); //re throwing a new Exception object
	}
	}
}

public class NumberFormatDemo {
	public static void main(String args[])
	{
	try{
	TDemo22 td2 = new TDemo22();
	td2.met2();

	}catch(Exception e)
	{
	e.printStackTrace();
	}
	}
}

When rethrowing an Exception may be required?
1. When you want to partially handle Exception situation, and further let invokers of your method, to handle the Exception.
2. When you want to hide class name of your internal exception, and rethrow another Exception.

You may also like to read:
How to print stack trace to a log file
List of inbuilt exception in Java
What is RuntimeException
How to create your own Exception?

Internal implementation of ArrayList and LinkedList Collections

ArrayList underlying implementation is based on Traditional Array data structure. Read Arrays in Java , for details on Arrays.

This post focuses on internal working of ArrayList and LinkedList Collections.

java.util.ArrayList class, is internally implemented as array.

What is array data structure?

An Array is a simplest data structure, which stores same type of elements, sequentially in memory.

Static Array
Static Array

Advantage of array

Accessing an element is very fast. Since base address of array is known, the required element which need to be fetched, can be retrieved, just by doing some manipulations on base address.

Disadvantage of array

Adding an element in between or in the beginning is very slow. Reason is, other existing elements need to be moved right by one position, and new element can be added, to the free slot created. This hits performance of program, and hence it is not recommendable to use Arrays for such situations.

java.util.LinkedList class is internally implemented using linked list data structure.

What is linked list data structure

linked list is a data structure, whose elements are not stored sequentially in memory, and are scattered in the memory. As shown in below picture, each node has Element, and reference to next and previous nodes.

what is linked list
linked list data structure

Advantage of link list data structure

An element can be added any where in between, just by changing previous and next references, as shown in below picture. This operation is slow in an array, as briefed above in array section.

Size of linked list can shrink or increase, during run time, based on the requirement.

Disadvantage of link list data structure

To Access an element, all elements need to be traversed, until the specific required element is reached. Hence searching an element is slower.

Another disadvantage of linked list is, there will be wastage of small memory, since each node need to store references to previous and next nodes.

You may also like to read:
Create our own linked list
When to use List and Set
Which are non synchronized Collections?
Generic version HashSet example

Access Specifier and Scope

Below are Access Specifiers supported in Java.
1. private
2. public
3. protected
4. default or none

private, public, protected are Access specifiers, which can be used only for members(data members and member methods) of a class.

private members can be accessed only within the class.

public members can be accessed with the class, other classes in current package, classes in other package.

protected members can be accessed within the class, and in the immediate derived class.

members with no access specifiers can be accessed within the class, and other classes only within current package.

Lifetime of variables

Lifetime of a variable, depends on the place where it has been declared.

Life time of Data members or instance variables is same as the object, in which they exist. An object is destroyed by garbage collector Java when there are no more reference to that object.

Local Variables:
Local variables are the variables declared in the method body. Local variable are available within method body until method returns.

Arguments or Parameters:
Arguments or Parameters are passed to constructor or methods, and are available until the constructor or method returns.

Also variables can be declared in a block(Eg. if, else block,etc…), within a method. Such variables are available only within the block where they have been declared.

Below is an example code snippet:

class Test1
{
	int i,j; //data members or member variables or instance variables

	Test1()//constructor
	{
	i = 20;
	j = 11;

	System.out.println("Test1() Constructor");
	}

	void add() //member methods
	{
	int k; //local variable i..e not a member variable of Test1 class
	//NOTE: k cannot be accessed from object of Test1 class
	k = i+j;
	System.out.println("Add Result is:"+k);
	}

	void sub()
	{
	int l = i-j; //l is local variable
	System.out.println("Sub Result is:"+l);
	}
}

public class ClassDemo {
//execution starts from here
public static void main(String args[])
{
//obj is local object
	Test1 obj; //declaring object reference
	obj=new Test1(); //creating object of Test1 class
	obj.add(); //invoking add() method of Test1 class, using object obj

	obj.sub();
}
}

You may also like to read:
purpose of static block
what is for each loop, in java

Difference between List and Set

Difference between List and Set
List and Set are interfaces and in java.util package.
Base interface for List and Set is java.util.Collection interface.

List can store duplicate object, but Set does not store duplicate objects.

Iterator and ListIterator can be used to traverse thru the elements of List. But only Iterator can be used to
traverse thru the elements of Set.

List stores elements in the same order as they are added. But Set stores the elements in different order, than they are added.

Difference between ListIterator and Iterator

List has two different implementations, ArrayList and LinkedList. ArrayList internal implementation is based on arrays, and LinkedList internal implementation is based on linked list data structure.

Set has two different implementations, HashSet and TreeSet. HashSet internal implementation is based on hashing the elements, TreeSet is based on Red Back Tree data structure.

ArrayList example:


import java.util.*;
public class ArrayListDemo {

	public static void main(String[] args) {

	//List allows duplicate values, stores values in the order given/added
	//Dynamic Arrays, can shrink or increase size dynamically unlike normal arrays
	ArrayList al = new ArrayList();
	al.add("BCD");
	al.add(0, "A1");
	al.add("A2");
	al.add(2, "A3");
	al.add(3, "A4");

	al.add(0, "C1");

	System.out.println("ArrayList is:"+al);

	Iterator itr = al.iterator();
	//using Iterator, we can traverse only in forward direction
	for(;itr.hasNext();)
	{
	String str = (String)itr.next(); //returns Object
	System.out.println(str+" ");
	}

	ListIterator litr = al.listIterator();

	for(;litr.hasNext();)
	{
	String str = (String)litr.next(); //returns Objectr

	//using ListIterator we can traverse backward as well
	//String pstr = (String) litr.previous();

	System.out.println("Next is "+str);
	}

	System.out.println("-------------------------");

	al.remove(2);
	//Getting Array
	Object obj[] = al.toArray();

	for(int i=0;i

output:
ArrayList is:[C1, A1, BCD, A3, A4, A2]
C1
A1
BCD
A3
A4
A2
Next is C1
Next is A1
Next is BCD
Next is A3
Next is A4
Next is A2
-------------------------
C1
A1
A3
A4
A2

HashSet example:


import java.util.*;

public class SetDemo {

public static void main(String args[])
{
//stores unique values only, no guarantee in the order of objects stored
HashSet hs = new HashSet();

hs.add("to");
hs.add("test");
hs.add("random1");
hs.add("string");
hs.add("some");
hs.add("random1");

System.out.println(" :"+hs);

Iterator itr = hs.iterator();

while(itr.hasNext())
{
System.out.println(itr.next());
}

//ListIterator not available for Set

Enumeration enm=Collections.enumeration(hs);

for(;enm.hasMoreElements();)
{
	System.out.println(enm.nextElement());
}

}

}

output:
:[to, test, string, random1, some]
to
test
string
random1
some
to
test
string
random1
some

You may also like to read:
Can a Collection be concurrent
HashSet using Generic class
How many loops are there in Java

operators in Java

Below are Operators supported, in Java

Arithmetic operators

+(addition), -(subtraction), *(multiplication), /(dividedby), %(Modulo – reminder of division)
++(increment) x++; means x = x+1;
–(decrement)

Difference between Pre increment and Post increment

Post increment
x++;
For eg, consider System.out.println(x++);
In above statement, first x is printed, and after that x is incremented

Pre increment
++x;
For eg, consider System.out.println(++x);
In above statement, first x is incremented, and after that x is printed

Similarly, pre and post increment can be used in other arithmetic expressions.

Difference between Pre decrement and Post decrement

Pre decrement and post decrement operator as well, can be used in arithmetic expressions.

Relational Operators or Comparison Operators

Relational or Comparison operators are used to perform comparison check between two variables or constants
x<3 (less than) > (greater than)
<= (less than or equal to) >= (greater than or equal to)
==( checking equal to),
!=(not equal to)

Generally Relational or Comparison expression evaluates to true or false.
Relational or Comparison operators are used with if, loops

Logical Operators

Logical operators are used two combine two or more Relational or Comparison expressions.
&&(Logical and): evaluates to true only if both operands are true
Eg.(y==3)&&(z>20)

||(Logical or): evaluates to true, when either of the operand is true

!(Logical not): Negates logical expression, converts true to false, and vice versa

logical or and not takes two operands, where as logical not takes one operand

Assignment Operators

=, +=(short hand assignment)
-=, *=, /=, %=
x op= y means x=x op y;
For eg. x+=y means x=x+y;
X*=y; means x =x*y;

Conditional Operator or Ternary Operator

?:

Conditional operator takes three arguments
usage:
relational_expression? expression_1 : expression_2;

If relational expression gets evaluated to true, expression_1 is returned, else expression_2 is returned.

Eg. b = (a == 15) ? 21 : 52;
As shown in above example, if value of a is 15, 21 is assigned to b, else 52 is assigned to b

Bitwise Operator

Bitwise operators perform operations on each binary representation
& – bitwise AND
| – bitwise OR
^ – bitwise XOR
<< - bit wise left shift >> – bit wise right shift

16 & 8
0010000(binary representation of 16)
0001000(binary representation of 8)
Result: 00000000

instanceof operator

instanceof example

We cannot overload operators in Java.How ever few operators like + has builtin overloading.

You may also like to read:
Basic data types in Java

How to install Java

Below are the steps involved in installing Java on Windows.

1. First find, if you are using Windows version is 32 bit or 64 bit.
2. Download and install JRE 32bit or 64bit(based on your Windows version), from below URL
http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html

What is JRE? JRE stands for Java Run time Environment, which comprises JVM(Java Virtual Machine) and Run time libraries required to run .class file i..e byte code.

How to Download JRE
Download JRE

3. Download and install JDK 32bit or 64bit(based on your Windows version), from below URL
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
How to Download JDK
Download JDK

What is JDK? JDK stands for Java Development Kit, which comprises tools required for developing and compiling Java Applications.
4.Set PATH environment variable
PATH need to be set, to access tools such as javac to be used any where on the installed system. If PATH is not set developer need to specify full absolute path
5.set CLASSPATH environment variable
6.Install IDE(Integrated Development Environment) of your choice. Also note that installing and setting up IDE is not compulsory. You can use IDE of your choice, Eclipse, Netbeans IDEs are being widely used for developing Java Applications.

How to Setup Eclipse for Java

1. Eclipse can be downloaded from below url
http://www.eclipse.org/downloads/packages/eclipse-ide-java-developers/junor
2. Unzip Eclipse downloaded zip file
3. Open eclipse.exe, whcih is Eclispe IDE.
NOTE: Eclipse is not installable setup file, instead it can be directly run, whenever you want to open Eclipse IDE.
4. To set common JRE, for all Java Projects
Select Preferences -> Java -> Installed JRE’s tab. Click Add, and follow on Screen instructions to complete adding JRE.
5. To set JRE for individual Java Projects in Eclipse IDE
a) Right click your project > properties
b) Select “Java Build Path” on left, then “JRE System Library”, click Edit…
c) Select “Workspace Default JRE”
d) Click “Installed JREs”
e) If you see JRE you want in the list select it (selecting a JDK is OK too)
f) If not, click Search…, navigate to Computer > Windows C: > Program Files > Java, then click OK
g) Now you should see all installed JREs, select the one you want and Click OK or Finish