Sunday, April 26, 2015

Serialization

package com.sync;

import java.io.Serializable;

public class Student implements Serializable {
    int id;
    String name;

    public Student(int idVal, String nameVal) {
        this.id = idVal;
        this.name = nameVal;
    }
}


package com.sync;

import java.io.*;

class Persist {
    public static void main(String args[]) throws Exception {
        Student s1 = new Student(211, "renu");

        FileOutputStream fout = new FileOutputStream("f.txt");
        ObjectOutputStream out = new ObjectOutputStream(fout);

        out.writeObject(s1);
        out.flush();
        System.out.println("success");
    }
}

Synchronization

package com.sync;

class Table {

    synchronized void printTable(int n) {// method not synchronized
        for (int i = 1; i <= 5; i++) {
            System.out.println(n * i);
            try {
                Thread.sleep(400);
            } catch (Exception e) {
                System.out.println(e);
            }
        }

    }
}

class MyThread1 extends Thread {
    Table t;

    MyThread1(Table t) {
        this.t = t;
    }

    public void run() {
        t.printTable(5);
    }

}

class MyThread2 extends Thread {
    Table t;

    MyThread2(Table t) {
        this.t = t;
    }

    public void run() {
        t.printTable(100);
    }
}




Creating test class

package com.sync;

class TestSynchronization1 {
    public static void main(String args[]) {
        Table obj = new Table();// only one object
        MyThread1 t1 = new MyThread1(obj);
        MyThread2 t2 = new MyThread2(obj);
        t1.start();
        t2.start();
    }
}

Tuesday, April 21, 2015

Threads Sample Code

class RunnableDemo implements Runnable {
    //class RunnableDemo extends Thread
   private Thread t;
   private String threadName;
  
   RunnableDemo(String name){
       threadName = name;
       System.out.println("Creating " +  threadName );
   }
  
   public void start ()
   {
      System.out.println("Starting " +  threadName );
      if (t == null)
      {
         t = new Thread(this, threadName);
         t.start();
      }
   }

   public void run() {
          System.out.println("Running " +  threadName );
          try {
             for(int i = 4; i > 0; i--) {
                System.out.println("Thread: " + threadName + ", " + i);
                // Let the thread sleep for a while.
                Thread.sleep(60*1000);
             }
         } catch (InterruptedException e) {
             System.out.println("Thread " +  threadName + " interrupted.");
         }
         System.out.println("Thread " +  threadName + " exiting.");
       }
      
}



public class TestDemo {
   
    public static void main(String args[])
    {
        RunnableDemo demo = new RunnableDemo("Thread1");
       
        demo.start();
    }

}

Sunday, April 19, 2015

Threads



There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface. 

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run(). 

1. public void run(): is used to perform action for a thread.

Starting a thread:

start() method of Thread class is used to start a newly created thread. It performs following tasks: 
· A new thread starts(with new callstack).
· The thread moves from New state to the Runnable state.
· When the thread gets a chance to execute, its target run() method will run.

Life Cycle of a Thread:

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.

· 
New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.
· 
· 
Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.
· 
· 
Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.
· 
· 
Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
· 
· 
Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.
· 

Monday, April 13, 2015

JDBC Example

package com.JDBC;

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



public class JDBCExample {

public static void main(String arg[]) {

 Connection connection = null;
 //Register the driver class
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("MySQL JDBC Driver Registered!");
         //Creating connection
            //            driver     //service url   / DBName , username, pwd
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
            System.out.println("SQL Connection to database established!");

            Statement stmt = connection.createStatement();
            ResultSet rows = stmt.executeQuery("select * from users");
           
            while (rows.next())
            {
             System.out.println(rows.getInt(1));
             System.out.println(rows.getString("username"));
             System.out.println(rows.getString("password"));
           
            }
           
            //Creating thePrepare Statement
           
            PreparedStatement pstmt = connection.prepareStatement("insert into users values (?,?,?)");
            pstmt.setInt(1, 3);
            pstmt.setString(2, "Murali");
            pstmt.setString(3, "pswd1");
           
            //Executing the Query
           
            int norows = pstmt.executeUpdate();
            System.out.println("No. of rows inserted; " +norows);
           
        }
       
        catch (ClassNotFoundException e) {
            System.out.println("MySQL JDBC Driver not found !!");
            return;
        }
        catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            return;
        } finally {
            try
            {
                if(connection != null)
                    connection.close();
                System.out.println("Connection closed !!");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
}

}

Monday, April 6, 2015

JDBC Code

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

public class JDBCExample {

public static void main(String arg[]) {

Connection connection = null;
//Register the driver class
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("MySQL JDBC Driver Registered!");
        //Creating connection
            //  driver     //service url   / DBName , username, pwd
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "test");
            System.out.println("SQL Connection to database established!");

       
        }
        catch (ClassNotFoundException e) {
            System.out.println("MySQL JDBC Driver not found !!");
            return;
        }
        catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            return;
        } finally {
            try
            {
                if(connection != null)
                    connection.close();
                System.out.println("Connection closed !!");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
}

}

Wednesday, April 1, 2015

ArrayList with Beans

Employee.java (Bean class)

public class Employee {

private int empId;
private String empName;
private int salary;
private String email;

public int getEmpId() {
return empId;
}
public void setEmpId(int employeeId) {
this.empId = employeeId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}

@Override
public String toString() {
String employeedetails = this.empId+","+this.empName+","+this.email+","+this.salary;
return employeedetails;
}
}



ArrayList Implementation
import java.util.ArrayList;
import java.util.Iterator;


public class ListExample {
public static void main(String args[])
{
Employee emp = new Employee();
emp.setEmpId(1);
emp.setEmpName("Murali");
emp.setEmail("murali@gmail.com");
emp.setSalary(60000);
Employee emp1 = new Employee();
emp1.setEmpId(2);
emp1.setEmpName("Renu");
emp1.setEmail("renu@gmail.com");
emp1.setSalary(45000);
ArrayList<Employee> employeeList = new ArrayList<Employee>();
employeeList.add(emp);
employeeList.add(emp1);
Iterator<Employee> itr = employeeList.iterator();
while(itr.hasNext())
{
Employee employee = itr.next();
System.out.println(employee.toString());
System.out.println("Employee id is "+employee.getEmpId());
System.out.println("Employee name is "+employee.getEmpName());
System.out.println("Employee email is "+employee.getEmail());
System.out.println("Employee salary is "+employee.getSalary());
}
}

}

JDBC Basics

Creating JDBC Application:

There are six steps involved in building a JDBC application which I'm going to brief in this tutorial:

Import the packages:

This requires that you include the packages containing the JDBC classes needed for database programming. The package needed for JDBC is java.sql.*

Register the JDBC driver:

This requires that you initialize a driver so you can open a communications channel with the database. 
The driver for MySql is "com.mysql.jdbc.Driver" 
The driver for Oracle is "oracle.jdbc.driver.OracleDriver"

Open a connection:

This requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database. This method requires Database URL, username, Password.

Execute a query:

This requires using an object of type Statement or PreparedStatement for building and submitting an SQL statement to the database
Extract data from result set:
This step is required in case you are fetching data from the database. You can use the appropriate ResultSet.getXXX() method to retrieve the data from the result set 

Clean up the environment:

You should explicitly close all database resources versus relying on the JVM's garbage collection 

Monday, March 30, 2015

SQL Syntax

select columnnames from tablename where condition;
Eg:
SELECT empid,empname,email,salary FROM employee WHERE empid=1;

insert into tablename(col1,col2...) values(val1,val2,...)
Eg:
INSERT INTO employee(empid,empname,email,salary) VALUES(1,'xxxx','xxx@gmail.com',10000);


delete from tablename where condition;
Eg:
DELETE FROM employee WHERE empid=1;


update employee set empname='cccc' where empid=1;

Monday, March 23, 2015

IO Stream

A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.

OutputStream

Java application uses an output stream to write data to a destination, it may be a file,an array,peripheral device or socket.
InputStream

Java application uses an input stream to read data from a source, it may be a file,an array,peripheral device or socket.

FileInputStream and FileOutputStream (File Handling)

In Java, FileInputStream and FileOutputStream classes are used to read and write data in file. In another words, they are used for file handling in java.

import java.io.FileOutputStream;

class Test {
public static void main(String args[]) {
try {
FileOutputStream fout = new FileOutputStream("C:\\abc.txt"); // It is creating a new file
String s = "Sachin Tendulkar is my favourite player!!!!!";
byte b[] = s.getBytes();// converting string into byte array
fout.write(b); //Sending Byte[] to write method in FileOutputStream
//fout.close();  
/*FileOutputStream fout1 = new FileOutputStream("C:\\abc.txt");*/
String str = "New char";
byte[] b1 = str.getBytes();
fout.write(b1);
System.out.println("success...");
} catch (Exception e) {
System.out.println(e);
}
}
}

Tuesday, March 17, 2015

Queue

package com.queuesample;

import java.util.*;

public class QueueDemo {

public static void main(String[] args) {

System.out.println( "Queue in Java" );
System.out.println("-----------------------" );
System.out.println("Adding items to the Queue"  );
// Creating queue would require you to create instance of LinkedList
// and assign
// it to Queue
// Object. You cannot create an instance of Queue as it is abstract
Queue queue = new LinkedList();

// you add elements to queue using add method
queue.add("Java");
queue.add(".NET");
queue.add("Javascript");
queue.add("HTML5");
queue.add("Hadoop");

System.out.println( "Items in the queue..." + queue );
System.out.println("Before removing "+queue.element());
// You remove element from the queue using .remove method
// This would remove the first element added to the queue, here Java
System.out.println("remove element: " + queue.remove() );

// .element() returns the current element in the queue, here when "java"
// is removed
// the next most top element is .NET, so .NET would be printed.
System.out.println("retrieving element: " + queue.element()  );

// .poll() method retrieves and removes the head of this queue
// or return null if this queue is empty. Here .NET would be printed and
// then would
// be removed
// from the queue
System.out.println("remove and retrieve element, null if empty: "
+ queue.poll() );
System.out.println("After the polling method "+queue.element());

// .peek() just returns the current element in the queue, null if empty
// Here it will print Javascript as .NET is removed above
System.out.println("retrieve element, null is empty " + queue.peek()
);
PriorityQueue priorityQueue = (PriorityQueue)queue;
}
}

Monday, March 16, 2015

Java API - Predefined Packages

Package NameExample ClassesFunctionality (Purpose)
java.langSystem, String, Object, Thread, Exception etc.These classes are indispensable for every Java program. For this reason, even if this package is not imported, JVM automatically imports.
java.utilThese are called as utility (service) classes and are used very frequently in coding.
java.ioFileInputStream, FileOutputStream, FileReader, FileWriter, RandomAccessFile, BufferedReader, BufferedWriter etc.These classes are used in all I/O operations including keyboard input.
java.netURL, ServerSocket, Socket, DatagramPacket, DatagramSocket etc.Useful for writing socket programming (LAN communication).
java.appletAppletContext, Applet, AudioStub, AudioClip etcRequired for developing applets that participate on client-side in Internet (Web) programming.
java.awtButton, Choice, TextField, Frame, List, Checkbox etc.Essential for developing GUI applications.
java.awt.eventMouseListener, ActionListener, ActionEvent, WindowAdapter etc.Without these classes, it is impossible to handle events generated by GUI components
java.sqlDriverManager, Statement, Connection, ResultSet etcRequired for database access in JDBC applications.

Thursday, March 12, 2015

HashMap Example

package com.mapsample;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class MapDemo {

public static void main(String[] args) {

Hashtable<String, String> hashtableobj = new Hashtable<String, String>();
hashtableobj.put("Alive is ", "awesome");
hashtableobj.put("Love", "yourself");
hashtableobj.put("Clean", "World");
//hashtableobj.put(null,"Testing");

System.out.println("Hashtable object output :" + hashtableobj);

HashMap hashmapobj = new HashMap();
hashmapobj.put("Alive is ", "awesome");
hashmapobj.put("Love", "yourself");
hashmapobj.put("Clean", "World");
//hashmapobj.put(null,"Testing");
System.out.println("HashMap object output :" + hashmapobj);

Set keys = hashmapobj.keySet();
System.out.println(keys);
Iterator itr = keys.iterator();
while(itr.hasNext())
{
String key = itr.next().toString();
System.out.println("Key is "+key+" and value is "+hashmapobj.get(key));
}





// Create a hash map
/* HashMap hm = new HashMap();
// Put elements to the map
hm.put("Zara", new Double(3434.34));
hm.put("Mahnaz", new Double(123.22));
hm.put("Ayan", new Double(1378.00));
hm.put("Daisy", new Double(99.22));
hm.put("Qadir", new Double(-19.08));

// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into Zara's account
double balance = ((Double) hm.get("Zara")).doubleValue();
hm.put("Zara", new Double(balance + 1000));
System.out.println("Zara's new balance: " + hm.get("Zara"));

TreeMap treeMap = new TreeMap();

treeMap.put("Zara", new Double(3434.34));
treeMap.put("Mahnaz", new Double(123.22));
treeMap.put("Ayan", new Double(1378.00));
treeMap.put("Daisy", new Double(99.22));
treeMap.put("Qadir", new Double(-19.08));
System.out.println(treeMap);


*/ }
}

Map

The java.util.Map interface represents a mapping between a key and a value. The Map interface is not a subtype of the Collection interface.
A HashMap contains values based on the key. It implements the Map interface and extends AbstractMap class.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.


The java.util.SortedMap interface is a subtype of the java.util.Map interface, with the addition that the elements stored in the map are sorted internally.
By default the elements are iterated in ascending order, starting with the "smallest" and moving towards the "largest". But it is also possible to iterate the elements in descending order using the method TreeMap.descendingKeySet().

Set Overview

HashSet class

contains unique elements only.
Difference between List and Set:

List can contain duplicate elements whereas Set contains unique elements only. It makes no guarantees about the sequence of the elements when you iterate them.

LinkedHashSet differs from HashSet by guaranteeing that the order of the elements during iteration is the same as the order they were inserted into the LinkedHashSet. Reinserting an element that is already in the LinkedHashSet does not change this order.


TreeSet also guarantees the order of the elements when iterated, but the order is the sorting order of the elements. In other words, the order in which the elements whould be sorted if you used a Collections.sort() on a List or array containing these elements. This order is determined either by their natural order (if they implement Comparable), or by a specific Comparator implementation.

Set Exmaple

package com.setsample;

import java.util.*;

public class SetDemo {

  public static void main(String args[]) {
     int count[] = {34, 22,10,60,30,22};
     Set<String> set = new HashSet<String>();
     try{
        set.add("BDG");
        set.add("CDF");
        set.add("ADE");
        set.add("FED");
        set.add("EDR");
        System.out.println(set);
       
        LinkedHashSet hashSet = new LinkedHashSet();
        hashSet.add("BDG");
        hashSet.add("CDF");
        hashSet.add("ADE");
        hashSet.add("FED");
        hashSet.add("ADE");
        hashSet.add("EDR");
        System.out.println("Set with duplicated "+hashSet);
       
        TreeSet sortedSet = new TreeSet<String>(set);
        TreeSet treeset = new TreeSet();
       
        treeset.add("DDDD");
        treeset.add("AAAAA");
        treeset.add("CCCC");
       
        Iterator itr = treeset.iterator();
        while(itr.hasNext())
        {
        if(itr.next().toString().startsWith("C"))
        System.out.println(itr.next());
        }
        System.out.println(treeset);
       
        System.out.println("The sorted list is:");
        System.out.println(sortedSet);

        System.out.println("The First element of the set is: "+
                          (Integer)sortedSet.first());
        System.out.println("The last element of the set is: "+
                        (Integer)sortedSet.last());
     }
     catch(Exception e){}
  }

Assignment on List and Set

There are few employees with below details:

Emp Id
Emp Name
Designation
Salary
Address
Qualification
Department
1
XXXX
SSE
50000
1, 2nd st, NY
B.Tech
IT
2
AAAA
PM
100000
101, 22nd st, DS
M.Tech
ADMIN
3
BBBB
SE
25000
1, 23rd  st, NY
BE
IT
4
YYYY
GM
120000
123, 2nd st, NY
MBA
SALES
5
CCCC
DM
150000
2121, 2nd st, NY
MBA
OPERATION
2
AAAA
PM
100000
101, 22nd st, DS
M.Tech
ADMIN

1. Add this to list and Sort it Alphabetical order. Remove if there is any duplicate. display the index of the employee "BBBB". Dont use Set.

2. The same example use set to sort it and to remove duplicates.