Comparison Local Variables v. Instance Variables Start Comparing Local and Instance variable... 1. Local variables must be initialized before use while it is not necessary to initialize Instance variables Instance variables always get a default value. Local variables do not get default value. If you use local variable without initializing it then there will be a compiler error. Declaration Instance Variables are declared inside class. Local Variables are declared inside methods.
Hash Set import java.util.HashSet; import java.util.Iterator; /** * * @author Darur venu gopal * This class Demonstrates ability to store values in HashSet and Retrieve. * First Step Store some values in HashSet, * Observe the Storage. Hashset Stores the values randomly. * Hashset stores no duplicate values, and stores in random order. * */public class HashSetDemo { /** * This method add values (Label number) to a hashSet. * @return */ public HashSet addValuesInHashSet( ){ HashSet hashSet = new HashSet(); for( int i = 0; i< 100; i++ ){ String name = "LABEL"; String valueToAdd = name + i; hashSet.add( valueToAdd ); } return hashSet; } /** * Iterate and hashset. and print all the values in this Hashset. * @param hashSet */ public void retrieveHashSet( HashSet hashSet ){ Iterator iterator = hashSet.iterator(); while ( iterator.hasNext() ){ String labelNo=( String ) iterator.next(); System.out.println( "LabelNo: " + labelNo ); }
} // Examine what you have done in main method. public static void main( String [] args ){ HashSetDemo hashSetDemo = new HashSetDemo( ); HashSet hashSet = hashSetDemo.addValuesInHashSet(); hashSetDemo.retrieveHashSet(hashSet); } Output of the Program: LabelNo: LABEL19 LabelNo: LABEL18 LabelNo: LABEL17 LabelNo: LABEL16 LabelNo: LABEL15 LabelNo: LABEL14 LabelNo: LABEL13 LabelNo: LABEL12 .. .. LabelNo: LABEL76 LabelNo: LABEL75 LabelNo: LABEL74 LabelNo: LABEL73 LabelNo: LABEL72 LabelNo: LABEL71 LabelNo: LABEL70 LabelNo: LABEL69 LabelNo: LABEL68 LabelNo: LABEL67 LabelNo: LABEL66 LabelNo: LABEL65 LabelNo: LABEL64 LabelNo: LABEL63 LabelNo: LABEL62 LabelNo: LABEL61 LabelNo: LABEL60 LabelNo: LABEL59 LabelNo: LABEL58 LabelNo: LABEL57 LabelNo: LABEL56 LabelNo: LABEL55 LabelNo: LABEL54 .. .. } import java.util.Iterator; import java.util.TreeSet; /** *
* @author Darur venu gopal * This class Demonstrates ability to store values in TreeSet and *Retrieve. * First Step Store some values in TreeSet, * Observe the Storage. Treeset Stores the values in a particular sorted *order. *.*. * */ public class TreeSetDemo { /** * This method add values (Label number) to a TreeSet. * @return */ public TreeSet addValuesInTreeSet( ){ TreeSet treeSet = new TreeSet(); for( int i = 0; i< 20 ; i++ ){ Integer number = new Integer( i ); treeSet.add( number); } return treeSet; } /** * Iterate and treesett. and print all the values in this Treeset. * @param treeSet */ public void retrieveHashSet( TreeSet treeSet ){ Iterator iterator = treeSet.iterator(); while ( iterator.hasNext() ){ int labelNo=( ( Integer ) iterator.next() ).intValue(); System.out.println( "LabelNo: " + labelNo ); } } // Examine what you have done in main method. public static void main( String [] args ){ TreeSetDemo treeSetDemo = new TreeSetDemo( ); TreeSet treeSet = treeSetDemo.addValuesInTreeSet(); treeSetDemo.retrieveHashSet( treeSet ); } } Output : LabelNo: LabelNo: LabelNo: LabelNo: LabelNo: LabelNo: LabelNo: LabelNo: LabelNo: LabelNo: LabelNo: LabelNo:
0 1 2 3 4 5 6 7 8 9 10 11
LabelNo: LabelNo: LabelNo: LabelNo: LabelNo: LabelNo: LabelNo: LabelNo: 19 //Java.util.LinkedHashSet //Java Collections -LinkedHashSet //LinkedHashSet implements Set Interface
import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.TreeSet; /** * * @author Darur venu gopal * This class Demonstrates ability to store values in LinkedHashSet and Retrieve. * First Step Store some values in LinkedHashSet, * Observe the Storage. LinkedHashset Stores the values in order of entry. * */ public class LinkedHashSetDemo { /** * This method add values (Label number) to a TreeSet. * @return */ public LinkedHashSet addValuesInLinkedHashSet( ){ LinkedHashSet linkedHashSet = new LinkedHashSet(); // observe the order of entry, while retieve the same order of entry is guaranteed. linkedHashSet.add( "DARUR" ); linkedHashSet.add( "ARORA" ); linkedHashSet.add( "SAVANT" ); linkedHashSet.add( "INTELLIGENT" ); linkedHashSet.add( "APPLICATIONS" ); linkedHashSet.add( "IBM MACHINES" ); linkedHashSet.add( "SUN MICRO SYSTEM" ); linkedHashSet.add( "GREAT GATES" ); return linkedHashSet; } /** * Iterate and hashset. and print all the values in this Hashset. * @param linkedHashSet */ public void getLinkedHashSet( LinkedHashSet linkedHashSet ){ Iterator iterator = linkedHashSet.iterator(); while ( iterator.hasNext() ){ String label= ( String) iterator.next() ;
12 13 14 15 16 17 18
System.out.println( "WORD: " + label ); } System.out.println( "THUS ORDER OF ENTRY IS SAME AS ORDER YOU ENTERED" ); } // Examine what you have done in main method. public static void main( String [] args ){ LinkedHashSetDemo linkedHashSetDemo = new LinkedHashSetDemo( ); LinkedHashSet linkedHashSet = linkedHashSetDemo.addValuesInLinkedHashSet(); linkedHashSetDemo.getLinkedHashSet( linkedHashSet ); } } Output : WORD: DARUR WORD: ARORA WORD: SAVANT WORD: INTELLIGENT WORD: APPLICATIONS WORD: IBM MACHINES WORD: SUN MICRO SYSTEM WORD: GREAT GATES THUS ORDER OF ENTRY IS SAME AS ORDER YOU ENTERED import java.util.ArrayList; import java.util.Iterator; // Darur public class ArraylistDemo { public ArrayList addValuesInArrayList ( ){ ArrayList arrayList = new ArrayList( ); arrayList.add( "Bria " ); arrayList.add( "Bria " ); arrayList.add( "TI " ); arrayList.add( "TI " ); arrayList.add( "CL " ); arrayList.add( "CL " ); arrayList.add( "CLA " ); arrayList.add( "VENU " ); arrayList.add( "GOPAL" ); arrayList.add( "NARAYANA " ); arrayList.add( "JANAKI RAM " ); arrayList.add( "VASAVI " ); return arrayList; } //
public void printValuesInArrayList( ArrayList arrayList ){ System.out.println( "--------USING FOR ITERATOR------------" ); Iterator iterator = arrayList.iterator(); while( iterator.hasNext() ){ String name = ( ( String ) iterator.next() ).toUpperCase(); System.out.println( "Name: " + name ); } System.out.println( "--------USING FOR ITERATOR------------" ); } // public void printValuesInArrayListUsingForLoop( ArrayList arrayList ){ System.out.println( "--------USING FOR LOOP START------------" ); for( int i = 0 ; i < arrayList.size() ; i++ ){ String name = ( ( String ) arrayList.get( i ) ).toUpperCase(); System.out.println( "Name: " + name ); } System.out.println( "--------USING FOR LOOP END------------" ); } public static void main ( String [] args ){ ArraylistDemo arraylistDemo = new ArraylistDemo( ); ArrayList arrayList = arraylistDemo.addValuesInArrayList(); arraylistDemo.printValuesInArrayList(arrayList); arraylistDemo.printValuesInArrayListUsingForLoop(arrayList); } } output of the program may be like this: -------USING FOR ITERATOR-----------Name: BRIA Name: BRIA Name: TI Name: TI Name: CLA Name: CLA Name: CLAY Name: VENU Name: GOPAL Name: NARAYANA Name: JANAKI RAM Name: VASAVI --------USING FOR ITERATOR-------------------USING FOR LOOP START-----------Name: BRIA Name: BRIA Name: TI Name: TI Name: CLA Name: CLA Name: CLA Name: VENU Name: GOPAL
Name: NARAYANA Name: JANAKI RAM Name: VASAVI --------USING FOR LOOP END------------
Java Collections -Vector Vector implements LIST Interface Example
import java.util.Iterator; import java.util.Vector; public class VectorDemo { public Vector addValuesInVector( ){ Vector vector = new Vector(); vector.add( "VNU" ); vector.add( "RAVI" ); vector.add( "HARANATH" ); vector.add( "DEV" ); vector.add( "SREERAM" ); vector.add( "GIRI" ); vector.add( "SREEDHAR" ); vector.add( "JANARDHAN" ); vector.add( "KRISI" ); vector.add( "SISI" ); vector.add( "VASUDEV" ); vector.add( "MPRAVEEN" ); vector.add( "KPRAVEEN" ); vector.add( "SIDHU" ); vector.add( "95MECHVASAVI99" ); vector.add( "SHAHENSHA" ); vector.add( "ENGINE OIL" ); vector.add( "MECHANICAL DRAWING" ); vector.add( "HEAD OF MECHANICAL DEPARTMENT" ); vector.add( "VASAVI COLLEGE OF ENGINEEERING" ); vector.add( "RAKESH RAVI DEV SLIDED TO ELECTRONICS" ); return vector; } public void printVector( Vector vector ){ System.out.println( "--------USING FOR ITERATOR------------" ); Iterator iterator = vector.iterator();
while( iterator.hasNext() ){ String name = ( ( String ) iterator.next() ).toUpperCase(); System.out.println( "Name: " + name ); } System.out.println( "--------USING FOR ITERATOR------------" ); } public void printValuesInVectorUsingForLoop( Vector vector ){ System.out.println( "--------USING FOR LOOP START------------" ); for( int i = 0 ; i < vector.size() ; i++ ){ String name = ( ( String ) vector.get( i ) ).toUpperCase(); System.out.println( "Name: " + name ); } System.out.println( "--------USING FOR LOOP END------------" ); } public static void main( String [] args ){ VectorDemo vectorDemo = new VectorDemo(); Vector vector = vectorDemo.addValuesInVector(); vectorDemo.printVector(vector); vectorDemo.printValuesInVectorUsingForLoop(vector); } }
Output : --------USING FOR ITERATOR-----------Name: VNU Name: RAVI Name: HARANATH Name: DEV Name: SREERAM Name: GIRI Name: SREEDHAR Name: JANARDHAN Name: KRISI Name: SISI Name: VASUDEV Name: MPRAVEEN Name: KPRAVEEN Name: SIDHU Name: 95MECHVASAVI99 Name: SHAHENSHA Name: ENGINE OIL Name: MECHANICAL DRAWING Name: HEAD OF MECHANICAL DEPARTMENT Name: VASAVI COLLEGE OF ENGINEEERING Name: RAKESH RAVI DEV SLIDED TO ELECTRONICS --------USING FOR ITERATOR-------------------USING FOR LOOP START-----------Name: VNU
Name: RAVI Name: HARANATH Name: DEV Name: SREERAM Name: GIRI Name: SREEDHAR Name: JANARDHAN Name: KRISI Name: SISI Name: VASUDEV Name: MPRAVEEN Name: KPRAVEEN Name: SIDHU Name: 95MECHVASAVI99 Name: SHAHENSHA Name: ENGINE OIL Name: MECHANICAL DRAWING Name: HEAD OF MECHANICAL DEPARTMENT Name: VASAVI COLLEGE OF ENGINEEERING Name: RAKESH RAVI DEV SLIDED TO ELECTRONICS --------USING FOR LOOP END-----------Java.util.LinkedList Java Collections -LinkedList LinkedList implements LIST Interface
Example import java.util.Iterator; import java.util.LinkedList; /** * LinkedList implements interface. Implements all optional list operations, * and permits all elements (including null). In addition to implementing the List interface, * provides uniformly named methods to get, remove and insert an element ( addFirst, addLast) * at the beginning and end of the list. * linkedlists would be used as a stack, queue, or double-ended queue (deque). * Above is extract from www.SUN.com * CHAITANYA KANDIKONDA * @author Darur * */ public class LinkedListDemo { public LinkedList addValuestoLinkedList( ){ LinkedList linkedList = new LinkedList(); linkedList.add( 1 ); linkedList.add( 2 ); linkedList.add( 7 ); linkedList.add( 7 ); linkedList.add( 8 ); linkedList.add( 3 );
linkedList.add( 4 ); linkedList.add( 5 ); linkedList.add( 6 ); linkedList.add( 7 ); return linkedList; } // add first element // add last element and print public void PrintLinkedList( LinkedList linkedList ){ linkedList.addFirst( 0 ); linkedList.addLast( 10 ); Iterator iterator = linkedList.iterator(); while( iterator.hasNext() ){ System.out.println( "THE VALUE: " + iterator.next()); } } public static void main( String [] args ){ LinkedListDemo linkedListDemo = new LinkedListDemo(); LinkedList linkedList =linkedListDemo.addValuestoLinkedList(); linkedListDemo.PrintLinkedList(linkedList); } }
Output : THE VALUE: 0 THE VALUE: 1 THE VALUE: 2 THE VALUE: 7 THE VALUE: 7 THE VALUE: 8 THE VALUE: 3 THE VALUE: 4 THE VALUE: 5 THE VALUE: 6 THE VALUE: 7 THE VALUE: 10 Java.util.Properties Java Collections -Properties Properties implements Cloneable, Serializable, Map
Example
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.Hashtable; import java.util.Properties;
/** * This class Demonstrates a way to use properties. * In huge applications projects may need to have many things as configurable properties, * this may be because the business needs. * It is a very bad habbit to hard code the values in the program. * It's best practise to use properties in a property file. * * Also most desginers will have this in mind for any application. * Generally the properties loaded from the file are kept in the application scope. * So the properties will be loaded once when the application triggers a start point. * Web environment, best way to initiliaze properties, is when * Application Context is started. * Write a class which implements HttpContextListener, call your property initializer in context startup. * * * Your File may have duplicate entries, generally you have to avoid duplicate entries * in the file * @author Darur * */ public class PropertiesDemo { // /** * @return */ public static Properties readPropertiesFromFile( String fileName ) { Properties properties = new Properties(); InputStream inStream; try{ inStream = new FileInputStream( new File( fileName ) ); properties.load(inStream); }catch( FileNotFoundException fileNotFoundException ){ System.err.println( "FILE NOT FOUND EXCEPTION WHILE READING THE FILE: "+ fileName + "\n" + fileNotFoundException); }catch( IOException ioException ){ System.err.println( "IOEXCETION WHILE READING THE FILE: " + fileName + "\n" + ioException); } return properties; } /**
* add all the prope * @param args */ public static Hashtable buildPropertiesTable( Properties properties ){ Hashtable hashTable = new Hashtable(); Enumeration enumeration = properties.keys(); while( enumeration.hasMoreElements() ){ String key =(String) enumeration.nextElement(); //key is a string in property file String value = properties.getProperty(key); hashTable.put(key, value); } return hashTable; } public static void main( String [] args ){ Properties properties = readPropertiesFromFile( "C:\\properties.txt" ); Hashtable hashTable = buildPropertiesTable(properties); HashTableDemo hashTableDemo = new HashTableDemo(); // Remember we wrote this class HashTableDemo. Follow this link if you need this. hashTableDemo.prinHashTable( hashTable ); } } Output : usertype : premium port : 1046 driver : jdbc connectionport : 127.0.0.1
-----------------------------------------------------------------------------------Sample Properties in this file:
usertype = premium driver = jdbc connectionport = 127.0.0.1 port = 1040 port = 1041 port = 1042 port = 1043 port = 1044 port = 1045 port = 1046
Save this in file and process in main method -----------------------------------------------------------------------------------** * We will struggle in parsing java dates to required format. * Please use this class run in your environment by changing package name you will get * All the formats of the dates. THIS IS THE BEST EXAMPLE FOR PARSING DATES */ import java.io.Serializable; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class IforeRunnerDateExample extends Date implements Serializable { private final static DateFormat time = new SimpleDateFormat("HHmmss"); private final static DateFormat date = new SimpleDateFormat("MMddyyyy"); private final static DateFormat dateTime = new SimpleDateFormat("MMddyyyyHHmmss"); private final static DateFormat yyMMdd = new SimpleDateFormat("yyMMdd"); private final static DateFormat hhmm = new SimpleDateFormat("HHmm"); private final static DateFormat yyyymmddhhMM = new SimpleDateFormat("yyyyMMddHHmm"); private final static DateFormat yyyymmddhhMMss = new SimpleDateFormat("yyyyMMddHHmmss"); private final static DateFormat yyMMddhhmmss = new SimpleDateFormat("yyMMddHHmmss"); private final static DateFormat MMyy = new SimpleDateFormat("MMyy"); private final static DateFormat MMDDHHmm = new SimpleDateFormat("MMDDHHmm"); private final static DateFormat yyyymmdd = new SimpleDateFormat("yyyyMMdd"); private final static DateFormat hhmmssyyyyMMdd = new SimpleDateFormat("HHmmssyyyyMMdd"); private final static DateFormat MMddyy = new SimpleDateFormat("MMddyy"); private final static DateFormat yyMM = new SimpleDateFormat("yyMM"); private final static DateFormat dateFormatmmddyyyy = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); private final static DateFormat dateFormatmmddyy = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
public String getdateFormatmmddyyyy() { return dateFormatmmddyyyy.format(this); } public String getdateFormatmmddyy() { return dateFormatmmddyy.format(this); } /** * */ private static final long serialVersionUID = 1L; /** * Constructor which accepts a java.util.Date as input * @param date */ public IforeRunnerDateExample(java.util.Date date) { setTime(date.getTime()); } /** * Expects a string in MMddyyyyhhmmss format to parse into a IforeRunnerDateExample * @param dateTimeString * @throws ParseException */ public IforeRunnerDateExample(String dateTimeString) throws ParseException { this.setTime(dateTime.parse(dateTimeString).getTime()); } /** * */ public IforeRunnerDateExample() { super(); } /** * @param arg0 */ public IforeRunnerDateExample(long arg0) { super(arg0); } /** * * @return date string in MMddyyyy format */ public String getyyMMddString() { return yyMMdd.format(this); } /** * * @return date string in hhmm format */
public String gethhmmString() { return hhmm.format(this); } /** * * @return date string in MMddyyyy format */ public String getMMddyyyyString() { return date.format(this); } /** * * @return date string in hhmmss format */ public String getHHmmssString() { return time.format(this); } /* * @return date String in yyyymmddhhMM format */ public String getyyyymmddhhMMString(){ return yyyymmddhhMM.format(this); } /* * @return date String in yyyymmddhhMM format */ public String getyyMMddhhmmssString(){ return yyMMddhhmmss.format(this); } /** * @return date String in mmyy format */ public String getMMyyString(){ return MMyy.format(this); } /** * * @return Date String in hhmm format */ public String getHHmmString(){ return hhmm.format(this); } public static IforeRunnerDateExample getMMddyyyyDate(String MMddyyyy) throws ParseException { return new IforeRunnerDateExample(date.parse(MMddyyyy)); } public static IforeRunnerDateExample getyyMMddhhmmssDate(String yyMMddhhmmss) throws
ParseException { return new IforeRunnerDateExample(yyMMddhhmmss.parse(yyMMddhhmmss)); } public static IforeRunnerDateExample getHHmmssDate(String HHmmss) throws ParseException { return new IforeRunnerDateExample(time.parse(HHmmss)); } public static IforeRunnerDateExample getYyMMddDate(String syyMMddhhmmss) throws ParseException { return new IforeRunnerDateExample(yyMMdd.parse(syyMMddhhmmss)); } public static IforeRunnerDateExample getyyMMddDate(String yyMMdd) throws ParseException { return new IforeRunnerDateExample(yyMMdd.parse(yyMMdd)); } public static IforeRunnerDateExample gethhmmssyyyyMMddDate(String hhmmssyyyyMMdd) throws ParseException { return new IforeRunnerDateExample(hhmmssyyyyMMdd.parse(hhmmssyyyyMMdd)); } /** * * @param yyyymmddhhMM * @return * @throws ParseException */ public static IforeRunnerDateExample getyyyymmddhhMM(String yyyymmddhhMM) throws ParseException { return new IforeRunnerDateExample(yyyymmddhhMM.parse(yyyymmddhhMM)); } public static IforeRunnerDateExample getyyyymmddhhMMss(String yyyymmddhhMMss) throws ParseException { return new IforeRunnerDateExample(yyyymmddhhMMss.parse(yyyymmddhhMMss)); } /* * @return date String in yyyymmdd format */ public String getyyyymmddString(){ return yyyymmdd.format(this); } /* * @return date String in yyyymmdd format */ public String gethhmmssyyyyMMddString(){ return hhmmssyyyyMMdd.format(this); } /* * @return date String in yyyymmdd format */ public String getMMddyyString(){ return MMddyy.format(this); } public String getyyMMString(){
return yyMM.format(this); } public String getMMDDHHmmString(){ return MMDDHHmm.format(this); } /** * * @param mmyy * @return * @throws ParseException */ public static IforeRunnerDateExample getMMyy(String MMyy)throws ParseException { return new IforeRunnerDateExample(MMyy.parse(MMyy)); } public static IforeRunnerDateExample getyyyymmdd(String yyyymmdd)throws ParseException { return new IforeRunnerDateExample(yyyymmdd.parse(yyyymmdd)); } public static IforeRunnerDateExample getyyMMdd(String yyMMdd)throws ParseException { return new IforeRunnerDateExample(yyMMdd.parse(yyMMdd)); } public static IforeRunnerDateExample getMMDDHHmm(String MMDDHHmm)throws ParseException { return new IforeRunnerDateExample(MMDDHHmm.parse(MMDDHHmm)); } public boolean equals(Object obj) { return (obj.getClass().equals(IforeRunnerDateExample.class) && (((IforeRunnerDateExample) obj).getTime() == this .getTime())); } public static void main( String [] args){ IforeRunnerDateExample IforeRunnerDateExample = new IforeRunnerDateExample(); DateFormat MMddyyyy = new SimpleDateFormat("MMddyyyy"); DateFormat MMddyy = new SimpleDateFormat("MMddyy"); DateFormat MMyy = new SimpleDateFormat("MMyy"); DateFormat Mddyy = new SimpleDateFormat("Mddyy"); try { // try some parsings here IforeRunnerDateExample.setTime(Mddyy .parse("10101").getTime()); IforeRunnerDateExample.setTime(MMddyyyy .parse("10212007").getTime()); } catch (Exception e) { } System.out.println( IforeRunnerDateExample.getdateFormatmmddyyyy()); } }
public class WrapperDemo { public static void main( String [] args ){ String intValue= "1212"; String doubleValue="121212.30";//double String floatValue= "0.112"; String byteValue = "112";
//CONVERTING STRING TO NUMERIC VALUES int toIntValue= Integer.parseInt(intValue); double toDoubleValue = Double.parseDouble( doubleValue ); float toFloatValue = Float.parseFloat(floatValue); byte toByteValue = Byte.parseByte( byteValue ); System.out.println( "--------------"); System.out.println( toDoubleValue ); System.out.println( toIntValue ); System.out.println( toFloatValue); System.out.println( toByteValue ); System.out.println( "--------------"); //Conversion from NUMERIC primitive to NUMERIC Wrapper Object is very easy //byte byteValue() Byte toByte= new Byte( (byte)16 ); //cast mandatory for byte Integer toInt = new Integer( 16 ); Double toDouble = new Double(Math.E); //short shortValue() short getShortValue = toInt.shortValue(); //int intValue() int getIntValue = toInt.intValue(); //long longValue() long getLong = toInt.longValue(); //float floatValue() float getFloat = toDouble.floatValue(); //double doubleValue() double getDouble = toDouble.doubleValue(); System.out.println( getDouble ); System.out.println( getIntValue ); } } OUT PUT
-------------121212.3 1212 0.112 112 -------------2.718281828459045 16 Java.util.LinkedHashMap Java Collections -LinkedHashMap LinkedHashMap implements Map Interface Example import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedHashMap; // Order of Entry is guaranteed in linked HashMap public class LinkedHashMapDemo { public LinkedHashMap buildLinkedHashMap(){ LinkedHashMap linkedHashMap = new LinkedHashMap(); linkedHashMap.put( "Name" , "Venugopal Darur" ); linkedHashMap.put( "RollNo" , "639" ); linkedHashMap.put( "College" , "Vasavi College Of Engineering" ); linkedHashMap.put( "City" , "Hyderabad" ); linkedHashMap.put( "State" , "Andhra Pradesh" ); linkedHashMap.put( "Country" , "India" ); return linkedHashMap; } public void printLinkedHashMap( LinkedHashMap linkedHashMap ){ Iterator iterator = linkedHashMap.keySet().iterator(); while ( iterator.hasNext() ){ String key = ( String ) iterator.next(); String value = ( String ) linkedHashMap.get( key ); System.out.println( key + "\t\t: \t" + value ); } } public static void main( String [] args ){ LinkedHashMapDemo linkedHashMapDemo = new LinkedHashMapDemo( ); LinkedHashMap linkedHashMap =linkedHashMapDemo.buildLinkedHashMap(); linkedHashMapDemo.printLinkedHashMap( linkedHashMap ); } }
Output : Name : Venugopal Darur
RollNo : 639 College : Vasavi College Of Engineering City : Hyderabad State : Andhra Pradesh Country : India
// Java Example Of Hashtable import java.util.Enumeration; import java.util.Hashtable;
public class HashTableDemoExample { public Hashtable buildHashTable(){ Hashtable hashTable = new Hashtable(); hashTable.put( "Name" , "Venugopal Darur" ); hashTable.put( "RollNo" , "639" ); hashTable.put( "College" , "Vasavi College Of Engineering" ); hashTable.put( "City" , "Hyderabad" ); hashTable.put( "State" , "Andhra Pradesh" ); hashTable.put( "Country" , "India" ); return hashTable; } public void prinHashTable( Hashtable hashTable ){ Enumeration enumerator = hashTable.keys(); while ( enumerator.hasMoreElements() ){ String key = ( String ) enumerator.nextElement(); String value = ( String ) hashTable.get( key ); System.out.println( key + "\t\t: \t" + value ); } } public static void main( String [] args ){ HashTableDemo hashtableDemo = new HashTableDemo( ); Hashtable hashtable =hashtableDemo.buildHashTable(); hashtableDemo.prinHashTable( hashtable ); } } Output : Name : Venugopal Darur State : Andhra Pradesh City : Hyderabad College : Vasavi College Of Engineering RollNo : 639 Country : India // Hashtable cannot store even one Null Value
Example for Java HashMap. import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator;
public class HashMapDemo { public HashMap buildHashTable(){ HashMap hashMap = new HashMap(); hashMap.put( "Name" , "Venu gopal Darur" ); hashMap.put( "RollNo" , "639" ); hashMap.put( "UNIVERSITY " , "Some University" ); hashMap.put( "City" , "Hyderabad" ); hashMap.put( "State" , "Andhra Pradesh" ); hashMap.put( "Country" , "India" ); hashMap.put( null , "India" ); return hashMap; } public void prinHashTable( HashMap hashMap ){ Iterator iterator = hashMap.keySet().iterator();// Iterate on keys //We can also Iterate on values how? i.e. your homework while ( iterator.hasNext() ){ String key = ( String ) iterator.next(); String value = ( String ) hashMap.get( key ); System.out.println( key + "\t\t: \t" + value ); } } public static void main( String [] args ){ HashMapDemo hashMapDemo = new HashMapDemo( ); HashMap hashMap =hashMapDemo.buildHashTable(); hashMapDemo.prinHashTable( hashMap ); } } -------------------------------------------------------------------------------------------------------------------------------------Output : RollNo : 639 City : Hyderabad Name : Venugopal Darur College : Some University Country : India State : Andhra Pradesh null : India
// HashMap can store one Null Value, use this example to show that HashMap can use one null value as key. // Hashtable cannot store one null value as key
TreeMap implements Cloneable, Map, Serializable, SortedMap Treemap is a sorted map according to the keys' natural order. Java Collections -TreeMap ---Java Collections -LinkedHashSet
Java.util.TreeMap Java Collections -TreeMap
Example import java.security.KeyStore.Entry; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; // Darur VenuGopal public class TreeMapDemo { /** * Build a TREE MAP * compatible to java1.5, but not suggested to use since this is not using java generics * * Put a String key and String value */ public TreeMap buildTreeMap( ){ TreeMap treeMap = new TreeMap<String, String>(); treeMap.put( "URL" , "HTTP://WWW.IFORERUNNER.COM" ); treeMap.put( "URL1" , "HTTP://WWW.IFORERUNNER8.COM" ); treeMap.put( "URL2" , "HTTP://WWW.IFORERUNNER7.COM" ); treeMap.put( "URL3" , "HTTP://WWW.IFORERUNNER6.COM" ); treeMap.put( "URL4" , "HTTP://WWW.IFORERUNNER5.COM" ); treeMap.put( "URL5" , "HTTP://WWW.IFORERUNNER4.COM" ); treeMap.put( "URL6" , "HTTP://WWW.IFORERUNNER3.COM" ); treeMap.put( "URL7" , "HTTP://WWW.IFORERUNNER2.COM" ); treeMap.put( "URL8" , "HTTP://WWW.IFORERUNNER1.COM" ); return treeMap;
} /** * Get the MAP key Values, * Get the value assigned to a key * print the key and value * @param treeMap */ public void printTreeMap( TreeMap treeMap ){ Iterator iterator = treeMap.entrySet().iterator(); while( iterator.hasNext() ){ Map.Entry keyEntry = (Map.Entry ) iterator.next(); String key = ( String )keyEntry.getKey(); System.out.print( " KEY : " + key); String value = (String) treeMap.get(key); System.out.println( " \t\t\tThe Value for the key: " + value ); } } public static void main( String [] args ){ TreeMapDemo treeMapDemo = new TreeMapDemo(); TreeMap treeMap = treeMapDemo.buildTreeMap(); treeMapDemo.printTreeMap(treeMap); } }
Output : KEY : URL The Value for the key: HTTP://WWW.IFORERUNNER.COM KEY : URL1 The Value for the key: HTTP://WWW.SUN.COM KEY : URL2 The Value for the key: HTTP://WWW.JAVASOFT.COM KEY : URL3 The Value for the key: HTTP://WWW.JAVA.COM KEY : URL4 The Value for the key: HTTP://WWW.SERVERSIDE.COM KEY : URL5 The Value for the key: HTTP://WWW.HIBERNATE.ORG KEY : URL6 The Value for the key: HTTP://WWW.GOOGLE.COM KEY : URL7 The Value for the key: HTTP://WWW.IFORERUNNER.COM KEY : URL8 The Value for the key: HTTP://WWW.IFORERUNNER.COM
OOPs Concepts Encapsulation Encapsulation is the process of combining instance variables and methods into a type of structure usually called as "Class". In java language we can't write a single tiny program without using class. Imagine you have a code for a class and other programmers wrote code by making use of your class. But their code changes your instance variables values. Their code bought errors in your code. This type scenario might happen in structured programming languages. But this is a java program you are able to bring out newer version of the class, which other programmers could replace in their code without changing your code. This scenario brings the three key benefits which we stated earlier flexibility, maintainability and extensibility. But these benefits will not come automatically. You have to write your code that should support the benefits. If you made your instance variables as Public other programmers
can change their state (here state means the values). So you have to keep your class instance variables private or protected. But here you may ask a question that how could we access these protected instance variables? Here we have to make our instance methods public and we can access protected variables through these public methods. The ability to change the behavior of your code without changing your implementation code is a key benefit of encapsulation. You want to hide implementation details behind a public programming interface. By interface, we mean the set of accessible methods your code makes available for other code to call-in other words, your code's API. By hiding implementation details, you can rework your method code without forcing a change in the code that calls your changed method. If you want maintainability, flexibility, and extensibility 1.Keep instance variables protected (with an access modifier, often private). 2. Make public accessor methods, and force calling code to use those methods rather than directly accessing the instance variable. 3. For the methods, use the JavaBeans naming convention of set and get. public class Box { // protect the instance variable; //Only an instance of Box Class can access it private int size; // Provide public getters and setters public int getSize() { return size; } public void setSize(int newSize) { size = newSize; } } //This should be saved in Box.java
class BoxMain { public static void main(String args[]) { //create instance of Box Box b=new Box(); //access methods trough box objects b.setSize(25); System.out.println("Size:"+b.getsize()); } //This program should be saved in BoxMain.java Compile both the classes c:/>javac Box.java c:/>javac BoxMain.java Run the BoxMain Class c:/>java BoxMain Output: Size:25
Output of the program is as follows: PRINT NAME: Venu Gopal Darur PRINT NUMBER: 0 PRINT ONE 1 OOPs Concepts Polymorphism Polymorphism allows the software developer to reuse names as well as code. Polymorphism is a term that describes a situation where one name may refer to different methods. Polymorphism is the ability of a programming language to process object differently depending on their datatype or class. Polymorphism is the capability of method to do different things based on the object that it is acting upon. The meaning of the word polymorphism is one name, many forms, in java in the form of multiple methods with the same name
Compile-time-Polymorphism In compiletime polymorphism the compiler will identify which method to be invoked during compile time itself and statically link it (Static linking or static binding). Method overloading is a best example of compile time polimorphism. Method overloading occurs when several methods have same names with different method signature.overloading of method is determined at the compile time. Overloaded methods let you reuse the same method name in a class, but with different arguments (and optionally, a different return type). The rules are simple: " Overloaded methods must change the argument list. " Overloaded methods can change the return type. " Overloaded methods can change the access modifier. " Overloaded methods can declare new or broader checked exceptions. " A method can be overloaded in the same class or in a subclass. In other words, if class A defines a display(int i) method, the subclass B could define a display(String s) method without overriding the superclass version that takes an int. So two methods with the same name but in different classes can still be considered overloaded, if the subclass inherits one version of the method and then declares another overloaded version in its class definition. Legal Overloads Let's look at a method we want to overload: public void changeSize(int size, String name, float pattern) { } The following methods are legal overloads of the changeSize() method: public void changeSize(int size, String name) { } public int changeSize(int size, float pattern) { } public void changeSize(float pattern, String name) throws IOException { } Example1
class Adder { public int addThem(int x, int y) { return x + y; } // Overload the addThem method to add doubles instead of ints public double addThem(double x, double y) { return x + y; } } // From another class, invoke the addThem() method public class TestAdder { public static void main (String [] args) { Adder a = new Adder(); int b = 27; int c = 3; int result = a.addThem(b,c); // Which addThem is invoked? double doubleResult = a.addThem(22.5,9.3); // Which addThem? }
}
In the preceding TestAdder code, the first call to a.addThem(b,c) passes two ints to the method, so the first version of addThem()-the overloaded version that takes two int arguments-is called. The second call to a.addThem(22.5, 9.3) passes two doubles to the method, so the second version of addThem()-the overloaded version that takes two double arguments-is called. Runtime-Polymorphism The runtime polymorphism is achieved through function overriding. Function overriding means suppose you have two classes one is super class and another on is sub class. If both classes have a method which has the same return type as well as same number and type of argument list then the function is said to be overridden. This scenario is said to be runtime polymorphism because JVM will decide at runtime that which version of the function either the one which is super class or the one which is in sub class. Example see the following code public class Doctor { public void details() { System.out.println("Doctor without any specialization"); } } class Dentist extends Doctor { public void details() { System.out.println("Doctor with specialization: Dentist "); } } both the classes have details() method. But which version it displays will be decided based on the object type. The Doctor class creator might have decided that for the purposes of polymorphism, all Doctor subtypes should have a details() method defined in a unique, specific way. Polymorphically, when someone has an Doctor reference that refers not to Doctor instance, but to a Doctor subclass instance (here Dentist), the caller should be able to invoke details() on the Doctor reference, but the actual runtime object (say, a Dentist instance) will run its own specific details() method. Main method for above two classes public class Test { public static void main (String [] args) { Doctor d = new Doctor(); Doctor b = new Dentist(); //Doctor ref, but a Dentist object d.details(); // Runs the Doctor version b.details(); // Runs the Dentist version } }
The variable b is of type Doctor, which has a public details () method. But remember that at runtime, Java uses virtual method invocation to dynamically select the actual version of the method that will run, based on the actual instance. A Doctor reference can always refer to a Dentist instance, because Dentist IS-A Doctor. What makes that superclass reference to a subclass instance possible is that the subclass is guaranteed to be able to do everything the superclass can do and can also do the things which are specific to the subclass.. The following rules are applied when you are implementing function overriding. " The argument list must exactly match that of the overridden method. If they don't match, you can end up with an overloaded " The return type must be the same as, or a subtype of, the return type declared in the original overridden method in the superclass. " The access level can't be more restrictive than the overridden method's. That is the super class method's access level should always either public or protected but it should not be private. Because private methods cannot be inherited " The access level can be less restrictive than that of the overridden method. " Instance methods can be overridden only if they are inherited by the subclass. " A subclass within the same package as the instance's superclass can override any superclass method that is not marked private or final. " You cannot override a method marked final. " You cannot override a method marked static. " If a method can't be inherited, you cannot override it. Remember that overriding implies that you're reimplementing a method you inherited Example Base.java public class Base { public void display(String s) { System.out.println("String:"+s+" Displayig from Superclass"); } }
Sub1.java public class Sub1 extends Base { public void display(String d) { System.out.println("String"+d+" Displaying from Sub1 class"); }
public void details() { System.out.println("This is subclass1"); } }
Sub2.java public class Sub2 extends Base { public void display(String g) { System.out.println("String:"+g+" Displaying from Sub2 class"); } public void prnt() { System.out.println("This is another method of Sub2 class"); } }
MainClass.java public class MainClass { public static void main(String args[]) { String h ="Hello"; Base b= new Base(h); b.display();// executes base class version of display() method Sub1 s1=new Sub1(h); s1.display();//executes sub1 class display() method s1.details(); // executes details() method Sub2 s2=new Sub2(); s2.display(h);//executes sub2 version of display() s2.prnt(); b=new Sub1(); b.display(h);// executes sub1 class display() method //b.details(); compiler error since base class doest know about details() method so it will not execute b=new Sub2(); b.display(h);// executes sub2 class display() method }
}
An EXCEPTION, is an abnormal event in a program, that means an Exception breaks the normal flow of execution. There are several reasons which leads to exceptions including hardware failures, resource exhaustion. When an exceptional event occurs in a Java program the normal flow will be break down and then the control has to go into some other place, this is something called as an Exception that is "thrown." The code that's responsible for doing something about the exception is called an "Exception Handler," and it "catches" the thrown exception. Exception handling works by transferring the execution of a program to an appropriate exception handler when an exception occurs. For example, if you call a method that opens a file but the file cannot be opened, execution of that method will stop, and code that you wrote to deal with this situation will be run. Therefore, we need a way to tell the JVM what code to execute when a certain exception happens. Using try and catch We use the try and catch keywords. The try is used to define a block of code in which exceptions may occur. This block of code is called a guarded region (which means "risky code is there in this block"). One or more catch clauses match a specific exception to a block of code that handles it. Suppose lets check the following code. Public class ExceptionTest { try { ------------------------------------------------------------------} catch(MyExceptionOne) { ----------------------------------------} catch(MyExceptionTwo) { ------------------------------------} } In the above class the block which is enclosed by try keyword is guarded region. That is we are explicitly saying to the JVM that here some abnormal event may occur and the block which are enclosed with the catch keyword is called Exception handler block. Whenever an abnormal event occurred then the control will go into this block. Notice that the catch blocks immediately follow the try block. This is a requirement; if you have one or more catch blocks, they must immediately follow the try block. Additionally, the catch blocks must all follow each other, without any other statements or blocks in between and also, the order in which the catch blocks appear matters. Suppose lets say the execution is started, the control is entered into try block an exception has occurred at line one of try block then the control will immediately pass into one of the its catch blocks and executes. Here the remaining lines of the try block will not execute. After executing a catch block the control will never come again into the try block instead it just executes statements
after the catch blocks. Here when an exception occurred it checks its type and if a match is found at one of the catch blocks, then that catch block will be executed. For example an exception has occurred in try block which is of type MyExceptionOne then the control checks the matching catch block here the matched catch block is first catch block itself. So it'll be executed. If the try block is executed without any exceptions then the catch blocks will not be executed. The statements after the catch blocks will be executed. Example Program that generates Arithmetic Exception class TestException { public static void main(String args[]) { int i=15; double d; try { for(int j=0;j<=5;j++) d=i/j; } catch(Exception e){ System.out.println("The generated Exception is: "+e); }}} We know that when 15 is divided by non zero value it'll give some result but when it is divided by zero the result we may not predict. So we have kept that code in try block and handled in catch block. If you execute above code the following out it gives. Output: The generated Exception is: java.lang.ArithmeticException :/(divided by) byzero package venu.darur.gopal.examples.java.IO.FileWriter; import java.io.FileWriter; import java.io.IOException; public class FileWriterDemo { public static void main ( String [] args ){ String fileWriterString= "C:\\FIleWRITER.TXT"; FileWriter fileWriter =null; try{ fileWriter= new FileWriter( fileWriterString, true ); // true for appending text String abc = "HELLO WORLD"; fileWriter.write(abc); }catch (IOException eIOException) { System.out.println( "IOEXCEPTION IN READING THE FILE" + eIOException); }finally{ try{ if( fileWriter!=null ){ fileWriter.close(); } }catch (IOException eIOException) { System.out.println( "IOEXCEPTION IN READING THE FILE" + eIOException); }
} } Java Collections Java provides a wide range of collections, Package : java.util. In java Collection is an interface. Collections are classified into three types. "Why need collections? We know that class java.lang.Array, an array holds similar data types and its size is defined while initializing, some times when there is a dynamic environment,the size of the array may have to be changed from time to time, which is not possible always. to address these issues SUN has come with collections, In java 1.5 it has gone more advanced, here we are trying to give a clear understanding of all the collections, will work for java 1.4 versions.
The following table is the classified explanation of all the collections Set Storage
Examples
SET Storage
Only Unique values • • •
List Can store duplicates
Map Store a Key and a pair value • HashMap ArrayList • Hashtable Vector • LinkedHashMap LinkedList • TreeMap
• • •
Hashset TreeSet LinkedHashset
HashSet Only Unique values
TreeSet Unique values in sorted order
ArrayList Can store duplicates
Vector Can store duplicates
LinkedHashSet Unique values and order of entry is assured
Examples
LIST Storage
LinkedList Can store duplicates order of entry is guaranteed. Can add elements first and last. it can be acted like Queue, Stack or Deque
Not Synchronized synchornised Examples MAP Storage
Hashmap Key pair value & can store one null key based value Not synchornised
HashTable TreeMap Key pair value & cannot Key pair value in store null key based sorted key based value order. Synchronized
Examples
/** * * @author Venugopal Darur * Practical way to use String Buffer in Java is explained. * It is always efficient to use StringBuffer when we append
* more than 5 strings. * For example * if we add 100 Strings concatenation it will tak more time to execute * But if we use a Stringbuffer in comparitively very less. * In interviews you need answer this, instead of saying briefly * Mutable or Immutable no one understands. * * Please say the difference between String and StringBuffer is performance when * concatenating more strings. * Using StringBuffer saves us more time and in production environments * recommend Stringbuffer to String. * */ public class StringBufferDemo { public static void main( String [] args ){ // Time taken for String concatenation. String bufferString = "S"; double startTime = System.currentTimeMillis(); bufferString=stringAddition(bufferString); double endTime = System.currentTimeMillis(); System.out.println( (endTime-startTime)/100); // Add this String for 100 times using String addition startTime = System.currentTimeMillis(); bufferString = "StringBuffer"; bufferString=stringBufferAddition(bufferString); endTime = System.currentTimeMillis(); System.out.println( (endTime-startTime)/100); bufferString = "StringBuilder"; bufferString=stringBuilderAddition(bufferString); endTime = System.currentTimeMillis(); System.out.println( (endTime-startTime)/100); // See the output time there is huge difference }
/** * StringConcatenation * @param bufferString * @return */ public static String stringAddition( String bufferString ){ for( int i =0; i<=25; i++ ){ bufferString = bufferString+""+bufferString; } return bufferString; } /** * 1 Construct StringBuffer Example Method * 2 Convert StringBuffer to String * @param bufferString * @return */
public static String stringBufferAddition( String bufferString ){ StringBuffer stringBuffer = new StringBuffer(); for( int i =0; i<=10000; i++ ){ //simpple append method is used stringBuffer.append(bufferString); } //convert StringBuffer to String bufferString=stringBuffer.toString(); return bufferString; } /** * Difference between StringBuffer and StringBuilder is synchronization * 1 Construct StringBuilder Example Method * 2 Convert StringBuilder to String * @param builderString * @return */ public static String stringBuilderAddition( String builderString ){ StringBuilder stringBuilder = new StringBuilder(); for( int i =0; i<=10000; i++ ){ //simpple append method is used stringBuilder.append(builderString); } //convert StringBuilder to String builderString=stringBuilder.toString(); return builderString; } } /** * output of the program in our local machine * * 6.57 shows less performance * 0.0 shows More performance * 0.16 shows little more performance * */
Serialization Serialization is the process of saving an object onto a storage medium (such as a file, or a memory buffer) or to transmit it across a network connection link, either in binary form, or in some human-readable text format such as XML. The series of bytes or the format can be used to recreate an object that is identical in its internal state to the original object (actually a clone). This process of serializing an object is also called deflating or marshalling an object. The opposite operation, extracting a data structure from a series of bytes, is deserialization (which is also called inflating or unmarshalling). The process of packaging and unpackaging data that must be moved between different parts of a computer program or from one program to another. It is typically accomplished by serializing the data to a shared memory area. Serialization is used for lightweight persistence and for communication via sockets or Remote Method Invocation (RMI). The default encoding of objects
protects private and transient data, and supports the evolution of the classes. Quite simply, object Serialization provides a program that has the ability to read or write a whole object to and from a raw byte stream. It allows Java objects and primitives to be encoded into a byte stream suitable for streaming to some type of network or to a file-system, or more generally, to a transmission medium or storage facility. Serialization is the mechanism used by RMI to pass objects between JVMs, either as arguments in a method invocation from a client to a server or as return values from a method invocation. Serialization lets you save object and all its instance variables, unless you have explicitly marked a variable transient, which means informing to the JVM that don't include the transient variable's value as a part of the object serialization state.. Working with ObjectOutputStream and ObjectInputStream The basic object Serialization happens with just two methods one to serialize objects and write them to a stream, and a second to read the stream and deserialize objects. ObjectOutputStream.writeObject() ObjectOutputStream.readObject() Since java.io.ObjectOutputStream and java.io.ObjectInputStream classes are high level classes. So they have to wrap lower level classes such as java.io.FileOutputStream and java.io.FileInputStream package jdbc; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; /** * This interface has all the constants for making JDBC Connections * * @author Darur Venugopal * */ public interface IJDBCConstants { // In Interface all the variables are public , static and final String host = "jdbc:oracle:thin:@localhost:1521:xe"; String username = "HR"; String password = "ORACLE"; String driverName = "oracle.jdbc.driver.OracleDriver"; // Declare methods , In interface just method signature are defined. Connection makeConnection(); Statement makeStatement(); // ResultSet getresultSet(); void LoadDriver(); } package jdbc; import java.sql.Connection;
import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class PerfectJdbc { private static final String sqlQuery = "select email ,first_name, last_name from employees"; public static void main(String[] args) { System.out.println("STEP 1 is LOAD JAVA DRIVER IN THIS RUNNONG ENVIRONMENT"); IJDBCConstants jdbcImplementor = new JDBCImplementor(); // valid instantiation // step 1 jdbcImplementor.LoadDriver(); System.out.println("STEP 2 IS TO MAKE CONNECTION FROM JAVA TO DATABASE"); Connection connection = jdbcImplementor.makeConnection(); Statement statement; try { statement = connection.createStatement(); // step 3 ResultSet resultSet = statement.executeQuery( sqlQuery); // step4 int i = 0; // now we got the result set, print the values from // result set. // while (resultSet.next()) { System.out.println("----------------:" + (++i)+ "START :----------------"); System.out.println("First Name: \t\t\t"+ resultSet.getString("first_name")); System.out.println("last Name: \t\t\t"+ resultSet.getString("last_name")); System.out.println("Email: \t\t\t\t" + resultSet.getString("email")); System.out.println("----------------:" + (i)+ " end:----------------"); } } catch (SQLException e) { System.err.println("SQLEXCEPTION: " + e); } } }
package jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class SQLInsertion { private static final String sqlQuery = "select email ,first_name, last_name from employees"; private static final String sqlQueryForsql ="select sino, name,place ,email from sqltable"; // insertion statement private static final String insertQuery ="INSERT INTO SQLTABLE VALUES ( ? , ? , ?,? ) "; public static void main(String[] args) { System.out.println("STEP 1 is LOAD JAVA DRIVER IN THIS RUNNONG ENVIRONMENT"); IJDBCConstants jdbcImplementor =new JDBCImplementor(); // valid instantiation // step 1 jdbcImplementor.LoadDriver(); System.out.println("STEP 2 IS TO MAKE CONNECTION FROM JAVA TO DATABASE"); Connection connection = jdbcImplementor.makeConnection(); Statement statement; try { statement = connection.createStatement(); // step 3 ResultSet resultSet = statement.executeQuery(sqlQuery); // step4 int i = 0; // now that I got the result set i want to print the values from // result set. // while (resultSet.next()) { String name =resultSet.getString("first_name") +" " + resultSet.getString("last_name"); String email = resultSet.getString("email"); String place ="NIZAMABAD"; PreparedStatement preparedStatement = connection.prepareStatement(insertQuery); // For Insertions USe Prepared Insertions preparedStatement.clearParameters(); preparedStatement.setString(1, name);
preparedStatement.setString(2, place); preparedStatement.setInt(3, ++i); preparedStatement.setString(4, email); preparedStatement.executeUpdate(); } ResultSet resultSetForsql = jdbcImplementor.makeStatement().executeQuery(sqlQueryForsql); while (resultSetForsql.next()) { System.out.println("11111"); String name =resultSetForsql.getString("name"); String email =resultSetForsql.getString("email"); String place =resultSetForsql.getString("place"); int siNo = resultSetForsql.getInt("sino"); String result = siNo +" " + name + " " + email; System.out.println(result); } } catch (SQLException e) { System.err.println("SQLEXCEPTION: " + e); } } } package jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCImplementor implements IJDBCConstants { public static Connection connection = null; public static Statement statement = null; public void LoadDriver() { // CHecked Exceptions try { Class.forName(driverName); System.out.println("DRIVER LOADED SUCCESSFULLY"); }
catch (ClassNotFoundException classNotFound) { System.out.println("CLASS NOT FOUND EXCEPTION " + classNotFound); } } public Connection makeConnection() { try { connection = DriverManager.getConnection(host, username, password); System.out.println("Connected properly "); } catch (SQLException sqlException) { System.out.println("SQLEXCEPTION: " + sqlException); } return connection; } public Statement makeStatement() { if (connection != null) { try { statement = connection.createStatement(); } catch (SQLException sqlException) { System.out.println("SQLEXCEPTION: " + sqlException); } } return statement; } } SELECTION package jdbc; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; /** * This interface has all the constants for making JDBC Connections * * @author Darur Venugopal
* */ public interface IJDBCConstants { // In Interface all the variables are public , static and final String host = "jdbc:oracle:thin:@localhost:1521:xe"; String username = "HR"; String password = "ORACLE"; String driverName = "oracle.jdbc.driver.OracleDriver"; // Declare methods , In interface just method signature are defined. Connection makeConnection(); Statement makeStatement(); // ResultSet getresultSet(); void LoadDriver(); } package jdbc; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class PerfectJdbc { private static final String sqlQuery = "select email ,first_name, last_name from employees"; public static void main(String[] args) { System.out.println("STEP 1 is LOAD JAVA DRIVER IN THIS RUNNONG ENVIRONMENT"); IJDBCConstants jdbcImplementor = new JDBCImplementor(); // valid instantiation // step 1 jdbcImplementor.LoadDriver(); System.out.println("STEP 2 IS TO MAKE CONNECTION FROM JAVA TO DATABASE"); Connection connection = jdbcImplementor.makeConnection(); Statement statement; try { statement = connection.createStatement(); // step 3 ResultSet resultSet = statement.executeQuery( sqlQuery); // step4 int i = 0; // now we got the result set, print the values from // result set.
// while (resultSet.next()) { System.out.println("----------------:" + (++i)+ "START :----------------"); System.out.println("First Name: \t\t\t"+ resultSet.getString("first_name")); System.out.println("last Name: \t\t\t"+ resultSet.getString("last_name")); System.out.println("Email: \t\t\t\t" + resultSet.getString("email")); System.out.println("----------------:" + (i)+ " end:----------------"); } } catch (SQLException e) { System.err.println("SQLEXCEPTION: " + e); } } } package jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class SQLInsertion { private static final String sqlQuery = "select email ,first_name, last_name from employees"; private static final String sqlQueryForsql ="select sino, name,place ,email from sqltable"; // insertion statement private static final String insertQuery ="INSERT INTO SQLTABLE VALUES ( ? , ? , ?,? ) "; public static void main(String[] args) { System.out.println("STEP 1 is LOAD JAVA DRIVER IN THIS RUNNONG ENVIRONMENT"); IJDBCConstants jdbcImplementor =new JDBCImplementor(); // valid instantiation // step 1 jdbcImplementor.LoadDriver(); System.out.println("STEP 2 IS TO MAKE CONNECTION FROM JAVA TO DATABASE"); Connection connection = jdbcImplementor.makeConnection(); Statement statement; try { statement = connection.createStatement(); // step 3 ResultSet resultSet = statement.executeQuery(sqlQuery); // step4
int i = 0; // now that I got the result set i want to print the values from // result set. // while (resultSet.next()) { String name =resultSet.getString("first_name") +" " + resultSet.getString("last_name"); String email = resultSet.getString("email"); String place ="NIZAMABAD"; PreparedStatement preparedStatement = connection.prepareStatement(insertQuery); // For Insertions USe Prepared Insertions preparedStatement.clearParameters(); preparedStatement.setString(1, name); preparedStatement.setString(2, place); preparedStatement.setInt(3, ++i); preparedStatement.setString(4, email); preparedStatement.executeUpdate(); } ResultSet resultSetForsql = jdbcImplementor.makeStatement().executeQuery(sqlQueryForsql); while (resultSetForsql.next()) { System.out.println("11111"); String name =resultSetForsql.getString("name"); String email =resultSetForsql.getString("email"); String place =resultSetForsql.getString("place"); int siNo = resultSetForsql.getInt("sino"); String result = siNo +" " + name + " " + email; System.out.println(result); } } catch (SQLException e) { System.err.println("SQLEXCEPTION: " + e); } } } package jdbc; import java.sql.Connection; import java.sql.DriverManager;
import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCImplementor implements IJDBCConstants { public static Connection connection = null; public static Statement statement = null; public void LoadDriver() { // CHecked Exceptions try { Class.forName(driverName); System.out.println("DRIVER LOADED SUCCESSFULLY"); } catch (ClassNotFoundException classNotFound) { System.out.println("CLASS NOT FOUND EXCEPTION " + classNotFound); } } public Connection makeConnection() { try { connection = DriverManager.getConnection(host, username, password); System.out.println("Connected properly "); } catch (SQLException sqlException) { System.out.println("SQLEXCEPTION: " + sqlException); } return connection; } public Statement makeStatement() { if (connection != null) { try { statement = connection.createStatement(); } catch (SQLException sqlException) { System.out.println("SQLEXCEPTION: " + sqlException); } }
return statement; } }