Page 1 of 148 rambabumandalapu@yahoo.com
Java.util Package
Collections class
Collections obj
ADVANCED JAVA
A group of elements are handled by representing with an array.
A group of objects are also handled with array.
To store objects in Array
Employee arr[ ] = new Employee[100];
for(int i = 0; i<100; i++) { arr[ i ] = new Employee(……); } Collections object (or) Container Object: - It is an object that stores a group other objects. Collections class (or) Container class: - It is a class whose object can store other objects. All collection classes have defined in java.util package. Frame work means group of classes. What is collections frame work? ***** Ans: - Collections frame work is a class library to handle groups of objects. Collection frame work is defined in java.util package. What is the difference between collection and Collections? ***** Ans: - Collection is an interface. Collections is a class. Advanced Java Page 2 of 148 rambabumandalapu@yahoo.com Collections objects will not act upon primitive datatypes. (or) collections objects will not store primitive datatypes. Collections objects stores references of other objects. All collection classes are defined into 3 types. 1. Sets: - A set represents a group of objects is called as Set. Ex: - HashSet, LinkedHashSet, TreeSet, etc… 2. Lists: - A list represents the group of elements or objects. List is also similar to set. It will also store elements or objects. Sets will not allow the duplicate values but Lists will duplicate values. This is the difference between Lists and Sets. Ex: - ArrayList, Vector, LinkedList etc… Which of the collection class will not allow duplicate values? ***** Ans: - Sets of the collection class will not allow the duplicate values. Set will not stores the object in ordered/sorted order. Lists of the collection class will allow the duplicate values. List will stores the object in ordered/sorted order. Sorted means iterating through a collection in a natural sorted order. 3. Maps: - A map stores elements in the form of the keys and value pairs. Ex: - Hashmap, Hashtable etc… List of interfaces and classes in java.util package (or) Collection framework: S. No. Interfaces Collection Classes 1. Set ArrayList 2. List Vector 3. Map LinedList 4. SortedSet HashSet 5. SortedMap TreeSet 6. Iterator Collections 7. ListIterator LinkedHashSet 8. Enumeration HashMap Collection objects Advanced Java Page 3 of 148 rambabumandalapu@yahoo.com 9. TreeMap 10. HashTable 11. LinkedHashMap ArrayList: - It is dynamically growing array that stores objects. It is not synchronized1. 1. To create an ArrayList ArrayList arl = new ArrayList(); ArrayList arl = new ArrayList(100); 2. To add objects use add() method. arl.add(“Apple”); arl.add(2, “Apple”); 3. To remove objects use remove() method. arl.remove(“Apple”); arl.remove(2); 4. To know number of objects use size() method. int n = arl.size(); 5. To covert ArrayList into an array use toArray() method. object x[ ] = arl.toArray(); Object is the super class of other classes including user defined classes also. When we are retreiveing the elements from ArrayList, it will maintains and gives the same order what we have added the elements to the ArrayList. ArrayList doesn’t supports the null values. ArrayList supports sort method by using the below code Collections.sort(al); //al is ArrayList Class object reference. Ex: - //ArrayList creation with string objects import java.util.*; class ArrayListDemo { public static void main(String args[ ]) { //Create an ArrayList 1 Synchronized: - It means only one process will allow to act on one object. Advanced Java Page 4 of 148 rambabumandalapu@yahoo.com ArrayList arl = new ArrayList(); //Add elements to arl arl.add(“Apple”); //QApple, Grapes, Guava, Banana …are objects arl.add(“Grapes”); arl.add(“Guava”); arl.add(“Banana”); arl.add(“Mango”); //Display the content of ArrayList (or) in arl System.out.println(“Array list = ” +arl); //Remove elements arl.remove(“Apple”); arl.remove(2); //Display the content of ArrayList (or) in arl System.out.println(“Array list = ” +arl); //Find number of elements in arl System.out.println(“Size of Array list = ” +arl.size()); //Use Terator to retrieve elements Iterator it = arl.iterator(); while(it.hasNext()) System.out.println(it.next()); } } There are three types of interfaces are available, which are useful to retrieve the objects or elements one by one from array list. They are 1. Iterator 2. ListIterator 3. Enumeration What are the difference between Iterator and ListIterator: - Iterator ListIterator 1. Iterator supports only hasNext(), next() and remove() methods. 1. Iterator supports add(), set(), next(), hasNext(), previous(), hasPrevious(), nextIndex(), previousIndex() and Advanced Java Page 5 of 148 rambabumandalapu@yahoo.com remove() methods. 2. Access the collections in the forward direction only. 2. Access the collections in forward and backward directions. 3. Iterator is a super interface 3. ListIterator is the sub interface of Iterator super interface. What are the difference between Iterator and Enumeration: - Iterator Enumeration 1. Iterator supports a remove() method. 1. Enumeration doesn’t supports a remove() method. 2. It is not synchronized. 2. It is synchronized. 3. Iterator supports ArrayList, Vector, HashMap, HashTable. 3. Enumeration doesn’t supports ArrayList, HashMap. 4. It doesn’t supports legacy methods. 4. It supports legacy methods like as hasMoreElements(), nextElement(). Vector: - It is a dynamically growing array that stores objects. But it is synchronized. When the object is synchronized then we will get reliable results or values. Vectors are suitable objects. 1. To create a vector Vector v = new Vector(); Vector v = new Vector (100); 2. To know the size of Vector, use size() method. int n = v.size(); 3. To add elements use add() method. v.add(obj); v.add(2, obj); 4. To retrieve elements use get() method v.get(2); 5. To remove elements use remove() method v.remove(2); To remove all elements Advanced Java Page 6 of 148 rambabumandalapu@yahoo.com v.clear(); 6. To know the current capacity, use capacity() method int n = v.capacity(); 7. To search for last occurrence of an element use indexOf() method int n = v . intdexOf(obj); 8. To search for last occurrence of an element use lastIndexOf() method int n = v . lastIndexOf(obj); 9. Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument. void ensureCapacity(int minCapacity); ArrayList is not synchronized by default, but by using some methods we can synchronized the ArrayList. List myList = Collections.synchronizedList(myList); Vector is synchronized default. When we are retreiveing the elements from Vector, it will maintains and gives the same order what we have added the elements to the Vector. Vector doesn’t supports the null values. Ex: - //A Vector of int values import java.util.*; class VectorDemo { public static void main(String args[ ]) { //Create an empty Vector Vector v = new Vector (); //Take (an one dimensional) int type array int x [ ] = {10, 22, 33, 44, 60, 100}; //Read int values from x and store into v for(int i = 0; i< x.lenght(); i++) v.add(new Integer(x[ i ])); //Retrieve and display the elements for(int i = 0; i< v.size(); i++) System.out.println(v.get(i)); //Retrieve elements using ListIterator Advanced Java Page 7 of 148 rambabumandalapu@yahoo.com ListIterator lit = v. listIterator(); //QIn the above statement ListIterator is an Interface, listIterator() is a method System.out.println(“In forward direction: ” ); while(lit.hasNext()) System.out.print (lit.next() +“\t”); System.out.println (“\n In reverse direction: ”); while(lit.previous()) System.out.print(lit.previous() + “\t”); } } What are differences between ArrayList and Vector: - ArrayList Vector 1. An ArrayList is dynamically growing array that stores objects. 1. Vector is dynamically growing array that stores objects. 2. It is not synchronized. 2. It is synchronized. 3. It is efficient than Vector, due to ArrayList is fast iterartion and fast random access. 3. It is not efficient than ArrayList, it is slower than ArrayList due to its synchronized methods. 4. ArrayList supports only Iterator interface. 4. Vector supports Iterator and enumeration interfaces. 5. ArrayList doesn’t supports the legacy methods. 5. Vector supports the legacy methods like hasMoreElements(), nextElement(). 6. ArrayList doesn’t supports the capacity(). Its default capacity is 10. 6. Vector supports the capacity(). The default capacity of vector is 10. Maps: - A map represents storage of elements in the form of the key and value pairs. Keys must be unique and keys cannot allow duplicate values. HashTable: - Hashtable stores object in the form of keys and value pairs. It is synchronized. 1. To create a HashTable HashTable ht = new HashTable(); //Initial Capacity = 11, load factor = 0.75 HashTable ht = new HashTable(100); Advanced Java Page 8 of 148 rambabumandalapu@yahoo.com 2. To store key-Value pair the HashTable ht.put(“Sachin”, “Cricket Player”); 3. To get the value when is given ht.get(“Sachin”); 4. To remove the key (and its corresponding value) ht.remove(“Sachin”); 5. To know the number of keys in the HashTable. int n = ht.size(); 6. To clear all the keys. ht.clear(); What is load factor? ***** Ans: - Load factor determines the point at which the capacity of HashTable or HashMap will be automatically doubled. Ex: - For HashTable initial capacity (11) X load factor (0.75) = 8 i.e. After storing 8th pair the capacity of the HashTable will be doubled i.e. becomes 22 (11 x 2). Initial capacity = 11, this value depends on the version. Ex: - //HashTable with Cricket Scores import java.util.*; import java.io.*; class HashtableDemo { public static void main(String args[ ]) throws IOException { //Create an empty hash table HashTable ht = new HashTable(); //Store Player Name, Score //Q Here Player Name is Key and Score is a Value ht.put(“Amarnadh”, new Integer(50)); ht.put(“Sachin”, new Integer(150)); ht.put(“Dhoni”, new Integer(125)); ht.put(“Kapil”, new Integer(175)); Advanced Java Page 9 of 148 rambabumandalapu@yahoo.com ht.put(“Ganguly”, new Integer(86)); //Retrieve all keys Enumeration e = ht.keys(); System.out.println(“Player Name: ”); While(e.hasMoreElements()) System.out.println(e.nextElement()); //Ask for Player Name from Keyboard BufferedReader br = new BufferedReader(InputStreamReader(System.in)); //QIn the above statement (System.in) represents Keyboard System.out.println(“Enter Player Name: ”); String name = br.readLine(); //Find number of runs of this player Integer score = (Integer) ht.get(name); if(score!=null) { int runs = score.intValue(); System.out.println(Name+”Scored runs = ”+runs); } else System.out.println(“Player not found”); } } Ex 2: - import java.util.*; public class DemoHashTable { public static void main(String[] args) { Hashtable ht=new Hashtable(); ht.put("1", "Babu"); ht.put("2", "Anand"); ht.put("3", "Mogili"); ht.put("0", "@Marlabs"); System.out.println("---Retreiveing the elements--- = "+ht); System.out.println(ht.get("1")); System.out.println(ht.get("2")); Advanced Java Page 10 of 148 rambabumandalapu@yahoo.com System.out.println(ht.get("3")); System.out.println(ht.get("0")); Enumeration e=ht.elements(); while(e.hasMoreElements()){ System.out.println("---Retreving the elements using enumeration from HashTable = "+e.nextElement()); } Enumeration e1=ht.keys(); while(e1.hasMoreElements()){ System.out.println("---Retreving the keys using enumeration from HashTable = "+e1.nextElement()); } } } O/P: - ---Retreiveing the elements--- = {3=Mogili, 2=Anand, 1=Babu, 0=@Marlabs} Babu Anand Mogili @Marlabs ---Retreving the elements using enumeration from HashTable = Mogili ---Retreving the elements using enumeration from HashTable = Anand ---Retreving the elements using enumeration from HashTable = Babu ---Retreving the elements using enumeration from HashTable = @Marlabs ---Retreving the keys using enumeration from HashTable = 3 ---Retreving the keys using enumeration from HashTable = 2 ---Retreving the keys using enumeration from HashTable = 1 ---Retreving the keys using enumeration from HashTable = 0 Ex 3: - import java.util.*; public class DemoHashTable { public static void main(String[] args) { Hashtable ht=new Hashtable(); ht.put("1", "Babu"); Advanced Java Page 11 of 148 rambabumandalapu@yahoo.com ht.put(null, "Anand"); (or) ht.put(“2”, null); ht.put("3", "Mogili"); ht.put("0", "@Marlabs"); System.out.println("---Retreiveing the elements--- = "+ht); System.out.println(ht.get("1")); System.out.println(ht.get("2")); System.out.println(ht.get("3")); System.out.println(ht.get("0")); Enumeration e=ht.elements(); while(e.hasMoreElements()){ System.out.println("---Retreving the elements using enumeration from HashTable = "+e.nextElement()); } Enumeration e1=ht.keys(); while(e1.hasMoreElements()){ System.out.println("---Retreving the keys using enumeration from HashTable = "+e1.nextElement()); } } } O/P: - Exception in thread "main" java.lang.NullPointerException at java.util.Hashtable.put(Unknown Source) at com.marlabs.vara.DemoHashTable.main(DemoHashTable.java:7 Enumeration will not maintain objects in the same order. IOException may caused by readLine() method. IO stands for input/output. Playernames are all keys and scores are all values. When we retreving the elements or keys using HashTable it will gives the elements or keys in revrse order only. In HashTable duplicate keys are not allowed but duplicate values are allowed. HashMap: - HashMap stores objects in the form of keys and value pairs. It is not synchronized. 1. To create a HashMap Advanced Java Page 12 of 148 rambabumandalapu@yahoo.com HashMap hm = new HashMap(); //Initial Capacity = 16, load factor = 0.75 HashMap hm = new HashMap(101); 2. To store key-Value pair the HashMap hm.put(“Sachin”, “Cricket Player”); 3. To get the value when is given hm.get(“Sachin”); 4. To remove the key (and its corresponding value) hm.remove(“Sachin”); 5. To know the number of key-value pairs in the HashMap. int n = hm.size(); 6. To clear all the keys. hm.clear(); HashMap is similar to HashTable but the difference between these two is HashTable is synchronized but HashMap is not synchronized When we retreving the elements or keys using HashMap it will gives the elements or keys irregular order, not even the same order that we have added keys and elements. In HashMap duplicate keys are not allowed but duplicate values are allowed. Map myMap = Collections.synchronizedMap(myMap); Ex: - //Telephone entry book import java.util.*; import java.io.*; class Tele { public static void main(String args[ ]) throws IOException { //Vars HashMap hm = new HashMap(); String name, str; Long phno; BufferedReader br = new BufferedReader(InputStreamReader(System.in)); //Menu Advanced Java Page 13 of 148 rambabumandalapu@yahoo.com while(true) //It is an infinite loop { System.out.println(“1 Enter entries into Phone Book”); System.out.println(“2 Lookup for a Phone Number”); System.out.println(“3 Exit”); int n = Integer.parseInt(br.readLine()); //Depending on n value, perform a task switch(n) { case 1: System.out.print(“Enter Person Name: ”); Name = br.readLine(); System.out.print(“Enter Phone No. ”); str = br.readLine(); //Convert str into Long obj phno = new Long(str); //Store name, phone in hm break; case 2: System.out.print(“Enter Person Name”); name = br.readLine(); //Pass name to hm and get the Phone No. phno = (Long)hm.get(name); System.out.println(“Phone No: ”+phno); break; default: return; } } } } Ex 1: - import java.util.*; public class DemoHashmap { Advanced Java Page 14 of 148 rambabumandalapu@yahoo.com public static void main(String args[]){ HashMap hm=new HashMap(); System.out.println("---HasMap initial size---"+hm.size()); hm.put("1", "Vara"); hm.put("2", "anji"); hm.put("3", "anand"); hm.put("4", "bujji"); System.out.println("---HasMap size---"+hm.size()); System.out.println("---Retrieving the elements HasMap---"+hm); System.out.println(hm.get("4")); System.out.println(hm.get("1")); System.out.println(hm.get("3")); System.out.println(hm.get("2")); Set s=hm.keySet(); Iterator it=s.iterator(); while(it.hasNext()) System.out.println("Retreiveing the Keys = "+it.next()); } } O/P: - ---HasMap initial size---0 ---HasMap size---4 ---Retrieving the elements HasMap---{3=anand, 2=anji, 4=bujji, 1=Vara} bujji Vara anand anji Retreiveing the Keys = 3 Retreiveing the Keys = 2 Retreiveing the Keys = 4 Retreiveing the Keys = 1 Ex 2: - import java.util.*; public class DemoHashmap { Advanced Java Page 15 of 148 rambabumandalapu@yahoo.com public static void main(String args[]){ HashMap hm=new HashMap(); System.out.println("---HasMap initial size---"+hm.size()); hm.put("1", "Vara"); hm.put(null, null); hm.put("3", null); hm.put("4", "bujji"); System.out.println("---HasMap size---"+hm.size()); System.out.println("---Retrieving the elements HasMap---"+hm); System.out.println(hm.get("4")); System.out.println(hm.get("1")); System.out.println(hm.get("3")); System.out.println(hm.get("2")); Set s=hm.keySet(); Iterator it=s.iterator(); while(it.hasNext()) System.out.println("Retreiveing the Keys = "+it.next()); } } O/P: - ---HasMap initial size---0 ---HasMap size---4 ---Retrieving the elements HasMap---{null=null, 3=null, 4=bujji, 1=Vara} bujji Vara null null Retreiveing the Keys = null Retreiveing the Keys = 3 Retreiveing the Keys = 4 Retreiveing the Keys = 1 What are differences between HashMap and HashTable: - Advanced Java Page 16 of 148 rambabumandalapu@yahoo.com HashMap HashTable 1. It stores the objects in the form of key and value pairs. 1. It stores the objects in the form of key and value pairs. 2. It is not synchronized. 2. It is synchronized. 3. It will makes fastest updates (key/value pairs) so it is efficient than HashTable. 3. It is not efficient than HashMap due to its synchronized methods. 4. It supports only Iterator interface. 4. HashTable supports Iterator and enumeration interfaces. 5. It doesn’t supports legacy methods. 5. It supports legacy methods like hasMoreElement(), nextElement(). 6. HashMap initial capacity is 16 and the capacity of HashMap depends on version of Java. 6. HashTable initial capacity is 11 and the capacity of HashTable depends on version of Java. 7. HashMap doesn’t maintained the orderd of elements, not even the keys and the elements added to it. 7. HashTable maintained the orderd of elements in reverse. 8. HapMap takes only one null key and many null values. 8. HashTable doesn’t takes null keys and null values. StringTokenizer: - The StringTokenizer class is useful to break a string into small pieces, called tokens. 1. To create an object to StringTokenizer StringTokenizer st = new StringTokenizer(str, “delimiter”); (or) StringTokenizer st = new StringTokenizer(str, “,”); (or) StringTokenizer st = new StringTokenizer(str, “, :”); QHere , : are called as delimiters 2. To find the next piece in the string. String piece = st.nextToken(); 3. To know if more pieces are remaining. booleab x = st.hasMoreTokens(); 4. To know how many number of pieces are there. int no = st.countTokens(); Advanced Java Page 17 of 148 rambabumandalapu@yahoo.com Token means piece of string. Ex: - //Cutting the string into pieces import java.util.*; class STDemo { public static void main(String args[ ]) { //Take a string String str = “It is our capital city called New Delhi”; //brake the string into species StringTokenizer st = new StringTokenizer(str, “ ”); //retrieve the pieces and display System.out.println(“The token are: ”); while(st.hasMoreTokens()) { String s1 = st.nextToken(); System.out.println(s1); } } } (or) //Cutting the string into pieces import java.util.*; class STDemo { public static void main(String args[ ]) { //Take a string String str = “It, is our: capital city, called New: Delhi”; //brake the string into species StringTokenizer st = new StringTokenizer(str, “, : ”); //retrieve the pieces and display System.out.println(“The token are: ”); while(st.hasMoreTokens()) { Advanced Java Page 18 of 148 rambabumandalapu@yahoo.com String s1 = st.nextToken(); System.out.println(s1); } } } Calendar: - This class is useful to handle, date & time. 1. To create an object to calendar class: Calendar cl = Calendar.getInstance(); 2. Use get() method to retrieve date or time from calendar object. This method returns an integer. cl.get(constant); Note: - Constants: - Calendar.DATE Calendar.MONTH Calendar.YEAR Calendar.HOUR Calendar.MINUTE Calendar.SECOND 3. Use set() to get the date or time in the calendar object. cl.set(calendar.MONTH,10); //Default counting of January month starts with 0 booleab x = st.hasMoreTokens(); 4. To convert a date into string, use toString(). This method returns a string. cl.toString(); Gregorian calendar is another type class like as calendar class. Form Server Name Address Name Ok Section Advanced Java Page 19 of 148 rambabumandalapu@yahoo.com Ex: - //System date and time import java.util.*; class Cal { public static void main(String args[ ]) { //Create an obj to calendar class Calendar cl = Calendar.getInstance(); //retrieve date details int dd = cl.get(Calendar.DATE); int mm = cl.get(Calendar.MONTH); int yy = cl.get(Calendar.YEAR); ++mm; System.out.println(“System date: ”); System.out.println(“dd+ “/” +mm+ “/” +yy); //retrieve time details int h = cl.get(Calendar.HOUR); int m = cl.get(Calendar.MINUTE); int s = cl.get(Calendar.SECOND); System.out.println(“System time: ”); System.out.println(h+ “:” +m+ “:” +s)); } } Date Class: - Date class is class useful to handle date and time. 1. To create an object to Date class. Date d = new Date(); 2. Format the date and times using getDateInstance() or getDateTimeInstance() methods of DateFormat class. This is in java.txt package. Syntax: - DateFormat fmt = DateFormat.getDateInstance(formatconst, region); QHere region is the place/the country. Ex:-DateFormat fmt=DateFormat.getDateInstance(DateFormat.Medium, Locale.UK); Syntax: - DateFormat fmt = DateFormat.getDateInstance(formatconst, formatconst region); Ex: - DateFormat fmt = DateFormat.getDateInstance(DateFormat.Medium, Advanced Java Page 20 of 148 rambabumandalapu@yahoo.com DateFormat.SHORT, Locale.US); Note: - ---------------------------------------------------------------------------------------------------------------- formatconst Example (region = LocaleUK) ---------------------------------------------------------------------------------------------------------------- DateFormat.LONG 03 September 2004 19:43:14 GMT + 5.30 DateFormat.FULL 03 September 2004 19:43:14 oclock GMT + 5.30 DateFormat.MEDIUM 03-Sep-04 19:43:14 DateFormat.LONG 03/09/04 7.43 pm ---------------------------------------------------------------------------------------------------------------- 3. Applying format to Date object is done by format () method. String str = fmtt.format(d); Ex: - //To display system date and time import java.util.*; import java.text.*; class MyDate { public static void main(String args[ ]) { //Create an obj to Date class Date d = new Date(); //Store the format in DateFormat obj DateFormat fmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.UK); //Applying the format to d String s = fmt.format(d); //Display the formatted date and time System.out.println(“System date and time: ”+s); } } QHere d represents the system date & time already consists after creating an object. H.W. Advanced Java Page 21 of 148 rambabumandalapu@yahoo.com 1. Create an Employee class with an employee’s id, name, and address store objects of this class in an ArrayList. When an employee’s ID is given, display his name and address. 2. Create a vector with a group of strings. Sort them and display them in a ascending order. Display them in reverse order also? 3. Create HashTable with some students hall tickets no.’s & their results. Type a hall ticket number and display his result? 4. Cut the string into pairs of pieces: “India=>Delhi, America=>Washington,
Britain=>London, France=>Paris”
Now display the token as given below.
City Capital
Delhi India
Washington America
London Britain
Paris France
What is the difference between Observable and Observer? *****
Ans: - Observable is a class is used to create subclasses that other parts of our
program can observe. When an object of such a subclass undergoes a change,
Observing classes are notified. Observing classes must implement the Observer
interface. It will have more methods than Observer interface.
An Observer is an interface, which is useful to observe an observable object,
and must implement the observer interface. This interface will defines only one
method i.e. void update(Observable observOb, Object arg). Here observOb is the
object being observed, and arg is the value passed by notifyObservers(). The
update() method is called when a change in the observed object take place.
STREAMS: - A stream represents flow of data from one place to another place.
They are two types of streams,
1. Input Streams: - It receives or reads the data to output stream.
2. Output Stream: - It sends or writes the data to some other place.
Streams are represented by classes in java.io package.
Streams (java.io): - A stream is a sequence of bytes, or characters traveling from
source to a destination.
Advanced Java
Page 22 of 148 rambabumandalapu@yahoo.com
When the bytes passing then it is called as byte stream and when the
characters are passing then it is called as character stream.
To handle data in the form of ‘bytes’, the abstract class: InputStream and
OutputStream are used.
InputStream
|
----------------------------------------------------------------------
| | |
FileInputStream FilterInputStream ObjectInputStream
|
-----------------------------------------
| |
BufferedInputStream DataInputStream
OutputStream
|
-----------------------------------------------------------------------
| | |
FileOutputStream FilterOutputStream ObjectOutputStream
|
-----------------------------------------
| |
BufferedOutputStream DataOutputStream
a) FileInputStream/FileOutputStream: - They handle data to be read or written to
disk files.
b) FilterInputStream/FilterOutputStream: - They read data from one stream and
write it another stream.
c) ObjectInputStream/ObjectOutputStream: - They handle storage of objects and
primitive data.
Storing objects in a file called serialization.
Retrieving the data from files is called de-serialization.
Reader
|
-----------------------------------------------------------------------------------------------
| | | |
BufferedReader CharArrayReader IntputStreamReader PrintReader
|
FileReader
Writer
|
Advanced Java
Page 23 of 148 rambabumandalapu@yahoo.com
-----------------------------------------------------------------------------------------------
| | | |
BufferedWriter CharArrayWriter IntputStreamWriter PrintWriter
|
FileWriter
ByteStream stores the data in the form of bytes, CharacterStream stores the
data in the form of characters.
Buffered means a block of memory.
a) BufferedReader/BufferedWriter: - Handles character (text) by buffering them.
They provide efficiency.
b) CharArrayReader/CharArrayWriter: - Handles array of characters.
c) InputStreamReader/OutputStreamWriter: - They are bridge between byte
streams and character streams. Reader reads bytes and then decode them into 16-
bit Unicode character, write decodes character into bytes and then write.
d) PrinterReader/PrinterWriter: - Handle printing of characters on the screen.
A file is an organized collection of data.
How can you improve Java I/O performance:
Java applications that utilise Input/Output are excellent candidates for
performance tuning. Profiling of Java applications that handle significant volumes of
data will show significant time spent in I/O operations. This means substantial gains
can be had from I/O performance tuning. Therefore, I/O efficiency should be a high
priority for developers looking to optimally increase performance. The basic rules for
speeding up I/O performance are:
ı Minimise accessing the hard disk.
ı Minimise accessing the underlying operating system.
ı Minimise processing bytes and characters individually.
Let us look at some of the techniques to improve I/O performance.
ı Use buffering to minimise disk access and underlying operating system. As
shown below, with buffering
large chunks of a file are read from a disk and then accessed a byte or character at a
time.
Without buffering : inefficient code
try{
File f = new File("myFile.txt");
FileInputStream fis = new FileInputStream(f);
Advanced Java
Page 24 of 148 rambabumandalapu@yahoo.com
int count = 0;
int b = ;
while((b = fis.read()) != -1){
if(b== '\n') {
count++;
}
}
// fis should be closed in a finally block.
fis.close() ;
}
catch(IOException io){}
Note: fis.read() is a native method call to the underlying system.
With Buffering: yields better performance
try{
File f = new File("myFile.txt");
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
int count = 0;
int b = ;
while((b = bis.read()) != -1){
if(b== '\n') {
count++;
}
}
//bis should be closed in a finally block.
bis.close() ;
}
catch(IOException io){}
Note: bis.read() takes the next byte from the input buffer and only rarely access the
underlying operating system.
Instead of reading a character or a byte at a time, the above code with
buffering can be improved further by reading one line at a time as shown below:
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
Advanced Java
Page 25 of 148 rambabumandalapu@yahoo.com
While (br.readLine() != null) count++;
By default the System.out is line buffered, which means that the output buffer
is flushed when a new line character is encountered. This is required for any
interactivity between an input prompt and display of output.
The line buffering can be disabled for faster I/O operation as follows:
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);
PrintStream ps = new PrintStream(bos,false);
System.setOut(ps);
while (someConditionIsTrue)
System.out.println(“blah…blah…”);
}
Uses of files: -
1. We can store the data permanently into the hard disk. (When we are strong the
data in HashTable, vector etc… the data will store temporarily on the RAM).
2. Once we stored the data in the form of file we can share that data in different
programs.
The above two are main advantages of file.
System.in –it is a InputStream object
Here System is a class java.io. package.
in is a field.
System.in – InputStream obj – Keyboard
System.out – PrintSream obj – Monitor
System.err – PrintSream obj – Monitor
System.out will displays normal messages on the monitor, System.err will
displays error messages on the monitor.
What is use of Stream? *****
Ans: - Stream will handle input/output devices. The achieving the hardware
independent of java programs we are using stream.
Advanced Java
Page 26 of 148 rambabumandalapu@yahoo.com
Ex: - //Creating a file
import java.io.*;
class Create1
{
public static void main(String args[ ])
throws IOException
{
//Attach the keyboard to DataInputStream
DataInputStream dis = new DataInputStream(System.in);
//Connect file to FileOutputStream
FileOutputStream fout = new FileOutputStream(“myfile”);
//reading data from DataInputStream and write that data into FileOutputStream
char ch;
System.out.println(“Enter data (@at end): ”);
while((ch = char) dis.read()) != ‘@’)
fout.write(ch);
//close the file
fout.close();
}
}
After executing & running the program, we can also open file using command
“type” (i.e. a Ms-Dos Command). Every time executing & running the program old
data will be remove/overwrite and new data will stored. To overcome this problem or
to appending the data we have to use ‘true’ in the following statement.
FileOutputStream fout = new FileOutputStream(“myfile”, true);
Ex: - //Creating a file
DataInputStream
System.in
FillOutputStrea
m
myfile
Advanced Java
Page 27 of 148 rambabumandalapu@yahoo.com
import java.io.*;
class Create1
{
public static void main(String args[ ])
throws IOException
{
//Attach the keyboard to DataInputStream
DataInputStream dis = new DataInputStream(System.in);
//Connect file to FileOutputStream
FileOutputStream fout = new FileOutputStream(“myfile”, true);
//reading data from DataInputStream and write that data into FileOutputStream
char ch;
System.out.println(“Enter data (@at end): ”);
while((ch = char) dis.read()) != ‘@’)
fout.write(ch);
//close the file
fout.close();
}
}
To improve the efficiency or the speed of execution of program we to use
Buffered class.
BufferedOutputStream bos = new BufferedOutputStream(fout, 1024);
Default size used by any Buffered class is 512 bytes.
In the place of fout.write(); we have to use bos.write(); and in the place of
fout.close(); we have to use bos.close();
Ex: - //Creating a file
import java.io.*;
class Create1
{
public static void main(String args[ ])
throws IOException
{
//Attach the keyboard to DataInputStream
DataInputStream dis = new DataInputStream(System.in);
Advanced Java
Page 28 of 148 rambabumandalapu@yahoo.com
//Connect file to FileOutputStream
FileOutputStream fout = new FileOutputStream(“myfile”, true);
BufferedOutputStream bos = new BufferedOutputStream(fout, 1024);
//reading data from DataInputStream and write that data into FileOutputStream
char ch;
System.out.println(“Enter data (@at end): ”);
while((ch = char) dis.read()) != ‘@’)
bos.write(ch);
//close the file
bos.close();
}
}
Ex: - //Reading data from a text file
import java.io.*;
class Read1
{
public static void main(String args[ ])
throws IOException
{
//Attach the file to FileInputStream
FileInputStream fin = new FileInputStream(“myfile”);
//now read from FileInputStream and display
int ch;
while((ch = fin.read()) != -1)
System.out.println((char)ch);
//close the file
fin.close();
}
}
Ex: - //Reading data from a text file
import java.io.*;
class Read1
{
public static void main(String args[ ])
Advanced Java
Page 29 of 148 rambabumandalapu@yahoo.com
throws IOException
{
BufferedInputStream bin = new BufferedInputStream(fin);
//Attach the file to FileInputStream
FileInputStream fin = new FileInputStream(“myfile”);
//now read from FileInputStream and display
int ch;
while((ch = bin.read()) != -1)
System.out.println((char)ch);
//close the file
bin.close();
}
}
Ex: - //Reading data from a text file
import java.io.*;
class Read1
{
public static void main(String args[ ])
throws IOException
{
try{
//to enter filename from keyboard
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.ot.print(“Enter file name: ”);
String fname = readLine();
//Attach the file to FileInputStream
FileInputStream fin = new FileInputStream(fname);
//now read from FileInputStream and display
int ch;
while((ch = bin.read()) != -1)
System.out.println((char)ch);
//close the file
bin.close();
}
Advanced Java
Page 30 of 148 rambabumandalapu@yahoo.com
catch(FileNotFoundException fe)
{
System.out.println(“File not found”);
}
}
Ex: - //Creating a file
import java.io.*;
class Create2
{
public static void main(String args[ ])
throws IOException
{
//to write data into file
FileWriter fw = new FileWriter(“myfile1.txt”);
//take string
String str = “This is an institute” + “\nIam a student here”;
//read char by char from str and write into fw
for(int i = 0; i
Ex: - //A Client that receives data
import java.io.*;
import java.net.*;
Server
Socket
Client
Socket
Advanced Java
Page 37 of 148 rambabumandalapu@yahoo.com
class Client1
{
public static void main(String args)
throws Exception
{
//Create Client Socket
Socket s= new Socket(ipaddress/”loacalhost”, 777);
//attach InputStream to Socket
InputStream obj = s.getInputStream();
//To receive the data to this Socket
BufferedReader br = new BufferedReader(new InputStreamReader(obj));
//Accept data coming from Server
String str;
while(str=br.readLine()) !=null)
System.out.println(str);
//Disconnect the Server
s.close();
br.close();
}
}
We can run as many JVM’s at a time.
Communicating from the Server: -
1. Create a ServerSocket
ServerSocket ss = new ServerSocket(Port No.);
2. Accept any Client
Socket s = ss.accept(); ------ It returns Socket object.
3. To send data, connect the OutputStream to the Socket
OutputStream obj = s.getOutputStream();
4. To receive data from the Client, connect InputStream to the Socket
InputStream obj = s.getInputStream();
5. Send data to the Client using PrintStream
Ex: - PrintStream ps = new PrintStream(obj);
ps.print(str);
ps.println(str);
Advanced Java
Page 38 of 148 rambabumandalapu@yahoo.com
6. Read data coming from the Client using BufferedReader.
BufferedReader br = new BufferedReader(new InputStreamReader(obj);
ch = br.read();
str = br.readLine();
Communicating from Client: -
1. Create a Client Socket
Socket s= new Socket(ipaddress/”loacalhost”, 777);
2. To send data connect the OutputStream to the Socket
OutputStream obj = s.getOutputStream();
3. To receive data fro the Server, connect InputStream to the Socket
InputStream obj = s.getInputStream();
4. Send data to the Server using DataOutputStream.
Ex: - DataOutputStream dos = new DataOutputStream(obj);
Dos.writebyte(str);
5. Read data coming from the Server using BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(obj);
ch = br.read();
str = br.readLine();
3. Closing Communication: -
Close all Streams and Sockets
ps.close();
br.close();
dos.close();
ss.close();
s.close();
RMI (Remote Method Invocation) It is a technology to call and use remote
methods of remote objects.
Ex: - //Chat Server
import java.io.*;
import java.net.*;
class Server2
{
public static void main(String args)
Advanced Java
Page 39 of 148 rambabumandalapu@yahoo.com
throws Exception
{
//Create Server Socket
ServerSocket ss= new ServerSocket(888);
//make this Socket wait for Client connection
Socket s = ss.accept();
System.out.println(“Connection Established”);
//to send data to the Client
PrintStream ps = new PrintStream(s.getOutputStream());
//to receive data from Client
BufferedReader br = new BufferedReader(newInputStreamReader (s.getInputStream()));
//to read data from Keyboard
BufferedReader kb=new BufferedReader(new InputStreamReader(System.in()));
//now communicate
while(true) // Server runs continuously
{
String str, str1;
while(str = br.readLine() != null)
{
System.out.println(str);
str1 = kb.readLine();
ps.println(str1);
}
//Disconnect the Server
ss.close();
s.close();
ps.close();
br.close();
kb.close();
System.exit(0);
}
}
}
Ex: - //Chat Client
Reference Object
Advanced Java
Page 40 of 148 rambabumandalapu@yahoo.com
import java.io.*;
import java.net.*;
class Client2
{
public static void main(String args)
throws Exception
{
//Create Client Socket
Socket s= new Socket(“Localhost”, 888);
//to send data to the Server
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
//to receive data from Server
BufferedReader br=new BufferedReader(new InputStream(s.getInputStream()));
//to read data from Keyboard
BufferedReader kb=new BufferedReader(new InputStreamReader(System.in()));
//now start communicate
String str, str1;
while(str = br.readLine() .equals(“exit”))
//As long as the String are not typing exit.
{
dos.writeBytes(str+”\n”);
str1 = br.readLine();
System.out.println(str1);
}
//Disconnect the Server
s.close();
dos.close();
br.close();
kb.close();
}
}
H. W.
8. Develop a server that sends to system data and time to the client display that data
and time at client side (Hint: Use Port No.13)
Advanced Java
Page 41 of 148 rambabumandalapu@yahoo.com
9. Write client server programs so that the client sends the name of a file to the
server and the server sends the file content to client display the file contents at client
side (the file should present in the
server).
Thread: - A thread represents a process
of execution (or) executing the set of
statements is called a thread.
Every java program is executed by using one thread i.e. is called main thread.
JVM will execute statements step by step.
Ex: - //Every java program has a thread
class Current
{
public static void main(String args)
{
System.out.println(“This is first line”);
Thread t = Thread.currentThread();
System.out.println(“Present thread = ”+t);
System.out.println(“Its name = ”+t.getName());
}
}
C:\rnr>javac Current.java¿
C:\rnr>java Current ¿
O/P: - This is first line
Present Thread = Thread[main, 5, main]
Here main is a thread name.
5 is the Priority Number.
[main, 5, main] is called as Thread group.
From the above thread name is main. Thread has priority number. Priority
number will varies from 1 to 10.
Priority No. 1 ------- Minimum Priority
Priority No. 5 ------- Normal Priority
Priority No. 10 ------- Maximum Priority
----------
----------
----------
Statements
JVM
or
Microprocessor
Advanced Java
Page 42 of 148 rambabumandalapu@yahoo.com
Main thread priority number is 5.
We can provide more threads to the microprocessor. Microprocessor will
execute the 10billions of machine code instructions per second.
Executing the tasks (one or more statements is two types.
1. Single tasking: - Executing one task at a
time is called single tasking. In a Single
tasking lot of processor time wasted.
Time Slice: - Time slice is the time allotted
by the Microprocessor to execute each task.
Round Robin Method: - Microprocessor uses round robin method to execute
several tasks simultaneously.
Executing first task after last task is called round robin method.
Ex: - Robin is a bird which will comes down by making rounds and it will jump up by
making rounds that’s why they have compared the microprocessor like that above.
2. Multitasking: - Executing several tasks simultaneously is called multitasking.
a) Process based multitasking: - Executing several programs at a time is called
process based multitasking.
Time slice, Round robin methods are process based multitasking.
b) Thread based multitasking: -
Executing several parts of a program
simultaneously is called thread based
multitasking.
Using more than one thread is
called multithreading to perform multiple tasks simultaneously at a time.
Create a thread: -
1. Write a class that extends thread class or implements runnable interface.
Task
Microprocessor
Microprocessor
0.25ms 0.25ms 0.25ms 0.25ms
Memory
Task
Microprocessor will allot equal timings (0.25milli
seconds) for each task.
Microprocessor
Three
diff.
types
of
blocks
Advanced Java
Page 43 of 148 rambabumandalapu@yahoo.com
Thread class, runnable implements will helpful to create a thread. These two
are available in java.lang package.
2. Write public void run in the class thread will execute only this method.
public void run()
Thread can’t act upon any method, but default it works only on run() method.
3. Create an object to the class.
4. Attach a thread to this object.
5. Start thread, then will act upon that object.
Ex: - //Creating thread
Class MyThread extend Thread
{
public void run()
{
for(int i = 1; i<100000; i++) { System.out.println(i); } } } class TDemo { public static void main(String args[ ]) { MyThread obj = new MyThread(); Thread t1 = new Thread(); t1.start(); } } stop() method is used to stop the thread in old versions. But stop() method is deprecated in new versions. Forcibly to terminate the program we have to use “control + c” (Ctrl+c keys in the keyboard). To stop the thread also we have to use control + c keys. Advanced Java Page 44 of 148 rambabumandalapu@yahoo.com Ex: - //Creating thread and smoothly terminate/stop the program or thread Import java.io.*; Class MyThread extend Thread { boolean stop = false; public void run() { for(int i = 1; i<100000; i++) { System.out.println(i); if(stop) return; } } } class TDemo { public static void main(String args[ ]) { MyThread obj = new MyThread(); Thread t1 = new Thread(); t1.start(); System.in.read(); obj.stop = true; } } This above program is for stopping the thread smoothly. How can you stop the thread which is running? ***** Ans: - 1. Declare a boolean variable and initialize it as false Ex: - boolean stop = false; 2. When ever the thread should be stopped store true into this variable Ex: - obj.stop = true; 3. If the variable becomes true using return statement come out run() method Ex: - if(stop) return; run() { ----- ----- } Microprocessor object Advanced Java Page 45 of 148 rambabumandalapu@yahoo.com What is the difference between extends and implement Runnable? Which one is advantage? ***** Ans: - There is no difference between these two. Implement Runnable is advantage because interfaces is always better than classes. If we extend thread class, there is no scope any another class, this is the limitation of extends. If we implement Runnable interface still there is a scope to extend other class. The main advantage of multitasking is utilizing a processor time in an optimum way. Ex: - //Theatre Example class MyThread implements Runnable { String str; MyThread(String str) { this.str = str; } public void run() { for(int i = 1; i<=10; i++) { System.out.println(str+ “ : ” +i); try{ Thread.sleep(2000); }catch(InterruptedException ie) { ie.printStackTrace(); } } } } class Theatre run() { ----- ----- } Microprocessor object run() { ----- ----- } object 1 Microprocessor run() { ----- ----- } object 2 t1 thread t2 thread Advanced Java Page 46 of 148 rambabumandalapu@yahoo.com { public static void main(String args[ ]) { //create objects to MyThread class MyThread obj1=new MyThread(“Cut ticket”); MyThread obj2=new MyThread(“Show ticket”); //Create two threads and attach them to //these two objects Thread t1 = new Thread(obj1); Thread t2 = new Thread(obj2); //start the thread t1.start(); t2.start(); } } When multiple threads are acting on the one or same object we will get sometimes unreliable results. Ex: - //Two threads acting on one object class Reserve implements Runnable { int available = 1; int wanted; Reserve (int i) { wanted = i; } public void run() { System.out.println(“Number of berths available = ”+available); if(available >= wanted)
{
String name = Thread.currentThread.getName();
System.out.println(wanted + “berths reserved for”+name);
try{
Thread.sleep(2000);
-------------------
-
-------------------
-------------------
-
-------------------
object
Synchronization
2nd thread
1st thread
Advanced Java
Page 47 of 148 rambabumandalapu@yahoo.com
available = available – wanted;
}
catch(Interrupted Exception ie){ }
}
else
System.out.println(“Sorry, no berths to reserve”);
}
}
class Syn
{
public static void main(String args[ ])
{
//create an obj to Reserve class with 1 berth
Reserve obj = new Reserve(1);
//create 2 threads and attach them to obj
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
//give names to threads
t1.setName(“First Person”);
t2.setName(“Second Person”);
//run the threads
t1.start();
t2.start();
}
}
This above program will allot tickets for both persons. For this permanent
solution we have to block the 2nd thread till the completion of the 1st thread. So we
have to use synchronization method to block the 2nd thread.
Ex: - //Two threads acting on one object
class Reserve implements Runnable
{
int available = 1;
int wanted;
Reserve (int i)
Advanced Java
Page 48 of 148 rambabumandalapu@yahoo.com
{
wanted = i;
}
public void run()
synchronized(obj)
{
System.out.println(“Number of berths available = ”+available);
if(available >= wanted)
{
String name = Thread.currentThread.getName();
System.out.println(wanted + “berths reserved for”+name);
try{
Thread.sleep(2000);
available = available – wanted;
}
catch(Interrupted Exception ie){ }
}
else
System.out.println(“Sorry, no berths to reserve”);
}
}
}
class Syn
{
public static void main(String args[ ])
{
//create an obj to Reserve class with 1 berth
Reserve obj = new Reserve(1);
//create 2 threads and attach them to obj
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
//give names to threads
t1.setName(“First Person”);
t2.setName(“Second Person”);
Advanced Java
Page 49 of 148 rambabumandalapu@yahoo.com
//run the threads
t1.start();
t2.start();
}
}
Thread Synchronization (or) Synchronization: - Synchronization is locking the
object, so that when a thread is processing object any other thread will not be
allowed to act upon the object. Synchronized object is also called as Mutex i.e.
Mutually Exclusive lock.
An object can be synchronized in two ways
1. Synchronized block(): -
synchronized(obj)
{ For group of statements we can use this synchronized
statements; block.
}
Ex: - class BlockLevel {
//shared among threads
SharedResource x, y ;
//dummy objects for locking
Object xLock = new Object(), yLock = new Object();
pubic void method1() {
synchronized(xLock){
//access x here. thread safe
}
//do something here but don't use
SharedResource x, y ;
synchronized(xLock) {
synchronized(yLock) {
//access x,y here. thread safe
}
}
//do something here but don't use
SharedResource x, y ;
}
Advanced Java
Page 50 of 148 rambabumandalapu@yahoo.com
}
2. By making a method as synchronized method
synchronized void method()
{ For entire method to synchronized we will use
statements; this method.
}
Ex: - class MethodLevel {
//shared among threads
SharedResource x, y ;
pubic void synchronized
method1() {
//multiple threads can't access
}
pubic void synchronized
method2() {
//multiple threads can't access
}
public void method3() {
//not synchronized
//multiple threads can access
}
}
Synchronization important: - Without synchronization, it is possible for one thread
to modify a shared object while another thread is in the process of using or updating
that object’s value. This often causes dirty data and leads to significant errors.
Disadvantage of synchronization is that it can cause deadlocks when two threads
are waiting on each other to do something. Also synchronized code has the
overhead of acquiring lock, which can adversely the performance.
Synchronization is also known as thread safe, unsynchronized is also known
as thread unsafe.
Locking means it will not allow another thread still the completion of one task
of one thread.
Ex: - //To cancel the ticket
Class CancelTicket extends Thread
Advanced Java
Page 51 of 148 rambabumandalapu@yahoo.com
{
object train, comp;
CancelTicket(object train, object comp)
{
this.train = train;
this.comp = comp;
}
public void run()
{
synchronized(comp)
{
System.out.println(“CancelTicket locked the compartment”);
try{
sleep(100);
}catch(InterruptedException ie){ }
System.out.println(“CancelTicket wants to lock on train”);
synchronized(train)
{
System.out.println(“CancelTicket now locked train”);
}
}
}
}
class BookTicket extends Thread
{
object train, comp;
BookTicket(object train, object comp)
{
this.train = train;
this.comp = comp;
}
public void run()
{
synchronized(train)
100ms comp.obj
BookTicket
train.obj
Thread 1
Thread 2
200ms
CancelTicket
Advanced Java
Page 52 of 148 rambabumandalapu@yahoo.com
{
System.out.println(“BookTicket locked the train”);
try{
sleep(200);
}catch(InterruptedException ie){ }
System.out.println(“BookTicket wants to lock on compartmet”);
synchronized(comp)
{
System.out.println(“BookTicket now locked compartment”);
}
}
}
}
class DeadLock
{
public static void main(String args[ ])
throws Exception
{
//take train and compartment as objects
object train = new object();
object compartment = new object();
//create objects to CancelTicket, BookTicket
CancelTicket obj1 = new CancelTicket(train, compartment);
BookTicket obj1 = new BookTicket (train, compartment);
//create 2 threads and attach them to these objects
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
//run the threads
t1.start();
t2.start();
}
}
Save it as DeadLock.java compile & run the program.
Output: -
Advanced Java
Page 53 of 148 rambabumandalapu@yahoo.com
CancelTicket locked the Compartment
BookTicket locked the Train
CancelTicket wants to lock on train
BookTicket wants to lock the Compartment
Press Ctrl+c for forcibly to terminate the program, because to solve this program in
another way.
Ex: - //To cancel the ticket Solution for dead lock
Class CancelTicket extends Thread
{
object train, comp;
CancelTicket(object train, object comp);
{
this.train = train;
this.comp = comp;
}
public void run()
{
synchronized(comp)
{
System.out.println(“CancelTicket locked the compartment”);
try{
sleep(100);
}catch(InterruptedException ie){ }
System.out.println(“CancelTicket wants to lock on train”);
synchronized(train)
{
System.out.println(“CancelTicket now locked train”);
}
}
}
}
class BookTicket extends Thread
{
100ms comp.obj
BookTicket
train.obj
Thread 1
Thread 2
200ms
CancelTicket
Locking
Solution for
DeadLock Changing
direction of thread 2
Advanced Java
Page 54 of 148 rambabumandalapu@yahoo.com
object train, comp;
BookTicket(object train, object comp);
{
this.train = train;
this.comp = comp;
}
public void run()
{
synchronized(comp)
{
System.out.println(“BookTicket locked the Compartment”);
try{
sleep(200);
}catch(InterruptedException ie){ }
System.out.println(“BookTicket wants to lock on compartmet”);
synchronized(train)
{
System.out.println(“BookTicket now locked train”);
}
}
}
}
class DeadLock
{
public static void main(String args[ ])
throws Exception
{
take train and compartment as objects
object train = new object();
object compartment = new object();
//create objects to CancelTicket, BookTicket
CancelTicket obj1 = new CancelTicket(train, compartment);
BookTicket obj1 = new BookTicket (train, compartment);
//create 2 threads and attach them to these objects
Advanced Java
Page 55 of 148 rambabumandalapu@yahoo.com
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
//run the threads
t1.start();
t2.start();
}
}
DeadLock of thread: - When a thread locked an object and waiting for another
object which has been already locked by another thread and the other thread is also
waiting for the first object it leads to DeadLock situation.
In DeadLock both the threads mutually keep under waiting forever and further
processing is canceled.
A programmer should avoid DeadLock situations in his program by properly
planning designing the program.
Thread Class Methods: -
1. To know the currently running thread.
Thread t = Thread.currentThread();
2. To start thread
t.start();
3. To stop execution of a thread for a specified time
Thread.sleep(milliseconds);
4. To get the name of a thread
String name = t.getName();
5. To set a new to a thread
t.setName(“name”);
6. To get the priority of a thread
int priority_no = t.getPriority();
7. To set the priority of a thread
t.setPriority(int priority_no);
Note: - The priority number constants are as given below
Thread.MAX_PRIORITY value is 10
Thread.MIN_PRIORITY value is 0
Thread.NORM_PRIORITY value is 5
8. To test if a thread is still alive
Advanced Java
Page 56 of 148 rambabumandalapu@yahoo.com
t.isAlive(); returns true/false
9. To wait till a thread dies
t.join();
10. To send a notification to awaiting thread
obj.notify();
11. To send notification to all waiting threads
obj.notifyAll();
12. To wait till the obj is released (till notification is sent)
obj.wait();
notify() method will sends a notification to a thread, i.e. some object is
available to the thread.
The above three methods (10, 11, 12) are belong to object class.
What is the difference between Green thread and Nativethread? *****
Ans: - A program thread uses two types of operating system threads, they are Green
Thread model and Native Thread model. Green Thread model will provide only one
thread for a program thread, where as Native Thread provides a separate thread for
each program thread.
Ex: - //Thread Communication
Class Communicate
{
public static void main(String args[ ])
{
//create Producer, Consumer, objects
Producer obj1 = new Producer();
Consumer obj2 = new Consumer(obj1);
//create 2 threads and attach them obj1, obj2
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
//run the threads
t1.start();
t2.start();
}
}
Advanced Java
Page 57 of 148 rambabumandalapu@yahoo.com
class Producer extends Thread
{
Boolean dataprodover = false; //Qdataprodove is a data production over
SrtingBuffer sb;
producer()
{
sb = new StringBuffer();
}
public void run()
{
for(int i = 1; i<=10; i++) { try { sb.append(i+”:”); sleep(100); System.out.println(“appending”); } catch(Exception e){ } } dataprodover = true; } } class Consumer extends Thread { Producer prod; Consumer(Producer prod) { this.prod = prod; } public void run() { try{ while(!prod.dataprodover) Producer Consumer Data Provider 1 2 3 - - - 10 true Advanced Java Page 58 of 148 rambabumandalapu@yahoo.com { sleep(10); } }catch(Exception e){ } System.out.println(prob.sb); } } Save it as communication.java. This above program/method is not efficient way to communication between threads. If we want communicate efficient way we have to use notify() method. Ex: - //Thread communication in efficient way Class Communicate { public static void main(String args[ ]) { //create Producer, Consumer, objects Producer obj1 = new Producer(); Consumer obj2 = new Consumer(obj1); //create 2 threads and attach them obj1, obj2 Thread t1 = new Thread(obj1); Thread t2 = new Thread(obj2); //run the threads t1.start(); t2.start(); } } class Producer extends Thread { SrtingBuffer sb; producer() { sb = new StringBuffer(); } Producer Consumer Data Provider 1 2 3 - - - 10 true Advanced Java Page 59 of 148 rambabumandalapu@yahoo.com public void run() { synchronized() { for(int i = 1; i<=10; i++) { try { sb.append(i+”:”); sleep(100); System.out.println(“appending”); } catch(Exception e){ } } sn.notify(); // or we can use sb.notifyAll(); } } } class Consumer extends Thread { Producer prod; Consumer(Producer prod) { this.prod = prod; } public void run() { synchronized(prod.sb) { try{ prod.wait(); }catch(Exception e){ } System.out.println(prod.sb); } Advanced Java Page 60 of 148 rambabumandalapu@yahoo.com } } What is the difference between sleep() method and wait() method? ***** Ans: - Both methods will make the thread wait for some time. When the thread comes out of sleep() method the object may be still lock. When the threads comes out of the wait() method the object is automatically unlocked. But both methods will wait temporarily. Ex: - synchronized(obj) synchronized(obj) { { ---------------------- ---------------------- ---------------------- ---------------------- sleep(2000); wait(2000); ---------------------- ---------------------- ---------------------- ---------------------- } } What are different types of threads: - 1. User thread or Main thread. 2. Daemon thread 3. GUI thread What is Daemon thread? ***** Ans: - A Daemon thread is a thread that continuously provides services to other threads i.e. Daemon thread are used for background services. Ex: - To start mysql F:\rnr>mysqld¿ QHere d is the Daemon thread.
F:\rnr>
Now onwards Daemon thread makes the mysql database running
continuously.
Daemon threads are generally used background services.
What is thread life cycle? *****
Ans: - Life cycle of thread means from the creation of thread till its termination. The
states assumed by the thread are called life cycle of a thread.
locked
locked
locked
Unlocked
Advanced Java
Page 61 of 148 rambabumandalapu@yahoo.com
Start ® run ® wait (or) blocked state ® Destroy State
Life Cycle of Thread
(or)
Runnable means it will executes public void run methods yield makes pausing
the thread.
Not Runnable means thread will stop runnable.
Afetr executing the all methods by run() method then the thread will be
terminated.
Runnable: - Waiting for its turn to be picked for execution by the thread schedular
based on thread priorities.
Running: - The processor is actively executing the thread code. It runs until it
becomes blocked, or voluntarily gives up its turn with this static method
Thread.yield(). Because of context switching overhead, yield() should not be used
very frequently.
New Thread Not Runnable
Runnable
Yield
Running
Dead
sleep()
wait()
blocked on I/O
Start
The run method terminates
Dead/Terminates
Advanced Java
Page 62 of 148 rambabumandalapu@yahoo.com
Waiting: - A thread is in a blocked state while it waits for some external processing
such as file I/O to finish.
Sleeping: - Java threads are forcibly put to sleep (suspended) with this overloaded
method: Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);
Blocked on I/O: Will move to runnable after I/O condition like reading bytes of data
etc changes.
Blocked on synchronization: Will move to Runnable when a lock is acquired.
Dead: The thread is finished working.
What is the difference between yield and sleeping? *****
Ans: - When a task invokes yield(), it changes from running state to runnable state.
When a task invokes sleep(), it changes from running state to waiting/sleeping state.
What are the states of thread? *****
Ans: - New thread state ® Runnable ® Running ® wait (or) blocked state ®
Destroy State
Thread Group: - A group of threads as single unit is called ThreadGroup.
If we applied certain methods on the ThreadGroup it will effect all other
threads. Controlling all the threadsx by giving a single command or method is
possible, because of ThreadGroup.
ThreadGroup tg = new ThreadGroup(“group name”);
Thread t1 = new Thread(tg, obj, “threadname”);
QHere obj is target object
Thread t2 = new Thread(tg, obj1, “threadname”);
We can also add one ThreadGroup to another ThreadGroup.
ThreadGroup tg1 = new ThreadGroup(tg, “group name”);
Daemon Thread: - Daemon threads are service providers fro other threads or
objects. A daemon thread executes continuously. It provides generally a background
processing.
1. To make a thread as Daemon thread
t.setDaemon(true);
2. To know if a thread is Daemon or not
Boolean x = t.isDaemon();
t1
t2
tg1
t4
t3
tg
res
can
Advanced Java
Page 63 of 148 rambabumandalapu@yahoo.com
Ex: - /*Using thread groups*/
class WhyTGroups
{
public static void main(String args[ ])
throws Exception
{
Reservation res = new Reservation();
Cancellation can = new Cancellation();
//create a ThreadGroup with name
ThreadGroup tg = new ThreadGroup(“Reservation Group”);
//create 2 threads and add them to ThreadGroup
Thread t1 = new Thread(tg, res, “First thread”);
Thread t2 = new Thread(tg, res, “Second thread”);
//create another ThreadGroup as a child to tg
ThreadGroup tg1 = new ThreadGroup(tg, “Cancellation Group”);
Thread t3 = new Thread(tg1, res, “Third thread”);
Thread t4 = new Thread(tg1, res, “Fourth thread”);
System.out.println(‘Number of threads in a group = ”+tg.activeCount());
//Find parent group of tg1
System.out.println(‘Parent of tg1 = ”+tg1.getParent());
//set maximum priority to tg1 as 7
tg1.setMaxPriority (7);
//know the ThreadGroup of t1 and t2
System.out.println(‘ThreadGroup of t1 = ”+t1.getThreadGroup());
System.out.println(‘ThreadGroup of t2 = ”+t2.getThreadGroup());
//start the threads
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Reservation extends Thread
{
Advanced Java
Page 64 of 148 rambabumandalapu@yahoo.com
public void run()
{
System.out.println(‘I am Reservation thread”);
}
}
class Cancellation extends Thread
{
public void run()
{
System.out.println(‘I am Cancellation thread”);
}
}
H.W.
10. Create a thread that display the time on the screen continuously, till enter button
is pressed.
11. Create a parallel server using 3 or 4 threads that can serve several clients
simultaneously.
User can interact with application in two ways.
1. CUI (Character User Interface): - In CUI the user can interact with the application
by typing the characters. The user cannot remember all commands every time in
CUI.
2. GUI (Graphic User Interface): - If the user interacts with the application through
graphics (Pictures/Images/…..).
Advantages of GUI: -
1. GUI is user friendly.
2. GUI makes an application more attractive.
3. Using GUI we can simulate real objects.
Components means Push Buttons, Radio Buttons, Check boxes,…
java.awt package: - AWT Standards for Abstract Window Toolkit. It is a package
that provides a set of classes and interfaces to create GUI components.
- - - label
|
- - - Button
|
Advanced Java
Page 65 of 148 rambabumandalapu@yahoo.com
- - - Checkbox
|
- - - Choice
|
Object- - -Component- - - - - - - List
| |
CheckBoxGroup - - - Canvas
|
- - - Scrollbar - - - TextFiled
|
- - - TextComponent - - -
|
- - - Container - - - TextArea
Panel Window
Applet Frame
Layout manager is an interface that arranges the components on the screen.
Layout manager is implemented in the following classes.
- - - FlowLayout
|
- - - BorderLayout
|
Object - - - - - - - - GridLayout
|
- - - CardLayout
|
- - - GridBagLayout
A frame is a top level window that is not contained in another window.
A window represents the some rectangular part on the screen.
What is the difference between window and frame? *****
Advanced Java
Page 66 of 148 rambabumandalapu@yahoo.com
Ans: - A window represents a rectangular part of the screen.
A frame is a window with title bar and some button to minimize, maximize or
close i.e. is called frame.
Pixel is a short form of a picture each dot (.) is a pixel. Pixel means picture
element.
Creating a frame: -
1. Create an object to frame class.
Ex: - Frame f = new Frame();
2. Write a class that extends a frame and then creates an object to that class.
Ex: - class MyFrame extends Frame
MyFrame f = new MyFrame();
This is advantageous than 1st method.
Ex: - //creating a frame
import java.awt.*;
class MyFrame
{
public static void main(String args[ ])
{
//create an object to Frame class
Frame f = new Frame();
//increase the size of frame
f.setSize(400,300);
//display the frame
f.setVisible(true); (or) f.show();
}
}
Components are to display but not to perform any task.
Ex: - //creating a frame –version-2.0.
import java.awt.*;
class MyFrame extends Frame
{
public static void main(String args[ ])
{
(x, y)
(0, 0)
(0, 600)
* (10, 500)
*(400, 300)
(800, 0)
(800, 600)
Advanced Java
Page 67 of 148 rambabumandalapu@yahoo.com
//create an object to frame class
MyFrame f = new MyFrame();
//increase the size of frame
f.setSize(400,300);
//display the title
f.steTitle(“My AWT Frame”);
//display the frame
f.setVisible(true); (or) f.show();
}
}
Event: - User interaction with the component is called Event.
Ex: - Clicking, Double Clicking, Pressing a key, moving the mouse and dragging the
item.
Listener: - Listener is an interface that will added to the component. It is listen to the
event.
What is Event Delegation model? *****
Ans: - Events are generated by user to perform a task. The component will delegate
the event to a listener. The listener will delegate the event to the method and finally
the method will handle the event. This is called Event Delegation model.
Delegation means handing over the work to another.
Event delegation model separate/isolated presentation logic and business
logic. A programmer can modify one part without affecting the other part. Each logic
can be developed using different technologies.
To close the frame: -
1. Attach a WindowListener to the frame. A Listener is an interface.
2. Implement all the methods of WindowListener interface.
3. When an event is generated a relevant method is called and executed by the
Listener.
Ok listener
Advanced Java
Page 68 of 148 rambabumandalapu@yahoo.com
Ex: - //creation of frame and closing the frame
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
public static void main(String args[ ])
{
//create an obj to Frame class
MyFrame f = new MyFrame();
//increase the size of frame
f.setSize(400,300);
//display the title
f.steTitle(“My AWT Frame”);
//display the frame
f.setVisible(true); (or) f.show();
//attach a WindowListener to the frame
//f.addWindowListener(WindowListener obj);
f.addWindowListener(new Myclass());
}
}
class Myclass implements WindowListener
{
public void windowActivated(windowEvent e){ }
public void windowClosed(windowEvent e){ }
public void windowClosing(windowEvent e){ }
{
System.exit(0);
}
public void windowDeactivated(windowEvent e){ }
public void windowDeiconified(windowEvent e){ }
public void windowIconified(windowEvent e){ }
public void windowOpended(windowEvent e){ }
} (or)
Ex: - //creation of frame and closing the frame
Advanced Java
Page 69 of 148 rambabumandalapu@yahoo.com
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
public static void main(String args[ ])
{
//create an obj to Frame class
MyFrame f = new MyFrame();
//increase the size of frame
f.setSize(400,300);
//display the title
f.steTitle(“My AWT Frame”);
//display the frame
f.setVisible(true); (or) f.show();
//attach a WindowListener to the frame
f.addWindowListener(new WindowAdaptor()
{
public void windowClosing(windowEvent we)
{
System.exit(0);
}
});
}
}
class Myclass implements WindowAdaptor
{
public void windowClosing(windowEvent e){ }
{
System.exit(0);
}
}
What is adaptor class? *****
Advanced Java
Page 70 of 148 rambabumandalapu@yahoo.com
Ans: - An adaptor class is similar to an interface, which contains empty implements
of all the methods of the interface. WindowAdaptor is the adaptor class interface.
What is anonymous inner class? *****
Ans: - It is an inner class whose name is hidden to outer class and for only which is
created.
A Frame is used to display following things
1. Messages
2. To display images/photos/icons/.gif files
3. To display components (Radio buttons, push buttons, check buttons etc…)
Displaying the messages in the Frame: - For this purpose we should use
drawString() method of graphics class.
Ex: - g.drawString(“Message”, x, y);
Here x, y are coordinates of pixels.
Ex: - //Displaying a message in the frame
import java.awt.*;
import java.awt.event*;
class Message extends Frame
{
//vars
//Default Constructor
Message()
{
//write code to close the frame
this.addWindowListener(new windowAdaptor()
{
public void windowClosing(windowEvent e)
{
System.exit(0);
}
});
} //end of constructor
Advanced Java
Page 71 of 148 rambabumandalapu@yahoo.com
public void paint(Graphics g)
{
//set a background color for frame
this.setBackground(new color(100,20,20);
//set a text color
set.Color(Color.green);
//set a font for text
Font f = new Font(“Helvetica”, Font.BOLD+Font.ITALIC, 35);
g.setFont(f);
//now display the messages
g.drawString(“Hello Students”, 20, 100);
}
public static void main(String args[ ])
{
//create the frame
Message m = new Message();
//set the size of frame
m.setSize(500,400);
//set a title to the frame
m.steTitle(“My message”);
//display the frame
m.setVisible(true); (or) m.show();
}
} (or)
Ex: - //Displaying a message in the frame
import java.awt.*;
import java.awt.event.*;
class Message extends Frame
{
//vars
//Default Constructor
Message()
{
//write code to close the frame
Advanced Java
Page 72 of 148 rambabumandalapu@yahoo.com
addWindowListener(new windowAdaptor()
{
public void windowClosing(windowEvent e)
{
System.exit(0);
}
});
} //end of constructor
public void paint(Graphics g)
{
//set a background color for frame
setBackground(new color(100,20,20);
//set a text color
set.Color(Color.green);
//set a font for text
Font f = new Font(“Helvetica”, Font.BOLD+Font.ITALIC, 35);
g.setFont(f);
//now display the messages
g.drawString(“Hello Students”, 20, 100);
}
public static void main(String args[ ])
{
//create the frame
Message m = new Message();
//set the size of frame
m.setSize(500,400);
//set a title to the frame
m.steTitle(“My message”);
//display the frame
m.setVisible(true); (or) m.show();
}
}
To specify a color in awt: -
1. We can directly specify a color name from color class.
Advanced Java
Page 73 of 148 rambabumandalapu@yahoo.com
Ex: - Color.yellow, Color.red, Color.gray etc…
Here Color is a class, yellow is variable.
2. By creating color class object with a combination of red, green, blue values
Ex: - Color c = new Color(r,g,b);
R,G,B, values are varies from 0 – 255.
Ex: - Color c = new Color(255,0,0);
Color c = new Color(25,0,0);
Color c = new Color(0,0,0); It is a black color
Color c = new Color(255,255,255); It is pure white color
Color c = new Color(100,20,20); it is snuff color
In font there will be three types they are
1. Font.BOLD 2. Font.ITALIC 3. Font.PLAIN
In the above program public void paint(Graphics g)
paint() method belongs to component class.
Graphics is an Abstract class.
g is an object.
GIF – Graphic image format
JPEG – Joint photographer’s expert group
MPEG – Motion pictures expert group. (or) Moving pictures expert group
To display image in a frame for this purpose we should use drawImage of
graphic class.
g.drawImage(image, x, y, Image observer obj);
Image observer containing the address of the image and history of the image.
Ex: - //To display an image
import java.awt.*;
import java.awt.event*;
class Message extends Frame
{
//vars
static Image img; //QImage is a class name & img is a variable.
//Default Constructor
Images()
{
//Load an image into img
50
setIconImage()
drawImage()
50
Advanced Java
Page 74 of 148 rambabumandalapu@yahoo.com
img = Toolkit.getDefaultToolkit().getImage(“twist.gif”);
//To keep the processor with till image is loaded into image.
MediaTracker track = new MediaTracker(this); //Q’this’ is a current class object.
//now add image to track
track.addImage(img, 0); //Q Here ‘0’ is Image ID No.
//wait till the image is loaded
try{
track.waitForID(0);
}catch(InterrputedException ie){ }
//close the frame
addWindowListener(new windowAdaptor()
{
public void windowClosing(windowEvent e)
{
System.exit(0);
}
});
} //close constructor
public void paint(Graphics g)
{
//Display the image in frame
g.drawImage(img, 50, 50, null);
}
public static void main(String[ ] args)
{
//create the frame
Image i = new Image();
//set the size of frame
i.setSize(500,400);
//set a title to the frame
i.steTitle(“My Image”);
//display the image in the title bar
i.setIconImage(img);
//display the frame
Advanced Java
Page 75 of 148 rambabumandalapu@yahoo.com
i.setVisible (true); (or) i.show();
}
} (or)
Ex: - //To display an image
import java.awt.*;
import java.awt.event.*;
class Message extends Frame
{
//vars
static Image img; //QImage is a class name & img is a variable.
//Default Constructor
Images()
{
//Load an image into img
img = Toolkit.getDefaultToolkit().getImage(“twist.gif”);
//To keep the processor with till image is loaded into image.
MediaTracker track = new MediaTracker(this); //Q’this’ is a current class object.
//now add image to track
track.addImage(img, 0); //Q Here ‘0’ is Image ID No.
//wait till the image is loaded
try{
track.waitForID(0);
}catch(InterrputedException ie){ }
//close the frame
addWindowListener(new windowAdaptor()
{
public void windowClosing(windowEvent we)
{
System.exit(0);
}
});
} //close constructor
public void paint(Graphics g)
{
Advanced Java
Page 76 of 148 rambabumandalapu@yahoo.com
//Display the image in frame
g.drawImage(img, 50, 50, 300, 350, null); //Q300, 350 are x,y, pixels
}
public static void main(String[ ] args)
{
//create the frame
Image i = new Image();
//set the size of frame
i.setSize(500,400);
//set a title to the frame
i.steTitle(“My Image”);
//display the image in the title bar
i.setIconImage(img);
//display the frame
i.setVisible(true); (or) i.show();
}
}
Button: - Button class is useful to create push buttons. A push button triggers a
series of events.
1. To create a push button with a label
Button b = new Button(“label”); // Qlabel -The text will displayed on the button.
2. To get the label of the button
String l = b.getLabel();
3. To set the label of the button:
b.setLabel(“label”);
4. To get the label of the button clicked:
String s = ae.getActionCommand(); //QHere ae is object of ActionEvent.
Listeners: - A Listener is an interface that listens to an event from component.
Listeners are in java.awt.event package.
S. No. Component Listener Listener Methods
1. Button ActionListener actionPerformed(ActionEvent e)
2. CheckBox ItemListener itemStateChanged(ItemEvent e)
Advanced Java
Page 77 of 148 rambabumandalapu@yahoo.com
3. CheckBoxGroup ItemListener
4. Label - - -
5. TextField ActionListener (or)
FocusListener
focusGained(FocusEvent e)
6. TextArea ActionListener (or)
FocusListener
7. Choice ItemListener (or)
ActionListener
8. List ItemListener (or)
ActionListener
9. Scrollbar AdjustmentListener(or)
MouseMotionListener
adjustmentValueChanged(adjuste
ment e)
mouseDragged(MouseEvent e)
mouseMoved(MouseEvent e)
Note 1: - The above all Listener methods are all ‘public void’ methods.
Note 2: - A Listener can be added to a component using addxxxListener() method.
Ex: - addActionListener();
Note 3: - A Listener can be removed from a component using removexxxListener()
method.
Ex: - removeActionListener();
Note 4: - A Listener takes an object of xxxEvent class.
Ex: - actionPerformed(ActionEvent e);
Ex: - //Push Buttons
import java.awt.*;
import java.awt.event.*;
class MyButton extends Frame implenets ActionListener
{
//vars
Button b1, b2, b3;
//Default Constructor
MyButton()
{
Advanced Java
Page 78 of 148 rambabumandalapu@yahoo.com
//donot set any layout manager
setLayput(new FlowLayout()); // (or) setLayout(null); Here null means not
setting any Layout.
//Create 3 push buttons
b1 = new Button(“Yellow”);
b2 = new Button(“Blue”);
b3 = new Button(“Pink”);
//set position of these buttons
b1 = setBounds(50, 100, 75, 40); /*Here 50, 100 are x, y coordinates where
the buttons should place in the frame., 75 is the width of button, 40 is the height of
the button.*/
b2 = setBounds(50, 150, 75, 40);
b3 = setBounds(50, 200, 75, 40);
//add these buttons to the frame
add(b1);
add(b2);
add(b3);
//add action listener to the frame
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
//close the frame
addWindowListener(new windowAdaptor()
{
public void windowClosing(windowEvent we)
{
System.exit(0);
}
});
} //close constructor
public void actionPerformed(ActionEvent ae)
{
//Know which button is clicked
String str = ae.getActionCommand();
Advanced Java
Page 79 of 148 rambabumandalapu@yahoo.com
if(str.equals(“Yellow”))
setBackground(Color.yellow);
if(str.equals(“Blue”))
setBackground(Color.blue);
if(str.equals(“Pink”))
setBackground(Color.pink);
}
public static void main(String args[ ])
{
//create the frame
MyButton mb = new MyButton();
//set the size of frame
mb.setSize(500,400);
//set a title to the frame
mb.steTitle(“My Push Buttons”);
//display the frame
mb.setVisible(true); (or) mb.show();
}
}
What is default layout manager in frame? *****
Ans: - BorderLayout manger
What is default layout manager in Applets? *****
Ans: - FlowLayout manager
What is default layout manager in Panel? *****
Ans: - FlowLayout manager
Frame: - Frame is also a component. A frame is a top level window that oes not
contain in another window. It is a container to place the components.
1. To create a Frame, extend your class to Frame class. Then create an object to our
class.
Advanced Java
Page 80 of 148 rambabumandalapu@yahoo.com
2. To set a title for the frame, use setTitle()
3. To set a size for the frame, use setSize()
4. To display the frame, use show() (or) setVisible()
Refreshing the contents of a Frame: -
5. The component class got a method paint() that paints (refreshes) the area in a
frame.
Displays text in a Frame: -
6. Use Graphics class method: drawString()
Displaying images in a Frame: -
7. Use Graphics class method: drawImage()
About components (Component class methods): -
8. An component can be added to a frame using add()
9. A component can be removed from a frame using remove()
10. All components can removed from frame using removeAll()
11. Any component can be displayed using setVisible(true)
12. A component can be disappeared using setVisible(false)
13. A component’s colors can be set using
setBackground()
setForeground()
14. Font for the displayed text on the component can be set with setFont();.
15. A component can be placed in a particular location in the Frame with
setBounds();.
Creating Font: -
Font f = new Font();
setFont(f); //Component class methods also in Graphics class.
Creating Color: -
Ex 1: - setColor(Color.yellow);
Ex 2: - Color c = new Color(255, 0, 0);
//Q(255, 0, 0) are R, G, B, Values respectively
setColor(c);
Maximum size of screen in pixels: -
1024 x 768, (or) 800 x 600 (or) 640 x 480
Advanced Java
Page 81 of 148 rambabumandalapu@yahoo.com
Check box: - A check box is a square shape box, which provides a set of options to
the user.
1. To create a check box:
Checkbox cb = new Checkbox(“label”);
2. To create a checked checkbox:
Checkbox cb = new Checkbox(“label”, null, true);
Here ‘null’ is checkbox group object.
3. To get the state of a checkbox
boolean b = cb.getState();
4. To get the state of Checkbox
cb.setState(true);
5. To get the label of a checkbox
String s = cb.getLabel();
6. To get the selected checkbox label into an array we can use getSelectedObjects();
method. This method returns an array size 1 only.
Object x[ ] = cb.getSelectedObjects();
Ex: - //CheckBoxes
import java.awt.*;
import java.awt.event.*;
class MyCheckbox extends Frame implements ItemListener
{
//Variables
Checkbox c1, c2, c3;
String msg = “ “;
MyCheckbox()
{
//Set flow layout manager
setLayout(new FlowLayout());
//Create 3 check boxes
c1 = new Checkbox(“Bold”, null, true);
c1 = new Checkbox(“Italic”);
c1 = new Checkbox(“Underline”);
//Add checkboxes to frame
add(c1);
Advanced Java
Page 82 of 148 rambabumandalapu@yahoo.com
add(c2);
add(c3);
//Add item listeners to checkboxes
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
//close the frame
addWindowListener(new windowAdaptor()
{
public void windowClosing(windowEvent we)
{
System.exit(0);
}
});
}
public void itemStateChanged(ItemEvent ie)
{
repaint(); // (or) call paint();
}
public void paint(Graphics g)
{
//Display the status of check boxes
g.drawString(“Status of Checkboxes”, 200, 100);
msg = “Bold: ”+e1.getState();
g.drawString(msg, 20, 120); //Q 20, 120 are x, coordinates
msg = “Italic: ”+e2.getState();
g.drawString(msg, 20, 140);
msg = “Underline: ”+e3.getState();
g.drawString(msg, 20, 160);
}
public static void main(String args[ ])
{
//Create Frame
MyCheckbox mc = new MyCheckbox();
Advanced Java
Page 83 of 148 rambabumandalapu@yahoo.com
//Set size and title
mc.setSize(500, 400);
mc.setTitle(“My Check Boxes);
//Display the frame
mc.setVisible(true);
}
}
Save it as MyCheckbox.java.
Which method is called by repaint() method? *****
Ans: - repaint(); method calls update() method. Then update() method will calls the
paint() method.
How can reduce in graphics or awt or frames? *****
Ans: - By overridingUpadte() method in specifying background color in update()
method.
Choice menu (or) Choice Box: - Choice is a popup list of items. Only one item can
be selected.
1. To create a choice menu
Choice ch = new Choice();
2. To ad items to the choice menu
ch.add(“text”);
3. To know the name of the item selected from the choice menu
String s = ch.getSelectedItem();
4. To know the index of the currently selected item
int i = ch.getSelectedIndex();
This method returns -1 if nothing is selected.
Ex: - //Choice Box
import java.awt.*;
import java.awt.event.*;
class MyChoice extends Frame implements ItemListener
{
Advanced Java
Page 84 of 148 rambabumandalapu@yahoo.com
//Variables
String msg;
Choice ch;
MyChoice()
{
//Set flow layout manager
setLayout(new FlowLayout());
ch = new Choice();
//add items to choice box
ch.add(“Idly”);
ch.add(“Dosee”);
ch.add(“Chapathi”);
ch.add(“Veg Biryani”);
ch.add(“Parata”);
//Add the Choice box to the frame
add(ch);
//ad item listener to the choice box
ch.addItemListener(this);
//Window closing
addWindowListener(new windowAdaptor()
{
public void windowClosing(windowEvent we)
{
System.exit(0);
}
});
}
public void itemStateChanged(ItemEvent ie)
{
//call the paint()
repaint(); // (or) call paint();
}
public void paint(Graphics g)
{
Advanced Java
Page 85 of 148 rambabumandalapu@yahoo.com
//know the user selected item
msg = ch.getSelectedItem();
g.drawString(“Selected item: ”, 10,150);
g.drawString(msg, 10,170);
}
public static void main(String args[ ])
{
//Create Frame
MyChoice mc = new MyChoice();
//Set size and title
mc.setSize(500, 400);
mc.setTitle(“My Choice menu”);
//Display the frame
mc.setVisible(true);
}
} (or)
Save the above code as MyChoice.java
//Choice Box
import java.awt.*;
import java.awt.event.*;
class MyChoice extends Frame implements ItemListener
{
//Variables
String msg[ ];
List ch;
MyChoice()
{
//Set flow layout manager
setLayout(new FlowLayout());
ch = new List(3, true);
//add items to choice box
ch.add(“Idly”);
ch.add(“Dosee”);
ch.add(“Chapathi”);
Advanced Java
Page 86 of 148 rambabumandalapu@yahoo.com
ch.add(“Veg Biryani”);
ch.add(“Parata”);
//Add the Choice box to the frame
add(ch);
//ad item listener to the choice box
ch.addItemListener(this);
//Window closing
addWindowListener(new windowAdaptor()
{
public void windowClosing(windowEvent we)
{
System.exit(0);
}
});
}
public void itemStateChanged(ItemEvent ie)
{
//call the paint()
repaint(); // (or) call paint();
}
public void paint(Graphics g)
{
//know the user selected item
msg = ch.getSelectedItems();
g.drawString(“Selected items: ”, 10,150);
for(int i = 0; i
Save it as x.html.
Open IntenetExplorer page.
Applet viewer is a tool to test the applet. It is developed by the (Software
people) Sum Microsystem.
F:\rnr>appletviewer x.html¿ (Q Where as appletviewer is a tool in J2SDK)
IIS – Internet Informat Server.
Hyper text means the text that uses hyperlink to directly jump to any piece of
information.
tag specify the text, that is hyper link.