How to Serialize an array or Collection of objects

Hope you have already gone thru basic working of Serialization. To Serialize an array of objects of a class, below are the steps.
1. The class whose array of objects need to be serialized, has to implement java.io.Serializable interface
2. Create another class, which has an array or Collection of objects, as a data member. This class also has to implement Serializable interface.
3. Now, you can follow normal steps to Serialize class created in above, step2

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication2;

import java.io.Serializable;

class StudentInfo implements Serializable
{
 //transient data members will not take part in Serialization   
 String name;
int rid;
 StudentInfo(String n, int r)
 {
  this.name = n;
  this.rid = r;
 }

 void printStudentInfo()
 {
     System.out.println("StudentInfo details Test:"+name+" "+rid+" ");
 }
 
 public String toString()
 {
     return "name="+name+", id="+rid;
 }
}


class StudentInfoArray implements Serializable{
    StudentInfo arr[];
    
    StudentInfoArray(StudentInfo arr[])
    {
        this.arr = arr;
    }
}
package javaapplication2;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeArray
{
    
 public static void main(String[] args)
 {
 try
 {
//Serialization starts here
  StudentInfo si1 = new StudentInfo("checkingnexttime", 310);
  
  StudentInfo si2 = new StudentInfo("checkingnexttime1", 311);
  
  StudentInfo si3 = new StudentInfo("checkingnexttime2", 312);
  
  StudentInfo sarr[] = {si1, si2, si3};
  
  StudentInfoArray sia = new StudentInfoArray(sarr);
  
  //.ser is a standard file extension, to store serialized object
  FileOutputStream fos = new FileOutputStream("C:\\student.ser");

  //instead of writing object stream to a file, it is also possible to send object thru 
  //Network using socket programming
  ObjectOutputStream oos = new ObjectOutputStream(fos);

  System.out.println("Serialing the object...");
  oos.writeObject(sia);
  oos.close();
  fos.close();  
  }
  catch (Exception e)
  { e. printStackTrace(); }
 }
}
package javaapplication2;

import java.io.*;

public class DeSerializeArray {
 public static void main(String[] args)
 {
 try
 {
  
  System.out.println("De serializing object...");
  //DeSerialization starts here
  FileInputStream fis = new FileInputStream("C:\\student.ser");
  ObjectInputStream ois = new ObjectInputStream(fis);
  StudentInfoArray toa = (StudentInfoArray)ois.readObject();

  System.out.println("before printing Object");

  for(StudentInfo si:toa.arr)//foreach
  {
      System.out.println(si);
  }
    
  //RMI(Remote Method Invocation) is based on Serialization/Deserialization
  }
  catch (Exception e)
  { e. printStackTrace(); }
    }
}

What is CallableStatement in java?

A procedure exists in database.
JDBC provides CallableStatement to invoke stored procedure available in database.
Below is simple procedure which accepts student id and produces student name as OUT parameter.

DELIMITER //
CREATE PROCEDURE getStdntName1(IN stdntid BIGINT, OUT stdntname VARCHAR(500))
BEGIN
SELECT sname INTO stdntname FROM students WHERE sid=stdntid;
END //
DELIMITER ;

Steps: #1. Save above stored procedure as a abcd.sql in C drive.
#2. From MySQL prompt, run the command “create database aaaa;
#3. Then run “use aaaa;
#4. Then create procedure in db by running “source c:\abcd.sql

Below is Java Program to invoke above stored procedure.

//STEP 1. Import required packages
import java.sql.*;

public class CallableStatementDemo {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/trial";

   //  Database credentials
   static final String USER = "root";
   static final String PASS = "abcdfe";
   
   public static void main(String[] args) {
   Connection conn = null;
   CallableStatement stmt = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName(JDBC_DRIVER);

      //STEP 3: Open a connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);

      //STEP 4: Execute a query
      System.out.println("Creating statement...");
      String sql = "{call getStdntName1(?, ?)}";//? is place holder for IN and OUT parameters
      stmt = conn.prepareCall(sql);
      
      //Bind IN parameter first, then bind OUT parameter
      int student_id = 9;
      stmt.setInt(1/*parameter number*/, student_id); // This would set ID
      // Because second parameter is OUT so register it
      stmt.registerOutParameter(2, java.sql.Types.VARCHAR);
      
      //Use execute method to run stored procedure.
      System.out.println("Executing stored procedure..." );
      stmt.execute(); //now stored procedure gets executed in the database

      //Retrieve student name with getXXX method
      String student_name = stmt.getString(2);//2 is OUT parameter number
      
      
      System.out.println("Student with ID:" +student_id + " is " + student_name);
      stmt.close();
      conn.close();
   }catch(SQLException se){
      //Handle errors for JDBC
      se.printStackTrace();
   }catch(Exception e){
      //Handle errors for Class.forName
      e.printStackTrace();
   }finally{
      //finally block used to close resources
      try{
         if(stmt!=null)
            stmt.close();
         conn.close();
      }catch(SQLException se2){
      }// nothing we can do
   }//end try
   System.out.println("Done!");
}//end main
}//end JDBCExample

You may also like to read:

How to Connect Java Program to a Database

purpose of join() method in Thread

join() method is defined in Thread class. join() method waits for a thread to die. That means, it causes the currently running threads to stop executing until the thread it joins with completes its task.


class NewThread1 implements Runnable{
	String name; //name of Thread
	Thread t;
	
	NewThread1(String threadname){
		name=threadname;
		t = new Thread(this,name);
		System.out.println("New thread:"+t);
		t.start();
	}
	
	public void run(){
		try
		{
		for(int i=5;i>0;i--)
		{
		System.out.println(name+":"+i);
		Thread.sleep(1000);
		}
		}
		catch(InterruptedException ie){
			System.out.println(name+" Interrupted");
		}
		
		System.out.println(name+" Exiting");
	}
	
	
}


public class JoinCheck {
	public static void main(String args[])
	{
	NewThread1 nt1=new NewThread1("One");
	NewThread1 nt2;
	NewThread1 nt3;
	NewThread1 nt4;
	//start the threads
	//nt1=new NewThread1("One");
	nt2=new NewThread1("Two");
	nt3=new NewThread1("Three");
	nt4=new NewThread1("Four");
	
	threads_status(nt1,nt2,nt3,nt4);
	try
	{
	nt1.t.join();
	nt2.t.join();
	nt3.t.join();
	nt4.t.join();

	
	
	System.out.println("completed all four threads");
	}catch(Exception ien)
	{
		System.out.println("main thread Interrupted");
	}
	
	threads_status(nt1,nt2,nt3,nt4);
	System.out.println("main thread Exiting");
	}

	private static void threads_status(NewThread1 nta,NewThread1 ntb,NewThread1 ntc,NewThread1 ntd)
	{
	System.out.println("Thread One Alive?"+nta.t.isAlive());
	System.out.println("Thread Two Alive?"+ntb.t.isAlive());
	System.out.println("Thread Three Alive?"+ntc.t.isAlive());
	System.out.println("Thread Four Alive?"+ntd.t.isAlive());
	}
	
}

How to Set priority to a Thread

By default all the threads created, get medium priority, unless a specific priority explicitly is set to the thread. Below are the priority related constants provided in Thread class.
Thread.MIN_PRIORITY (value is 0)
Thread.NORM_PRIORITY (value is 5, which is default priority)
Thread.MAX_PRIORITY (value is 10)

Any numeric value between 0 and 10 can be set as priority to a Thread. Below are priority related methods provided in Thread class
void setPriority(int priority);
int getPriority();

A thread with high priority gets allocated with more CPU time, compared to threads with relatively low priority threads. Hence a thread with high priority threads executes faster, compared to low priority threads.

			
class NewThread2 implements Runnable{
	String name; //name of Thread
	Thread t;
	
	NewThread2(String threadname,int priority){
		name=threadname;
		t = new Thread(this,name);
		System.out.println("New thread:"+t);
		t.start();
		t.setPriority(priority);
	}
	
	public void run(){
		try
		{
			for(int i=50;i>0;i--)
			{
			System.out.println(name+":"+i);
			//Thread.sleep(100);
			}
		}catch(Exception ie)
		{
		System.out.println("Exception:");
		ie.printStackTrace();
		}
		System.out.println(name+" Exiting");
	}
}


public class ThreadPriority {
	
	public static void main(String args[])
	{
	//start the threads

	NewThread2 nt2=new NewThread2("Two",Thread.MAX_PRIORITY);
	NewThread2 nt3=new NewThread2("Three",3/*Thread.NORM_PRIORITY*/);
	NewThread2 nt1=new NewThread2("One",Thread.MIN_PRIORITY);
		
	try
	{
	nt1.t.join();
	nt2.t.join();
	nt3.t.join();
	}catch(Exception ien)
	{
	System.out.println("main thread Interrupted");
	}
	
	
	System.out.println("Thread One Alive?"+nt1.t.isAlive());
	System.out.println("Thread Two Alive?"+nt2.t.isAlive());
	System.out.println("Thread Three Alive?"+nt3.t.isAlive());
	
	System.out.println("Main thread has exited");
	
	System.out.println("main thread Exiting");
	}

}

HTML, How to display shadow effect of the Text

Below is HTML code snippet, which shows how to display Text with shadow effect, using HTML, CSS. Please note that color of main text, shadow color, position of shadow, sharpness of shadow can be fully controlled, by changing corresponding values in below code snippet.

<html>
<head>
<style>
#shd {
text-shadow: 1px/*right*/ 1px/*bottom*/ 0px/*sharpness*/ red;

color:green;
}
</style>
</head>
<body>

<h1 id=”shd”>Text-shadow effect!</h1>

<div id=”shd”>
<p><b>Note:</b> This is Text only</p>
<p>Test only
</div>
</body>
</html>

how to display text with shadow

conditional statements in Java

Conditional/Control Flow statements
#1. to perform an action when a condition is true
if(condition)
{
//statements
}
Eg. if(z<20)
{
//statements
}
#2. to perform action1 when a condition is true, and perform another action, when condition is false
if(condition)
{
//statements 1
}else
{
//statements 2
}
#3.
if(condition1)
{
//statements
}
else if(condition2)
{
//statements
}
else if(condition3)
{
//statements
}
else
{
}

What is the control flow, when Exception occurs

Below is an example showing different flow of control, when different Exception occurs, during program execution.
However, exceptions should not be used only to control the flow, rather appropriate control flow statements can be used.


public class ExceptionControlFlow {
	public static void main(String[] args){
	try{
	System.out.println("stmt 1");
	Object obj = null; 
	System.out.println("stmt 2");
	obj.getClass(); //NullPointerException
	System.out.println("stmt 3");
	}
	catch(NullPointerException et)
	{
	System.out.println("stmt 4");
	System.out.println("Exception occurred:"+et.getMessage());
	}
	catch(Exception ep)
	{
	System.out.println("stmt 5");
	}
	}

}

can exceptions be nested

Exceptions can be nested, that means a try block can exist within another try block. Also note that a try block can exist in a catch block.

Below is an example showing nesting of Java Exceptions.


public class SimpleException {

	public static void main(String[] args) {
	try{
	System.out.println("in try");
	
	int arr[] = new int[20];
	
	arr[40] = 23;
	System.out.println("in try 2");
	
	try{
	if(true)
	{
	throw new Exception("Sample Exception");
	}
	}
	catch(Exception en)
	{
	System.out.println("Nested try catch:"+en.getMessage());
	}
	System.out.println("end of outside try");
	}
	catch(ArithmeticException e)
	{
	System.out.println("AE occurred:"+e.getMessage());
	}
	catch(ArrayIndexOutOfBoundsException ae)
	{
	System.out.println("ABE occurred:"+ae.getMessage());
	}
	catch(Exception en)
	{
	en.printStackTrace();
	System.out.println("Exception occurred:"+en.getMessage());
	}
	}

}

how to use throws in handling Exceptions

As briefed in difference between Checked and Unchecked Exception, unchecked exceptions may or may not be handled. But, be aware that all Checked Exceptions either need to be handled using try and catch blocks or need to be further thrown using throws keyword. However it is responsibility of invokers of the method(which throws Exception) to handle it with try catch blocks, or further throw using throws keyword.

throws keyword need to be used along with method declaration, it just indicates that the method may throw an Exception, and invokers of the method need to either handle it or further throws it.

Also note that multiple Exceptions separated with comma, can be used with throws keyword. For eg

public void show() throws NullPointerException, Exception
{
//..statements
}

This feature, helps third party framework to throw an Exception, and let application developers to handle it appropriately.

Below is an example of throws keyword.


class TDemo1{
	public void met1() throws Exception
	{
	if(true)
	{
		throw new Exception("Some Exception");
	}
	}
}

class TDemo2{
	public void met2() throws Exception,NullPointerException
	{

	TDemo1 td = new TDemo1();
		
	td.met1();
	}
}

public class ThrowsDemo {
	public static void main(String args[]) throws Exception
	{
	try{
	TDemo2 td2 = new TDemo2();
	td2.met2();
		
	}catch(Exception e)
	{
		
	e.printStackTrace();
	//printsline number, class name, file name where the exception has occurred
	//and the methods thru which exception has been propogated, until caught
	throw e;//further rethrowing the exception
	}
	finally{
	System.out.println("dsdsfds");
	}
		
	}
}

You may also like to read:
Create user defined Exception
How to create Unchecked Exception
List of exceptions in java.lang package

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();
	}

}