Wednesday, June 4, 2014

Java Examples

Example using ArrayList:

import java.util.ArrayList;
import java.util.Iterator;
/**
 *
 * @author rdayala
 */
public class WelcomeJava {
    public static void main(String args[])
    {
        System.out.println("Welcome to Java Learning!");       
        Integer x = 5;
        Object obj = 5;
        int y = x.intValue();
        int z = ((Integer)obj).intValue();
        String name = "Raghu";
       
        System.out.printf("Y : %d, Z : %d\n\n", y, z);
       
        ArrayList list = new ArrayList();
        list.add("Raghu");
        list.add(1);
        list.add(12.5);              
                     
        Class listClass = list.getClass();
        System.out.println("list type: " + listClass.getName());
        System.out.println("list size: " + list.size());
        System.out.println("list elements are:");
       
// traversing ArrayList using iterator

        Iterator it = list.iterator();
        while(it.hasNext())
        {
            System.out.println(it.next());
        }
               
    }
}

Another Example:

import java.util.Scanner;
import javax.swing.JOptionPane;
import java.nio.file.*;
public class HelloWorld {

    /**
     * @param args the command line arguments
     */
    public static void main(String []args) {
        // TODO code application logic here
        System.out.println("Hello,World - Raghu!");
        System.out.println("Welcome to Java Programming Language");
       
        String valueFromUI = JOptionPane.showInputDialog("Enter Your Name:");
        System.out.println("Your name is: " + valueFromUI + ", Lenght of Name:" + valueFromUI.length());
       
        System.out.println("Enter a value from console:");
        Scanner input = new Scanner(System.in);       
        int value = input.nextInt();
       
        System.out.println("Value read from console is : " + value);
       
        int []num = new int[5];
        Class cls = num.getClass();
       
        System.out.println("Type of the array : " + cls.getName());
       
        int[] numArray = {1, 2, 3, 4, 5};
        int[] cpArray;
        cpArray = new int[5];
        System.arraycopy(numArray, 0, cpArray, 0, numArray.length);
        cpArray[3]=7;
       
        System.out.println("Num Array is: ");
        for(int val : numArray)
            System.out.print(val + " ");
       
        System.out.println("\nCopy Array is: ");
        for(int val : cpArray)
            System.out.print(val + " ");
       
        int[] clArray;
        clArray = numArray.clone();
        clArray[3]=8;
       
        System.out.println("\nNum Array is: ");
        for(int val : numArray)
            System.out.print(val + " ");
       
        System.out.println("\nClone Array is: ");
        for(int val : clArray)
            System.out.print(val + " ");
       
        FileSystem fs = FileSystems.getDefault();
        System.out.println("\nFileSystem is : " + fs.toString());
       
        Iterable<Path> roots = FileSystems.getDefault().getRootDirectories();
        for(Path rt : roots)
            System.out.println("\nRoot is: " + rt.toString());
               
        Path path = FileSystems.getDefault().getPath("home", "user", "images.gif");
        System.out.println("\nPath is : " + path.toString());

    }
}

Exception Example:

public class ExceptionTest {
       
    public static void main(String[] args) {
        int a = 15, b = 0;
        int c;
        try {
                if( a == 15)
                    throw new Exception("Please enter valid number for a");
                c = a / b;
        } catch(ArithmeticException e) {
            System.out.println("Inside catch block");
        }
        catch(Exception e)
        {
            System.out.println("General exception caught by throw statement.");
        }
        finally {
            System.out.println("Inside finally block");           
        }
    }
   
}

Convert a string to date in Java:

import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
  public static void main(String[] args) throws Exception {
    SimpleDateFormat myDateFormat = new SimpleDateFormat("dd/MM/yyyy");
    Date dateToday = dateFormat.parse("25/06/2011");
    System.out.println(myDateFormat.format(dateToday));
  }
}

Date & Time Example:

import java.util.Date;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DatesAndTimes {
    public static void main(String[] args)
    {
        Date today = new Date();
        System.out.println("Today is : " + today.toString());
       
        Calendar cal = Calendar.getInstance();
        System.out.println("Today is : " + cal.getTime().toString());
        System.out.println("Timezone is : " + cal.getTimeZone().getID());
       
        Date todaysDate = new Date();
        int compareTo = today.compareTo(todaysDate);
        SimpleDateFormat formatter = new SimpleDateFormat("EEEE, dd-MMMM-yyyy HH:mm:ss a ZZZZ");
        String formattedString = formatter.format(todaysDate);
        System.out.println(formattedString);
       
        DateFormat df = DateFormat.getDateTimeInstance();
        String formatString = df.format(todaysDate);
        System.out.println(formatString);
       
        DateFormat df1 = DateFormat.getTimeInstance();
        String formatString1 = df1.format(todaysDate);
        System.out.println(formatString1);
       
        String dateString = "Jan 12, 1952 3:30:32 pm";
        DateFormat df2 = DateFormat.getDateTimeInstance();
        try {
            Date date1 = df2.parse(dateString);
            System.out.println("Parsed Date: " + date1.toString());
        } catch (ParseException ex) {
            Logger.getLogger(DatesAndTimes.class.getName()).log(Level.SEVERE, null, ex);
        }
       
        // date arithmetic using Date objects
        Date date = new Date();
        long time = date.getTime();
        time += 5*24*60*60*1000;
        Date futureDate = new Date(time);
       
        // date arithmetic using Calendar objects
        Calendar nowCal = Calendar.getInstance();
        nowCal.add(Calendar.DATE, 5);
       
        Date date1 = new Date();
        Date date2 = new Date();
        long time1 = date1.getTime();
        long time2 = date2.getTime();
       
        long diff = time2 - time1;
        System.out.println("Difference in days = " + diff/(1000*60*60*24));      
       
        if (date1.equals(date2)) {
            System.out.println("dates are the same.");
        }
        else {
            if (date1.before(date2)) {
                System.out.println("date1 before date2");
            }
            else {
                System.out.println("date1 after date2");
            }
        }
       
        System.out.println("Today is : " + cal.toString());
        System.out.println("Day of week: " + cal.get(Calendar.DAY_OF_WEEK));
        System.out.println("Month: " + cal.get(Calendar.MONTH));
        System.out.println("Year: " +  cal.get(Calendar.YEAR));
        System.out.println("Week number: " + cal.get(Calendar.WEEK_OF_YEAR));
       
        //long start = System.currentTimeMillis();
        // do some other stuff…
        // long end = System.currentTimeMillis();
        // long elapsedTime = end – start;
       
    }
}

Serialization Example:

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ObjectSerializeTest implements Serializable {
   
    private int age;
    private String name;
   
    public void setAge(int ageVal) {
        age = ageVal;
    }
   
    public void setName(String nameVal) {
        name = nameVal;
    }
   
    public void Display() {
        System.out.println("Name: " + name + ", Age: " + age);
    }
   
    public static void main(String[] args) {
        ObjectSerializeTest obj1 = new ObjectSerializeTest();
        obj1.setAge(32);
        obj1.setName("Raghunath");       
       
        FileOutputStream fops;
        try {
            fops = new FileOutputStream("raghu.txt");      
            ObjectOutputStream oos = new ObjectOutputStream(fops);
            oos.writeObject(obj1);
        }
        catch (FileNotFoundException ex) {
            Logger.getLogger(ObjectSerializeTest.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (IOException ex) {
            Logger.getLogger(ObjectSerializeTest.class.getName()).log(Level.SEVERE, null, ex);
        }
       
        FileInputStream fips;
        try {
            fips = new FileInputStream("raghu.txt");
            ObjectInputStream oips = new ObjectInputStream(fips);
            ObjectSerializeTest obj2 = (ObjectSerializeTest)oips.readObject();
            obj2.Display();
        }
        catch (FileNotFoundException ex) {
            Logger.getLogger(ObjectSerializeTest.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (IOException ex) {
            Logger.getLogger(ObjectSerializeTest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ObjectSerializeTest.class.getName()).log(Level.SEVERE, null, ex);
        }
       
    }   
}


Singleton using Enum:

enum MySingleton
{
    RAGHU;
    public void sayHello()
    {
        System.out.println("Hello Raghu!");
    }
   
    public void sayBye()
    {
        System.out.println("Bye Raghu!");
    }
}
public class Singleton {
    public static void main(String[] args)
    {
        MySingleton ms = MySingleton.RAGHU;
        ms.sayHello();
        ms.sayBye();
        MySingleton ms1 = MySingleton.RAGHU;
       
        if(ms == ms1)
            System.out.println("Referring to same singleton class");
    }
}

Final fields having different values, initialized using Constructor:

public class FinalFieldsExample {
    public final int a;
   
    FinalFieldsExample(int val) {
        a = val;
    }
   
    public void display()
    {
        System.out.println("The value of final field a is : " + a);
    }
   
    public static void main(String[] args) {
        FinalFieldsExample t1 = new FinalFieldsExample(10);
        t1.display();
       
        FinalFieldsExample t2 = new FinalFieldsExample(20);
        t2.display();       
       
    }
   
}


File Read and Write examples in Java

Here is the code of java program to Read text File Line by Line:

http://www.roseindia.net/java/beginners/java-read-file-line-by-line.shtml

import java.io.*;
class FileRead
{
 public static void main(String args[])
  {
  try{
  // Open the file that is the first 
  // command line parameter
  FileInputStream fstream = new FileInputStream("c:\\textfile.txt");
  // Get the object of DataInputStream
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine;
  //Read File Line By Line
  while ((strLine = br.readLine()) != null)   {
  // Print the content on the console
  System.out.println (strLine);
  }
  //Close the input stream
  in.close();
    }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
  }
  }
}


Other way of reading file data:

import java.io.*;
/**
* How To Read File In Java with BufferedReader class
*
*/
public class ReadUsingBufferedReader {
        public static void main(String[] args) 
        {
                System.out.println("Reading File with BufferedReader class");
                //Name of the file
                String fileName="test.text";
                try{
                
                //Create object of FileReader
                FileReader inputFile = new FileReader(fileName);
                
                //Instantiate the BufferedReader Class
                BufferedReader bufferReader = new BufferedReader(inputFile);

                //Variable to hold the one line data
                String line;
                
                // Read file line by line and print on the console
                while ((line = bufferReader.readLine()) != null)   {
                     System.out.println("File Line is: " + line);
                }
                //Close the buffer reader
                bufferReader.close();
                } 
                catch(Exception e){
                    System.out.println("Error in reading file:" + e.getMessage());                  
                }
        }
}
 
Read a specific line: 

import java.io.*;
public class ReadSpecificLine {

        public static void main(String[] args) {
                String line = "";
                int lineNo;
                try {
                        FileReader fr = new FileReader("new.txt");
                        BufferedReader br = new BufferedReader(fr);
                        for (lineNo = 1; lineNo < 10; lineNo++) {
                                if (lineNo == 5) {
                                        line = br.readLine();
                                } else
                                        br.readLine();
                        }
                } catch (IOException e) {
                        e.printStackTrace();
                }
                System.out.println("Line: " + line);
        }
}
 
 

Java read file in memory

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class ReadFileInMemory {
        public static void main(String[] args) throws Exception {
             File f = new File("C:/hello.txt");
             long length = f.length();
             MappedByteBuffer buffer = new FileInputStream(f).getChannel().map(
                                FileChannel.MapMode.READ_ONLY, 0, length);
             int i = 0;
             while (i < length) {
                    System.out.print((char) buffer.get(i++));
             }
             System.out.println();
        }
}
 
Reading binary file into byte array in Java 
 
import java.io.*;
public class ReadingBinaryFileIntoByteArray
{
        public static void main(String[] args) 
        {
                System.out.println("Reading binary file into byte array example");
                try{
                        //Instantiate the file object
                        File file = new File("test.zip");
                        //Instantiate the input stread
                        InputStream insputStream = new FileInputStream(file);
                        long length = file.length();
                        byte[] bytes = new byte[(int) length];

                         insputStream.read(bytes);
                         insputStream.close();
        
                         String s = new String(bytes);
                        //Print the byte data into string format
                         System.out.println(s);
                 }
                 catch(Exception e){
                        System.out.println("Error is:" + e.getMessage());
                }
        }
} 

Writing a file using Appending:

import java.io.*;
class WriteToFileWithoutOverwriting {
 public static void main(String args[])
  {
  try{
          FileWriter fstream = new FileWriter("log.txt",true);
          BufferedWriter out = new BufferedWriter(fstream);
          out.write("Line Added on: " + new java.util.Date()+"\n");
          out.close();
    }catch (Exception e){
         System.err.println("Error while writing to file: " +
          e.getMessage());
    }
  }
}
 

Copying Characters from One file to Another file (Copy file):

import java.io.*;

class CopyCharacters {
        public static void main(String[] args) {
           File inFile = new File("input.dat");
           File outFile = new File("output.dat");

           FileReader ins = null;
           FileWriter outs = null;

           try {
                ins = new FileReader(inFile);
                outs = new FileWriter(outFile);

                int ch;
                while((ch = ins.read()) != -1) 
                {
                    outs.write(ch);
                }
            }
            catch(IOException e) {
                   System.out.println(e);
                   System.exit(-1);
            }
            finally {
                   ins.close();
                   outs.close();
            }
       }
  }

Writing Bytes to a file:

import java.io.*;

class WriteBytes {
        public static void main(String[] args) {
           byte cities[] = {'D', 'E', 'L', 'H', 'I', '\n', 'M','A','D','R','S','\n'}
         
           FileOutputStream outfile = null;
 
           try {
                 outfile = new FileOutputStream("city.txt");
                 outfile.write(cities);
                 outfile.close();
           }
           catch(IOException e) {
                  System.out.println(e);
                  System.exit(-1);
           }
     }
 }
 
Reading bytes from file: 

import java.io.*;

class ReadBytes {
        public static void main(String[] args) {
            FileInputStream infile = null;
            
            int b;
            try {
                  infile = new FileInputStream(args[0]);
                  while ((b = infile.read())!= -1)
                  {
                      System.out.println((char)b);
                  }
                  infile.close(); 
             }
             catch( IOException e)
             {
                  System.out.println(e);
              }
       }
  }
 
 
 

Friday, May 30, 2014

DB programming with Java

In this post, we will learn how to interact with Database using Java programming language. We are going to cover these:

  • Installing MySQL
  • Using MySQL
  • Combining Java and MySQL
  • Using MySQL in Netbeans
  • Creating an App
Have Java installed on your machine.

Next install Python as MySQL server components might require. So, it is recommended to install Python first. (www.python.org)

Install MySQL Community Server(http://dev.mysql.com/downloads/). 

After that download, MySQL connector for Java. Download, platform independent, ZIP archive. (http://dev.mysql.com/downloads/connector/J)

Extract the ZIP file to directory like D:\connectorJ and add the complete path to the library file to CLASSPATH (like, D:\connectorJ\mysql-connector-java-5.1.30\ )




Setting up a Database:

Go to MySQL command line client with appropriate password and you should get the mysql> prompt.

To create a database(CREATE DATABASE):

mysql> create database library;

This command will create the database named 'library'. To use that library, use the following command:

mysql> use library;

Now the 'library' database is opened and you can use it for creating tables, etc.

To create tables in the Database (CREATE TABLE):

mysql> create table book (
    -> isbn varchar(13) primary key,
    -> title varchar(50),
    -> author varchar(50),
    -> price float(11));


Now the table is created.

Insert data into table (INSERT):

mysql> insert into book values ('0764508814', 'Java 2 Database Programming', 'Raghu Dayala', 24.99);

mysql> insert into book values ('9780471269236', 'MySQL and Java Programming', 'Mark Mathews', 34.99);

Querying data from table (SELECT):

mysql> select * from book;

mysql> select title, author from book;

mysql> select isbn, price from book;

mysql> select * from book where price > 25;

Update data already in table (UPDATE):

mysql> update book
    -> set price = 26.99
    -> where title = 'MySQL and Java Programming';


Remove records from table (DELETE) :

Before that, lets enter one more row in to the table.

mysql> insert into book values('9780596009205', 'Head First Java', 'Kathy Sierra', 45.99); 

Now let's delete this row from table:

mysql> delete from book where title = 'Head First Java';

To drop a table:

mysql> drop table book;


Exercises Using MySQL:

mysql> create table books (
    -> isbn varchar(13),
    -> title varchar(50),
    -> author varchar(50),
    -> price float(11),
    -> publisher varchar(50));

mysql> create table publishers (
    -> id varchar(3),
    -> name varchar(50),
    -> city varchar(50));


mysql> insert into books values ('1234567890', 'Example Book', 'Raghu', 49.99, 'Apress');
mysql> insert into books values('9876543210', 'New Book', 'ABC', 32.99, 'Prentice Hall');
mysql> insert into books values('4567890123', 'Great Java Book', 'XYZ', 25.99, 'Mc Graw Hill');


mysql> insert into publishers values ('001', 'Apress', 'New York City');
mysql> insert into publishers values('002', 'Prentice Hall', 'California');

mysql> insert into publishers values('003', 'Mc Graw Hill', 'Washington');

Note:

Please make sure you have added the path to the driver mysql-connector-java-5.1.30-bin.jar to the CLASSPATH.

However,  IDEs and app servers ignore it.

The right way to do it depends on how you're using it:

  1. If you're running inside an IDE like Eclipse or IntelliJ, you have to add the JAR to a library.
  2. IF you're running in a command shell, use the -p option for javac.exe when you compile and java.exe when you run.
  3. If you're using it in a web app, you can start by putting it in the WEB-INF/lib directory of your WAR file. If you're using a servlet/JSP engine like Tomcat 6, put it in the Tomcat /lib directory.
Simplest way to check if things are all fine:

Test Connection to MySQL using Java:
 
public class TestMySQLConnection {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            System.out.println("Connected to MySQL");
        }
        catch (Exception e) {
            System.out.println("Cannot connected to MySQL");
        }
    }
}


Connecting to DB using Java:

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

/**
 *
 * @author rdayala
 */

import java.sql.*;

public class ConnectDB {
    Connection connection;
   public ConnectDB() {
      try {
         Class.forName("com.mysql.jdbc.Driver").newInstance();
      }
      catch (Exception e) {
         System.out.println("Could not load driver.");
      }
   }

   public void connectToDB() {
      try {
         connection = DriverManager.getConnection(
                                    "jdbc:mysql://localhost/library", "raghu", "chotu123");
         System.out.println("Connected to MySQL database.");
      }
      catch (Exception e) {
         System.out.println("Cannot connect to database.");
      }
   }


   public static void main(String[] args) {
      ConnectDB conn = new ConnectDB();
      conn.connectToDB();
   }
}


Executing the SQL query within Java code:


public void execSQL()
   {
       try {
           Statement stmt = connection.createStatement();
           ResultSet rs = stmt.executeQuery("select * from books;");
          
           while(rs.next()) {             
               System.out.println(rs.getString(1) + "  " + rs.getString(2));
           }

       }
       catch(Exception e)
       {
           System.out.println("Error executing the query");
       }
   }


Updating table data within Java code:

public void updateSQL()
   {
       try {
           Statement stmt = connection.createStatement();
           String update = "update books set title = 'Java: How to Program'";
           update += " where isbn = '9876543210'";
           int success = stmt.executeUpdate(update);
                     
       }
       catch(Exception e)
       {
           System.out.println("Error executing the query");
       }
   }


Inserting Data into table from within Java code:

public void execSQL() {
      try {
         Statement stmt = connection.createStatement();
         BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
         System.out.print("Enter the isbn: ");
         String isbn = input.readLine();
         System.out.print("Enter the title: ");
         String title = input.readLine();
         System.out.print("Enter the author: ");
         String author = input.readLine();
         System.out.print("Enter the price: ");
         String p = input.readLine();
         double price = Double.parseDouble(p);
         System.out.print("Enter the publisher: ");
         String pub = input.readLine();
         String insert = "Insert into books values (" + "'" + isbn + "','" + title +
                         "','" + author + "'," + price + ",'" + pub + "')";
         System.out.println(insert);
         int inserted = stmt.executeUpdate(insert); // returns 1 for success, 0 for failure
         if (inserted > 0) {
            System.out.println("Successfully inserted " + inserted + " row.");
         }
      }
      catch (Exception e) {
         System.out.println("Error executing SQL");
      }
   }



Deleting Data from Table from within Java code: 

public void execSQL() {
      try {
         Statement stmt = connection.createStatement();
         BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
         System.out.println("Enter a title: ");
         String title = input.readLine();
         String delete = "delete from books where title = '" + title + "'";
         System.out.println(delete);
         int deleted = stmt.executeUpdate(delete); // returns 1 for success, 0 for failure
         if (deleted > 0) {
            System.out.println("Successfully deleted " + deleted + " row.");
         }
      }
      catch (Exception e) {
         System.out.println("Error executing SQL");
      }
   }



 Accessing Oracle DB from Java:

// FLOW:
// Load Driver --> DriverManager.getConnection --> createStatement -->
// Execute Query --> ResultSet


import java.sql.*;

public class DatabaseAccessExample {
   
    // STEP 1: JDBC driver name and database URL
    static final String JDBC_DRIVER = "oracle.jdbc.OracleDriver"; 
    static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:xe";
   
    //  Database credentials
   static final String USER = "raghu";
   static final String PASS = "raghu";
  
   public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try
        {
                      
           //STEP 2: Register JDBC driver. The below statements loads the driver class 

           // 'oracle.jdbc.OracleDriver' to be available for DriverManager instance
           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...");
           stmt = conn.createStatement();
           String sql;
           sql = "SELECT emp_id, emp_name, join_date FROM Employee";
           ResultSet rs = stmt.executeQuery(sql);
           //STEP 5: Extract data from result set
           while(rs.next())
           {
              //Retrieve by column name
              int id  = rs.getInt("emp_id");      
              String first = rs.getString("emp_name");
              Date joindate = rs.getDate("join_date");

              //Display values
              System.out.print("Emp ID: " + id);        
              System.out.print(", Name: " + first);
              if(joindate != null)
                 System.out.println(", Join Date: " + joindate.toString());
              else
                  System.out.println(", Join Date: " + null);
           }
          
           //STEP 6: Clean-up environment
           rs.close();
           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();
                }catch(SQLException se2){
                }// nothing we can do
                try{
                   if(conn!=null)
                      conn.close();
                }catch(SQLException se){
                   se.printStackTrace();
                }//end finally try
        }//end try
       
        System.out.println("Goodbye!");
       
    }//end main
}