Java Hibernate tutorials


For Java Hibernate tutorials visit the link below :


http://javalite.io/activejdbc

Insert - Update - Delete in JDBC ....

Insert - Update - Delete in JDBC ....

package jdbcpack;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

//import com.mysql.jdbc.PreparedStatement;

public class InsUpdDel
{

    public static void main(String[] args)
    {
        Connection con=null;
        PreparedStatement pstat = null;
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
           
            pstat = con.prepareStatement("Insert into student values(?,?,?)");
            pstat.setInt(1, 2009);
            pstat.setString(2, "Rohit");
            pstat.setInt(3,22);
            int x= pstat.executeUpdate();
            if(x>=1)
                System.out.println("\n successfully inserted !!");
           
            System.out.println("\n........Updating .......");
           
            Scanner sc =  new Scanner(System.in);
            System.out.println("Please enter the sid");
            int i = sc.nextInt();
            pstat = con.prepareStatement("Update student set age=30 where sid=?");
                    pstat.setInt(1, i);
                            x= pstat.executeUpdate();
                            if(x>=1)
                                System.out.println("successfully updated !!");
                           
           
            System.out.println("\n.............Delete Statement........................");
           
           
            System.out.println("Please enter the sid to be deleted !!");
            i=sc.nextInt();
            pstat=con.prepareStatement("delete from student where sid=?");
            pstat.setInt(1,i);
            x= pstat.executeUpdate();
           
            if(x>=1)
                System.out.println("successfully Deleted !!");
            else
                System.out.println("not found !!");
           
           
           
        }
       
        catch(Exception ex)
        {
            System.out.println(ex.toString());
        }
        finally
        {
            try
            {
                con.close();
                pstat.close();
            }
   
            catch (SQLException e)
            {
                e.printStackTrace();
            }
   
        }
    }

}

Simple JDBC Programme

Simple JDBC Programme



package jdbcpack2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class Test1 {

    public static void main(String[] args)
    {
        Connection con=null;
        Statement stmt=null;
       
        try
        {
           
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
            stmt=con.createStatement();
            ResultSet rs = stmt.executeQuery("select *from student");
            while(rs.next())
            {
                System.out.println("Result :" + rs.getInt(1) + " " + rs.getString(2) + " " + rs.getInt(3));
               
            }
        }
        catch (ClassNotFoundException e)
        {
           
            e.printStackTrace();
        }
       
        catch (SQLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
   
    }

}


calculate Month from Two Dates

int calculateMonth()
{
int month;

month = this.getOpenDate().getMonth() - this.getCloseDate().getMonth();
int year =  this.getCloseDate().getYear()-this.getOpenDate().getYear();
month = month + year*12;
this.setTime(month);

return month;

}



--------------------------------------------------------------------------------------------------------------------------

public Date getCloseDate()
{
SimpleDateFormat ft = new SimpleDateFormat("dd/MM/yyyy");
Date dt = null;
try
{

dt =ft.parse( this.closeDate);
}

catch (ParseException e)
{

e.printStackTrace();
}
return dt;
}

-------------------------------------------------------------------------------------------------------------------------

public void setCloseDate(String closeDate) 
{
this.closeDate = closeDate;
}

Serialization-with Merge two files without no redundant object

package iopack;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

import pkg.Student;

public class SerializationTest {

public static void main(String[] args)
{
Student s = new Student("Ram",5005,"MCA",5);
Student s1 = new Student("Sham",5004,"MCA",4);
Student s2 = new Student("Nanda",5003,"MCA",3);
Student s3 = new Student("Krishna",5002,"MCA",5);
Student s4 = new Student("Krishna",5002,"MCA",5);

Set <Student> stt = new TreeSet<Student>(); // for Merging

ObjectOutputStream oos = null;

try
{
oos = new ObjectOutputStream(new FileOutputStream("D:\\Stud.ser"));
oos.writeObject(s);
oos.writeObject(s1);
oos.writeObject(s2);
oos.writeObject(s3);
oos.writeObject(s4);

System.out.println("Write done");

}

catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

catch (IOException e)
{

e.printStackTrace();
}
finally
{
try
{
oos.close();
}

catch (IOException e)
{

e.printStackTrace();
}
}

ObjectInputStream ois =null;
ObjectInputStream ois1 =null;

try
{
ois = new ObjectInputStream(new FileInputStream("D:\\Stud.ser"));
Student ss =(Student) ois.readObject();
Student ss1 =(Student) ois.readObject();
Student ss2 =(Student) ois.readObject();
Student ss3 =(Student) ois.readObject();
Student ss4 =(Student) ois.readObject();

//storing to TreeSet for Merging to a new file ..............

stt.add(ss);
stt.add(ss1);
stt.add(ss2);
stt.add(ss3);
stt.add(ss4);

System.out.println("Objectas added !");

//System.out.println(ss1+ " " +ss2 + " " + ss3);
}




catch (FileNotFoundException e)
{

e.printStackTrace();
}

catch (IOException e)
{

e.printStackTrace();
}

catch (ClassNotFoundException e)
{

e.printStackTrace();
}

finally
{
try
{
ois.close();
}

catch (IOException e)
{

e.printStackTrace();
}





//------------File Merging -----------------------------------------------------




ObjectOutputStream oosMerge = null;

try
{

oosMerge = new  ObjectOutputStream(new FileOutputStream("D:\\StudMerge.ser"));
Iterator<Student> itr = stt.iterator();
     

while(itr.hasNext())
       {
        Student ss = itr.next();
        oosMerge.writeObject(ss);
         
       }
     
       System.out.println(oosMerge);
     
       //Retrive from oosMerge file and print the data
     

   ois1 = new ObjectInputStream(new FileInputStream("D:\\StudMerge.ser"));
 
Student ss =(Student) ois1.readObject();
Student ss1 =(Student) ois1.readObject();
Student ss2 =(Student) ois1.readObject();
Student ss3 =(Student) ois1.readObject();
Student ss4 =(Student) ois1.readObject();

System.out.println(ss + "  " + ss1 + "  " + ss2 + "  " + ss3 + " " + ss4);


}

catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

catch (ClassNotFoundException e)

{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}


}
}

}

DataInputTest

package iopack;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataInputTest {

public static void main(String[] args)
{
int x= 20;
float f = 10.5f;
double d = 25.4;
DataOutputStream dos = null;
DataInputStream dis = null;


try
{
dos = new DataOutputStream(new FileOutputStream("D:\\mailto.txt"));
dos.writeInt(x);
dos.writeFloat(f);
dos.writeDouble(d);
System.out.println("Write Completo !");


}



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

catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

finally
{
try
{
dos.close();
}

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

try
{
dis =new DataInputStream(new FileInputStream("D:\\mailto.txt"));
int x1= dis.readInt();
float f1 = dis.readFloat();
double d1 = dis.readDouble();

System.out.println(x1);
System.out.println(f1);
System.out.println(d1);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

finally
{
try
{
dis.close();
System.out.println("dis closed !");
}

catch (IOException e)
{

e.printStackTrace();
}
}


}

}

FileReadWriteTest - File IO

package iopack;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileReadWriteTest
{

public static void main(String[] args)
{
File f = new File("D:\\exp.txt");
File f1 = new File("D:\\mailto.txt");


System.out.println(f.exists());
FileInputStream fis = null;
FileOutputStream fos = null;

try
{
fos = new FileOutputStream(f1);
fis= new FileInputStream(f);
int ch = 0;
char chr = 'm' ;
while ((ch = fis.read()) !=-1)
{

fos.write(chr);
chr= (char)ch;
System.out.print((char)ch);
}


}

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


catch(NullPointerException n)
{
n.printStackTrace();
}

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

finally
{
try
{
fis.close();
System.out.println("Closed");

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

}

}

File IO - SerializationTest

package iopack;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import pkg.Student;

public class SerializationTest {

public static void main(String[] args)
{
Student s = new Student("Ram",5005,"MCA",5);
ObjectOutputStream oos = null;

try
{
oos = new ObjectOutputStream(new FileOutputStream("D:\\Stud.ser"));
oos.writeObject(s);

System.out.println("Write done");

}

catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try
{
oos.close();
}

catch (IOException e)
{

e.printStackTrace();
}
}

ObjectInputStream ois =null;

try
{
ois = new ObjectInputStream(new FileInputStream("D:\\Stud.ser"));
Student ss =(Student) ois.readObject();

System.out.println(ss);
}

catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

finally
{
try
{
ois.close();
}

catch (IOException e)
{

e.printStackTrace();
}

}
}

}

Comma Separated File

 Comma Separated File.

package exercise;

import java.util.Arrays;
import java.util.StringTokenizer;
//Input Format
//JAVA 14, JEE 10, JME 12

public class CommaSepFile {

    public static void main(String[] args) {
        int i=0,j=0,k=0,tot=0,d=1,c=0,remai=0;
        boolean p=false;
        String s1[]=new String[6];
        Integer a[]=new Integer[10];
        String s3=Arrays.toString(args);
    StringTokenizer s=new StringTokenizer(s3,",");
   
    while(s.hasMoreElements())
    {
         s1[i]  = (String) s.nextElement();
        //System.out.println(x);
        i++;
    }
    s1[0]=s1[0].substring(1);
    //System.out.println(s1.length);
   
    for(String s2:s1)
    {
       
        if(i%2==0)
        {
            s1[j]=s2;
            System.out.print(s1[j]+" ");
            j++;
        }else
        {
            String q=s2.substring(1,3);
            a[k]=Integer.parseInt(q);
            System.out.print(a[k]+" ");
            tot=tot+a[k];
            k++;
       
           
        }
        a[k]=0;
        //System.out.print(s2+" ");
        //System.out.println("");
        i++;
        }
    System.out.println("\n\nSubject Time  Day");
k=0;
    while(tot>0)
    {
        if(p==false&&a[k]!=0)
        {
            if(a[k]>=8)
            {
                a[k]=a[k]-8;
            System.out.println(s1[k]+"     8     " +d);
            d++;
            tot=tot-8;
           
        }else
        {
            c=a[k];
            System.out.println(s1[k]+"     "+c+"     "+d);
            k++;
            tot=tot-c;
            p=true;
            }
        }else if(a[k]!=0&&p==true)
        {
            remai=8-c;
            System.out.println(s1[k]+"     "+remai+"     "+d);
            a[k]=a[k]-remai;
            tot=tot-remai;
            d++;
            p=false;
        }else
        {
            k++;
        }
    }
    }

}

Collections - Telephone Directry -Add / Remove

 Collections - Telephone Directry -Add / Remove

public class MapTest
{

    public static void main(String[] args)
    {
        Map mp = new Hashtable<String, String>();
        mp.put("Ram", "9830632010");
        mp.put("Sham", "9830632011");
        mp.put("Hari", "12001010002");
       
        System.out.println(mp);
       
        System.out.println( mp.containsKey("Ram"));
        mp.remove("Ram");
       
        System.out.println(mp);
       
       

    }

}

Retrive numeric values from an ArrayList

Retrive numeric values from an ArrayList

ArrayList a= new ArrayList();
        a.add(1);
        a.add(1.78);
        a.add('A');
        a.add("Hello");
        a.add(78);
        double sum=0;
        for(Object o:a)
        {
        Number d=null;
        // cast the object based on type and use it
        if(o instanceof Number)
        {
        d=(Number)o;
        sum =sum+d.doubleValue();
        }
    }
        System.out.print(sum);}


Library management -book borrow /Fine calculation

            Library management -book borrow /Fine calculation


package muttablepack;

public class Book {

    private int id;
    private String name;
   
    public Book(){}
   
    public Book(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

   
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Book [id=" + id + ", name=" + name + "]";
    }
   
   
}


--------------------------------------------------------------------------------------------------------------------
package muttablepack;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Borrow
    {

    private int slno;
    private Member member;
    private Book book;
    String borrowDate;
   
   
   
    public Borrow(){}

   

    public Borrow(int slno, Member member, Book book, String borrowDate)
    {
        this.slno = slno;
        this.member = member;
        this.book = book;
        this.borrowDate = borrowDate;
    }



    public Member getMember()
    {
        return member;
    }

    public void setMember(Member member)
    {
        this.member = member;
    }

    public Book getBook()
    {
        return book;
    }

    public void setBook(Book book)
    {
        this.book = book;
    }



    public int getSlno()
    {
        return slno;
    }



    public void setSlno(int slno)
    {
        this.slno = slno;
    }



    public String getBorrowDate()
    {
        return borrowDate;
    }



    public void setBorrowDate(String borrowDate)
    {
        this.borrowDate = borrowDate;
    }
   
   
}


--------------------------------------------------------------------------------------------------------
package muttablepack;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class Library {

    private ArrayList<Member> memberList = new ArrayList<Member>();
    private ArrayList<Book> bookList = new ArrayList<Book>();
    static Date date = new Date();
   
   
    public Library(){}
    public void addBook(Book book)
    {
         bookList.add(book);
    }
    public void addMember(int index, Member member)
    {
        memberList.add(index, member);
    }
    public ArrayList searchMember()
    {
        return memberList;
    }
   
    public static Date getDate() {
        return date;
    }
    public static void setDate(Date date)
    {
        SimpleDateFormat ft = new SimpleDateFormat("dd/MM/yyyy");
        ft.format(date);
        Library.date = date;
    }

    public String issue(Book book, Member member)
    {
        if(!member.hasBook())
        {
        member.setBook(book);
        return "issued the book successfully";
        }
        else
            return " member cant access more than one book";
       
    }

    public double bill(Borrow b) throws ParseException
    {
        double amount = 0.0;
        SimpleDateFormat ft = new SimpleDateFormat("dd/MM/yyyy");
        Date d = ft.parse(b.getBorrowDate());
        int days =  (int) (Library.getDate().getTime() - d.getTime())/(24*60*60*1000);
        System.out.println("days = " + days);
        if(days<=7)
        {
            days = 0;
            amount = 0.0;
        }
        else if ((days>7) && (days<=30))
        {
           
            days = days - 7;
            System.out.println("inside days = " + days);
            amount = days * 10;
           
        }
        else if((days>30) && (days<=60))
        {
            days = 23 + (days - 30);
            amount = days * 50;
        }
        else
            {
                int remainingDays  = days - 53;
                double months = Math.ceil(remainingDays/30);
                amount = 53 * 50 + months * 50;
            }
        return amount;
       
    }

    public static void main(String ar[]) throws ParseException
    {
        Library l = new Library();
        Book b1 = new Book(100,"Java");
        Member m1 = new Member(2000,"Vikas");
        l.addBook(b1);
        l.addMember(0, m1);
        System.out.println(l.issue(b1, m1));
        //System.out.println(l.issue(b1, m1));
        Borrow b = new Borrow(1, m1, b1, "10/10/2014");
        System.out.println(b.getBorrowDate());
        System.out.println(l.bill(b));
    }
}

Anagram using Java !

 Anagram using Java !


package pkgArrayToString;
import java.util.*;
public class Anagram {

    public static void main(String[] args)
    {
         Scanner scn = new Scanner(System.in);
         boolean b=false;
       
            System.out.println("Put in a set: ");
            String input = scn.nextLine();
           
            System.out.println(input);
           
            Scanner tokenizer = new Scanner(input);
           
            tokenizer.useDelimiter(" ");
            ArrayList<String> arr = new ArrayList<String>();
           
            while(tokenizer.hasNext())
            {
                arr.add(tokenizer.next());
            }
           
            for (int i=0;i<arr.size();i++)
            {
                String strAng = arr.get(i);
                for (int j=0;j<arr.size();j++)
                {
                    b= Check(strAng,arr.get(j));
                    if (b==true)
                        System.out.println("The strings are Anagram :" + strAng + "And" + arr.get(j));
                }
            }
    scn.close();
    tokenizer.close();
   
    }
   
    public static boolean Check(String stMain , String str2)
    {
       
        boolean chk=false;
        stMain= stMain.toLowerCase();
        str2= str2.toLowerCase();
       
        char[] crMain = stMain.toCharArray();
        char [] crVar= str2.toCharArray();
        if(Arrays.equals(crMain, crVar)==true)
        {
            return chk;
        }
        else
        {
        Arrays.sort(crMain);
        Arrays.sort(crVar);
        chk=Arrays.equals(crMain, crVar);
        }
        return chk;
       
       
    }
}


Words to Sentence in JAVA

.......Words to Sentence in JAVA .......

String [] arr= {"hello","How","are","You","??"};
        System.out.println("The words are :\n");
        for(String s:arr)
        System.out.println(s);
       
       
        //----------------------Form a sentence from those words==============
       
        System.out.println("The sentence is :\n");
        String joined = String.join(" ", arr);;
        System.out.println(joined);
       

Garbage collector

The Garbage Collector
Some object-oriented languages require that you keep track of all the objects you create and that you explicitly destroy them when they are no longer needed. Managing memory explicitly is tedious and error-prone. The Java platform allows you to create as many objects as you want (limited, of course, by what your system can handle), and you don't have to worry about destroying them. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection.
An object is eligible for garbage collection when there are no more references to that object. References that are held in a variable are usually dropped when the variable goes out of scope. Or, you can explicitly drop an object reference by setting the variable to the special value null. Remember that a program can have multiple references to the same object; all references to an object must be dropped before the object is eligible for garbage collection.
The Java runtime environment has a garbage collector that periodically frees the memory used by objects that are no longer referenced. The garbage collector does its job automatically when it determines that the time is right.

“finalize ()” is called by the garbage collector no an object when garbage collection determines that there are no more references to the object. A sub class overrides the “finalize ()” to dispose of of system resource or to perform other clean-up.
Garbage collection is a tool which removes unreferenced object from the memory. When garbage collector remove object from the memory it calls the finalize method.    
There is no guarantee when garbage collector will be invoked and what object referenced will be removed.

Using System.gc ()-         we can invoke garbage collector.

------------------------------->>>>>>>>>>>>
/**Garbage collector dosenot gureenties when and what object will be removed,
but gureenties its will remove unrefrence object only if removes,
by overriding the finalize method **/

public class GarbageDemo
{
public static void main (String...args)
{
int i=0;
while(i++<10000000)
{
MyClass mc=new MyClass();
mc.i=i;
}
System.gc();//Used to invoke garbage collector.
}
}
class MyClass
{
int i=0;
public void finialize()
//This method is called Automatically for clearing unreferenced object.

{
System.out.println("Object removed"+i);
}
}

ArrayList insert / Search / Delete in Java !

ArrayList insert / Search / Delete in Java !

package PKG;
import java.util.*;

//import javax.xml.bind.ValidationEvent;

public class ArrayListProg {

    public static void main(String[] args)
    {
        Integer valDel;
        int index;
       
        ArrayList<Integer> arr = new ArrayList();
        Scanner sc = new Scanner(System.in);
        System.out.println("Please Enter the elements of array");
        //Insert.................................................
       
        for (int i=0;i<5;i++)
        {
        arr.add(sc.nextInt());
        }
   
        do{
        // .. Delete.............................................
        System.out.println("Please Enter the value to be deleted");
        valDel= sc.nextInt();
        for (Integer i:arr)
        {
            if(arr.contains(valDel))
            {       
                index = arr.indexOf(valDel);
               
                arr.remove(index);
                System.out.println("Deleted");
                break;
            }
            /*else
                System.out.println("not found :");*/
        }
        //....Find...............................................
       
       
        System.out.println("Please Enter the value to be Searched :");
        valDel= sc.nextInt();
       
        if( arr.contains(valDel)==true)
            System.out.println("Value Exist :");
        else
            System.out.println("Value not Exist :");
       
        System.out.println("Please Enter 555 to exit \n any other number to continue :");
        valDel=sc.nextInt();
        } while (valDel !=555);
    }

}

Matrix Addition Using JAVA

 Matrix Addition Using JAVA
  
package PKG;
import java.util.Scanner;

public class MatrixAddition {

    static final int ROW=3;
    static final int COL=3;
   
   
    public static void main(String[] args)
    {
        Scanner sc= new Scanner (System.in);
        int [][] arr1 = new int[ROW][COL];
        int [][] arr2 = new int [ROW][COL];
        int [][] Result = new int [ROW][COL];
        int i=0 ;
        int j=0 ;
        System.out.println("1st array :");
        for(i=0;i<ROW;i++)
        {
            for(j=0;j<COL;j++)
            {
                arr1[i][j] = sc.nextInt();
               
            }
        }
        System.out.println("2nd array :");
       
        for(i=0;i<ROW;i++)
        {
            for(j=0;j<COL;j++)
            {
                arr2[i][j] = sc.nextInt();
               
            }
        }
       
        for(i=0;i<ROW;i++)
        {
            for(j=0;j<COL;j++)
            {
               
                Result[i][j]=arr1[i][j] + arr2[i][j];
               
               
            }
        }
       
        System.out .println("Result : ");
       
        for(i=0;i<ROW;i++)
        {
            for(j=0;j<COL;j++)
            {
               
                System.out.print(Result[i][j]+"\t");
               
               
            }
           
            System.out.println("");
        }
       
    }

}