To store 100 objects of employee class: To store 100 objects of employee class:
-A group of objects can be stored in any array but there are two limitations. A group of objects can be stored in any array but there are two limitations. 1) It is not possible to store different class objects in to the same array. 1) It is not possible to store different class objects in to the same array. 2) Methods are not available to process the elements of the array. 2) Methods are not available to process the elements of the array.
java.util java.util Objects Objects Collection class Collection class Collection
Collection object object ContainerContainer
A collection object or container object is an object that stores a group of other A collection object or container object is an object that stores a group of other objects. A collection class or container class is a class whose class object can store a objects. A collection class or container class is a class whose class object can store a group of other class.
group of other class.
What is collection frame work
What is collection frame work ??
It represents group of classes. It is a class library to handle groups of objects. It represents group of classes. It is a class library to handle groups of objects. Collection frame work implemented java.util package
Collection frame work implemented java.util package
Note: - Collection objects stores only references. (Collection object does not store other Note: - Collection objects stores only references. (Collection object does not store other object. It requires group of objects)
object. It requires group of objects)
Objects Objects
Object reference Object reference
Collection object can not handle (does not store) primitive data type. Collection object can not handle (does not store) primitive data type.
All the classes in collection frame work have been defined in 3 types. They are All the classes in collection frame work have been defined in 3 types. They are 1) Sets
1) Sets 2) Lis2) Lists 3) Mts 3) Maps.aps. 1)
1) SetsSets: - A set represents a group of elements.: - A set represents a group of elements. Ex: - Hash set, linked hash set, Tree set. Ex: - Hash set, linked hash set, Tree set. 2)
2) ListsLists: - A list also similar to sets, a list is like an array which stores a group of : - A list also similar to sets, a list is like an array which stores a group of events (events means elements). Sets will not allow duplicate values, where as list events (events means elements). Sets will not allow duplicate values, where as list will allows duplicates values also.
will allows duplicates values also. Ex
Ex: - linked list, Array list, and vector.: - linked list, Array list, and vector. 3)
3) MapsMaps: - A map stores the elements in the form of key valve pairs.: - A map stores the elements in the form of key valve pairs. Ex
Ex: - Hash table, Hash map.: - Hash table, Hash map. Array List
Array List: - It is dynamically glowing array that stores objects. It is not synchronized.: - It is dynamically glowing array that stores objects. It is not synchronized. Pr
Only one thread allows the object, it is called synchronized. Or more than 1 Only one thread allows the object, it is called synchronized. Or more than 1 object can not take object is called as synchronized.
object can not take object is called as synchronized.
Several threads take at a time is called unsynchronized. Several threads take at a time is called unsynchronized. 1) To create an array list.
1) To create an array list.
ArrayList arl = new ArrayList( ); ArrayList arl = new ArrayList( ); ArrayList arl = new ArrayLlist (20); ArrayList arl = new ArrayLlist (20); 2) To add objects; use add ( ) method. 2) To add objects; use add ( ) method.
arl.add(“sudheer”); arl.add(“sudheer”); arl.add(2,“sudheer”); arl.add(2,“sudheer”);
3) To remove objects use remove ( ) 3) To remove objects use remove ( )
arl.remove(“sudheer”); arl.remove(“sudheer”); arl.remove(2);
arl.remove(2);
4) To know no. of objects use size ( ) 4) To know no. of objects use size ( )
int n=arl.size( ); int n=arl.size( );
5) To convert ArrayList in to an arry use .toArray( ) 5) To convert ArrayList in to an arry use .toArray( )
object x[ ]=arl.toArray( ); object x[ ]=arl.toArray( );
Object is super class for all class. Object is super class for all class. // creating an array list
// creating an array list import java.util.*;
import java.util.*; class ArrayaListDemo class ArrayaListDemo {{
public static void main(String[] args) public static void main(String[] args) {{
// creating an array list // creating an array list
ArrayList arl=new ArrayList( ); ArrayList arl=new ArrayList( ); // store elements in to arl
// store elements in to arl arl.add("apple"); arl.add("apple"); arl.add("banana"); arl.add("banana"); arl.add("pine apple"); arl.add("pine apple"); arl.add("grapes"); arl.add("grapes"); arl.add("mango"); arl.add("mango");
//display the contents of arl //display the contents of arl
System.out.println("ArrayList = "+arl); System.out.println("ArrayList = "+arl); // remove some elements from arl
// remove some elements from arl arl.remove("apple");
arl.remove("apple"); arl.remove(1);
arl.remove(1);
// display the contents of arl // display the contents of arl
System.out.println("ArrayList = "+arl); System.out.println("ArrayList = "+arl); // find no of elements in url
// find no of elements in url
System.out.println("size of lists = "+arl.size( )); System.out.println("size of lists = "+arl.size( ));
// retrieve the elements using iterator // retrieve the elements using iterator Iterator it=arl.iterator( ); Iterator it=arl.iterator( ); while(it.hasNext( )) while(it.hasNext( )) System.out.println(it.next( )); System.out.println(it.next( )); }} }}
D:\psr\Adv java>javac ArrayaListDemo.java D:\psr\Adv java>javac ArrayaListDemo.java D:\psr\Adv java>java ArrayaListDemo
D:\psr\Adv java>java ArrayaListDemo
ArrayaList = [apple, banana, pine apple, grapes, mango] ArrayaList = [apple, banana, pine apple, grapes, mango] ArrayaList = [banana, grapes, mango]
ArrayaList = [banana, grapes, mango] size of lists = 3 size of lists = 3 banana banana grapes grapes mango mango Note:
Note: - to extract the events one by one from collection objects we can use only one of - to extract the events one by one from collection objects we can use only one of the following
the following 11)) IItteerraattoorr 2)
2) LiLisstItIttereratatoror 3)
3) EEnunummereraatitionon Vectors
Vectors: - It is a dynamically growing array that stores objects, but it synchronized.: - It is a dynamically growing array that stores objects, but it synchronized. 1) To crate a vector
1) To crate a vector
Vector v=new Vector( ); Vector v=new Vector( ); Vector v=new Vecteor(100); Vector v=new Vecteor(100);
2) To know the size of a vector use size( ) 2) To know the size of a vector use size( )
int n=v.size( ); int n=v.size( ); 3) To add elements 3) To add elements v.add(obj); v.add(obj); v.add(2,obj); v.add(2,obj); 4) to retrieve elements 4) to retrieve elements v.get(2); v.get(2); 5) To remove elements 5) To remove elements v.remove( ); v.remove( );
To remove all elements To remove all elements v.clear( );
v.clear( );
6) To know the current capacity 6) To know the current capacity
int n=v.capacity( ); int n=v.capacity( );
7) To search for first occurrence of an element in the vector 7) To search for first occurrence of an element in the vector
int n=v.indexOf(obj) int n=v.indexOf(obj)
8) To search for last occurrence of an element 8) To search for last occurrence of an element
int n=v.lastIndexOf(obj); int n=v.lastIndexOf(obj); // a vector with int values // a vector with int values
import java.util.*; import java.util.*; class VectorDemo class VectorDemo {{
public static void main(String[] args) public static void main(String[] args) {{
// creating an vector v // creating an vector v Vector v=new Vector( ); Vector v=new Vector( ); // take an int type of array x[] // take an int type of array x[] int x[]={10,33,45,67,89}; int x[]={10,33,45,67,89};
// read from x[] & store into v // read from x[] & store into v for(int i=0;i<x.length;i++) for(int i=0;i<x.length;i++) {{ v.add(new Integer(x[i])); v.add(new Integer(x[i])); }}
// retrieve objects using get( ) // retrieve objects using get( ) for(int i=0;i<v.size( );i++) for(int i=0;i<v.size( );i++) {{
System.out.println(v.get(i)); System.out.println(v.get(i)); }}
// retrieve elements from v using Iterator // retrieve elements from v using Iterator ListIterator lit=v.listIterator( );
ListIterator lit=v.listIterator( );
System.out.println("\n in forward Direction :"); System.out.println("\n in forward Direction :"); while(lit.hasNext( ))
while(lit.hasNext( ))
System.out.println(lit.next ( )+""); System.out.println(lit.next ( )+"");
System.out.println("\n reverse Direction :"); System.out.println("\n reverse Direction :"); while(lit.hasPrevious( )) while(lit.hasPrevious( )) System.out.println(lit.previous( )+""); System.out.println(lit.previous( )+""); }} }}
D:\psr\Adv java>javac VectorDemo.java D:\psr\Adv java>javac VectorDemo.java D:\psr\Adv java>java VectorDemo
D:\psr\Adv java>java VectorDemo 1100 3333 4455 6677 8899 in forward Direction : in forward Direction : 1100 3333 4455 6677 8899 reverse Direction : reverse Direction : 8899 6677 4455 3333 1100 Hashtable
Hashtable: - Hashtable Stores objects in the form of keys & values pairs. It is: - Hashtable Stores objects in the form of keys & values pairs. It is synchronized. It will not allow more threads at a time.
synchronized. It will not allow more threads at a time. 1) To create a hash table.
1) To create a hash table.
HashTable ht=new HashTable( ); HashTable ht=new HashTable( ); // initial capacity=11, load factor=0.75 // initial capacity=11, load factor=0.75 HashTable ht=new HashTable(100); HashTable ht=new HashTable(100); 2) To store key value pair
2) To store key value pair
ht.put(“Sunil”, cricket player); ht.put(“Sunil”, cricket player); 3) To get the value when key is given 3) To get the value when key is given
ht.get(“Sunil”); ht.get(“Sunil”);
4) To remove the key (and its corresponding value) 4) To remove the key (and its corresponding value)
ht.remove(“Sunil”); ht.remove(“Sunil”); 5) To know the no. of keys 5) To know the no. of keys
int n=ht.size( ); int n=ht.size( ); 6) To clear all the keys 6) To clear all the keys
ht.clear( ); ht.clear( ); What is load factor?
What is load factor?
A) Load factor determines at what point the initial capacity of a hash table or a hash A) Load factor determines at what point the initial capacity of a hash table or a hash map will be double. Load factor is 0.75 of hash table.
map will be double. Load factor is 0.75 of hash table.
For a hash table initial capacity x load factor = 11x0.75=8 approximately. It For a hash table initial capacity x load factor = 11x0.75=8 approximately. It means after storing 8
means after storing 8ththkey value pair will be doubled=22.key value pair will be doubled=22.
// Hashtable with cricket scores // Hashtable with cricket scores import java.io.*; import java.io.*; import java.util.*; import java.util.*; class HashtableDemo class HashtableDemo {{
public static void main(String[] args) throws IOException public static void main(String[] args) throws IOException {{
// create hash table // create hash table
Hashtable ht=new Hashtable( ); Hashtable ht=new Hashtable( ); // store player name & score // store player name & score
ht.put("Sachin",new Integer(320)); ht.put("Sachin",new Integer(320)); ht.put("Ganguli",new Integer(300)); ht.put("Ganguli",new Integer(300)); ht.put("Dravid",new Integer(150)); ht.put("Dravid",new Integer(150)); ht.put("Dhoni",new Integer(100)); ht.put("Dhoni",new Integer(100)); ht.put("Yuvaraj",new Integer(56)); ht.put("Yuvaraj",new Integer(56)); ht.put("Sehwag",new Integer(000)); ht.put("Sehwag",new Integer(000)); // retrieve keys & display
// retrieve keys & display Enumeration e=ht.keys( ); Enumeration e=ht.keys( ); while(e.hasMoreElements( )) while(e.hasMoreElements( )) System.out.println(e.nextElement( )); System.out.println(e.nextElement( )); // to accept the data
// to accept the data
BufferedReader br=new BufferedReader(new BufferedReader br=new BufferedReader(new
InputStreamReader(System.in)); InputStreamReader(System.in)); System.out.println("Enter player name:");
System.out.println("Enter player name:"); String name=br.readLine( );
String name=br.readLine( ); // pass name & store
// pass name & store
Integer score=(Integer)ht.get(name); Integer score=(Integer)ht.get(name); if(score!=null) if(score!=null) {{ int runs=score.intValue( ); int runs=score.intValue( );
System.out.println(name+" has scored runs "+runs); System.out.println(name+" has scored runs "+runs); }}
else else
{{
System.out.println("player not found"); System.out.println("player not found"); }}
}} }}
D:\psr\Adv java>javac HashtableDemo.java D:\psr\Adv java>javac HashtableDemo.java D:\psr\Adv java>java HashtableDemo
D:\psr\Adv java>java HashtableDemo Yuvaraj Yuvaraj Ganguli Ganguli Dhoni Dhoni Sehwag Sehwag Dravid Dravid Sachin Sachin
Enter player name: Enter player name:
Ganguli has scored runs 300 Ganguli has scored runs 300 Hash map
Hash map: - Stores objects in the form of keys & value pairs. It is synchronized.: - Stores objects in the form of keys & value pairs. It is synchronized. 1) To create a hash table
1) To create a hash table
HashMap hm=new HashMap( ) HashMap hm=new HashMap( )
// initial capacity=11, load factor=0.75 // initial capacity=11, load factor=0.75 HashMap hm=new HashMap(100); HashMap hm=new HashMap(100); 2) To store key value pair
2) To store key value pair
hm.put(“Sunil”, cricket player); hm.put(“Sunil”, cricket player); 3) To get the value when key is given 3) To get the value when key is given
hm.get(“Sunil”); hm.get(“Sunil”);
4) To remove the key (and its corresponding value) 4) To remove the key (and its corresponding value)
hm.remove(“Sunil”); hm.remove(“Sunil”);
5) To know the no. of key value pairs. 5) To know the no. of key value pairs.
int n=hm.size( ); int n=hm.size( );
6) To clear all the key value pairs 6) To clear all the key value pairs
hm.clear( ); hm.clear( );
// Hash map with telephone entries // Hash map with telephone entries import java.io.*; import java.io.*; import java.util.*; import java.util.*; class HashMapDemo class HashMapDemo {{
public static void main(String[] args) throws IOException public static void main(String[] args) throws IOException {{
// vars // vars
HashMap hm=new HashMap( ); HashMap hm=new HashMap( );
BufferedReader br=new BufferedReader(new BufferedReader br=new BufferedReader(new
InputStreamReader(System.in)); InputStreamReader(System.in)); String name,str; String name,str; long phno; long phno; // menu // menu
while(true) while(true) {{
System.out.println("1.Enter entries into phone book"); System.out.println("1.Enter entries into phone book");
System.out.println("2. Look up in phone book"); System.out.println("2. Look up in phone book"); int n=Integer.parseInt(br.readLine( )); int n=Integer.parseInt(br.readLine( )); switch(n) switch(n) {{ case 1: case 1: System.out.println("Enter name : "); System.out.println("Enter name : "); name=br.readLine( ); name=br.readLine( );
System.out.println("Enter phone number : "); System.out.println("Enter phone number : ");
str=br.readLine( ); str=br.readLine( ); phno=new Long(str); phno=new Long(str); hm.put(name,phno); hm.put(name,phno); break; break; case 2: case 2: System.out.println("Enter name : "); System.out.println("Enter name : "); name=br.readLine( ); name=br.readLine( ); phno=(Long)hm.get(name); phno=(Long)hm.get(name);
System.out.println("Phone number : "+phno); System.out.println("Phone number : "+phno); break; break; default : default : return; return; }} }} }} }}
D:\psr\Adv java>javac HashMapDemo.java D:\psr\Adv java>javac HashMapDemo.java D:\psr\Adv java>java HashMapDemo
D:\psr\Adv java>java HashMapDemo 1. Enter entries into phone book 1. Enter entries into phone book 2. Look up in phone book
2. Look up in phone book 11
Enter name: Enter name: Sunil
Sunil
Enter phone number: Enter phone number: 247283
247283
1. Enter entries into phone book 1. Enter entries into phone book 2. Look up in phone book
2. Look up in phone book 22 Enter name: Enter name: Sunil Sunil Phone number: 247283 Phone number: 247283
1. Enter entries into phone book 1. Enter entries into phone book 2. Look up in phone book
2. Look up in phone book 33
What is the difference between Vector & array list
A) 1) From the API perspective, the two classes are same. A) 1) From the API perspective, the two classes are same.
2) Vector is synchronized & array list is not synchronized. 2) Vector is synchronized & array list is not synchronized. Note
Note: - We can make array list also synchronized by using:: - We can make array list also synchronized by using: Collections. synchronizedList(new ArrayList( )); Collections. synchronizedList(new ArrayList( ));
3) Internally both are hold onto their contents using an array. A vector by default 3) Internally both are hold onto their contents using an array. A vector by default increments its size by doubling it, & on array list increases its size by 50%.
increments its size by doubling it, & on array list increases its size by 50%.
4) Both are good for retrieving elements from a specific position in the container or 4) Both are good for retrieving elements from a specific position in the container or for adding & removing elements from the end of the container. All of these for adding & removing elements from the end of the container. All of these operations can be performed in constant time---0(1), but adding & removing operations can be performed in constant time---0(1), but adding & removing elements in the middle takes more time. So in this case a linked list is better.
elements in the middle takes more time. So in this case a linked list is better. What is the difference between hash table & hash map?
What is the difference between hash table & hash map?
A)
A) 1) Hash table is a 1) Hash table is a synchronized, where as hash map is not.synchronized, where as hash map is not. Note
Note: - We can make hash map also synchronized by using:: - We can make hash map also synchronized by using: Collections. synchronizedList(new HashMap( )); Collections. synchronizedList(new HashMap( ));
2) Hash map allows null values as keys & values, where as hash table does not. 2) Hash map allows null values as keys & values, where as hash table does not. 3) That iterator in the hash map is fail-safe, while enumerator for the hash table 3) That iterator in the hash map is fail-safe, while enumerator for the hash table isn’t.
isn’t.
What is the difference between a set & list?
What is the difference between a set & list?
A) 1) Sets represent collection of elements. Lists represent ordered A) 1) Sets represent collection of elements. Lists represent ordered
Collection of elements (also called sequence). Collection of elements (also called sequence).
2) Sets will not allow duplicates values. Lists will allow. 2) Sets will not allow duplicates values. Lists will allow. 3) Accessing elements by their index is possible in lists. 3) Accessing elements by their index is possible in lists. 4) Sets will not allow null elements, lists allow null elements. 4) Sets will not allow null elements, lists allow null elements. StringTokenizer
StringTokenizer: - The StringTokenizer class is useful to break a string into small: - The StringTokenizer class is useful to break a string into small piece called tokens.
piece called tokens.
1) To crate an object to StringTokenizer 1) To crate an object to StringTokenizer
StringTokenizer st=new StringTokenizer(str,”delimeter”); StringTokenizer st=new StringTokenizer(str,”delimeter”); Delimerer means character
Delimerer means character 2) To find the next piece in the string 2) To find the next piece in the string
String piece=st.nextToken( ); String piece=st.nextToken( );
3) To know if more pieces are remaining 3) To know if more pieces are remaining
boolean x=st.hasMoreTokens( ); boolean x=st.hasMoreTokens( );
4) To know how many no. of piece are there 4) To know how many no. of piece are there
int no=st.countTokens( ); int no=st.countTokens( );
The purpose of StringTokenizer is to cut the tokens into piece. The purpose of StringTokenizer is to cut the tokens into piece.
// to cut the string into piece // to cut the string into piece import java.util.*;
import java.util.*; class STDemo class STDemo {{
public static void main(String[ ] args) public static void main(String[ ] args) {{
// take a string // take a string
String str="Sunil Kumar Reddy\ is a nice gentle men\ and genious"; String str="Sunil Kumar Reddy\ is a nice gentle men\ and genious";
// cut str into pieces where space is pound // cut str into pieces where space is pound
StringTokenizer st=new StringTokenizer(str,"\"); StringTokenizer st=new StringTokenizer(str,"\"); // retrieve tokens & display
// retrieve tokens & display
System.out.println("the Tokens are ::"); System.out.println("the Tokens are ::"); while(st.hasMoreTokens( )) while(st.hasMoreTokens( )) {{ String s=st.nextToken( ); String s=st.nextToken( ); System.out.println(s); System.out.println(s); }} }} }}
D:\psr\Adv java>javac STDemo.java D:\psr\Adv java>javac STDemo.java D:\psr\Adv java>java STDemo
D:\psr\Adv java>java STDemo Sunil Kumar Reddy
Sunil Kumar Reddy is a nice gentle men is a nice gentle men and genious
and genious Calendar:
-Calendar: -This class is useful to handle date & time.This class is useful to handle date & time. 1) To create an object to Calendar class
1) To create an object to Calendar class Calendar cl=Calendar.getInstance( ); Calendar cl=Calendar.getInstance( );
2) Use gets to retrieve date or time from Calendar object. This method returns an 2) Use gets to retrieve date or time from Calendar object. This method returns an integer.
integer.
cl.get(Constant); cl.get(Constant); Note:
-Note: -ConstantsConstants
Calendar.DATE Calendar.DATE Calendar.MONTH Calendar.MONTH Calendar.YEAR Calendar.YEAR Calendar.HOUR Calendar.HOUR Calendar.MINUTE Calendar.MINUTE Calendar.SECOND Calendar.SECOND
3) Use set ( ) to the set the date or time 3) Use set ( ) to the set the date or time
ccll..sseett((CCaalleennddaarr..MMOONNTTHH,,1100));; /// / jjaann 00
4) To convert a date in to string, use toStirng( ), this returns a String. 4) To convert a date in to string, use toStirng( ), this returns a String.
String s=cl.toString( ); String s=cl.toString( ); // System date & time // System date & time import java.util.*;
import java.util.*; class Cal
class Cal {{
public static void main(String[] args) public static void main(String[] args) {{ // create calendar // create calendar Calendar cl=Calendar.getInstance( ); Calendar cl=Calendar.getInstance( ); // retrieve data // retrieve data int dd=cl.get(Calendar.DATE); int dd=cl.get(Calendar.DATE); int mm=cl.get(Calendar.MONTH); int mm=cl.get(Calendar.MONTH);
++mm; ++mm; int yy=cl.get(Calendar.YEAR); int yy=cl.get(Calendar.YEAR); System.out.print("Current date : "); System.out.print("Current date : "); System.out.println(dd+"/"+mm+"/"+yy); System.out.println(dd+"/"+mm+"/"+yy); //retrieve time //retrieve time int h=cl.get(Calendar.HOUR); int h=cl.get(Calendar.HOUR); int m=cl.get(Calendar.MINUTE); int m=cl.get(Calendar.MINUTE); int s=cl.get(Calendar.SECOND); int s=cl.get(Calendar.SECOND); System.out.print("Current tim System.out.print("Current time e : : ");"); System.out.println(h+":"+m+":"+s); System.out.println(h+":"+m+":"+s); }} }}
D:\psr\Adv java>javac Cal.java D:\psr\Adv java>javac Cal.java D:\psr\Adv java>java Cal
D:\psr\Adv java>java Cal Current date : 28/8/2007 Current date : 28/8/2007 Current time : 11:48:34 Current time : 11:48:34 Date:
-Date: -Date class is an also useful to handle Date & time.Date class is an also useful to handle Date & time. 1) To create an object to Date class
1) To create an object to Date class Date d=new Date( );
Date d=new Date( );
2) Format the Date & time, using getDateInstance( ) or getTimeInstance( ) or 2) Format the Date & time, using getDateInstance( ) or getTimeInstance( ) or getDateTimeInstance( ) methods of Date format class (this is in java.text)
getDateTimeInstance( ) methods of Date format class (this is in java.text) Syntax:
Syntax:
-DateFormat fmt.getDateInstance(formatConst, region); DateFormat fmt.getDateInstance(formatConst, region); EX:
EX:
-DateFormat fmt.getDateInstance(-DateFormat.MEDIUM,Locale UK); DateFormat fmt.getDateInstance(DateFormat.MEDIUM,Locale UK); Syntax: Syntax: -DateFormat fmt=-DateFormat.getDateTimeInstance(formatConst, DateFormat fmt=DateFormat.getDateTimeInstance(formatConst, formatConst,region); formatConst,region); Ex: Ex: -DateFormat fmt=-DateFormat.getDateTimeInstance DateFormat fmt=DateFormat.getDateTimeInstance (DateFormat.MEDIUM,DateFormat.SHORT,Locale.US); (DateFormat.MEDIUM,DateFormat.SHORT,Locale.US); Note: Note: -f foorrmmaattCCoonnsstt eexxaammpplle e ((rreeggiioonn==LLooccaallee..UUKK)) DateFor
DateFormat.Lmat.LONGONG 03 03 SeptemSeptember ber 2004 2004 19:43:119:43:14 4 GMT+GMT+0.5:300.5:30 Dat
DateForeFormatmat.FUL.FULLL 03 Sep03 Septemtember 20ber 2004 19:04 19:43:143:14 o’ cl4 o’ clock GMock GMT+0T+05:305:30 Da
DatteFeFoorrmmaatt.M.MEEDDIIUUMM 003-3-SSepep--004 4 1199::4343::1414 D
DaatteeFFoorrmmaatt..SSHHOORRTT 0033//0099//004 4 1199::4433
3) Applying format to date object is done by format( ) method. 3) Applying format to date object is done by format( ) method.
String str=fmt.format(d); String str=fmt.format(d); // System date & time
// System date & time import java.util.*;
import java.text.*; import java.text.*; class MyDate class MyDate {{
public static void main(String[] args) public static void main(String[] args) {{
// create date class obj // create date class obj Date d=new Date( ); Date d=new Date( ); // format date & time // format date & time DateFormat DateFormat fmt=DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFor fmt=DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFor mat.SHORT,Locale.US); mat.SHORT,Locale.US); // apply format to d // apply format to d String s=fmt.format(d); String s=fmt.format(d);
// display formated time & date // display formated time & date System.out.println(s);
System.out.println(s); }}
}}
D:\psr\Adv java>javac MyDate.java D:\psr\Adv java>javac MyDate.java D:\psr\Adv java>java MyDate
D:\psr\Adv java>java MyDate Aug 28, 2007 11:52 PM
Aug 28, 2007 11:52 PM Streams:
-Streams: -A stream represents flow of data from one place to another place. There areA stream represents flow of data from one place to another place. There are 2 types.
2 types.
1)
1) Input streams : -Input streams : -It read or receives data.It read or receives data.
2)
2) Output streams : -Output streams : - It sends or writes data.It sends or writes data.
Other type of classifications. Other type of classifications. 1) Byte streams:
-1) Byte streams: -These streams handle data in the form of bits & bytesThese streams handle data in the form of bits & bytes 2) Text streams:
-2) Text streams: -These streams handle data in the form of individual character.These streams handle data in the form of individual character. All the streams are represented by classes in java.io package.
All the streams are represented by classes in java.io package. 1) To handle data in the form of ‘bytes’:
1) To handle data in the form of ‘bytes’:
(The abstract classes: input stream & output stream): (The abstract classes: input stream & output stream):
-InputStream InputStream
FFiilleeIInnppuuttSSttrreeaam m FFiilltteerrIInnppuuttSSttrreeaam m OObbjjeeccttIInnppuuttSSttrreeaamm
B
BuuffffeerreeddIInnppuuttSSttrreeaamm DDaattaaIInnppuuttSSttrreeaamm
OutputStream OutputStream
Fil
FileOuteOutputputStreStream am FilFilterterOutOutputputStreStream am ObjObjectectOutOutputputStreStreamam
B
BuuffffeerreeddOOuuttppuuttSSttrreeaamm DDaattaaOOuuttppuuttSSttrreeaamm a) FileInputStream / FileoutputStream:
-a) FileInputStream / FileoutputStream: -They handle data to be read or written toThey handle data to be read or written to disk files.
disk files.
b) FilterInputStream / FilterOutputStream:
b) FilterInputStream / FilterOutputStream:- They read from one stream and write- They read from one stream and write into another stream.
into another stream.
c) ObjectInputStream /
ObjectOutputStream:-c) ObjectInputStream / ObjectOutputStream:- They handle storage of They handle storage of objectobjects s andand primitive data.
primitive data.
2) To handle date in the form of ‘text’:
2) To handle date in the form of ‘text’:
-(The abstract classes: Reader and writer) (The abstract classes: Reader and writer)
Reader Reader
BufferedReader
BufferedReader CharArrayReader CharArrayReader InputStramReader InputStramReader PrintReaderPrintReader FileReader
FileReader Writer
Writer
BufferedWriter
BufferedWriter CharArrayWriter CharArrayWriter InputStramWriter InputStramWriter PrintWriterPrintWriter FileWriter
FileWriter a) BufferedReader /BufferedWriter:
-a) BufferedReader /BufferedWriter: -Handles characters (text) by buffering them.Handles characters (text) by buffering them. They provide efficiency.
They provide efficiency.
b) CharArrayReader/CharArrayWriter:
-b) CharArrayReader/CharArrayWriter: -Handle array of character.Handle array of character. c)
c) InputInputStreamRStreamReader/Oueader/OutputSttputStreamWreamWriter: riter: -- ThThey ey arare e brbrididge ge betbetweween en bybytestes streams & character streams. Readers read bytes and then decode them into 16-bit streams & character streams. Readers read bytes and then decode them into 16-bit Unicode characters. Writers decode characters into bytes then write.
Unicode characters. Writers decode characters into bytes then write. d) PrintReader/PrintWriter:
D
DaattaaIInnppuuttSSttrreeaam m FFiilleeOOuuttppuuttSSttrreeaamm
System.in System.in // creating a file // creating a file import java.io.*; import java.io.*; class Create1 class Create1 {{
public static void main(String[] args) throws IOException public static void main(String[] args) throws IOException {{
// attach keyboard to dataInputStream // attach keyboard to dataInputStream
DataInputStream dis=new DataInputStream(System.in); DataInputStream dis=new DataInputStream(System.in); // attach my file to FileOutputStream
// attach my file to FileOutputStream FileOutputStream fout=new FileOutputStream fout=new FileOutputStream("myfile",true); FileOutputStream("myfile",true); BufferedOutputStream bout=new BufferedOutputStream bout=new BufferedOutputStream(fout,1024); BufferedOutputStream(fout,1024); // read data from dis & write into fout
// read data from dis & write into fout char ch;
char ch;
System.out.println("Enter data(@ at end):"); System.out.println("Enter data(@ at end):"); while((ch=(char)dis.read( ))!='@')
while((ch=(char)dis.read( ))!='@') bout.write(ch);
bout.write(ch); // close the file // close the file bout.close( ); bout.close( ); }}
}
} ffoouutt
110 0 sseecc 110 0 sseecc ttoottaall 1 1 11 2244 sseecc 1 1 11 bout bout 11 ttoottaall 11 11 1133 sseecc 10 sec 10 sec
So, we used the bout in the above program. So, we used the bout in the above program. D:\psr\Adv java>javac Create1.java
D:\psr\Adv java>javac Create1.java D:\psr\Adv java>java Create1
D:\psr\Adv java>java Create1 Enter data (@ at end):
Enter data (@ at end):
Hai I am Sunil Kumar Reddy. My hobbies are playing Cricket, playing Chess & Hai I am Sunil Kumar Reddy. My hobbies are playing Cricket, playing Chess & reading Books. My favorite actor is Junior N.T.R. My favorite actress is Maanya
reading Books. My favorite actor is Junior N.T.R. My favorite actress is Maanya
My dream girl name is Latha. She is one of the beautiful girls in the world. She My dream girl name is Latha. She is one of the beautiful girls in the world. She always laughs. That laughs attract me. I am also best friend of her. @
always laughs. That laughs attract me. I am also best friend of her. @
Keyboard
D:\psr\Adv java>type myfile D:\psr\Adv java>type myfile
Hai I am Sunil Kumar Reddy. My hobbies are playing Cricket, playing Chess & Hai I am Sunil Kumar Reddy. My hobbies are playing Cricket, playing Chess & reading Books. My favorite actor is Junior N.T.R. My favorite actress is Maanya
reading Books. My favorite actor is Junior N.T.R. My favorite actress is Maanya
My dream girl name is Latha. She is one of the beautiful girls in the world. She My dream girl name is Latha. She is one of the beautiful girls in the world. She always laughs. That laughs attract me. I am also best friend of her.
always laughs. That laughs attract me. I am also best friend of her.
FileInputStream FileInputStream
// to read data from a text file // to read data from a text file
iimmppoorrt t jjaavvaa..iioo..**; ; SSyysstteemm..oouutt class Read1
class Read1 {{
public
public static static void void main(String[] main(String[] args) args) throws throws IOExceptionIOException {{
try try {{
// accept file name from kayboard // accept file name from kayboard
BufferedReader br=new BufferedReader(new BufferedReader br=new BufferedReader(new
InputStreamReader(System.in)); InputStreamReader(System.in)); System.out.print("enter a file name :");
System.out.print("enter a file name :"); String fname=br.readLine( );
String fname=br.readLine( ); //attach my file to FileInputStream //attach my file to FileInputStream
FileInputStream fin=new FileInputStream(fname); FileInputStream fin=new FileInputStream(fname);
BufferedInputStream bin=new BufferedInputStream(fin); BufferedInputStream bin=new BufferedInputStream(fin); // read data from fin & display
// read data from fin & display int ch; int ch; while((ch=bin.read( ))!=-1) while((ch=bin.read( ))!=-1) System.out.print((char)ch); System.out.print((char)ch); // close the file
// close the file bin.close( ); bin.close( ); }} catch(FileNotFoundException fe) catch(FileNotFoundException fe) {{
System.out.println("Sorry,file not found"); System.out.println("Sorry,file not found"); }}
}} }}
D:\psr\Adv java>javac Read1.java D:\psr\Adv java>javac Read1.java D:\psr\Adv java>java Read1
D:\psr\Adv java>java Read1
MyFile
MyFile
Monitor
Monitor
enter a file name :myfile enter a file name :myfile
Hai I am Sunil Kumar Reddy. My hobbies are playing Cricket, playing Chess & Hai I am Sunil Kumar Reddy. My hobbies are playing Cricket, playing Chess & reading Books. My favorite actor is Junior N.T.R. My favorite actress is Maanya
reading Books. My favorite actor is Junior N.T.R. My favorite actress is Maanya
My dream girl name is Latha. She is one of the beautiful girls in the world. She My dream girl name is Latha. She is one of the beautiful girls in the world. She always laughs. That laughs attract me. I am also best friend of her.
always laughs. That laughs attract me. I am also best friend of her. // creating a file // creating a file import java.io.*; import java.io.*; class Create2 class Create2 {{
public static void main(String[] args) throws IOException public static void main(String[] args) throws IOException {{
// take a string // take a string
String str="This is an institute "+"\n I am a student here"; String str="This is an institute "+"\n I am a student here"; // take a file & attah in to FileWriter
// take a file & attah in to FileWriter
FileWriter fw=new FileWriter("textfile"); FileWriter fw=new FileWriter("textfile");
BufferedWriter bw=new BufferedWriter(fw,1024); BufferedWriter bw=new BufferedWriter(fw,1024); // read data from str & write in to fw
// read data from str & write in to fw for(int i=0;i<str.length( );i++)
for(int i=0;i<str.length( );i++) bw.write(str.charAt(i)); bw.write(str.charAt(i)); // close the file
// close the file bw.close( ); bw.close( ); }}
}}
D:\psr\Adv java>javac Create2.java D:\psr\Adv java>javac Create2.java D:\psr\Adv java>java Create2
D:\psr\Adv java>java Create2 D:\psr\Adv java>type textfile D:\psr\Adv java>type textfile This is an institute
This is an institute I am a student here I am a student here
// read data from textfile // read data from textfile import java.io.*;
import java.io.*; class Read2 class Read2 {{
public static void main(String[] args) throws IOException public static void main(String[] args) throws IOException {{
// attach textfile to FileReader // attach textfile to FileReader
FileReader fr=new FileReader("textfile"); FileReader fr=new FileReader("textfile"); BufferedReader br=new BufferedReader(fr); BufferedReader br=new BufferedReader(fr); // read data from fr & display
// read data from fr & display int ch; int ch; while((ch=br.read( ))!=-1) while((ch=br.read( ))!=-1) System.out.print((char)ch); System.out.print((char)ch); // close the file
// close the file br.close( ); br.close( ); }}
}}
D:\psr\Adv java>javac Read2.java D:\psr\Adv java>javac Read2.java D:\psr\Adv java>java Read2
D:\psr\Adv java>java Read2 This is an institute
This is an institute I am a student here I am a student here To zip the contents:
To zip the contents:
-DeflaterOutputStream. DeflaterOutputStream. To unzip the file:
To unzip the file:
-InflaterInputStream. InflaterInputStream.
These classes are include in java.util.zip package These classes are include in java.util.zip package
File1 File1
File2 File2 //to zip the file contents
//to zip the file contents import java.io.*; import java.io.*; import java.util.zip.*; import java.util.zip.*; class Compress class Compress {{
public static void main(String[] args) throws Exception public static void main(String[] args) throws Exception
{{
// attach file1 to FileInputStream // attach file1 to FileInputStream
FileInputStream fis=new FileInputStream("file1"); FileInputStream fis=new FileInputStream("file1"); // attach file2 to FileOutputStream
// attach file2 to FileOutputStream
FileOutputStream fos=new FileOutputStream("file2"); FileOutputStream fos=new FileOutputStream("file2"); // attach fos to DeflaterOutputStream
// attach fos to DeflaterOutputStream
DeflaterOutputStream dos=new DeflaterOutputStream(fos); DeflaterOutputStream dos=new DeflaterOutputStream(fos); // read data from fis & write in to dos
// read data from fis & write in to dos int data; int data; while((data=fis.read( ))!=-1) while((data=fis.read( ))!=-1) dos.write(data); dos.write(data); // close the files
// close the files fis.close( ); fis.close( ); dos.close( ); dos.close( ); }} }}
D:\psr\Adv java>javac Compress.java D:\psr\Adv java>javac Compress.java D:\psr\Adv java>edit file1
D:\psr\Adv java>edit file1 D:\psr\ Adv java>type file1 D:\psr\ Adv java>type file1 Hai i am Sunil Kumar Reddy Hai i am Sunil Kumar Reddy My pet name is Sudheer Reddy My pet name is Sudheer Reddy
fis
… … … …
D:\psr\Adv java>java Compress D:\psr\Adv java>java Compress D:\psr\Adv java>dir file*.* D:\psr\Adv java>dir file*.* Volume in drive D is DISK Volume in drive D is DISK
Volume Serial Number is 280A-AE9B Volume Serial Number is 280A-AE9B Directory of D:\psr\Adv java
Directory of D:\psr\Adv java 08/29/2007
08/29/2007 04:48 04:48 PM PM 353 353 file1file1 08/29/2007
08/29/2007 04:48 04:48 PM PM 71 71 file2file2 2
2 File(s) File(s) 424 424 bytesbytes 0
0 Dir(s) Dir(s) 9,683,542,016 9,683,542,016 bytes bytes freefree D:\psr\Adv java>type file2
D:\psr\Adv java>type file2
x£≤H╠T╚TH╠.═╦╠Q≡.═M,JMI⌐Σσ≥¡T(H-Q╚K╠MU╚,♠¬H╔HMà╩*((≡ryÉ⌐yΣΦΣσ☻ æ☼r╠ Q╚K╠MU╚,♠¬H╔HMà╩*((≡ryÉ⌐yΣΦΣσ☻ æ☼r╠
//to unzip the file contents //to unzip the file contents import java.io.*; import java.io.*; import java.util.zip.*; import java.util.zip.*; class UnCompress class UnCompress {{
public static void main(String[] args) throws Exception public static void main(String[] args) throws Exception
{{
// attach file2 to FileInputStream // attach file2 to FileInputStream
FileInputStream fis=new FileInputStream("file2"); FileInputStream fis=new FileInputStream("file2"); // attach file3 to FileOutputStream
// attach file3 to FileOutputStream
FileOutputStream fos=new FileOutputStream("file3"); FileOutputStream fos=new FileOutputStream("file3");
// attach fis to InflaterInputStream // attach fis to InflaterInputStream
InflaterInputStream iis=new InflaterInputStream(fis); InflaterInputStream iis=new InflaterInputStream(fis); // read data from iis & write in to fos
// read data from iis & write in to fos int data; int data; while((data=iis.read( ))!=-1) while((data=iis.read( ))!=-1) fos.write(data); fos.write(data); // close the files
// close the files iis.close( ); iis.close( ); fos.close( ); fos.close( ); }} }}
D:\psr\Adv java>javac UnCompress.java D:\psr\Adv java>javac UnCompress.java D:\psr\Adv java>java UnCompress
D:\psr\Adv java>java UnCompress D:\psr\Adv java>dir file*.*
D:\psr\Adv java>dir file*.* Volume in drive D is DISK Volume in drive D is DISK
Volume Serial Number is 280A-AE9B Volume Serial Number is 280A-AE9B Directory of D:\psr\Adv java
08/29/2007 08/29/2007 04:48 04:48 PM PM 353 353 file1file1 08/29/2007 08/29/2007 04:48 04:48 PM PM 71 71 file2file2 08/29/2007 08/29/2007 04:54 04:54 PM PM 353 353 file3file3 3
3 File(s) File(s) 777 777 bytesbytes 0
0 Dir(s) Dir(s) 9,683,546,119,683,546,112 2 bytes bytes freefree D:\psr\Adv java>type file3
D:\psr\Adv java>type file3 Hai i am Sunil Kumar Reddy Hai i am Sunil Kumar Reddy My pet name is Sudheer Reddy My pet name is Sudheer Reddy … … … … Net Net
working:-Inter connection of a computer as called network. Resource sharing is the main Inter connection of a computer as called network. Resource sharing is the main advantage of network. Internet is a global network of several computers existing on advantage of network. Internet is a global network of several computers existing on the earth. the earth. Web browser Web browser Web Server Web Server Web browser:
Web browser: - The software that initial on in internet client machine is called Web- The software that initial on in internet client machine is called Web browser.
browser. Web Server:
Web Server:- The software that should be installed on in a internet server machine is- The software that should be installed on in a internet server machine is called Web Server.
called Web Server.
A client is a machine that sends request for some service. A server is a machine A client is a machine that sends request for some service. A server is a machine that provides services to the clients. A network is also called client server model.
that provides services to the clients. A network is also called client server model. There are 3 requirements of network.
There are 3 requirements of network.
1)
1) Hard ware : -Hard ware : -you need cables, satellite etc.you need cables, satellite etc. 2)
2) Soft ware :Soft ware :- web logic, web spear, iis, Apache, jobs.- web logic, web spear, iis, Apache, jobs. 3)
3) Protocol :Protocol : - A protocol is specification of rules to be followed by every- A protocol is specification of rules to be followed by every
computer on the network. computer on the network.
A protocol represents a set of rules to be followed by every computer on the internet A protocol represents a set of rules to be followed by every computer on the internet or any network.
or any network. TCP / IP:
-TCP / IP: - (transmission control protocol / international protocol) is used to send or(transmission control protocol / international protocol) is used to send or receive the text.
receive the text. A packet contain group of bytes.A packet contain group of bytes. UDP:
-UDP: -(user datagram protocol) is used to transmit videos, audios & images.(user datagram protocol) is used to transmit videos, audios & images. HTTP:
-HTTP: -(hyper text transfer protocol) it is most widely used protocol on internet. It is(hyper text transfer protocol) it is most widely used protocol on internet. It is used to receiving the web pages.
used to receiving the web pages. FTP:
-FTP: -(file transfer protocol) is used to down load the files.(file transfer protocol) is used to down load the files. POP:
-POP: -(post office protocol) is used to receive mails from mail box.(post office protocol) is used to receive mails from mail box.
Client
Client
Server
Server
Different protocols are used on internet. Different protocols are used on internet. IP address:
IP address:
-IP address is a unique id number allotted to every computer on the network. The IP address is a unique id number allotted to every computer on the network. The computers on a network are identified because of IP address uniquely.
computers on a network are identified because of IP address uniquely. DNS:
DNS:- Domain naming service or system.- Domain naming service or system.
It is a service that maps the website names corresponding IP address. It is a service that maps the website names corresponding IP address.
.com
.com commercial websitecommercial website .edu
.edu educational websiteeducational website .mil
.mil mmiilliittaarry y ppeeooppllee ccoommmmeerrcciiaal l wweebbssiittee www.yahoo.com
www.yahoo.com
192.100.56.01 192.100.56.01
Code (root directory) Code (root directory) It is code for starting html file It is code for starting html file There are 5 types of IP address:
There are 5 types of IP address:
-class A class A 16,777,216 hosts 16,777,216 hosts class B class B 65,536 hosts 65,536 hosts class C class C 256 hosts 256 hosts class D class D Research Research class E class E Socket:
-Socket: - A socket is a point of connection between the server & client. Data flow isA socket is a point of connection between the server & client. Data flow is move one place to another place.
move one place to another place.
Socket Socket Port number is an
Port number is an identiidentificatification number given on number given to the socket. Every new to the socket. Every new socketsocket should have a new port number.
should have a new port number.
Establishing communication between server & client:
Establishing communication between server & client:
-Using a socket is called socket programming. Using a socket is called socket programming. Server socket class:
-Server socket class: -It is useful to create server side socketIt is useful to create server side socket Socket class:
-Socket class: -It is useful to create client side socket.It is useful to create client side socket.
00
N
Neettw
woorrk
k 77
L
Looccaal
l A
Addddrreesss
s 2244
Local Address 16
Local Address 16
Local Address 8
Local Address 8
Network14
Network14
Network 21
Network 21
10
10
110
110
SS
C
C
// a server that sends message to clients // a server that sends message to clients import java.io.*; import java.io.*; import java.net.*; import java.net.*; class Server1 class Server1 {{
public static void main(String args[]) throws Exception public static void main(String args[]) throws Exception {{
/// / ccrreeaatte e sseerrvveer r ssiidde e ssoocckkeet t ddeeffaauullt t ppoorrt t nnoo ServerSocket ss=new ServerSocket(777);
ServerSocket ss=new ServerSocket(777);
// server waits till a connection is accepted by the client // server waits till a connection is accepted by the client System.out.println("Server is waiting..."); System.out.println("Server is waiting..."); Socket s=ss.accept( ); Socket s=ss.accept( ); System.out.println("connected to client"); System.out.println("connected to client"); // attach output stream to socket
// attach output stream to socket
OutputStream obj=s.getOutputStream( ); OutputStream obj=s.getOutputStream( ); // to send data till the socket
// to send data till the socket
PrintStream ps=new PrintStream(obj); PrintStream ps=new PrintStream(obj); // send data from server
// send data from server String str="Hello Client "; String str="Hello Client "; ps.println(str);
ps.println(str);
ps.println("How are you ?"); ps.println("How are you ?"); ps.println("Bye"); ps.println("Bye"); // disconnect server // disconnect server ps.close( ); ps.close( ); ss.close( ); ss.close( ); s.close( ); s.close( ); }} }}
D:\psr\adv java>javac Server1.java D:\psr\adv java>javac Server1.java
// a server that sends message to clients // a server that sends message to clients import java.io.*; import java.io.*; import java.net.*; import java.net.*; class Client1 class Client1
SS
C
C
SS
C
C
{{
public static void main(String args[] ) throws Exception public static void main(String args[] ) throws Exception {{
// create client side socket // create client side socket
Socket s=new Socket("localhost",777); Socket s=new Socket("localhost",777); // add inputstream to the socket
// add inputstream to the socket
InputStream obj=s.getInputStream( ); InputStream obj=s.getInputStream( ); // to recieve data from socket
// to recieve data from socket
BufferedReader br=new BufferedReader(new BufferedReader br=new BufferedReader(new
InputStreamReader(obj)); InputStreamReader(obj)); // now receive data
// now receive data String str; String str; while((str=br.readLine( ))!=null) while((str=br.readLine( ))!=null) System.out.println(str); System.out.println(str); // disconnect server // disconnect server s.close( ); s.close( ); br.close( ); br.close( ); }} }} Compile:
-Compile: -compile & run the above 2 programs in 2 dos prompts on same time.compile & run the above 2 programs in 2 dos prompts on same time. D:\psr\adv java>javac Client1.java
D:\psr\adv java>javac Client1.java D
D::\\ppssrr\\aaddv v jjaavvaa>>jjaavva a SSeerrvveerr11 DD::\\ppssrr\\aaddv v jjaavvaa>>jjaavva a CClliieenntt11 SSeerrvveer r iis s wwaaiittiinngg... HHeellllo o CClliieenntt
ccoonnnneecctteed d tto o cclliieenntt HHoow w aarre e yyoou u ?? Bye
Bye
It is possible to run several JVM’S simultaneously in same computer system. It is possible to run several JVM’S simultaneously in same computer system. Communicating from server:
Communicating from server:
-1) Create a server socket 1) Create a server socket
ServerSocket ss=new ServerSocket(port no); ServerSocket ss=new ServerSocket(port no); 2) Accept any client connection
2) Accept any client connection Socket s=ss.accept( );
Socket s=ss.accept( );
3) To send data, connect the output stream to the socket 3) To send data, connect the output stream to the socket
OutputStream obj=s.getOutputStream( ); OutputStream obj=s.getOutputStream( );
4) To receive data from the client, connect input stream 4) To receive data from the client, connect input stream
InputStream obj=s.getInputStream( ); InputStream obj=s.getInputStream( ); 5) Send data to the client using print stream 5) Send data to the client using print stream PrintStream ps=new PrintStream(obj); PrintStream ps=new PrintStream(obj); ps.print(str);
ps.print(str); ps.println(str); ps.println(str);
6) Read data coming from the client using buffered reader 6) Read data coming from the client using buffered reader
BufferedReader br=new BufferedReader(new BufferedReader br=new BufferedReader(new
InputStreamReader(System.in(obj)); InputStreamReader(System.in(obj)); ch=br.read( );
str=br.readLine( ); str=br.readLine( ); Communicating from client:
Communicating from client:
-1) Create a client socket 1) Create a client socket
Socket s=new Socket (“IP address”, port no ); Socket s=new Socket (“IP address”, port no );
2) To send data, connect the OutputStream to the socket 2) To send data, connect the OutputStream to the socket
OutputStream obj=s.getOutputStream( ); OutputStream obj=s.getOutputStream( );
3) To receive data from the server, connect Input stream to the socket 3) To receive data from the server, connect Input stream to the socket
InputStream obj=s.getInputStream( ); InputStream obj=s.getInputStream( );
4) Send data to the server using data output stream. 4) Send data to the server using data output stream.
DataOutputStream dos=new DataOutputStream(obj); DataOutputStream dos=new DataOutputStream(obj); dos.writeBytes(str);
dos.writeBytes(str);
5) Read data coming from the server using BR 5) Read data coming from the server using BR
BufferedReader br=new BufferedReader(new BufferedReader br=new BufferedReader(new
InputStreamReader(System.in(obj)); InputStreamReader(System.in(obj)); ch=br.read(
ch=br.read( ); ); str=br.readLine( str=br.readLine( );); Closing communication:
Closing communication:- close all streams & sockets- close all streams & sockets ps.close( ); ps.close( ); br.close( ); br.close( ); dos.close( ); dos.close( ); ss.close( ); ss.close( ); s.close( ); s.close( ); // chat server // chat server import java.io.*; import java.io.*; import java.net.*; import java.net.*; class Server2 class Server2 {{
public static void main(String[] args) throws Exception public static void main(String[] args) throws Exception {{
// create ServerSocket // create ServerSocket
ServerSocket ss=new ServerSocket(999); ServerSocket ss=new ServerSocket(999); // wait till a client connection accepted // wait till a client connection accepted Socket s=ss.accept( );
Socket s=ss.accept( );
System.out.println("Connection established..."); System.out.println("Connection established..."); // send data to client
// send data to client
PrintStream ps=new PrintStream(s.getOutputStream( )); PrintStream ps=new PrintStream(s.getOutputStream( )); // to recive data from client
// to recive data from client
BufferedReader br=new BufferedReader(new BufferedReader br=new BufferedReader(new
InputStreamReader(s.getInputStream( ))); InputStreamReader(s.getInputStream( ))); // to read from keyboard
// to read from keyboard
BufferedReader kb=new BufferedReader(new BufferedReader kb=new BufferedReader(new
InputStreamReader(System.in)); InputStreamReader(System.in)); // communication with client
// communication with client while(true)
while(true) {{
1) local object 2) remote object : - it is an object that is 1) local object 2) remote object : - it is an object that is created another JVM, which is existing on the network. it created another JVM, which is existing on the network. it can be accessed through references.
String str,str1; String str,str1; while((str=br.readLine( ))!=null) while((str=br.readLine( ))!=null) {{ System.out.println(str); System.out.println(str); str1=kb.readLine( ); str1=kb.readLine( ); ps.println(str1); ps.println(str1); }}
//disconnect the Server //disconnect the Server ps.close( ); ps.close( ); br.close( ); br.close( ); kb.close( ); kb.close( ); ss.close( ); ss.close( ); s.close( ); s.close( ); System.exit(0); System.exit(0); }} }} }}
D:\psr\adv java>javac Server2.java D:\psr\adv java>javac Server2.java
// chat Client // chat Client import java.io.*; import java.io.*; import java.net.*; import java.net.*; class Client2 class Client2 {{
public static void main(String[] args) throws Exception public static void main(String[] args) throws Exception {{
// create ClientSocket // create ClientSocket
Socket s=new Socket("localhost",999); Socket s=new Socket("localhost",999); // send data to Server
// send data to Server
DataOutputStream dos=new DataOutputStream dos=new
DataOutputStream(s.getOutputStream( )); DataOutputStream(s.getOutputStream( )); // to receive data from Server
// to receive data from Server
BufferedReader br=new BufferedReader(new BufferedReader br=new BufferedReader(new
InputStreamReader(s.getInputStream( ))); InputStreamReader(s.getInputStream( ))); // to read data from keyboard
// to read data from keyboard
BufferedReader kb=new BufferedReader(new BufferedReader kb=new BufferedReader(new
InputStreamReader(System.in)); InputStreamReader(System.in)); // communication with client
// communication with client String str,str1; String str,str1; while(!(str=kb.readLine( )).equals("exit")) while(!(str=kb.readLine( )).equals("exit")) {{ dos.writeBytes(str+"\n"); dos.writeBytes(str+"\n"); str1=br.readLine( ); str1=br.readLine( ); System.out.println(str1); System.out.println(str1); }}
//disconnect the Server //disconnect the Server
s.close( ); s.close( ); dos.close( ); dos.close( ); br.close( ); br.close( ); kb.close( ); kb.close( ); }} }}
D:\psr\adv java>javac Client2.java D:\psr\adv java>javac Client2.java D
D::\\ppssrr\\aaddv v jjaavvaa>>jjaavva a SSeerrvveerr2 2 DD::\\ppssrr\\aaddv v jjaavvaa>>jjaavva a CClliieenntt22 C
Coonnnneeccttiioon n eessttaabblliisshheedd... . HHeellllooww! ! HHoow w r r uu?? H
Heellllooww! ! HHoow w r r uu? ? I I aam m ffiinnee. . WWhho o r r uu?? I
I aam m ffiinnee. . WWhho o r r uu? ? I I aam m UUsshha a RRaannii. . WWhhaatt''s s uur r nnaammee?? I
I am am Usha Usha Rani. Rani. WhatWhat's 's ur ur name? name? My My name name is is HarinaHarinath th Reddy. Reddy. AnyAny My
My name name is is Sudheer Sudheer Reddy. Reddy. Any Any way way I I will will chat chat later later with with u. u. Bye Bye ra.ra. way
way I I will will chat chat later later with with u. u. Bye Bye ra. ra. Smile Smile pleaseplease
SSmmiille e pplleeaasse e OOK K ttoommoorrrroow w I I wwiilll l mmeeaat t uu. . BByyee.. OK
OK totommororrorow w I I wiwill ll mmeaeat t u. u. ByBye. e. exexitit Threads:
-Threads: -A thread represents a process or execution of statements.A thread represents a process or execution of statements. // finding the presenting running thread
// finding the presenting running thread class MyClass
class MyClass {{
public static void main(String[] args) public static void main(String[] args) {{
System.out.println("This is Thread Program !"); System.out.println("This is Thread Program !"); Thread t=Thread.currentThread( );
Thread t=Thread.currentThread( );
System.out.println("Currently running thread ="+t); System.out.println("Currently running thread ="+t); System.out.println("Its name ="+t.getName( ));
System.out.println("Its name ="+t.getName( )); }}
}}
D:\psr\Adv java>javac MyClass.java D:\psr\Adv java>javac MyClass.java D:\psr\Adv java>java MyClass
D:\psr\Adv java>java MyClass This is Thread Program ! This is Thread Program !
Currently running thread =Thread[main,5,main] Currently running thread =Thread[main,5,main] Its name =main
Its name =main
Which is the thread internally running in every java program?
Which is the thread internally running in every java program?
A) Main thread. A) Main thread.
What is the difference between thread & process?
What is the difference between thread & process?
A) Process is a heavy weight, means it takes more memory & more processor time. A A) Process is a heavy weight, means it takes more memory & more processor time. A thread is a light weight process, means it takes less memory & less processor time. thread is a light weight process, means it takes less memory & less processor time.
11 min priority, 5min priority, 5 normal priority, 10normal priority, 10 max priority.max priority.
5 is the default priority. Every thread group can have name. in every java program 5 is the default priority. Every thread group can have name. in every java program main thread which executes first.
main thread which executes first.
Executing the statements is of two ways:
Executing the statements is of two ways: -1)
1) Single tasking Single tasking : - Executing : - Executing only one task only one task at a time is at a time is called single called single tasking.tasking.
Micro Processor Micro Processor Programs Programs --Time --Time
The micro processor’s time is vested in between the tasks. The micro processor’s time is vested in between the tasks.
Param is first super computer in India. Param is first super computer in India. 2) Multi tasking:
2) Multi tasking:
-Part of the micro processor time allotted to each task. Part of the micro processor time allotted to each task. Micro Processor Micro Processor Memory Memory 00..225 5 mms s 00..225 5 mms s 00..225 5 mms s 00..225 5 mmss Round robin:
-Round robin: -ExecutExecuting all the ing all the tasks in cyclic manner is called round robin method.tasks in cyclic manner is called round robin method. Time slice is the part of time allotted from each task.
Time slice is the part of time allotted from each task.
Executing several tasks simultaneously by the micro possessor is called multi Executing several tasks simultaneously by the micro possessor is called multi tasking. There are 2 types.
tasking. There are 2 types.
a)
a) Process based multi tasking : -Process based multi tasking : - Executing several programs at a time is calledExecuting several programs at a time is called
process based multi tasking. process based multi tasking.
b)
b) Thread Thread based based multi multi taskintasking g : : -- Using multiple threads to execute differentUsing multiple threads to execute different
blocks of code is called thread based multi tasking. blocks of code is called thread based multi tasking.
Tasks
Tasks
Processor time is utilize in optimum way is the main advantage of multi tasking. Processor time is utilize in optimum way is the main advantage of multi tasking. Uses of threads:
Uses of threads:
-1) Threads are used in creation of server software to handle multiple clients. 1) Threads are used in creation of server software to handle multiple clients. 2) Threads are used in animation & games development.
2) Threads are used in animation & games development. Crating a thread:
Crating a thread:
-1) Write a class as a sub class to thread class. 1) Write a class as a sub class to thread class.
class MyClass extends Thread (or) class MyClass extends Thread (or)
Write a class as an implementation class for runnable interface. Write a class as an implementation class for runnable interface. class MyClass implements Runnable
class MyClass implements Runnable 2) Write run method with body in the class 2) Write run method with body in the class
public void run( ) public void run( ) {{
statements; statements; }}
Note:
-Note: - Any thread can recognize only run method. A thread executes only the runAny thread can recognize only run method. A thread executes only the run method.
method.
3) Create an object to class 3) Create an object to class
MyClass mc=new MyClass( ); MyClass mc=new MyClass( );
4) Create a thread & attach to the object 4) Create a thread & attach to the object
Thread t=new Thread(obj); Thread t=new Thread(obj); 5) Run the thread
5) Run the thread t.start( ); t.start( ); // creating a thread // creating a thread import java.io.*; import java.io.*; class
class Myclass Myclass extends extends ThreadThread {{
public void run( ) public void run( ) {{ boolean x=false; boolean x=false; for(int i=1;i<100000;i++) for(int i=1;i<100000;i++) {{ System.out.println(i); System.out.println(i); if(x) return; if(x) return; }} }} }} class TDemo class TDemo {{
public static void main(String[] args) throws IOException public static void main(String[] args) throws IOException {{
Myclass obj=new Myclass( ); Myclass obj=new Myclass( );
Thread t=new Thread(obj); Thread t=new Thread(obj); t.start( );
t.start( );
System.in.read( );
System.in.read( ); //wait t//wait till enter ill enter pressedpressed obj.x=true;
obj.x=true; }}
}}
D:\psr\Adv java>javac TDemo.java D:\psr\Adv java>javac TDemo.java D:\psr\Adv java>java TDemo
D:\psr\Adv java>java TDemo 11
22 33 44
How can you stop in the thread in the middle?
How can you stop in the thread in the middle?
A) 1) Declare the boolean type of variable & initialize at false A) 1) Declare the boolean type of variable & initialize at false
boolean x=flase; boolean x=flase;
2) If the variable value is true , “x” return from the method. 2) If the variable value is true , “x” return from the method.
If(x) return; If(x) return;
3) To stoop the thread store true in to the variable 3) To stoop the thread store true in to the variable
System.in.read( ); System.in.read( ); obj.x=true;
obj.x=true; Mult
Multi i threadithreading: -ng: - Using more than one thread is called multi threading. It is used inUsing more than one thread is called multi threading. It is used in multi tasking.
multi tasking.
What the difference is between extends Thread & implements runnable?
What the difference is between extends Thread & implements runnable?
A) Functionally both are same. If we use extends Thread then there is no scope to A) Functionally both are same. If we use extends Thread then there is no scope to extend another class. Multiple inheritances are not supported in java.
extend another class. Multiple inheritances are not supported in java. class MyClass extends Thread,Frame // invalid
class MyClass extends Thread,Frame // invalid
But if we write implements Runnable then there is still scope to extends some other But if we write implements Runnable then there is still scope to extends some other class.
class.
class MyClass implements Thread,Frame // valid class MyClass implements Thread,Frame // valid So implements Runnable is more advantage of than extends. So implements Runnable is more advantage of than extends.
// 2 threads act on 2 obj // 2 threads act on 2 obj
class Theatre implements Runnable class Theatre implements Runnable {{ String str; String str; Theatre(String str) Theatre(String str) {{ this.str=str; this.str=str; }}
public void run( ) public void run( ) {{
for(int i=1;i<=10;i++) for(int i=1;i<=10;i++) {{
System.out.println(str+":"+i); System.out.println(str+":"+i); try try {{ Thread.sleep(2000); Thread.sleep(2000); }}
catch (InterruptedException ie) catch (InterruptedException ie) {{ ie.printStackTrace( ); ie.printStackTrace( ); }} }} }} }} class TDemo1 class TDemo1 {{
public static void main(String[] args) public static void main(String[] args) {{
Theatre obj1=new Theatre("cut Ticket "); Theatre obj1=new Theatre("cut Ticket "); Theatre obj2=new Theatre("Show Chairs"); Theatre obj2=new Theatre("Show Chairs"); Thread t1=new Thread(obj1);
Thread t1=new Thread(obj1); Thread t2=new Thread(obj2); Thread t2=new Thread(obj2); t1.start( ); t1.start( ); t2.start( ); t2.start( ); }} }}
D:\psr\Adv java>javac TDemo1.java D:\psr\Adv java>javac TDemo1.java D:\psr\Adv java>java TDemo1
D:\psr\Adv java>java TDemo1 cut Ticket :1 cut Ticket :1 Show Chairs:1 Show Chairs:1 cut Ticket :2 cut Ticket :2 Show Chairs:2 Show Chairs:2 … … … … cut Ticket :10 cut Ticket :10 Show Chairs:10 Show Chairs:10
// 2 threads acting on same thread // 2 threads acting on same thread class Reserve implements Runnable class Reserve implements Runnable {{ int wanted; int wanted; int available=1; int available=1; Reserve(int i) Reserve(int i) {{ wanted=i; wanted=i; }}
public void run( ) public void run( )
synchronized(this) synchronized(this)
{{
System.out.println("Available no. of berths = System.out.println("Available no. of berths =
"+available); "+available); if(available>=wanted)
if(available>=wanted) {{
String name=Thread.currentThread( ).getName( ); String name=Thread.currentThread( ).getName( );
System.out.println(wanted+"Berths allotted for "+name); System.out.println(wanted+"Berths allotted for "+name);
try try {{ Thread.sleep(2000); Thread.sleep(2000); available-=wanted; available-=wanted; }} catch(InterruptedException ie) catch(InterruptedException ie) {{ }} }} else else {{
System.out.println("Sorry, Berths not available "); System.out.println("Sorry, Berths not available ");
}} }} }} }} class Safe class Safe {{
public static void main(String[] args) public static void main(String[] args) {{
// create an obj to reserve class // create an obj to reserve class Reserve obj=new Reserve(1); Reserve obj=new Reserve(1);
// create 2 Threads & attach them tp obj // create 2 Threads & attach them tp obj Thread t1=new Thread(obj);
Thread t1=new Thread(obj); Thread t2=new Thread(obj); Thread t2=new Thread(obj); // set names to Threads
// set names to Threads t1.setName("1st person"); t1.setName("1st person"); t2.setName("2nd Person"); t2.setName("2nd Person"); // run the Threads
// run the Threads t1.start( ); t1.start( ); t2.start( ); t2.start( ); }} }}
D:\psr\Adv java>javac Safe.java D:\psr\Adv java>javac Safe.java D:\psr\Adv java>java Safe
D:\psr\Adv java>java Safe Available no. of berths = 1 Available no. of berths = 1 1Berths allotted for 1st person 1Berths allotted for 1st person Available no. of berths = 0 Available no. of berths = 0