You are on page 1of 148

Advanced Java

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(……); }

Java.util Package Collections class Collections obj

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.

Page 1 of 148

rambabumandalapu@yahoo.com

Advanced Java 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. 1. 2. 3. 4. 5. 6. 7. 8. Set List Map SortedSet SortedMap Iterator ListIterator Enumeration Interfaces ArrayList Vector LinedList HashSet TreeSet Collections LinkedHashSet HashMap Collection Classes Collection objects

Page 2 of 148

rambabumandalapu@yahoo.com

Advanced Java 9. 10. 11. TreeMap HashTable 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.
Page 3 of 148

rambabumandalapu@yahoo.com

They are 1. hasNext().iterator(). //Find number of elements in arl System.add(“Banana”). hasPrevious().remove(“Apple”).out. //Display the content of ArrayList (or) in arl System. next().out. //Add elements to arl arl.add(“Guava”).println(“Size of Array list = ” +arl. and previousIndex() //Θ Apple. ListIterator 1. Iterator supports add().remove(2). arl. which are useful to retrieve the objects or elements one by one from array list.out. arl. ListIterator 3.com .out. arl. //Use Terator to retrieve elements Iterator it = arl. previous(). Grapes. arl.hasNext()) System. //Display the content of ArrayList (or) in arl System. Banana …are objects Page 4 of 148 rambabumandalapu@yahoo. Guava. } } There are three types of interfaces are available.Advanced Java ArrayList arl = new ArrayList().add(“Apple”).add(“Grapes”). //Remove elements arl. set(). while(it. Iterator supports only hasNext().add(“Mango”).println(“Array list = ” +arl).size()).println(“Array list = ” +arl). next() and remove() methods. arl.println(it.next()). nextIndex(). Iterator 2. Enumeration What are the difference between Iterator and ListIterator: Iterator 1.

4. obj). 2. use size() method. HashMap. 5. 3. v. 2. 4. Iterator is a super interface 2. It is not synchronized.add(2. To create a vector Vector v = new Vector(). Enumeration doesn’t supports ArrayList. 3. Vectors are suitable objects. Enumeration doesn’t supports a remove() method. 2. When the object is synchronized then we will get reliable results or values.size(). What are the difference between Iterator and Enumeration: Iterator 1. Iterator supports ArrayList. 3. ListIterator is the sub interface of Iterator super interface. To remove elements use remove() method v. v.add(obj). Vector. Vector v = new Vector (100).get(2). HashMap. Enumeration 1. Iterator supports a remove() method. nextElement(). It supports legacy methods like as hasMoreElements().remove(2). But it is synchronized.com . To know the size of Vector. 4. To retrieve elements use get() method v. Access the collections in the forward direction only. Access the collections in forward and backward directions. Vector: . 1. HashTable. To add elements use add() method.It is a dynamically growing array that stores objects. 3. 3. int n = v. 2. It doesn’t supports legacy methods.Advanced Java remove() methods. It is synchronized. To remove all elements Page 5 of 148 rambabumandalapu@yahoo.

22.size(). 7. //Retrieve elements using ListIterator Page 6 of 148 rambabumandalapu@yahoo.add(new Integer(x[ i ])). ArrayList is not synchronized by default. but by using some methods we can synchronized the ArrayList.out. i++) System. Increases the capacity of this vector. to ensure that it can hold at least the number of components specified by the minimum capacity argument. if necessary. intdexOf(obj). To search for last occurrence of an element use lastIndexOf() method int n = v . it will maintains and gives the same order what we have added the elements to the Vector. i< x.com . 6. void ensureCapacity(int minCapacity). lastIndexOf(obj).*. List myList = Collections.util. 60. //Retrieve and display the elements for(int i = 0. class VectorDemo { public static void main(String args[ ]) { //Create an empty Vector Vector v = new Vector (). When we are retreiveing the elements from Vector. i< v.clear(). 33. Vector doesn’t supports the null values.synchronizedList(myList). //Take (an one dimensional) int type array int x [ ] = {10. use capacity() method int n = v. 9. 44. i++) v. 100}. Ex: . //Read int values from x and store into v for(int i = 0.Advanced Java v. To know the current capacity. Vector is synchronized default.get(i)).lenght().println(v.capacity().//A Vector of int values import java. To search for last occurrence of an element use indexOf() method int n = v . 8.

It is efficient than Vector. listIterator(). System. Capacity = 11. 3. 6. listIterator() is a method System. 1. To create a HashTable HashTable ht = new HashTable(). 4. The default capacity of vector is 10.com . while(lit. Keys must be unique and keys cannot allow duplicate values. ArrayList supports only Iterator Vector 1.out.Hashtable stores object in the form of keys and value pairs. } } What are differences between ArrayList and Vector: ArrayList 1. 2. 4.Advanced Java ListIterator lit = v. It is synchronized. HashTable: . 5.out. Vector supports Iterator and interface.75 HashTable ht = new HashTable(100). It is not synchronized. Vector supports the capacity(). 3.hasNext()) System. capacity(). //Θ In the above statement ListIterator is an Interface. while(lit. due to ArrayList is fast iterartion and fast random access. load factor = 0. ArrayList doesn’t supports the legacy methods.previous() + “\t”).print (lit.A map represents storage of elements in the form of the key and value pairs.next() +“\t”). ArrayList doesn’t supports the enumeration interfaces.previous()) System. Maps: .print(lit. 6.println(“In forward direction: ” ). 2. nextElement(). 5. Page 7 of 148 //Initial rambabumandalapu@yahoo. Its default capacity is 10.out.out. Vector is dynamically growing array that stores objects. it is slower than ArrayList due to its synchronized methods. It is synchronized. It is not efficient than ArrayList.println (“\n In reverse direction: ”). Vector supports the legacy methods like hasMoreElements(). An ArrayList is dynamically growing array that stores objects.

Initial capacity = 11.//HashTable with Cricket Scores import java.size(). ht. Ex: . new Integer(125)). ht.put(“Dhoni”. int n = ht. class HashtableDemo { public static void main(String args[ ]) throws IOException { //Create an empty hash table HashTable ht = new HashTable(). ht. 4. To store key-Value pair the HashTable ht.remove(“Sachin”). To get the value when is given ht.*.Load factor determines the point at which the capacity of HashTable or HashMap will be automatically doubled. 3.e. Page 8 of 148 rambabumandalapu@yahoo.put(“Kapil”.put(“Amarnadh”.com .75) = 8 i.e. Score //Θ Here Player Name is Key and Score is a Value ht. new Integer(150)). 5.io. Ex: .put(“Sachin”.util.put(“Sachin”. What is load factor? ***** Ans: . this value depends on the version. “Cricket Player”). To know the number of keys in the HashTable. new Integer(50)).Advanced Java 2. To clear all the keys. //Store Player Name. To remove the key (and its corresponding value) ht.*. ht. 6.get(“Sachin”). import java. After storing 8th pair the capacity of the HashTable will be doubled i.For HashTable initial capacity (11) X load factor (0. new Integer(175)).clear(). becomes 22 (11 x 2).

Advanced Java ht. While(e.out.out. String name = br.com .out.println(ht.put("3".= "+ht). "Babu").println(e.put("0".intValue().out.println(ht. ht. Page 9 of 148 rambabumandalapu@yahoo. System. new Integer(86)).*.get(name). if(score!=null) { int runs = score.println(“Enter Player Name: ”).put("2".hasMoreElements()) System. //Find number of runs of this player Integer score = (Integer) ht.put(“Ganguly”.in)).keys(). } else System. //Θ In the above statement (System.put("1". } } Ex 2: import java.util. System. public class DemoHashTable { public static void main(String[] args) { Hashtable ht=new Hashtable().println(“Player not found”).in) represents Keyboard System.out. System.get("2")).println(“Player Name: ”).out. "Mogili"). //Ask for Player Name from Keyboard BufferedReader br = new BufferedReader(InputStreamReader(System. System. "Anand").readLine().get("1")).nextElement()). "@Marlabs").println("---Retreiveing the elements--. ht.out. ht. System.out.println(Name+”Scored runs = ”+runs). //Retrieve all keys Enumeration e = ht. ht.

out.Advanced Java System. public class DemoHashTable { public static void main(String[] args) { Hashtable ht=new Hashtable().= {3=Mogili.util.com . ht. } Enumeration e1=ht.elements().println(ht.hasMoreElements()){ System.nextElement()). Page 10 of 148 rambabumandalapu@yahoo. 2=Anand.hasMoreElements()){ System.println("---Retreving the elements using enumeration from HashTable = "+e. Enumeration e=ht.out.nextElement()).put("1".println("---Retreving the keys using enumeration from HashTable = "+e1.out.keys(). 1=Babu.println(ht.*. while(e1. System. } } } O/P: ---Retreiveing the elements--. 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. "Babu").out.get("0")). while(e.get("3")).

HashMap stores objects in the form of keys and value pairs. Playernames are all keys and scores are all values. IOException may caused by readLine() method.out.Advanced Java ht.out.println("---Retreving HashTable = "+e. To create a HashMap Page 11 of 148 the elements using enumeration from rambabumandalapu@yahoo.out.println("---Retreving the keys using enumeration from HashTable = "+e1.get("3")). System.out. "Mogili"). while(e.vara. System. } } } O/P: Exception in thread "main" java.com .out.nextElement()). while(e1.get("2")).marlabs. Enumeration e=ht.get("0")).elements().out. "Anand"). IO stands for input/output.keys(). (or) ht.get("1")). System.NullPointerException at java.main(DemoHashTable.println(ht. 1. ht.= "+ht). It is not synchronized. ht.put("3". In HashTable duplicate keys are not allowed but duplicate values are allowed.DemoHashTable.java:7 Enumeration will not maintain objects in the same order.put(Unknown Source) at com. System.println("---Retreiveing the elements--.Hashtable. HashMap: .println(ht.out.put(“2”.hasMoreElements()){ System. When we retreving the elements or keys using HashTable it will gives the elements or keys in revrse order only.util.nextElement()). } Enumeration e1=ht.println(ht. System. null).put(null. "@Marlabs").hasMoreElements()){ System.lang.put("0".println(ht.

“Cricket Player”).remove(“Sachin”). 3. 5. int n = hm. Ex: .size().clear(). String name.com . In HashMap duplicate keys are not allowed but duplicate values are allowed.synchronizedMap(myMap).util. import java.*. //Menu Page 12 of 148 rambabumandalapu@yahoo. Map myMap = Collections. not even the same order that we have added keys and elements. To know the number of key-value pairs in the HashMap. //Initial Capacity = 16. str. BufferedReader br = new BufferedReader(InputStreamReader(System.put(“Sachin”. Long phno. class Tele { public static void main(String args[ ]) throws IOException { //Vars HashMap hm = new HashMap(). To remove the key (and its corresponding value) hm.Advanced Java HashMap hm = new HashMap(). 2.in)).get(“Sachin”).io. hm. To clear all the keys. load factor = 0. To get the value when is given hm.//Telephone entry book import java. 4. 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.*. 6. To store key-Value pair the HashMap hm.75 HashMap hm = new HashMap(101).

print(“Enter Person Name: ”). phno = (Long)hm.out. ”). break. } } } } Ex 1: import java. default: return.print(“Enter Person Name”).out. //Depending on n value.out. //Pass name to hm and get the Phone No. int n = Integer.*.Advanced Java while(true) //It is an infinite loop { System.print(“Enter Phone No. case 2: System. System.println(“1 Enter entries into Phone Book”).println(“Phone No: ”+phno). public class DemoHashmap { Page 13 of 148 rambabumandalapu@yahoo. perform a task switch(n) { case 1: System.readLine()).out. System. //Convert str into Long obj phno = new Long(str).get(name).com .println(“3 Exit”).parseInt(br.out.out.readLine().out. str = br. name = br. System.println(“2 Lookup for a Phone Number”).readLine(). Name = br. System.util. //Store name. phone in hm break.readLine().

*.println("---HasMap initial size---"+hm. System.get("2")).put("3".println(hm.println("---HasMap size---"+hm. } } O/P: ---HasMap initial size---0 ---HasMap size---4 ---Retrieving the elements HasMap---{3=anand.hasNext()) System. 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.next()). hm. hm.size()).com . "bujji").out. System.get("4")).put("2". System.size()). 4=bujji.out.out.out.keySet(). Set s=hm. hm.println(hm.println(hm. System.out.out.Advanced Java public static void main(String args[]){ HashMap hm=new HashMap(). Iterator it=s. System.println("---Retrieving the elements HasMap---"+hm).get("1")).println(hm. "anji").iterator(). System.println("Retreiveing the Keys = "+it.util. public class DemoHashmap { Page 14 of 148 rambabumandalapu@yahoo.out. 2=anji. hm. System. "anand").put("1".put("4". while(it.out.get("3")). "Vara").

Advanced Java public static void main(String args[]){ HashMap hm=new HashMap().iterator(). hm.put("1".out.next()). null).println(hm.get("3")).out. Set s=hm. System.println("---Retrieving the elements HasMap---"+hm). System.out.println(hm.get("4")).keySet().println(hm.get("1")). hm. System.get("2")).out. "bujji"). System. System.out.println(hm. hm.size()). "Vara"). System. Iterator it=s.put("4".hasNext()) System.com . System. 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: - Page 15 of 148 rambabumandalapu@yahoo.put(null.out. while(it.println("---HasMap initial size---"+hm. null). hm.out. 4=bujji.println("Retreiveing the Keys = "+it. } } O/P: ---HasMap initial size---0 ---HasMap size---4 ---Retrieving the elements HasMap---{null=null.out. 3=null.put("3".println("---HasMap size---"+hm.size()).

booleab x = st. StringTokenizer st = new StringTokenizer(str. To find the next piece in the string. StringTokenizer: . int no = st.countTokens(). :”). “. 4. It doesn’t supports legacy methods. It is not synchronized. String piece = st. HashMap initial capacity is 16 and the capacity of HashMap depends on version of Java. 7.nextToken(). (key/value pairs) so it is efficient than HashTable. It stores the objects in the form of key and value pairs. To know if more pieces are remaining. 4. HashTable supports Iterator and enumeration interfaces. HashTable maintained the orderd of elements in reverse. 1. 8. “delimiter”). nextElement(). It supports legacy methods like hasMoreElement(). To know how many number of pieces are there. 2. 3. It will makes fastest updates HashTable 1.com . : are called as delimiters (or) (or) 2. called tokens. It supports only Iterator interface. “.”). 5. It is not efficient than HashMap due to its synchronized methods. HashTable doesn’t takes null keys and null values. not even the keys and the elements added to it. Page 16 of 148 rambabumandalapu@yahoo. 3.hasMoreTokens(). 7. To create an object to StringTokenizer StringTokenizer st = new StringTokenizer(str.Advanced Java HashMap 1. 4. 2. 8. 5. HashMap doesn’t maintained the orderd of elements.The StringTokenizer class is useful to break a string into small pieces. It stores the objects in the form of key and value pairs. 6. It is synchronized. 3. Θ Here . 6. StringTokenizer st = new StringTokenizer(str. HapMap takes only one null key and many null values. HashTable initial capacity is 11 and the capacity of HashTable depends on version of Java.

} } } (or) //Cutting the string into pieces import java.hasMoreTokens()) { Page 17 of 148 rambabumandalapu@yahoo.hasMoreTokens()) { String s1 = st. “ ”). class STDemo { public static void main(String args[ ]) { //Take a string String str = “It. //retrieve the pieces and display System. “.println(“The token are: ”).Advanced Java Token means piece of string.out. Ex: . System.out. //retrieve the pieces and display System.*.out.*. 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.println(“The token are: ”).com . : ”).util. called New: Delhi”.println(s1).nextToken().//Cutting the string into pieces import java. while(st. while(st. //brake the string into species StringTokenizer st = new StringTokenizer(str.util. is our: capital city.

To convert a date into string.HOUR Calendar.toString(). date & time.hasMoreTokens().DATE Calendar.This class is useful to handle.10). cl. //Default counting of January month starts with 0 booleab x = st. } } } Form Name Address Server Section Name Ok Calendar: . 2.YEAR Calendar. cl.get(constant). Use set() to get the date or time in the calendar object.MINUTE Calendar. Use get() method to retrieve date or time from calendar object. This method returns an integer. Gregorian calendar is another type class like as calendar class.MONTH Calendar.out.nextToken(). 4.com . use toString().SECOND 3. To create an object to calendar class: Calendar cl = Calendar. Page 18 of 148 rambabumandalapu@yahoo. System.MONTH. Note: Constants: Calendar.Advanced Java String s1 = st.set(calendar.println(s1).getInstance(). cl. This method returns a string. 1.

MONTH). int yy = cl.Advanced Java Ex: .get(Calendar. formatconst region). int mm = cl.getInstance().HOUR). This is in java.UK).getDateInstance(formatconst.out. Date d = new Date().DateFormat fmt = DateFormat.get(Calendar.get(Calendar. Syntax: .Medium. 2.Medium. To create an object to Date class. 1.println(“System time: ”). System. Θ Here region is the place/the country. Ex: .getDateInstance(DateFormat. } } Date Class: .getDateInstance(formatconst.out.DateFormat fmt = DateFormat.out. Ex:-DateFormat fmt=DateFormat.println(h+ “:” +m+ “:” +s)).*. System. System.DateFormat fmt = DateFormat. region). int s = cl.YEAR). //retrieve time details int h = cl.MINUTE). Format the date and times using getDateInstance() or getDateTimeInstance() methods of DateFormat class.println(“System date: ”).getDateInstance(DateFormat. Locale.get(Calendar. class Cal { public static void main(String args[ ]) { //Create an obj to calendar class Calendar cl = Calendar.util. //retrieve date details int dd = cl.txt package.com .DATE).println(“dd+ “/” +mm+ “/” +yy).get(Calendar. Syntax: .get(Calendar.SECOND). Page 19 of 148 rambabumandalapu@yahoo. ++mm.out. System. int m = cl.Date class is class useful to handle date and time.//System date and time import java.

30 03-Sep-04 19:43:14 03/09/04 7.W. Ex: . class MyDate { public static void main(String args[ ]) { //Create an obj to Date class Date d = new Date(). import java.format(d). Page 20 of 148 rambabumandalapu@yahoo.Advanced Java DateFormat.SHORT.out.30 03 September 2004 19:43:14 oclock GMT + 5.US). //Store the format in DateFormat obj DateFormat fmt = DateFormat.text.SHORT. //Applying the format to d String s = fmt.util.UK). DateFormat. Applying format to Date object is done by format () method.println(“System date and time: ”+s).com . Note: ---------------------------------------------------------------------------------------------------------------formatconst DateFormat. String str = fmtt.FULL DateFormat. H.getDateTimeInstance(DateFormat.LONG Example (region = LocaleUK) 03 September 2004 19:43:14 GMT + 5.MEDIUM.*. //Display the formatted date and time System.//To display system date and time import java.format(d). } } Θ Here d represents the system date & time already consists after creating an object.LONG DateFormat. Locale.MEDIUM DateFormat.43 pm ---------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------3. Locale.*.

Page 21 of 148 rambabumandalapu@yahoo.A stream is a sequence of bytes.It sends or writes the data to some other place. and address store objects of this class in an ArrayList. Streams (java. Create HashTable with some students hall tickets no. display his name and address. 2.io): . Type a hall ticket number and display his result? 4. Observing classes must implement the Observer interface. void update(Observable observOb. Object arg).e. or characters traveling from source to a destination. Create a vector with a group of strings. An Observer is an interface. The update() method is called when a change in the observed object take place. They are two types of streams. Output Stream: . and must implement the observer interface.’s & their results. It will have more methods than Observer interface. which is useful to observe an observable object. STREAMS: . Streams are represented by classes in java. When an employee’s ID is given. When an object of such a subclass undergoes a change. 2. City Delhi Washington London Paris Capital India America Britain France What is the difference between Observable and Observer? ***** Ans: . Cut the string into pairs of pieces: “India=>Delhi. America=>Washington. This interface will defines only one method i. Create an Employee class with an employee’s id.Observable is a class is used to create subclasses that other parts of our program can observe. France=>Paris” Now display the token as given below.io package. Observing classes are notified. Britain=>London.A stream represents flow of data from one place to another place.It receives or reads the data to output stream. Input Streams: .Advanced Java 1. Display them in reverse order also? 3. name. Sort them and display them in a ascending order.com . Here observOb is the object being observed. and arg is the value passed by notifyObservers(). 1.

They handle data to be read or written to disk files.com . Storing objects in a file called serialization. Reader | ----------------------------------------------------------------------------------------------| | | | BufferedReader CharArrayReader IntputStreamReader PrintReader | FileReader Writer | Page 22 of 148 rambabumandalapu@yahoo. To handle data in the form of ‘bytes’.They read data from one stream and write it another stream. c) ObjectInputStream/ObjectOutputStream: . b) FilterInputStream/FilterOutputStream: .Advanced Java When the bytes passing then it is called as byte stream and when the characters are passing then it is called as character stream. InputStream | ---------------------------------------------------------------------| | | FileInputStream FilterInputStream ObjectInputStream | ----------------------------------------| | DataInputStream BufferedInputStream OutputStream | ----------------------------------------------------------------------| | | FileOutputStream FilterOutputStream ObjectOutputStream | ----------------------------------------| | BufferedOutputStream DataOutputStream a) FileInputStream/FileOutputStream: .They handle storage of objects and primitive data. the abstract class: InputStream and OutputStream are used. Retrieving the data from files is called de-serialization.

Advanced Java ----------------------------------------------------------------------------------------------| | | | 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 16bit 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);
Page 23 of 148

rambabumandalapu@yahoo.com

Advanced Java 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);
Page 24 of 148

rambabumandalapu@yahoo.com

Advanced Java 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.

Page 25 of 148

rambabumandalapu@yahoo.com

e. //reading data from DataInputStream and write that data into FileOutputStream char ch.in). 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.//Creating a file import java. a Ms-Dos Command).read()) != ‘@’) fout.com .write(ch).Advanced Java DataInputStream FillOutputStrea m System.io.in Ex: . class Create1 { public static void main(String args[ ]) throws IOException { //Attach the keyboard to DataInputStream myfile DataInputStream dis = new DataInputStream(System. //Connect file to FileOutputStream FileOutputStream fout = new FileOutputStream(“myfile”). } } After executing & running the program.println(“Enter data (@at end): ”).*.close(). System. Ex: . while((ch = char) dis. FileOutputStream fout = new FileOutputStream(“myfile”.out. we can also open file using command “type” (i.//Creating a file Page 26 of 148 rambabumandalapu@yahoo. //close the file fout. true).

io. //Connect file to FileOutputStream FileOutputStream fout = new FileOutputStream(“myfile”.close(). } } To improve the efficiency or the speed of execution of program we to use Buffered class. we have to use bos.*.in).in).read()) != ‘@’) fout.out.*. System.io.write(). Default size used by any Buffered class is 512 bytes.close().write(ch). BufferedOutputStream bos = new BufferedOutputStream(fout. In the place of fout. we have to use bos. while((ch = char) dis. 1024). class Create1 { public static void main(String args[ ]) throws IOException { //Attach the keyboard to DataInputStream DataInputStream dis = new DataInputStream(System.//Creating a file import java. Ex: . true). //reading data from DataInputStream and write that data into FileOutputStream char ch.Advanced Java import java.close().write().println(“Enter data (@at end): ”). class Create1 { public static void main(String args[ ]) throws IOException { //Attach the keyboard to DataInputStream DataInputStream dis = new DataInputStream(System. Page 27 of 148 rambabumandalapu@yahoo. and in the place of fout. //close the file fout.com .

//close the file fin. //close the file bos.io.out. class Read1 { public static void main(String args[ ]) throws IOException { //Attach the file to FileInputStream FileInputStream fin = new FileInputStream(“myfile”).*. while((ch = fin.println((char)ch).read()) != -1) System. //now read from FileInputStream and display int ch.println(“Enter data (@at end): ”).//Reading data from a text file import java.close(). true). 1024).io.//Reading data from a text file import java.*. } } Ex: . class Read1 { public static void main(String args[ ]) Page 28 of 148 rambabumandalapu@yahoo.com .write(ch). //reading data from DataInputStream and write that data into FileOutputStream char ch. } } Ex: .read()) != ‘@’) bos. System. while((ch = char) dis.Advanced Java //Connect file to FileOutputStream FileOutputStream fout = new FileOutputStream(“myfile”.close().out. BufferedOutputStream bos = new BufferedOutputStream(fout.

ot.io.println((char)ch).close(). String fname = readLine(). //Attach the file to FileInputStream FileInputStream fin = new FileInputStream(fname). //now read from FileInputStream and display int ch. //close the file bin.read()) != -1) System. //Attach the file to FileInputStream FileInputStream fin = new FileInputStream(“myfile”). class Read1 { public static void main(String args[ ]) throws IOException { try{ //to enter filename from keyboard BufferedReader br = new BufferedReader(new InputStreamReader(System. while((ch = bin. //now read from FileInputStream and display int ch.close().*.println((char)ch).in)).//Reading data from a text file import java. System.out. while((ch = bin.com .Advanced Java throws IOException { BufferedInputStream bin = new BufferedInputStream(fin).read()) != -1) System. } } Ex: . } Page 29 of 148 rambabumandalapu@yahoo.out.print(“Enter file name: ”). //close the file bin.

txt”).*.//Creating a file import java.write(str. //close the file fw. //take string Page 30 of 148 rambabumandalapu@yahoo.out. //take string String str = “This is an institute” + “\nIam a student here”.charAt(i)). BufferedWriter bw = new BufferedWriter(fw.println(“File not found”). //read char by char from str and write into fw for(int i = 0. i++) fw. } } Ex: . class Create3 { public static void main(String args[ ]) throws IOException { //to write data into file FileWriter fw = new FileWriter(“myfile1.length().Advanced Java catch(FileNotFoundException fe) { System.txt”).//Creating a file import java.com . 1024).io.close().*. } } Ex: . i<str.io. class Create2 { public static void main(String args[ ]) throws IOException { //to write data into file FileWriter fw = new FileWriter(“myfile1.

*. //close the file bw. while((ch = fr. class Read2 { public static void main(String args[ ]) throws IOException { //attach file to FileReader FileReader fr = new FileReader(“myfile1.ot.Advanced Java String str = “This is an institute” + “\nIam a student here”.//Creating a file import java. //read char by char from str and write into fw for(int i = 0. i++) bw. //close the file fr.write(str.io.charAt(i)).txt”). class Read3 { public static void main(String args[ ]) throws IOException { //attach file to FileReader FileReader fr = new FileReader(“myfile1.com . } } Ex: .*.println((char)ch). i<str. Page 31 of 148 rambabumandalapu@yahoo.close(). } } Ex: .//Reading data from the file import java. //now read data from fr and dispaly int ch.txt”).length().close().io.read()) != -1) System.

05 EMPSAL ObjectStream JDBC is more convenience to handle or storing and retrieve the data from the 0 1 Zip WinZip Software 01 101 Zipped file Writing here File 1 attach fos dos Writing here File 2 attach fos rambabumandalapu@yahoo.It is used to unzip the file. } } 1001 EMPID table form.zip packagae. //now read data from fr and dispaly int ch.read()) != -1) System. File format is changed.*. 512).println((char)ch).util. import java.zip.*. File converts to compressed. while((ch = br. In java language to zip and unzip a file we will use below two classes. Ex: .com . 1. 2.Advanced Java BufferedReader br = new BufferedReader(fr. InflaterOutputStream: .It is used to zip the file. 2.util. DeflaterOutputStream: . //close the file br. class Compress { public static void main(String args) throws Exception Page 32 of 148 Rama EMPNAME 7000. Zipping and Unzipping the file: Most repeated bit pattern 11111111 00000000 10101010 00001111 File 1.close().//Zipping import java. These above two classes are in java.ot.util.

close(). //attach file3 to FileOutputStream FileOutputStream fos = new FileOutputStream(“file3”). Ex: .close().write(data).Advanced Java { //attach file1 to FileInputStream FileInputStream fis = new FileInputStream(“file1”).util. while((data = fis. //attach fos to DeflaterOutputStream DeflaterOutputStream dos = new DeflaterOutputStream(fos).read()) != -1) dos. class UnCompress { public static void main(String args) throws Exception { //attach file2 to FileInputStream FileInputStream fis = new FileInputStream(“file2”). //close the files fis.*.util. //attach fis to InflaterInputStream (iis) InflaterInputStream iis = new InflaterInputStream (fis). } } Here we have to create file1 using Ms-Dos Edit command save it and then execute the java file. //read data from fis and write into dos int data.com .*. dos. //read data from iis and write into fos int data. //attach file2 to FileOutputStream FileOutputStream fos = new FileOutputStream(“file2”). Page 33 of 148 dos Writing here iis File 2 attach fis Writing here File 3 attach fos rambabumandalapu@yahoo. import java.zip.//UnZip import java.

01 --------is a equal to like www.01 ----. Append the contents of one file to another file existing file.192. Count the no. //close the files iis. Web Sphere. and lines in a text file. } } H. Internet is a network of all the computers existing on the earth.50.com . SMTP (Short Mail Transfer Protocol) is used for sending mails.close().216 Hosts Page 34 of 148 rambabumandalapu@yahoo. ISP – Internet Service Provider. 7. 192. Server is a machine that provides service to the clients.TCP/IP – Transmission Control Protocol/Internet Protocol HTTP is most widely used protocol on internet. Copy a file content into another file (new file) 6. 5. It will convert the name into the IP address.50. etc… Protocol represented by a set of rules. Web Logic.close(). words. Ex: . W.read()) != -1) fos. Internet protocol address is a Unique ID number is given to every computer in network. The software which is available on the server is called Web Server.45. fos. Tomcat.com DNS – Domain Naming System. FTP (File Transfer Protocol) is used when we are downloading files. Ex: .write().Apache. of characters.777. Ex: .It is a IP address of server. Network: Inter connections of computers is called Network. POP (Post Office Protocol) is used to receiving mails. The current version of IP address is 6.Advanced Java while((data = iis. A client is a machine that sends a request for some service. which uses 16 bytes. to be followed by every computer in network.yahoo.45. Class A 0 Network 7bits Local Address 24bits 16.

which transfer files. SMTP.com .536 Hosts Class C 110 Network 21bits Local Address 8bits 256 Hosts Class D Class E Research/Experimental works Classes are of IP address.net package. When we use new socket we use a new port number. this enables users to access mail boxes on remote system.1. 2. Every socket has an ID No. HTTP. These two classes are in java. which transfer webpage POP.Advanced Java Class B 10 Network 14bits Local Address 16bits 65. Some allotted port numbers: S. java. 4. Host means Server. 3. ServerSocket is a class to create a Socket server side. BOOTP. 7. which provides configuration at boot time. Page 35 of 148 Client Server Socket rambabumandalapu@yahoo. Socket: . 1. Port Number 13 21 23 25 67 80 109 Application Date and time services. which delivers mail messages. Socket is a class to create a Socket client side. An ID number is allotted to a socket is called Port number. No. that is Port No. When you will change socket number? ***** Ans: . On the same socket if the service changes.net package contains classes to create a socket for server and client. which provides remote login. 2. Telnet.A socket is a point of connection to connect a client and server. 5. 6. FTP.

//attach OutputStream to Socket OutputStream obj = s.out. //now send data String str = “Hello”. } } Now compile this program and don’t run it. //Disconnect the Server s.*.net.println(“Bye”).accept().close().com . import java.Advanced Java Ex: .net. //make that Socket accepts Client connection Socket s = ss. import java.//Create a server that sends messages import java. ps. System. ps.*.//A Client that receives data import java.io. [ To display IP address we have to use command igcong Syntax: -C:\rnr>ipconfig↵ Ex: .close(). then we have to create socket for client side. //to send data to the Socket PrintStream ps = new PrintStream(obj). ps.println(“Connection Established”). class Server { public static void main(String args) throws Exception { //Create Server Socket ServerSocket ss= new ServerSocket(777). ] Client Socket Server Socket Page 36 of 148 rambabumandalapu@yahoo.getOutputStream().*.println(str).*.io.

connect InputStream to the Socket InputStream obj = s. 5.print(str).close().PrintStream ps = new PrintStream(obj).getInputStream(). Send data to the Client using PrintStream Ex: . br. //To receive the data to this Socket BufferedReader br = new BufferedReader(new InputStreamReader(obj)).getInputStream().com . //Accept data coming from Server String str. 777).readLine()) !=null) System.close(). -----It returns Socket object.println(str). connect the OutputStream to the Socket OutputStream obj = s. //attach InputStream to Socket InputStream obj = s.). To send data. To receive data from the Client. while(str=br. //Disconnect the Server s. ps. } } We can run as many JVM’s at a time.out. Page 37 of 148 rambabumandalapu@yahoo. ps.accept(). Accept any Client Socket s = ss.println(str). Communicating from the Server: 1. 2.getOutputStream(). 3. 4.Advanced Java class Client1 { public static void main(String args) throws Exception { //Create Client Socket Socket s= new Socket(ipaddress/”loacalhost”. Create a ServerSocket ServerSocket ss = new ServerSocket(Port No.

close(). RMI (Remote Method Invocation) It is a technology to call and use remote methods of remote objects.getOutputStream(). Create a Client Socket Socket s= new Socket(ipaddress/”loacalhost”.//Chat Server import java. 777). ss. s. Read data coming from the Client using BufferedReader. ch = br.getInputStream(). Read data coming from the Server using BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(obj). 3. str = br.io.net. Closing Communication: Close all Streams and Sockets ps.close().writebyte(str).*. Ex: . connect InputStream to the Socket InputStream obj = s.readLine(). 2. 4.read().close(). str = br.Advanced Java 6.read(). br. Communicating from Client: 1. import java. Dos.close(). Ex: .*. dos. BufferedReader br = new BufferedReader(new InputStreamReader(obj).readLine().DataOutputStream dos = new DataOutputStream(obj).com . To send data connect the OutputStream to the Socket OutputStream obj = s. class Server2 { public static void main(String args) Page 38 of 148 rambabumandalapu@yahoo. 5. ch = br. Send data to the Server using DataOutputStream. To receive data fro the Server.close(). 3.

s.close(). br. System.println(str1).accept().close(). str1.getOutputStream()).out.Advanced Java throws Exception { //Create Server Socket ServerSocket ss= new ServerSocket(888).close().println(str). } } } Ex: . } //Disconnect the Server ss.out. kb. //make this Socket wait for Client connection Socket s = ss. ps.exit(0). //now communicate while(true) { String str. str1 = kb. System. //to receive data from Client BufferedReader br = new BufferedReader(newInputStreamReader (s.close().readLine() != null) { System.getInputStream())).readLine(). while(str = br. ps.close().println(“Connection Established”).in())). //to send data to the Client PrintStream ps = new PrintStream(s. Reference Object //to read data from Keyboard BufferedReader kb=new BufferedReader(new InputStreamReader(System.com .//Chat Client Page 39 of 148 // Server runs continuously rambabumandalapu@yahoo.

println(str1). 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.writeBytes(str+”\n”). 8.readLine() .close(). while(str = br. class Client2 { public static void main(String args) throws Exception { //Create Client Socket Socket s= new Socket(“Localhost”.close(). br.*.out. { dos.in())).io. str1.Advanced Java import java. str1 = br. W.*. //to receive data from Server BufferedReader br=new BufferedReader(new InputStream(s. } //Disconnect the Server s.net. //now start communicate String str.close().readLine().getOutputStream()).equals(“exit”)) //As long as the String are not typing exit.close(). System. kb.getInputStream())). //to read data from Keyboard BufferedReader kb=new BufferedReader(new InputStreamReader(System. import java. dos. } } H. 888).13) Page 40 of 148 rambabumandalapu@yahoo.com . //to send data to the Server DataOutputStream dos = new DataOutputStream(s.

5. 5 Priority No. Thread t = Thread.println(“This is first line”).out.e.com .This is first line Present Thread = Thread[main. } } C:\rnr>javac Current.java↵ C:\rnr>java Current ↵ O/P: . is called main thread.Advanced Java 9. Priority No.A thread represents a process of execution (or) executing the set of statements is called a thread.//Every java program has a thread class Current { public static void main(String args) { System. System. System.println(“Its name = ”+t. 1 Priority No. ---------------------------Statements JVM or Microprocessor Every java program is executed by using one thread i. 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). JVM will execute statements step by step. Thread: . main] is called as Thread group.out. 10 ------------------Minimum Priority Normal Priority Maximum Priority Page 41 of 148 rambabumandalapu@yahoo. Thread has priority number. From the above thread name is main.out. Ex: . 5 is the Priority Number.println(“Present thread = ”+t).currentThread().getName()). 5. Priority number will varies from 1 to 10. [main. main] Here main is a thread name.

Single tasking: .25ms 0. We can provide more threads to the microprocessor.25milli seconds) for each task. types of blocks Microprocessor rambabumandalapu@yahoo.Executing several programs at a time is called process based multitasking. 2.25ms 0. Executing the tasks (one or more statements is two types. Write a class that extends thread class or implements runnable interface.25ms Microprocessor will allot equal timings (0. Create a thread: 1. a) Process based multitasking: . Multitasking: . Time slice.Executing one task at a time is called single tasking.Microprocessor uses round robin method to execute several tasks simultaneously. 1. Microprocessor will execute the 10billions of machine code instructions per second. In a Single tasking lot of processor time wasted. Using more than one thread is called multithreading to perform multiple tasks simultaneously at a time. Round Robin Method: . Page 42 of 148 Task Microprocessor Three diff.com . Executing first task after last task is called round robin method.25ms 0.Advanced Java Main thread priority number is 5.Executing several tasks simultaneously is called multitasking. Ex: . Round robin methods are process based multitasking.Time slice is the time allotted by the Microprocessor to execute each task.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. Microprocessor Memory Task 0. b) Thread based multitasking: Executing several parts of a program simultaneously is called thread based multitasking. Time Slice: .

then will act upon that object. To stop the thread also we have to use control + c keys.Advanced Java Thread class.out. t1. Thread t1 = new Thread().com . Start thread. } } } class TDemo { public static void main(String args[ ]) { MyThread obj = new MyThread(). 5. These two are available in java.//Creating thread Class MyThread extend Thread { public void run() { for(int i = 1. Ex: .lang package. Page 43 of 148 rambabumandalapu@yahoo.println(i). i<100000. 3. } } stop() method is used to stop the thread in old versions. i++) { System. Write public void run in the class thread will execute only this method.start(). 2. Create an object to the class. public void run() Thread can’t act upon any method. Attach a thread to this object. Forcibly to terminate the program we have to use “control + c” (Ctrl+c keys in the keyboard). runnable implements will helpful to create a thread. 4. But stop() method is deprecated in new versions. but default it works only on run() method.

3. } } This above program is for stopping the thread smoothly. Declare a boolean variable and initialize it as false Ex: .in. public void run() { for(int i = 1. Page 44 of 148 run() { --------} object Microprocessor rambabumandalapu@yahoo. i<100000.read().stop = true. Thread t1 = new Thread().1.io.*. How can you stop the thread which is running? ***** Ans: . 2.Advanced Java Ex: . } } } class TDemo { public static void main(String args[ ]) { MyThread obj = new MyThread(). obj. When ever the thread should be stopped store true into this variable Ex: .println(i). Class MyThread extend Thread { boolean stop = false. if(stop) return. i++) { System. System.boolean stop = false.obj. t1.//Creating thread and smoothly terminate/stop the program or thread Import java.start().out. If the variable becomes true using return statement come out run() method Ex: .stop = true.if(stop) return.com .

Advanced Java What is the difference between extends and implement Runnable? Which one is advantage? ***** Ans: .println(str+ “ : ” +i). }catch(InterruptedException ie) { ie. there is no scope any another class. The main advantage of multitasking is utilizing a processor time in an optimum way.str = str.out.There is no difference between these two. i<=10.printStackTrace(). Implement Runnable is advantage because interfaces is always better than classes.//Theatre Example class MyThread implements Runnable { String str. } public void run() { for(int i = 1. Ex: . MyThread(String str) { this. i++) { System.sleep(2000). this is the limitation of extends. try{ Thread. If we implement Runnable interface still there is a scope to extend other class. } } } } class Theatre Page 45 of 148 run() { --------} object run() { --------} object 1 Microprocessor t1 thread Microprocessor run() t2 thread { --------rambabumandalapu@yahoo.com } object 2 . If we extend thread class.

if(available >= wanted) { String name = Thread.currentThread.out.Advanced Java { public static void main(String args[ ]) { //create objects to MyThread class MyThread obj1=new MyThread(“Cut ticket”). Page 46 of 148 //these two objects 1 thread ------------------------------------------------------------------------object Synchronization st 2nd thread rambabumandalapu@yahoo.com .println(“Number of berths available = ”+available). //Create two threads and attach them to Thread t1 = new Thread(obj1). int wanted. //start the thread t1. MyThread obj2=new MyThread(“Show ticket”).println(wanted + “berths reserved for”+name).start(). Reserve (int i) { wanted = i. Ex: . t2.out. System.getName(). } public void run() { System. Thread t2 = new Thread(obj2).start().sleep(2000).//Two threads acting on one object class Reserve implements Runnable { int available = 1. } } When multiple threads are acting on the one or same object we will get sometimes unreliable results. try{ Thread.

Reserve (int i) Page 47 of 148 rambabumandalapu@yahoo.start().out. int wanted. Ex: . //run the threads t1. For this permanent solution we have to block the 2nd thread till the completion of the 1st thread.setName(“Second Person”). } } This above program will allot tickets for both persons. t2. Thread t2 = new Thread(obj).println(“Sorry.start().setName(“First Person”).Advanced Java available = available – wanted. So we have to use synchronization method to block the 2nd thread. //create 2 threads and attach them to obj Thread t1 = new Thread(obj). } catch(Interrupted Exception ie){ } } else System.com . t2. no berths to reserve”). //give names to threads t1.//Two threads acting on one object class Reserve implements Runnable { int available = 1. } } class Syn { public static void main(String args[ ]) { //create an obj to Reserve class with 1 berth Reserve obj = new Reserve(1).

setName(“First Person”). try{ Thread.currentThread.out. available = available – wanted. Thread t2 = new Thread(obj). if(available >= wanted) { String name = Thread.out. Page 48 of 148 rambabumandalapu@yahoo. } } } class Syn { public static void main(String args[ ]) { //create an obj to Reserve class with 1 berth Reserve obj = new Reserve(1).println(“Number of berths available = ”+available).sleep(2000).Advanced Java { wanted = i.println(“Sorry.setName(“Second Person”). //create 2 threads and attach them to obj Thread t1 = new Thread(obj).getName().out. System. //give names to threads t1. } catch(Interrupted Exception ie){ } } else System. } public void run() synchronized(obj) { System. t2. no berths to reserve”).com .println(wanted + “berths reserved for”+name).

com .y here. y . pubic void method1() { synchronized(xLock){ //access x here.Synchronization is locking the object. thread safe } } //do something here but don't use SharedResource x. Synchronized object is also called as Mutex i. synchronized(xLock) { synchronized(yLock) { //access x.e. rambabumandalapu@yahoo. y . } } Thread Synchronization (or) Synchronization: .class BlockLevel { //shared among threads SharedResource x. Synchronized block(): synchronized(obj) { statements.start(). } Ex: . Mutually Exclusive lock. yLock = new Object(). An object can be synchronized in two ways 1. so that when a thread is processing object any other thread will not be allowed to act upon the object. //dummy objects for locking Object xLock = new Object(). t2. thread safe } //do something here but don't use SharedResource x. y . } Page 49 of 148 For group of statements we can use this synchronized block.Advanced Java //run the threads t1.start().

rambabumandalapu@yahoo. Ex: .com .//To cancel the ticket Class CancelTicket extends Thread Page 50 of 148 For entire method to synchronized we will use this method. unsynchronized is also known as thread unsafe.Advanced Java } 2. y .Without synchronization. This often causes dirty data and leads to significant errors. } Ex: . Also synchronized code has the overhead of acquiring lock.class MethodLevel { //shared among threads SharedResource x. Synchronization is also known as thread safe. Disadvantage of synchronization is that it can cause deadlocks when two threads are waiting on each other to do something. By making a method as synchronized method synchronized void method() { statements. which can adversely the performance. 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: . Locking means it will not allow another thread still the completion of one task of one thread. 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.

Advanced Java { object train. }catch(InterruptedException ie){ } System.out.train = train.obj 200ms train. CancelTicket(object train. object comp) { this.out. comp. } public void run() { synchronized(comp) { try{ sleep(100).comp = comp. object comp) { this. } public void run() { synchronized(train) Page 51 of 148 Thread 1 CancelTicket 100ms comp. } } } } class BookTicket extends Thread { object train.com .println(“CancelTicket now locked train”).println(“CancelTicket locked the compartment”). BookTicket(object train. rambabumandalapu@yahoo. synchronized(train) { System.obj BookTicket Thread 2 System. this. this.comp = comp.train = train. comp.out.println(“CancelTicket wants to lock on train”).

println(“BookTicket wants to lock on compartmet”). BookTicket CancelTicket obj1 = new CancelTicket(train.println(“BookTicket locked the train”). t2.println(“BookTicket now locked compartment”). //run the threads t1.start(). compartment). Output: Page 52 of 148 rambabumandalapu@yahoo. BookTicket obj1 = new BookTicket (train.out. try{ sleep(200). }catch(InterruptedException ie){ } System. //create objects to CancelTicket.Advanced Java { System.start(). } } } } class DeadLock { public static void main(String args[ ]) throws Exception { //take train and compartment as objects object train = new object(). //create 2 threads and attach them to these objects Thread t1 = new Thread(obj1).com . } } Save it as DeadLock. Thread t2 = new Thread(obj2). synchronized(comp) { System.out. compartment).out.java compile & run the program. object compartment = new object().

Ex: .comp = comp.out.train = train. } } } } class BookTicket extends Thread { Thread 1 CancelTicket 100ms Page 53 of 148 Locking Solution for DeadLock Changing direction of thread 2 Thread 2 BookTicket comp.println(“CancelTicket locked the compartment”). { this.obj . CancelTicket(object train.out.out.println(“CancelTicket now locked train”). synchronized(train) { System. object comp).println(“CancelTicket wants to lock on train”). this. } public void run() { synchronized(comp) { System.Advanced Java 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. try{ sleep(100). because to solve this program in another way.com 200ms train.obj rambabumandalapu@yahoo.//To cancel the ticket Solution for dead lock Class CancelTicket extends Thread { object train. }catch(InterruptedException ie){ } System. comp.

this.out. try{ sleep(200).println(“BookTicket now locked train”).Advanced Java object train.println(“BookTicket wants to lock on compartmet”). synchronized(train) { System.out. //create objects to CancelTicket.comp = comp. compartment).train = train. comp. compartment). BookTicket CancelTicket obj1 = new CancelTicket(train.println(“BookTicket locked the Compartment”). } } } } class DeadLock { public static void main(String args[ ]) throws Exception { take train and compartment as objects object train = new object(). }catch(InterruptedException ie){ } System.out. { this. //create 2 threads and attach them to these objects Page 54 of 148 rambabumandalapu@yahoo. BookTicket(object train. object compartment = new object(). } public void run() { synchronized(comp) { System.com . object comp). BookTicket obj1 = new BookTicket (train.

com .NORM_PRIORITY value is 5 8. t2. } } DeadLock of thread: .setName(“name”).start().getPriority(). To get the priority of a thread int priority_no = t. To set a new to a thread t.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. 2.The priority number constants are as given below Thread. Note: .getName().setPriority(int priority_no). To test if a thread is still alive Page 55 of 148 rambabumandalapu@yahoo. 4. A programmer should avoid DeadLock situations in his program by properly planning designing the program.start(). To know the currently running thread. Thread t2 = new Thread(obj2).Advanced Java Thread t1 = new Thread(obj1). In DeadLock both the threads mutually keep under waiting forever and further processing is canceled. //run the threads t1.MIN_PRIORITY value is 0 Thread. 6. Thread t = Thread.MAX_PRIORITY value is 10 Thread.start(). 3. 5. To get the name of a thread String name = t. Thread Class Methods: 1. To set the priority of a thread t. To stop execution of a thread for a specified time Thread.sleep(milliseconds). 7.currentThread(). To start thread t.

Consumer. 10. objects Producer obj1 = new Producer(). To send notification to all waiting threads obj.start(). Ex: .wait(). 11.start().A program thread uses two types of operating system threads. Green Thread model will provide only one thread for a program thread.notifyAll().com . returns true/false 9. notify() method will sends a notification to a thread. they are Green Thread model and Native Thread model. where as Native Thread provides a separate thread for each program thread. t2. To wait till a thread dies t.e.//Thread Communication Class Communicate { public static void main(String args[ ]) { //create Producer. obj2 Thread t1 = new Thread(obj1). 12. To wait till the obj is released (till notification is sent) obj. The above three methods (10. i.join().isAlive(). 11. Consumer obj2 = new Consumer(obj1). some object is available to the thread. } } Page 56 of 148 rambabumandalapu@yahoo. What is the difference between Green thread and Nativethread? ***** Ans: .Advanced Java t. To send a notification to awaiting thread obj. //run the threads t1. 12) are belong to object class. //create 2 threads and attach them obj1.notify(). Thread t2 = new Thread(obj2).

} public void run() { for(int i = 1. } catch(Exception e){ } } dataprodover = true. } public void run() { try{ while(!prod. } } class Consumer extends Thread { Producer prod.prod = prod. i<=10. System. producer() { sb = new StringBuffer().out. sleep(100).println(“appending”).append(i+”:”).dataprodover) Page 57 of 148 //Θ dataprodove is a data production over 1 2 3 10 Data Provider true Producer Consumer rambabumandalapu@yahoo. SrtingBuffer sb. Consumer(Producer prod) { this.Advanced Java class Producer extends Thread { Boolean dataprodover = false. i++) { try { sb.com .

objects Producer obj1 = new Producer().start().Advanced Java { sleep(10).com . obj2 Thread t1 = new Thread(obj1). Consumer. This above program/method is not efficient way to communication between threads. } }catch(Exception e){ } System. //run the threads t1.sb).java.start(). t2. } } class Producer extends Thread { SrtingBuffer sb.//Thread communication in efficient way Class Communicate { public static void main(String args[ ]) { //create Producer. } Producer Page 58 of 148 1 2 3 10 Data Provider true Consumer rambabumandalapu@yahoo. Thread t2 = new Thread(obj2). //create 2 threads and attach them obj1.out. Ex: .println(prob. } } Save it as communication. producer() { sb = new StringBuffer(). Consumer obj2 = new Consumer(obj1). If we want communicate efficient way we have to use notify() method.

println(prod. }catch(Exception e){ } System.Advanced Java public void run() { synchronized() { for(int i = 1. Consumer(Producer prod) { this.sb) { try{ prod.wait(). } public void run() { synchronized(prod. sleep(100).append(i+”:”). } } } class Consumer extends Thread { Producer prod. // or we can use sb.notify().notifyAll(). i++) { try { sb.prod = prod.println(“appending”). } Page 59 of 148 rambabumandalapu@yahoo. } catch(Exception e){ } } sn.com . System.out. i<=10.sb).out.

Ex: . Daemon thread are used for background services. GUI thread What is Daemon thread? ***** Ans: . User thread or Main thread. The states assumed by the thread are called life cycle of a thread. Daemon thread 3.Life cycle of thread means from the creation of thread till its termination.Advanced Java } } What is the difference between sleep() method and wait() method? ***** Ans: .A Daemon thread is a thread that continuously provides services to other threads i.To start mysql F:\rnr>mysqld↵ F:\rnr> Now onwards Daemon thread makes the mysql database running continuously.com .synchronized(obj) { ------------------------------------------sleep(2000). locked } locked synchronized(obj) { ------------------------------------------wait(2000). Ex: .Both methods will make the thread wait for some time. ------------------------------------------} What are different types of threads: 1. But both methods will wait temporarily. Daemon threads are generally used background services. Θ Here d is the Daemon thread. ------------------------------------------Unlocked locked Page 60 of 148 rambabumandalapu@yahoo. 2. What is thread life cycle? ***** Ans: . When the threads comes out of the wait() method the object is automatically unlocked. When the thread comes out of sleep() method the object may be still lock.e.

yield() should not be used very frequently. Running: . Because of context switching overhead. Not Runnable means thread will stop runnable. Afetr executing the all methods by run() method then the thread will be terminated.Waiting for its turn to be picked for execution by the thread schedular based on thread priorities. It runs until it becomes blocked. or voluntarily gives up its turn with this static method Thread. Runnable: .Advanced Java Start → run → wait (or) blocked state → Destroy State Life Cycle of Thread Running Yield New Thread Start Runnable The run method terminates Dead/Terminates (or) Dead sleep() wait() blocked on I/O Not Runnable Runnable means it will executes public void run methods yield makes pausing the thread. Page 61 of 148 rambabumandalapu@yahoo.The processor is actively executing the thread code.yield().com .

A daemon thread executes continuously. Controlling all the threadsx by giving a single command or method is possible.setDaemon(true). it changes from running state to runnable state. To know if a thread is Daemon or not Boolean x = t. Dead: The thread is finished working. 2. Sleeping: . Blocked on synchronization: Will move to Runnable when a lock is acquired. ThreadGroup tg1 = new ThreadGroup(tg. “threadname”). What are the states of thread? ***** Ans: . What is the difference between yield and sleeping? ***** Ans: .When a task invokes yield(). Blocked on I/O: Will move to runnable after I/O condition like reading bytes of data etc changes.New thread state → Runnable → Running → wait (or) blocked state → Destroy State Thread Group: . nanoseconds). 1.A thread is in a blocked state while it waits for some external processing such as file I/O to finish.sleep(milliseconds. Page 62 of 148 t1 t2 t3 res can t4 rambabumandalapu@yahoo. it changes from running state to waiting/sleeping state.isDaemon(). Daemon Thread: . It provides generally a background processing. Θ Here obj is target object Thread t2 = new Thread(tg.com tg1 tg . To make a thread as Daemon thread t.A group of threads as single unit is called ThreadGroup. If we applied certain methods on the ThreadGroup it will effect all other threads. When a task invokes sleep(). because of ThreadGroup. “threadname”). ThreadGroup tg = new ThreadGroup(“group name”). Thread t1 = new Thread(tg.Daemon threads are service providers fro other threads or objects. Thread. obj1. “group name”).sleep(milliseconds). obj. We can also add one ThreadGroup to another ThreadGroup.Java threads are forcibly put to sleep (suspended) with this overloaded method: Thread.Advanced Java Waiting: .

out.println(‘Parent of tg1 = ”+tg1.out.println(‘ThreadGroup of t2 = ”+t2. res. Thread t2 = new Thread(tg.getThreadGroup()). “Cancellation Group”).getThreadGroup()).start(). Thread t4 = new Thread(tg1. //set maximum priority to tg1 as 7 tg1. System.Advanced Java Ex: . “First thread”). Cancellation can = new Cancellation().start().println(‘Number of threads in a group = ”+tg.setMaxPriority (7). //know the ThreadGroup of t1 and t2 System. //create 2 threads and add them to ThreadGroup Thread t1 = new Thread(tg. Thread t3 = new Thread(tg1.println(‘ThreadGroup of t1 = ”+t1. “Second thread”). System. //start the threads t1. res.com . t2.activeCount()). res.out. //Find parent group of tg1 System.start()./*Using thread groups*/ class WhyTGroups { public static void main(String args[ ]) throws Exception { Reservation res = new Reservation(). “Fourth thread”). //create another ThreadGroup as a child to tg ThreadGroup tg1 = new ThreadGroup(tg. //create a ThreadGroup with name ThreadGroup tg = new ThreadGroup(“Reservation Group”).start().out.getParent()). “Third thread”). } } class Reservation extends Thread { Page 63 of 148 rambabumandalapu@yahoo. t3. res. t4.

GUI is user friendly.out. } } class Cancellation extends Thread { public void run() { System.out. Advantages of GUI: 1.com . till enter button is pressed.println(‘I am Reservation thread”).awt package: . GUI makes an application more attractive. 2..W.Button | Page 64 of 148 rambabumandalapu@yahoo... . GUI (Graphic User Interface): .AWT Standards for Abstract Window Toolkit. Components means Push Buttons. Check boxes.… java.Advanced Java public void run() { System. 10. User can interact with application in two ways. 1. CUI (Character User Interface): ..). Create a parallel server using 3 or 4 threads that can serve several clients simultaneously.println(‘I am Cancellation thread”). Radio Buttons.. The user cannot remember all commands every time in CUI. 2.If the user interacts with the application through graphics (Pictures/Images/…. It is a package that provides a set of classes and interfaces to create GUI components.label | . Create a thread that display the time on the screen continuously. Using GUI we can simulate real objects.In CUI the user can interact with the application by typing the characters. 11. 3. } } H.

..| ....GridLayout | . What is the difference between window and frame? ***** Page 65 of 148 rambabumandalapu@yahoo...com .Choice | Object. Layout manager is implemented in the following classes....... .Container ........ A window represents the some rectangular part on the screen.TextArea .Scrollbar | .Checkbox | ...List | CheckBoxGroup | .....Advanced Java .FlowLayout | .BorderLayout | Object .GridBagLayout A frame is a top level window that is not contained in another window..........TextFiled Panel Applet Window Frame Layout manager is an interface that arranges the components on the screen..CardLayout | .TextComponent .Canvas | ...-Component..

Advanced Java Ans: .300). 600) (800.*. Ex: .setVisible(true). 600) rambabumandalapu@yahoo.Frame f = new Frame().show().A window represents a rectangular part of the screen. 2. import java. 500) (0. Ex: .com . y) (0. Ex: . } } Components are to display but not to perform any task. 0) (800.awt. Pixel means picture element. maximize or close i.setSize(400.class MyFrame extends Frame MyFrame f = new MyFrame(). class MyFrame { public static void main(String args[ ]) { //create an object to Frame class Frame f = new Frame(). //increase the size of frame f. class MyFrame extends Frame { public static void main(String args[ ]) { Page 66 of 148 (x. This is advantageous than 1st method. Creating a frame: 1.e. A frame is a window with title bar and some button to minimize.0. //display the frame f. Write a class that extends a frame and then creates an object to that class. 300) * (10.*. Create an object to frame class. 0) *(400.) is a pixel. (or) f. is called frame.//creating a frame import java. Ex: . Pixel is a short form of a picture each dot (.//creating a frame –version-2.awt.

//display the title f. Pressing a key. Ok listener What is Event Delegation model? ***** Ans: . When an event is generated a relevant method is called and executed by the Listener.Listener is an interface that will added to the component. This is called Event Delegation model.Events are generated by user to perform a task. Each logic can be developed using different technologies. Listener: . (or) f. Delegation means handing over the work to another.User interaction with the component is called Event.setVisible(true). Event delegation model separate/isolated presentation logic and business logic. Double Clicking. Page 67 of 148 rambabumandalapu@yahoo. A Listener is an interface. moving the mouse and dragging the item. To close the frame: 1.steTitle(“My AWT Frame”). Attach a WindowListener to the frame. Ex: .Advanced Java //create an object to frame class MyFrame f = new MyFrame(). } } Event: .show().Clicking. The listener will delegate the event to the method and finally the method will handle the event.setSize(400. Implement all the methods of WindowListener interface.com . //increase the size of frame f. A programmer can modify one part without affecting the other part. It is listen to the event. 2. //display the frame f. The component will delegate the event to a listener.300). 3.

//display the title f.//creation of frame and closing the frame import java.event. class MyFrame extends Frame { public static void main(String args[ ]) { //create an obj to Frame class MyFrame f = new MyFrame().exit(0). import java.com .*. //increase the size of frame f.*. } } class Myclass implements WindowListener { public void windowActivated(windowEvent e){ } public void windowClosed(windowEvent e){ } public void windowClosing(windowEvent e){ } { System.addWindowListener(WindowListener obj).setSize(400. //display the frame f.addWindowListener(new Myclass()).300).//creation of frame and closing the frame Page 68 of 148 rambabumandalapu@yahoo.show().setVisible(true).steTitle(“My AWT Frame”).Advanced Java Ex: .awt.awt. (or) f. //attach a WindowListener to the frame //f. f. } public void windowDeactivated(windowEvent e){ } public void windowDeiconified(windowEvent e){ } public void windowIconified(windowEvent e){ } public void windowOpended(windowEvent e){ } } (or) Ex: .

com .*.setVisible(true). //increase the size of frame f.event.exit(0). } }).awt. //attach a WindowListener to the frame f. } } What is adaptor class? ***** Page 69 of 148 rambabumandalapu@yahoo. //display the frame f. class MyFrame extends Frame { public static void main(String args[ ]) { //create an obj to Frame class MyFrame f = new MyFrame().exit(0). //display the title f.addWindowListener(new WindowAdaptor() { public void windowClosing(windowEvent we) { System.Advanced Java import java.*.300).awt. } } class Myclass implements WindowAdaptor { public void windowClosing(windowEvent e){ } { System.steTitle(“My AWT Frame”).setSize(400.show(). (or) f. import java.

drawString(“Message”. Here x.//Displaying a message in the frame import java.awt. A Frame is used to display following things 1. which contains empty implements of all the methods of the interface. } //end of constructor Page 70 of 148 rambabumandalapu@yahoo.For this purpose we should use drawString() method of graphics class. import java. y). x.An adaptor class is similar to an interface.event*. class Message extends Frame { //vars //Default Constructor Message() { //write code to close the frame this.Advanced Java Ans: . y are coordinates of pixels.It is an inner class whose name is hidden to outer class and for only which is created. WindowAdaptor is the adaptor class interface.awt.gif files 3.*. Messages 2. } }). check buttons etc…) Displaying the messages in the Frame: .com . To display images/photos/icons/.exit(0). Ex: .g.addWindowListener(new windowAdaptor() { public void windowClosing(windowEvent e) { System. Ex: . push buttons. To display components (Radio buttons. What is anonymous inner class? ***** Ans: .

//now display the messages g. (or) m.show(). g.Advanced Java public void paint(Graphics g) { //set a background color for frame this.*.ITALIC.20. } } (or) Ex: . 20. //display the frame m. } public static void main(String args[ ]) { //create the frame Message m = new Message().awt. //set a text color set.setBackground(new color(100.setSize(500.setFont(f).400).BOLD+Font. import java.steTitle(“My message”). 100).//Displaying a message in the frame import java.awt. //set a font for text Font f = new Font(“Helvetica”.Color(Color.com . 35).drawString(“Hello Students”.event. //set the size of frame m.green).20). class Message extends Frame { //vars //Default Constructor Message() { //write code to close the frame Page 71 of 148 rambabumandalapu@yahoo. //set a title to the frame m.*.setVisible(true). Font.

} public static void main(String args[ ]) { //create the frame Message m = new Message(). We can directly specify a color name from color class.20.ITALIC.show(). } } To specify a color in awt: 1.400).setSize(500.Color(Color. //set a font for text Font f = new Font(“Helvetica”. (or) m. Page 72 of 148 rambabumandalapu@yahoo.20). //display the frame m. 100). //now display the messages g. //set a title to the frame m.green). //set a text color set.exit(0). } }).setVisible(true).steTitle(“My message”).com .setFont(f). Font. } //end of constructor public void paint(Graphics g) { //set a background color for frame setBackground(new color(100.Advanced Java addWindowListener(new windowAdaptor() { public void windowClosing(windowEvent e) { System. 20. //set the size of frame m.drawString(“Hello Students”. g.BOLD+Font. 35).

values are varies from 0 – 255. It is pure white color Color c = new Color(100.0).0. 2. It is a black color Color c = new Color(255.20).255).0).awt.*. Font. blue values Ex: .0). it is snuff color In font there will be three types they are 1.gray etc… Here Color is a class. Color. y. g. g is an object.//To display an image import java. yellow is variable. (or) Moving pictures expert group To display image in a frame for this purpose we should use drawImage of graphic class. Image observer obj).0.Color.B. //Default Constructor Images() { //Load an image into img Page 73 of 148 setIconImage() 50 50 drawImage() rambabumandalapu@yahoo. //Θ Image is a class name & img is a variable.com .20. Image observer containing the address of the image and history of the image.red.PLAIN In the above program public void paint(Graphics g) paint() method belongs to component class. Ex: .BOLD 2. Color c = new Color(0. Graphics is an Abstract class.255. R.yellow.g. Color c = new Color(25.awt.event*. Ex: . import java.Advanced Java Ex: .b).G.0. x. green. By creating color class object with a combination of red. Font. GIF – Graphic image format JPEG – Joint photographer’s expert group MPEG – Motion pictures expert group. Font.ITALIC 3. class Message extends Frame { //vars static Image img.Color c = new Color(r.drawImage(image. Color.Color c = new Color(255.

setSize(500. } }).drawImage(img.com .gif”). //set the size of frame i.exit(0). 50.addImage(img. //Θ Here ‘0’ is Image ID No. } //close constructor public void paint(Graphics g) { //Display the image in frame g. //set a title to the frame i. //wait till the image is loaded try{ track. //now add image to track track.setIconImage(img). } public static void main(String[ ] args) { //create the frame Image i = new Image().Advanced Java img = Toolkit. }catch(InterrputedException ie){ } //close the frame addWindowListener(new windowAdaptor() { public void windowClosing(windowEvent e) { System.getDefaultToolkit(). 0). MediaTracker track = new MediaTracker(this).waitForID(0). //display the image in the title bar i. //display the frame Page 74 of 148 rambabumandalapu@yahoo.steTitle(“My Image”). 50. null).400).getImage(“twist. //Θ ’this’ is a current class object. //To keep the processor with till image is loaded into image.

} }).show(). //Θ Image is a class name & img is a variable. //now add image to track track.*. //wait till the image is loaded try{ track.getImage(“twist.exit(0). import java. } //close constructor public void paint(Graphics g) { Page 75 of 148 rambabumandalapu@yahoo.awt.setVisible (true).gif”). }catch(InterrputedException ie){ } //close the frame addWindowListener(new windowAdaptor() { public void windowClosing(windowEvent we) { System.awt.//To display an image import java. (or) i. class Message extends Frame { //vars static Image img. //To keep the processor with till image is loaded into image.event.Advanced Java i. //Θ ’this’ is a current class object. MediaTracker track = new MediaTracker(this).com .getDefaultToolkit(). } } (or) Ex: . 0).addImage(img.*. //Default Constructor Images() { //Load an image into img img = Toolkit.waitForID(0). //Θ Here ‘0’ is Image ID No.

setSize(500. To get the label of the button clicked: String s = ae.setIconImage(img). 2. 4. //display the frame i.Button class is useful to create push buttons. //set a title to the frame i. Component Button CheckBox Listener ActionListener ItemListener Listener Methods actionPerformed(ActionEvent e) itemStateChanged(ItemEvent e) Page 76 of 148 rambabumandalapu@yahoo. 50.y. 1. pixels } public static void main(String[ ] args) { //create the frame Image i = new Image().show().event package. Listeners: .steTitle(“My Image”). //Θ 300. A push button triggers a series of events.A Listener is an interface that listens to an event from component. (or) i. 300. 3. 1. To create a push button with a label Button b = new Button(“label”). } } Button: .400). 2.com . 50. To set the label of the button: b.getActionCommand(). //set the size of frame i. No.Advanced Java //Display the image in frame g. To get the label of the button String l = b. //Θ Here ae is object of ActionEvent. null).setLabel(“label”). //display the image in the title bar i.setVisible(true).getLabel(). // Θ label -The text will displayed on the button.awt. 350 are x. 350.drawImage(img. Listeners are in java. S.

//Default Constructor MyButton() { Page 77 of 148 rambabumandalapu@yahoo. List ItemListener (or) ActionListener 9. b3. Scrollbar AdjustmentListener(or) MouseMotionListener adjustmentValueChanged(adjuste ment e) mouseDragged(MouseEvent e) mouseMoved(MouseEvent e) focusGained(FocusEvent e) Note 1: . Choice ItemListener (or) ActionListener 8.The above all Listener methods are all ‘public void’ methods. TextArea ActionListener (or) FocusListener 7. Ex: .*. import java.*.removeActionListener().A Listener can be added to a component using addxxxListener() method.addActionListener().A Listener can be removed from a component using removexxxListener() method. Note 4: . class MyButton extends Frame implenets ActionListener { //vars Button b1.actionPerformed(ActionEvent e).awt. 4. Note 3: . Note 2: . b2. Ex: .Advanced Java 3. Ex: .com . Ex: .A Listener takes an object of xxxEvent class.event.//Push Buttons import java.awt. 5. CheckBoxGroup Label TextField ItemListener --ActionListener (or) FocusListener 6.

Page 78 of 148 rambabumandalapu@yahoo. //Create 3 push buttons b1 = new Button(“Yellow”).addActionListener(this). //close the frame addWindowListener(new windowAdaptor() { public void windowClosing(windowEvent we) { System. 75 is the width of button. // (or) setLayout(null).com . 150. } //close constructor public void actionPerformed(ActionEvent ae) { //Know which button is clicked String str = ae.*/ b2 = setBounds(50. 100. b3 = new Button(“Pink”).addActionListener(this). b2 = new Button(“Blue”). b2. 40 is the height of the button.Advanced Java //donot set any layout manager setLayput(new FlowLayout()). 75. //add action listener to the frame b1. 75. 40). 100 are x. //set position of these buttons b1 = setBounds(50. 40). /*Here 50.. //add these buttons to the frame add(b1). 40). b3. add(b3). add(b2).getActionCommand(). 200.exit(0). } }). b3 = setBounds(50. 75. y coordinates where the buttons should place in the frame. Here null means not setting any Layout.addActionListener(this).

Advanced Java if(str. Then create an object to our class. //set a title to the frame mb. 1.setVisible(true). if(str.equals(“Pink”)) setBackground(Color.com . (or) mb. Page 79 of 148 rambabumandalapu@yahoo.400).blue). extend your class to Frame class. To create a Frame. } public static void main(String args[ ]) { //create the frame MyButton mb = new MyButton(). A frame is a top level window that oes not contain in another window.BorderLayout manger What is default layout manager in Applets? ***** Ans: . if(str.steTitle(“My Push Buttons”).show(). //set the size of frame mb.pink). } } What is default layout manager in frame? ***** Ans: .yellow).equals(“Blue”)) setBackground(Color.Frame is also a component.FlowLayout manager What is default layout manager in Panel? ***** Ans: .FlowLayout manager Frame: . It is a container to place the components.equals(“Yellow”)) setBackground(Color.setSize(500. //display the frame mb.

setFont(f). All components can removed from frame using removeAll() 11. use show() (or) setVisible() Refreshing the contents of a Frame: 5. //Θ (255. A component can be disappeared using setVisible(false) 13. An component can be added to a frame using add() 9. Creating Color: Ex 1: Ex 2: setColor(Color. A component can be removed from a frame using remove() 10. 0. Font for the displayed text on the component can be set with setFont(). Use Graphics class method: drawImage() About components (Component class methods): 8. Color c = new Color(255. 15.. Creating Font: Font f = new Font(). To set a size for the frame. To set a title for the frame. Use Graphics class method: drawString() Displaying images in a Frame: 7.yellow). Displays text in a Frame: 6. 0). (or) 800 x 600 (or) 640 x 480 Page 80 of 148 rambabumandalapu@yahoo. Maximum size of screen in pixels: 1024 x 768. G. 0) are R. use setTitle() 3. Values respectively setColor(c). The component class got a method paint() that paints (refreshes) the area in a frame. To display the frame. Any component can be displayed using setVisible(true) 12.com . A component can be placed in a particular location in the Frame with setBounds(). 0. use setSize() 4. B. A component’s colors can be set using setBackground() setForeground() 14..Advanced Java 2. //Component class methods also in Graphics class.

getState().getSelectedObjects(). //Add checkboxes to frame add(c1). 4. 1. To get the state of a checkbox boolean b = cb.awt. c2. Object x[ ] = cb. To get the state of Checkbox cb. String msg = “ “. 5.//CheckBoxes import java. method.*. c1 = new Checkbox(“Italic”). Page 81 of 148 rambabumandalapu@yahoo. true). null. Ex: . c3.awt. 3.A check box is a square shape box. import java. null. This method returns an array size 1 only. true). class MyCheckbox extends Frame implements ItemListener { //Variables Checkbox c1. 6. //Create 3 check boxes c1 = new Checkbox(“Bold”. Here ‘null’ is checkbox group object.event. c1 = new Checkbox(“Underline”).*. To create a check box: Checkbox cb = new Checkbox(“label”). 2.setState(true). To get the label of a checkbox String s = cb.getLabel(). which provides a set of options to the user.Advanced Java Check box: . To create a checked checkbox: Checkbox cb = new Checkbox(“label”.com . To get the selected checkbox label into an array we can use getSelectedObjects(). MyCheckbox() { //Set flow layout manager setLayout(new FlowLayout()).

add(c3). 20. 140). coordinates rambabumandalapu@yahoo. 20. msg = “Underline: ”+e3. } public void itemStateChanged(ItemEvent ie) { repaint(). 120). c3. g. 100). g.exit(0). //close the frame addWindowListener(new windowAdaptor() { public void windowClosing(windowEvent we) { System.drawString(msg. } public static void main(String args[ ]) { //Create Frame MyCheckbox mc = new MyCheckbox(). msg = “Italic: ”+e2.getState(). 160).getState().drawString(“Status of Checkboxes”.addItemListener(this).drawString(msg.addItemListener(this).Advanced Java add(c2). // (or) call paint(). } }).com . Page 82 of 148 //Θ 20. 120 are x. msg = “Bold: ”+e1.addItemListener(this). c2.getState(). } public void paint(Graphics g) { //Display the status of check boxes g.drawString(msg. //Add item listeners to checkboxes c1. 200. 20. g.

add(“text”).Choice is a popup list of items.*.java. 400). This method returns -1 if nothing is selected.setSize(500. Choice menu (or) Choice Box: .getSelectedIndex().setVisible(true). method calls update() method. Only one item can be selected.awt.By overridingUpadte() method in specifying background color in update() method. 2. To know the name of the item selected from the choice menu String s = ch.repaint(). 4. To create a choice menu Choice ch = new Choice().getSelectedItem().event.setTitle(“My Check Boxes). Then update() method will calls the paint() method. //Display the frame mc. Ex: .com .//Choice Box import java. mc. class MyChoice extends Frame implements ItemListener { Page 83 of 148 rambabumandalapu@yahoo. How can reduce in graphics or awt or frames? ***** Ans: . 3. 1. To know the index of the currently selected item int i = ch. To ad items to the choice menu ch. Which method is called by repaint() method? ***** Ans: .Advanced Java //Set size and title mc.*.awt. } } Save it as MyCheckbox. import java.

add(“Parata”).exit(0).Advanced Java //Variables String msg. } public void paint(Graphics g) { Page 84 of 148 rambabumandalapu@yahoo.add(“Chapathi”). //Window closing addWindowListener(new windowAdaptor() { public void windowClosing(windowEvent we) { System. } }). // (or) call paint(). MyChoice() { //Set flow layout manager setLayout(new FlowLayout()). //Add the Choice box to the frame add(ch).add(“Veg Biryani”). //add items to choice box ch. ch. } public void itemStateChanged(ItemEvent ie) { //call the paint() repaint(). //ad item listener to the choice box ch. ch. ch.add(“Idly”). Choice ch. ch = new Choice().add(“Dosee”). ch.addItemListener(this).com .

add(“Dosee”). ch. g. true).add(“Chapathi”). //Display the frame mc.150).*. 400).setSize(500.setTitle(“My Choice menu”).drawString(msg.*. g.event. ch = new List(3. } } //Choice Box import java.drawString(“Selected item: ”. List ch. } public static void main(String args[ ]) { //Create Frame MyChoice mc = new MyChoice().add(“Idly”). mc.com . Page 85 of 148 (or) Save the above code as MyChoice. //add items to choice box ch.setVisible(true). 10.getSelectedItem().awt. ch.170). MyChoice() { //Set flow layout manager setLayout(new FlowLayout()).Advanced Java //know the user selected item msg = ch. class MyChoice extends Frame implements ItemListener { //Variables String msg[ ]. 10. import java.java rambabumandalapu@yahoo.awt. //Set size and title mc.

} public void itemStateChanged(ItemEvent ie) { //call the paint() repaint(). } } public static void main(String args[ ]) { //Create Frame MyChoice mc = new MyChoice(). for(int i = 0. //ad item listener to the choice box ch. 10.exit(0). } public void paint(Graphics g) { //know the user selected item msg = ch. //Add the Choice box to the frame add(ch).getSelectedItems(). // (or) call paint(). i++) { g.170 + i * 20). Page 86 of 148 rambabumandalapu@yahoo.150).Advanced Java ch. ch.length. i<msg.com . } }).drawString(“Selected items: ”. g. 10.add(“Veg Biryani”). //Window closing addWindowListener(new windowAdaptor() { public void windowClosing(windowEvent we) { System.add(“Parata”).drawString(msg[ i ].addItemListener(this).

Advanced Java //Set size and title mc.setSize(500, 400); mc.setTitle(“My Choice menu”); //Display the frame mc.setVisible(true); } } List Box: - A list box is a similar to a choice box, but it allows the user to select multiple items. 1. To create a list box List lst = new List(); //Only 1 item can be selected. List lst = new List(4, true); //Multiple items can be selected. //and 4 items are initially visible From the above true means we can select multiple items, if we write false, it means we can select only single item. 2. To add items to list box lst.add(“text”); 3. To get the selected items String x[ ] = lst.getSelectedItems(); 4. To get the selected indexes int x[ ] = lst.getSelectedIndexes(); Ex: - //List 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);
Page 87 of 148

rambabumandalapu@yahoo.com

Advanced Java //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) { //know the user selected item msg = ch.getSelectedItems(); g.drawString(“Selected items: ”, 10,150); for(int i = 0; i<msg.length; i++) { g.drawString(msg[ i ], 10,170 + i * 20); } }
Page 88 of 148

rambabumandalapu@yahoo.com

Advanced Java 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); } } Radio Buttons: - A radio button represents a round shaped button, such that only one can be selected from a panel/group. Radio button can be treated using CheckboxGroup class and Checkbox classes. 1. To create a radio button CheckboxGroup cbg = new CheckboxGroup(); Checkbox cb = new Checkbox(“label”, cbg, true); 2. To know the selected checkbox Checkbox cb = cbg.getSelectedCheckbox(); 3. To know the selected checkbox label String label = cbg.getSelectedCheckbox().getLabel(); Ex: - //CheckboxGroup emo import java.awt.*; import java.awt.event.*; class Myradio extends Frame implements ItemListener { //Variables String msg =” ”; CheckboxGroup cbg; Choicebox y,n; Myradio () { //Set flow layout manager setLayout(new FlowLayout());
Page 89 of 148

rambabumandalapu@yahoo.com

100). //Set size and title mr. msg = cbg.com . } }).cbg. n. Page 90 of 148 //end of constructor public void itemStateChanged(ItemEvent ie) rambabumandalapu@yahoo.drawString(msg. } //Display the selected checkbox name public void paint(Graphics g) { msg = “Current Selection: ”. y = new Checkbox(“Yes”. } public static void main(String args[ ]) { //Create Frame Myradio mr = new Myradio().addItemListener(this).addItemListener(this). g.false). add(n). } { //call the paint() repaint().setSize(500. 10. y. 400).Advanced Java cbg = new CheckboxGroup(). add(y).exit(0).true). //Window closing addWindowListener(new windowAdaptor() { public void windowClosing(windowEvent we) { System. // (or) call paint(). n = new Checkbox(“No”.cbg.getSelectedCheckbox().getLabel().

p. 1. alignmentconstant). To create a TextFiled TextField tf = new TextField(25). Label.CENTER.tf.awt. (or) rambabumandalapu@yahoo. TextArea ta = new TextArea(rows.setVisible(true). Note: . but it accepts more than one line of text from the user.alignmentconstant: Label. //Display the frame mr. Ex: . tf.*.awt. To hide the text begin typed into the TextField.setEchoChar (‘char’). Label: .//Labels and TextField import java. Label.com . (Θ Here 25 is width of characters) 2.LEFT.*. Note: . Page 91 of 148 //(or) mr. 25).TextArea is similar to a TextField.A Label is a constant text that is displayed with a TextField.event. import java. class MyText extends Frame implements ActionListener { //Variables TextField name. 4. TextArea: . To create a label Label l = new Label(“text”. To get the text from a TextField TextField tf = new TextField(“default text”. CheckboxGroup cbg.setTitle(“My Radio Buttons”). by a character.TextArea supports getText(). pass. Label n.Advanced Java mr.setText (“text”). 3.setEchoChar (‘*’). 1. } } TextField: . To set the text into a TextFiled tf. To create a TextArea TextArea ta = new TextArea().RIGHT. and setText(). Ex: . cols).TextFiled allows a user to enter a single line of text. 1.show().

addActionListener(this). add(pass).Advanced Java MyText() { //Set flow layout manager setLayout(new FlowLayout()). //add the components to the Frame add(n). rambabumandalapu@yahoo. //create 2 textfields name = new TextField(20). pass = new TextField(15). p = new Label(“Password: ”. } Page 92 of 148 //end of constructor public void actionPerformed(ActionEvent ae) // (or) call paint(). add(p).setEchoChar(‘*’). //add actionListener to text fields name.com . add(name). pass. //create 2 labels n = new Label(“Enter Name: ”.RIGHT). } }).exit(0). //Closing for the Frame addWindowListener(new windowAdaptor() { public void windowClosing(windowEvent we) { System. //Hide the text filed in the pass filed pass.addActionListener(this). Label. } { //call the paint() repaint().RIGHT). Label.

//create 2 labels n = new Label(“Enter Name: ”.*. Label n. pass. p.awt.120).*. 400).drawString(“Name: ”+name.event.com .20.drawString(“Password: ”+pass.setTitle(“My Text Fields”). } public static void main(String[ ] args) { //Create Frame MyText mt = new MyText().RIGHT).awt.getText(). //create 2 textfields Page 93 of 148 //(or) mr.setVisible(true). Label.setSize(500. import java.RIGHT). mt. } } (or) //Labels and TextField import java.Advanced Java //Display the selected checkbox name public void paint(Graphics g) { g. //Display the frame mt.100). g. //Set size and title mt. class MyText extends Frame implements ActionListener { //Variables TextField name. p = new Label(“Password: ”. MyText() { //Set flow layout manager setLayout(new FlowLayout()).20. Label. CheckboxGroup cbg.show().getText(). rambabumandalapu@yahoo.

//Closing for the Frame addWindowListener(new windowAdaptor() { public void windowClosing(windowEvent we) { System.com . pass. //add actionListener to text fields name. //set colors and font for name name. 20).setFont(f). //Hide the text filed in the pass filed pass.addActionListener(this).PLAIN. add(p). Name. add(name). } //Display the selected checkbox name public void paint(Graphics g) { Page 94 of 148 //end of constructor public void actionPerformed(ActionEvent ae) // (or) call paint(). Font f = new Font(“Arial”. rambabumandalapu@yahoo. //add the components to the Frame add(n). } }). } { //call the paint() repaint(). pass = new TextField(15).addActionListener(this).red).setEchoChar(‘*’).setBackground(Color.exit(0).setForeground(Color.yellow). Font.Advanced Java name = new TextField(20). add(pass). name.

drawString(“Password: ”+pass. class Frame1 extends Frame implements ActionListener { //Variables Button b.//Moving from one frame to another frame import java.Advanced Java g. g.awt. } //end of constructor public void actionPerformed(ActionEvent ae) Page 95 of 148 //(or) mr. //Set size and title mt.show(). //Constructor Frame1() { //Closing for the Frame addWindowListener(new windowAdaptor() { public void windowClosing(windowEvent we) { System. import java.setTitle(“My Text Fields”). } public static void main(String[ ] args) { //Create Frame MyText mt = new MyText(). } }).getText().com .setVisible(true). rambabumandalapu@yahoo.100).event.20.20.drawString(“Name: ”+name.*. 400). } } Ex: .*. mt.exit(0).setSize(500.awt.120).getText(). //Display the frame mt.

} public static void main(String args[ ]) { //Create first Frame Frame1 f1 = new Frame1(). //(or) f1.event. f2.setTitle(“My Text Fields”). we have to write below code. rambabumandalapu@yahoo.setTitle(“My Next Window”).setVisible(true).setSize(500. b = new Button(“Back”).com .show(). f1. f2.awt. class Frame2 extends Frame implements ActionListener { //Variables Button b.setSize(300.awt.*. f2.300). import java. //Display the frame f1. add(b).*.java.Advanced Java { //Go to the next frame Frame2 f2 = new Frame2(). //This is Second Frame import java.setVisible(true). Page 96 of 148 //(or) f2. //Constructor Frame2() { //Set flow layout manager setLayout(new FlowLayout()). } } Save the above code as Frame1. //Set size and title f1. compile it but not run the above code.show(). 400).

String str = “Hello”. Page 97 of 148 (or) rambabumandalapu@yahoo. } public void actionPerformed(ActionEvent ae) { //Terminate the present frame this. b.java program.Advanced Java b.dispose(). add(b). compile it but not run the above code.*.awt. } } Save the above code as Frame2. initially we have to run the Frame1. b = new Button(“Next”). } }).exit(0). class Frame1 extends Frame implements ActionListener { //Variables Button b. //Constructor Frame1() { //Set flow layout manager setLayout(new FlowLayout()). //Closing for the Frame addWindowListener(new windowAdaptor() { public void windowClosing(windowEvent we) { System.awt.event. //Moving from one frame to another frame import java.addActionListener(this).com .*.addActionListener(this). import java.java.

f1. } } Save the above code as Frame1.setSize(300. rambabumandalapu@yahoo.setSize(500.awt.*. //(or) f1. f2.awt. 400).str = str. //Display the frame f1.300).setVisible(true).com . //This is Second Frame import java.*. class Frame2 extends Frame implements ActionListener { //Variables Button b. we have to write below code.setTitle(“My Text Fields”). f2. //Constructor Frame2(String str) { this. String str.setVisible(true).java.show().Advanced Java } { //Go to the next frame Frame2 f2 = new Frame2(str). import java. f2. } public static void main(String args[ ]) { //Create first Frame Frame1 f1 = new Frame1().show(). compile it but not run the above code.setTitle(“My Next Window”).event. Page 98 of 148 //end of constructor public void actionPerformed(ActionEvent ae) //(or) f2. //Set size and title f1.

Native code after creating the peer component it will returns the awt. All the AWT components are heavy weight components because they take (or) use more resources of the system i. Native code internally creates the peer component.java.dispose(). add(b).addActionListener(this).e. } } Save the above code as Frame2. AWT Peer Component based model The look and feel of components is changing. initially we have to run the Frame1. 150). AWT is peer component based model Button Native code (It is written in another language especially in C-Language) Button Peer Component AWT depends on native code. Heavy weight components Page 99 of 148 rambabumandalapu@yahoo. they take more memory and take more time to process by the processor. b. b = new Button(“Back”). 20. compile it but not run the above code. } public void paint(Graphics g) { g.Advanced Java //Set flow layout manager setLayout(new FlowLayout()). AWT depends on the Operating System. } public void actionPerformed(ActionEvent ae) { //Terminate the present frame this.drawString(str.com .java program.

java. It contains libraries that are completely portable.dnd: . This is the main difference of JFC with AWT. javax.To provide a native look and feel to swing components. menus. “Controller” deals with user interaction with the component and modifies the model or the view in response to the user action. 2. “View” creates the visual representation of the component from the data in the model. 3. JFC components will have same look and feel or all platforms (or) Operating Systems. (Θ Where geom stands for geometrical shapes).JFC is an extension of the original AWT. They take less system resources. 4.awt. JFC components are light-weight. 4.swing. JFC: . JFC does not replace AWT.swing: 1. JFC is written in pure Java language. (Θ In javax. x stands for extended package) 3. JFC offers a rich set of components with lots of features.plaf: .. etc.awt. JFC is an extension of AWT. The programmer can change the look and feel as suited for a platform. java. filling rotating the shapes. Page 100 of 148 rambabumandalapu@yahoo. 5.com . java. (Θ Where dnd stands for drag & drop the data (or) component).Advanced Java Due to the above disadvantages Javasoft people developed JFC (Java Foundation Classes) is a group of classes which are extended from AWT. All components in swing follow a Model View Controller (MVC) architecture.accessibility: . “Model” stores the data that defines the state of a button (pushed in or not) or text present in a text field.To drag and drop the components and data from one place to another place.To provide accessibility of applications to disabled persons.swing: . javax. javax. 1. 2.To draw 2D graphics. In JFC we have 5 packages.geom: . 5. Major packages in JFC: 1.To develop components like buttons. It is pluggable.

e. In MVC the Presentation logic and Business logic have been separated Advantages: a) We can develop Presentation logic and Business logic using different languages. It will inform the component changes view controlling on operator supporting model same data model.com . We can display different views now display that the data has pie chart i. b) Any changes to one part can be made without disturbing the other part.Advanced Java If Ok button is not pressed the value will Here Ok button is pressed be 0 1 Ok View Presentation logic Controller Model Business logic State of the component is represented by a model. 2. It is other components. Controller works like a mediator. MVC architecture is useful to creating plof components pluggable and lockable components. Model Window Panes: - A Controller View window pane represents an object that can contain an area of a window. another views. Different views we can reviews some same data different systems. 1. Page 101 of 148 rambabumandalapu@yahoo.

JFrame class methods: 1. getGlassPane() : .Returns an object of Container class : .Returns an object of JRootPane class : .com . To give Foreground we have to use Glass pane. getRootPane() 4. Page 102 of 148 rambabumandalapu@yahoo. getLayeredPane() 3. getContentPane() 2. Groups of components are attached to Layered pane. To give background we have to use Root pane.Returns an object of Component class Ex: .Returns an object of JLayeredPane class : .Going to Content Pane JFrame jf = new JFrame().Advanced Java Company Logo Title bar Minimize Restore Close Frame Window Pane Window Panes Content Pane our Components Layered Pane Components group Title Root Pane Background Components Glass Pane Foreground Components JFrame All individual components are attached to Content pane.

We can create a Frame b directly creating an object to JFrame JFrame obj = new JFrame(“Title”). class MyClass extends JFrame MyClass obj = new MyClass(). c.swing.| Component.awt |-----------------------javax.add(button).350). class MyFrame { public static void main(String args[ ]) { //create the frame JFrame obj = new JFrame(“My Swing Frame”).getContentPane(). Write a class that extends JFrame then create an object to it.setSize(400. (Θ Here obj represents the JFrame) Ex: . Page 103 of 148 Hierarchy of classes in Swing: - JRadioButton JCheckbox JTextField rambabumandalapu@yahoo. //increase the size of the frame obj. Window. 2.com . Component Container Window Frame JComponent JWindow JFrame (Θ Here c is a Container Object). Frame these four classes are belongs to awt package.swing-----------------------.//Creating a Frame in Swing import java.Advanced Java Container c = jf. Container. Creating a Frame: 1. JTabbedPane JButton JComboBox JLabel JToggleButton JList JMenu JmenuBar JmenuItem JTextComponent JTextArea |java.*.

EXIT_ON_CLOSE).setDefaultCloseOperation(JFrame.com .*.setVisible(true). class MyFrame extends JFrame { public static void main(String args[ ]) { //create the frame MyFrame obj = new MyFrame(). //display the frame obj. //increase the size of the frame obj.green).350). } } 1. //set the title for frame obj. //close the frame obj. Adding Components: To add a component to JFrame.getContentPane(). //reach the content pane Container c = obj.setTitle(“Swing Frame”). //Set background color to c (Θ Where c is Content pane) c.setVisible(true).awt. //close the frame obj. we should add it to container as shown below.swing.*. import java. Page 104 of 148 rambabumandalapu@yahoo.//Creating a Frame in Swing v2.0 import java. } } Ex: .setDefaultCloseOperation(JFrame.Advanced Java //display the frame obj.getContentPane(). Container c = jf.setSize(400.setBackground(Color.EXIT_ON_CLOSE).

setBackground(color). component. //default constructor Page 105 of 148 rambabumandalapu@yahoo. Border bd = BorderFactory.border.createLineBorder(color.left.bottom. import java.setToolTipText(“This is a Swing Component”).createMatteBorder(top.awt. menus and buttons.swing.*.createEtchedBorder(). componet.black.color.Advanced Java c. 7.swing.remove(component). It is used with ALT key to select an option. Border bd = BorderFactory.LOWERED).com .*.*. Border bd = BorderFactory.getContentPane().RAISED).setForeground(color). Border bd = BorderFactory.right.border. (or) jf. Removing Components: To remove a component c. Setting a shotcut key: A shortcut key (mnemonic) is an underlined character used in labels.3).createBevelBorder(BevelBorder. Setting line Borders: javax.setLayout(LayoutManager obj). Setting tooltip to a component: component.add(component).BorderFactory class is helpful to set different line borders.//A push button with all attributes import java.add(component). Setting colors for components: componet. Ex: . 2.createBevelBorder(BevelBorder. Border bd = BorderFactory. 4. import java. 5.swing. componet. Setting a Layout Manager: To set a LayoutManager for the Container c.black).get.setMnemonic(chart ‘c’).setBorder(bd). 3. class MyButtton extends JFrame { //variables JButton b. 6.

//close the frame this.setDefaultOperation(JFrame.yellow). //set a shortcut key b.Advanced Java MyButtton() { //go to content pane Container c = this. Font. b. ii).setForeground(Color.getContentPane().com .red). Page 106 of 148 rambabumandalapu@yahoo.add(b).setLayout(new FlowLayout()). //set tooltip text for b b. //Create ImageIcon object ImageIcon ii = new ImageIcon(“twist. //set size. b.setTitle(“My Push Button”).RAISED).setFont(f).setBorder(bd).25). title mb.createBevelBorder(BevelBorder. //add button to conten pane c.BOLD. //set colors to b b.gif”). b.setToolTipText(“I am a lazy button”).setBackground(Color.EXIT_ON_CLOSE). //create push button with image on it b = new JButton(“Click me”. //set a font to b Font f = new Font(“Arial”. //set a layout to contentpane c. { //create the frame MyButton mb = new MyButton(). } public static void main(String args[ ]).setMnemonic(‘c’). //set bevel border around b Border bd = BorderFactory.

//A push button with all attributes import java. b.gif”). } } Ex: .setSize(500.Advanced Java mb. Font. //create push button with image on it b = new JButton(“Click me”. class MyButtton extends JFrame implement ActionListener { //variables JButton b.swing. import java. import java.*.com . //default constructor MyButtton() { //go to content pane Container c = this.setFont(f).RAISED).yellow).createBevelBorder(BevelBorder.event. //set a font to b Font f = new Font(“Arial”. //display the frame mb. import java. JLabel lbl.setLayout(new FlowLayout()).setVisible(true).BOLD.*.*.awt. Page 107 of 148 rambabumandalapu@yahoo. b.setBackground(Color.awt.getContentPane(). //Create ImageIcon object ImageIcon ii = new ImageIcon(“twist. //set a layout to contentpane c.25). ii).400).border.setForeground(Color. //set colors to b b.*.swing.red). //set bevel border around b Border bd = BorderFactory.

//create an empty label and add to c lbl = new Label(). //set size.add(lbl): //add ActionListener to the button b.EXIT_ON_CLOSE). } public void actionPerformed(ActionEvent ae) { lbl. c. //display the frame mb.BOLD.addActionListener(this). true).setText(“Hello Students”).setBorder(bd). //add button to conten pane c.25). //set tooltip text for b b. //set a shortcut key b. //close the frame this.setMnemonic(‘c’).setFont(“Impact”.setToolTipText(“I am a lazy button”).setTitle(“My Push Button”).setDefaultOperation(JFrame. } } To create a checkbox and radio buttons JCheckBox cb = new JCheckBox(“label”. JRadioButton rb = new JRadioButton(“label”.com . Page 108 of 148 rambabumandalapu@yahoo. { //create the frame MyButton mb = new MyButton(). Font.400). title mb.add(b). } public static void main(String args[ ]). lbl. true).setVisible(true).Advanced Java b. mb.setSize(500.

ad(rb3). JLabel. JTextField tf = new JTextField(20).*. //default constructor CheckRadio() { //reach the content pane Container c = getContentPane().LEFT/JLabel.setLayout(new FlowLayout()). JRadioButton rb1.Advanced Java ButtonGroup bg = new ButtonGroup(). JLabel lbl = new JLabel(“text”.swing. bg.CENTER).//Checkboxes and Radio buttons import java. class CheckRadio extends JFrame implement ActionListener { //variables JCheckBox cb1. true). import java. ButtonGroup bg. cb2 = new JCheckBox(“J2EE”).com .*.*.20).of rows and 20 is No. //create 2 check boxes cb1 = new JCheckBox(“J2SE”. import java.awt. rb2 = new JRadioButton(“Female”).RIGHT/JLabel. of Columns) A label represents constant text i. //create 2 check boxes rb1 = new JRadioButton(“Male”. //set a layout to contentpane c.awt. true).ad(rb1). displayed in the content pane. bg.getContentPane(). Ex: . String str = “ ”.e.cb2.event.rb2. bg. JTextArea ta = new JTextArea(5. (or) Container c = this. (Θ Where 5 is No.ad(rb2). JTextArea ta. Page 109 of 148 rambabumandalapu@yahoo.

addActionListener(this).addActionListener(this).com .getModel().isSelected()).Advanced Java //Specify these 2 RadioButtons belong to one group bg = new ButtonGroup(). str +=”J2EE”.getModel().add(rb1). str +=”Female”. str +=”J2SE”. //send user selection to text area ta. Page 110 of 148 rambabumandalapu@yahoo. str=” ”. if(cb2.addActionListener(this).EXIT_ON_CLOSE). if(rb2. c.isSelected()).add(ta). rb2. c.setText(str). //add all these components to c c. cb2. bg.add(rb1). bg.addActionListener(this).20). rb1. //close the frame this.add(cb1).getModel(). c. str +=”Male”. //add ActionListener to the Checkboxes and Radio Buttons cb1.setDefaultOperation(JFrame.isSelected()). if(rb1.add(cb2). c. //create a text area ta = new JTextArea(5.getModel().add(rb2). } public void actionPerformed(ActionEvent ae) { //To know the user selection if(cb1.add(rb2).isSelected()).

//set a layout to contentpane c.event.*. import java.setLayout(new FlowLayout()). //default constructor CheckRadio() { //reach the content pane Container c = getContentPane().com . //create 2 check boxes cb1 = new JCheckBox(“J2SE”.400). (or) Container c = this. import java.*. class CheckRadio extends JFrame implement ActionListener { //variables JCheckBox cb1.cb2.setVisible(true).awt.awt.*. } } Ex: . ButtonGroup bg. String str = “ ”. Page 111 of 148 rambabumandalapu@yahoo.setTitle(“My CheckBoxes and Radio Buttons”).//Checkboxes and Radio buttons import java. true). //display the frame cr. //set size. cb2 = new JCheckBox(“J2EE”).setSize(500.Advanced Java } public static void main(String[ ] args). title cr. cr. JTextArea ta. { //create the frame CheckRadio cr = new CheckRadio().getContentPane().rb2. JRadioButton rb1.swing.

add(rb1). c. c.isSelected()).addActionListener(this).add(rb2). cb1.Advanced Java //set colors cb1.yellow).add(rb2).20). cb1. //Specify these 2 RadioButtons belong to one group bg = new ButtonGroup().com .setBackground(Color. c.20).addActionListener(this). rb2.getModel(). bg.getModel(). bg.add(cb2).addActionListener(this).setFont(new Font(“Sanserif”. str +=”J2SE”. //create a text area ta = new JTextArea(5.addActionListener(this).add(cb1). str +=”J2EE”. Page 112 of 148 rambabumandalapu@yahoo. cb2.add(rb1).setDefaultOperation(JFrame. } public void actionPerformed(ActionEvent ae) { //To know the user selection if(cb1.red).setForeground(Color. //add all these components to c c. //create 2 check boxes rb1 = new JRadioButton(“Male”.isSelected()).EXIT_ON_CLOSE). if(cb2. rb2 = new JRadioButton(“Female”). rb1. //add ActionListener to the Checkboxes and Radio Buttons cb1. //close the frame this. c. true). Font_ITALIC.add(ta).

setSize(500. cr.400). str +=”Female”. JTable Header String arr[4][3] data By using String arr[ ] [ ] we can store only one type of data. if we want to store different type of data it is better to use Vector. str +=”Male”. } public static void main(String[ ] args).setVisible(true). JTable: .setText(str). 1. and columns headings. Page 113 of 148 rambabumandalapu@yahoo. title cr. //set size. //send user selection to text area ta. } } A table represents several rows and columns of information.It represents data in the form of a table. if(rb2.setTitle(“My CheckBoxes and Radio Buttons”). column names).Advanced Java if(rb1.getModel(). { //create the frame CheckRadio cr = new CheckRadio().isSelected()). To create a JTable JTable tab = new JTable(data.isSelected()). The table can have rows of data.com . str=” ”. //display the frame cr.getModel().

500.*.swing.util.add(object). row.add(“Subba Rao”). JTableHeader head = tab. (or) row.JTableHeader class is defined in javax.//Creating Employee Table import java.*.add(“12. row. row. import javax. Note: . 3. we use getTableHeader() method of JTable class.*. row.swing.Advanced Java Here data and column names can be a 2D array or both can be Vector of Vectors. import javax.com .add(object).500.getTableHeader().add(object).table. Page 114 of 148 //Θ Here object represents a column.*.border.50”). rambabumandalapu@yahoo. //add this row to data table data. 2. To create a Table heading. row.add(“System Analyst”).add(row). //Create Second row add to data row = new Vector(). import javax. //store column data in row row. To create a row using a Vector Vector row = new Vector().swing. import java.awt. class Mytable extends JFrame { //Constructor Mytable() { //take data of table as Vector object Vector data = new Vector().50)). row.table package. //Create first row Vector row = new Vector().add(“Srinivasa Rao”).add(new Double(12.*. Ex: .swing.

row.add(“Sudha Sree”). cols. c.add(“Employee Name”).add(“Center”.setBorder(BorderFactory. row. row. cols).setLayout(new BorderLayout()).ad(“nort”. //set border layout to c c.add(“Sr. //create a row with column names Vector cols = new Vector().add(row). } public static void main(String args[ ]) { Page 115 of 148 North West Center East South rambabumandalapu@yahoo.Advanced Java row. head).com .EXIT_ON_CLOSE). cols.LOWERED)).add(“Salary”). //Go to the content pane Container c = getContenPane(). //add this row to data table data. row. //create the table now JTable tab = new JTable(data.000.000.getTableHeader(). cols.createBevelBorder(BevelBorder. //add this row to data table data.00”).add(“Designation”).add(“Receptionist”). tab)’ //close the frame setDefaultCloseOperation(JFrame.add(“16. //set a border to table tab.add(“35. //add head and tab to c c.add(row).75”). Programmer”). //Create third row add to data row = new Vector(). //display table heading JTableHeader head = tab.

2. 5. new CountriesPanel()).awt.Advanced Java Mytable nt = new Mytable(). } } JTabbedPane: . 1.addTab(“Title”. JTabbedPane is a container to add multiple components on every tab. mt. To remove all the tabs and their corresponding components jtp. To create a JTabbedPane JTabbedPane jtp = new JTabbedPane().removeAll().com .Pane means a window. class JTabbeddPaneDemo extends JFrame { //Constructor JTabbeddPaneDemo() { //Create tabbed pane JTabbeddPane jtp = new JTabbeddPane().removeTabAt(int index).*. jtp. 3. To create a panel containing some components class MyPanel extends JPanel Now pass ‘MyPanel’ class’s object to addTab().//Creating Employee Table import java. JPanel always represents group of components. To remove a tab (and its components) from the tabbed pane. import javax.*. Here.setVisible(true). To add tabs jtp. Ex: . 4.400). //add 2 tab sheets jtp. the object can be an object of panel. object). mt.setSize(500. Page 116 of 148 rambabumandalapu@yahoo.addTab(“Countries”. TabbedPane means a winow with tab sheets.swing. The user can choose a component from a tab.

add(c1). c. } public static void main(String args[ ]) { //Create a frame JTabbeddPaneDemo demo = new JTabbeddPaneDemo().add(jtp). b1 = new JButton(“India”). JCheckBox c1 = new JCheckBox(“Tokyo”). } } class CountriesPanel entends JPanel { CountriesPanel() { JButton b1. } } class CapitalsPanel entends JPanel { CapitalsPanel() { JCheckBox c1 = new JCheckBox(“New Delhi”). add(b2). b3 = new JButton(“Japan”).com .setVisible(true).Advanced Java jtp. b2 = new JButton(“USA”). add(b3).addTab(“Capitals”. JCheckBox c1 = new JCheckBox(“Wasington”). demo.setSize(500. new CapitalsPanel()). demo. b2. Page 117 of 148 rambabumandalapu@yahoo. b3. //attach jtp to Content pane Container c = getContenPane(). add(b1).400).

awt. 4.setDividerLocation(int pixels).event. orientation is JSplitPane. component1.JSplitPane is used to divide two (and only two) components. 3. 1.getDividerLocation().swing.//Split pane demo import java.com . Setting the divider location between the components sp. Creating a JSplitPane JSplitPane sp = new JSplitPane(orientation.*.awt. To remove a component fromsplit pane sp. class JSplitPaneDemo extends JFrame implements ActionListener Page 118 of 148 rambabumandalapu@yahoo. Getting the divider location int n = sp.VERTICAL_SPLIT to align the componets from top to bottom. import java. Here. add(c3). --------------------------------------------------- HORINZONTAL_SPLIT VERTICAL_SPLIT 2. To get the bottom or right side component Component obj = sp.Advanced Java add(c2). } } JSplitPane: .HORINZONTAL_SPLIT to align the componets from left to right. import javax.getBottomComponent().remove(Component obj).*. 6.getTopComponent(). JSplitPane. Ex: . component2). 5. To get the top or left side component Component obj = sp.*.

Advanced Java { //Variables String str = “This is my text being displayed in the text area” + “And this String will wrapped accorindly in the text area”; JSplitPane sp; JButton b; JTextArea ta; //Constructor JSplitPaneDemo() { //Go to the content pane Container c = getContenPane(); //set border layout to c c.setLayout(new BorderLayout()); //create a push button b = new JButton(“My Button”); //create the text area ta = new JTextArea(); //wrap the text in ta ta.setLineWrap(true); //create the split pane with b, ta sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, ta); //set the divider location sp.setDividerLocation(300); //add split pane to c c.add(“Center”, sp); //add action listener to b b.addActionListener(this); //Close the frame setDefaultCloseOperaton(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent ae) { //send str to ta
Page 119 of 148

rambabumandalapu@yahoo.com

Advanced Java ta.setText(str); } public static void main(String args[ ]) { //Create a frame JSplitPaneDemo jsp = new JSplitPaneDemo(); jsp.setSize(500,400); jsp.setTitle(“My Split Pane”); jsp.setVisible(true); } } JTree: - This component displays a set of hierachical data as an outline. C:\ -------- Root Noe (or) Root Directory Java Progs ----------JCheck.java JRadioButton.java 1. Create a node of the tree (root node, or node, or leaf node) using DefaultMutableTreeNode class. DefaultMutableTreeNode node = new DefaultMutableTreeNode(“Java Programs”); 2. Add the tree by supplying root node JTree tree = new JTree(root); 3. To find the path of selected of selected item TreePath tp = tse.getNewLoadSelectionPath(); Θ Where tse – tree seletion event 4. To find the selected item in the tree Object comp = tp.getLastPathComponent(); 5. To know the path number (this represents the level) int n = tp.getPathCount(); Ex: - //Creating a tree with directory names and file names import java.awt.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.tree.*; //TreeSelectionListener //TreePath
Page 120 of 148

Node

DefaultMutableTreeNode

JButton.java ---------- Leaf Node

rambabumandalapu@yahoo.com

Advanced Java class JTreeDemo extends JFrame implements TreeSelectionListener { //Variables JTree tree; DefaultMutableTreeNode root; //Constructor JTreeDemo() { //Go to the content pane Container c = getContenPane(); //set border layout to c c.setLayout(new BorderLayout()); //Create root, node, leaf nodes root = new DefaultMutableTreeNode(“C:\\”); DefaultMutableTreeNode dir1 = new DefaultMutableTreeNode(“Java Progs”); DefaultMutableTreeNode file1 = new DefaultMutableTreeNode(“JButton.java”); DefaultMutableTreeNode file2 = new DefaultMutableTreeNode(“JCheckBox.java”); DefaultMutableTreeNode file3 = new DefaultMutableTreeNode(“JRadioBut.java”); //add dir1 to root root.add(dir1); //add file1, file2, file3 to dir1 dir1.add(file1); dir1.add(file2); dir1.add(file3); //now create the tree tree = new JTree(root); //add this tree to c c.add(“North”, true); //add TreeSelectionListener to tree tree.addTreeSelectionListener(this); //close the frame setDefaultCloseOperaton(JFrame.EXIT_ON_CLOSE); } public void valueChanged(TreeSelectionListener tse)
Page 121 of 148

rambabumandalapu@yahoo.com

*.swing. } public static void main(String args[ ]) { //Create a frame JTreeDemo demo = new JTreeDemo().*. Page 122 of 148 //TreeSelectionListener //TreePath class JTreeDemo extends JFrame implements TreeSelectionListener rambabumandalapu@yahoo.getLastPathComponent(). demo. import javax.Advanced Java { //Know the path of item selected TreePath tp = tse. //Know the item selected Object comp = tp.println(“Path of selected item = ” +tp). import javax.setVisible(true).awt. System.swing.out.getNewLeadSelectionPath(). } } (or) Ex: . //Constructor JTreeDemo() { //Go to the content pane Container c = getContenPane(). DefaultMutableTreeNode root.out. demo.//Creating a tree with directory names and file names import java.setSize(500.out.println(“Item selected = ” +comp). { //Variables JTree tree.println(“Level of item = ” +n). System.event.400).getPathCount().com .*.*.swing. //Know the level of item selected int n = tp.tree. import javax. System.

EXIT_ON_CLOSE). //add file1.add(dir1).setLayout(new BorderLayout()). DefaultMutableTreeNode file1 = new DefaultMutableTreeNode(“JButton. DefaultMutableTreeNode file2 = new DefaultMutableTreeNode(“JCheckBox.getPathCount().println(“Item selected = ” +comp).add(file3).out.java”).println(“Level of item = ” +n).file1. //Know the item selected Object comp = tp. //add TreeSelectionListener to tree tree.com . System.java”). //Know the level of item selected int n = tp. //add this tree to c c. leaf nodes root = new DefaultMutableTreeNode(“C:\\”). //close the frame setDefaultCloseOperaton(JFrame.getNewLeadSelectionPath(). DefaultMutableTreeNode dir1 = new DefaultMutableTreeNode(“Java Progs”). } public static void main(String args[ ]) Page 123 of 148 rambabumandalapu@yahoo.out. System. node. //Create root. System. //add dir1 to root root.Advanced Java //set border layout to c c. true). DefaultMutableTreeNode file3 = new DefaultMutableTreeNode(“JRadioBut.java”). //now create the tree tree = new JTree(root). file3 to dir1 dir1.println(“Path of selected item = ” +tp). } public void valueChanged(TreeSelectionListener tse) { //Know the path of item selected TreePath tp = tse.addTreeSelectionListener(this).out.add(“North”. file2.getLastPathComponent().

setVisible(true). Add menu bar to the content pane. Steps: 1.setSize(500.Advanced Java { //Create a frame JTreeDemo demo = new JTreeDemo(). 2.com . 4. Attach this MenuBar to the container/Container Pane Page 124 of 148 rambabumandalapu@yahoo. Company Logo Title bar JMenuBar JMenu JmenuItem File New Open Close Print Edit Cut Copy Paste Sub menu Font Arial Times New Roman Creating a menu: Steps: 1. Create a menu and add it to another menu. Create menu items separately and add them to menus. demo. Create a MenuBar JMenuBar mb = new JMenuBar(). demo. 2. Creating a menu: 1.400).A menu represents a group of options for the user to select. Create menu items and add them to sub menu. } } Menu: . Creating a Sub menu: . 3. Create menus using JMenu class. Create menu bar using JMenuBar class 2.Sub menu is a menu inside another menu.

“File” is title for the menu which appears in the MenuBar.add(new). Create separate menu to attach to the MenuBar JMenu file = new JMenu(“File”). Attach this menu to the MenuBar mb. Create a menu: JMenu font = new JMenu(). JMenuItem op.event. class MyMenu extends JFrame implements ActionListener rambabumandalapu@yahoo. { //Variables JMenuBar mb.obj can be a MenuItem or JCheckBoxMenuItem or JRadioButtonMenuItem. MenuBar etc… //All Listeners in this package. 9. Attach this menu item to the menu file. 8.*. Now attach it to a menu file. JCheckBoxMenuItem pr. Note: . edit.swing. Create menu items using JMenuItem or JCheckBoxMenuItem or JRadioButtonMenuItem classes JMenuItem nw = new JMenuItem(“New”). 3. Ex: . Creating a sub menu: 7. font.add(file).add(font). import javax. Note: . import javax.com .swing.*.Advanced Java c. pt. 5. Attach menu items to the font sub menu font.add(obj). cp. cl.Here. 4.*.//Creating a menu import java.awt.add(mb). //Constructor MyMenu() { //Go to the content pane Page 125 of 148 //It is for Container //It is for JMenu. JMenu file. 6.

cp = new JMenuItem(“Copy”). cl = new JMenuItem(“Close”). edit = new JMenu(“File”). //create menu bar mb = new JMenuBar().add(cl).add(pr).com . //add pr to file menu file. mb).setEnabled(false). edit menus file = new JMenu(“File”). //add a line file. mb. //Create file. //add file.add(cp). //disable close item cl. //add op. //Create Print check box as a menu item pr = new JCheckBoxMenuItem(“Print”). //Create a font as a sub menu font = new JMenu(“Font”). //set border layout to c c.add(edit). edit menus to mb mb. //add cp. //create menu items op = new JMenuItem(“Open”). pt = new JMenuItem(“Paste”). //add menu bar to c c. file.add(file).setLayout(new BorderLayout()).addSeparator(). cl to file menu file.add(pt). pt to edit menu edit.add(“North”.Advanced Java Container c = getContenPane().add(op). edit. Page 126 of 148 rambabumandalapu@yahoo.

isArmed()) System. //set a font for text Font f = new Font(“Arail”).println(“Close Selected”). //add listeners to menu items op. font. if(cp. //Clsoe the frame setDefaultCloseOperaton(JFrame.println(“Printer On”). cl.out. if(cl.add(font).out.EXIT_ON_CLOSE).isArmed()) System.addActionListener(this). //add menu items to font font.println(“Copy Selected”).out.getModel.isArmed()) System. cp.addActionListener(this).println(“Paste Selected”).addActionListener(this).isArmed()) System. if(pt.addActionListener(this).add(f2). pr.isSelected()) System. pt.com .add(f1). if(pt.out. Font f1 = new Font(“Times New Roman”).addActionListener(this).println(“Open Selected”).out. } public void actionPerformed(ActionEvent ae) { //Know which item is selected by user if(op. } public static void main(String args[ ]) { //Create a frame Page 127 of 148 rambabumandalapu@yahoo.Advanced Java //add font to file menu file.

setSize(500. JCheckBoxMenuItem pr. Ex: . //set border layout to c c.add(“North”. edit = new JMenu(“File”). //Create file. pt.Advanced Java MyMenu mm = new MyMenu().400).setLayout(new BorderLayout()). JMenuItem op.swing. import javax.*. //add file. edit menus file = new JMenu(“File”). import javax. MenuBar etc… //All Listeners in this package.swing. //create menu items Page 128 of 148 class MyMenu extends JFrame implements ActionListener rambabumandalapu@yahoo. edit. mm.*. { //Variables JMenuBar mb. edit menus to mb mb. mb). //Constructor MyMenu() { //Go to the content pane Container c = getContenPane().*. } } (or) //It is for Container //It is for JMenu.//Creating a menu import java.setVisible(true).add(edit). //create menu bar mb = new JMenuBar().add(file).awt. mm.event. //add menu bar to c c. cp. JMenu file.com . mb. font. cl.

//add pr to file menu file. //add a line file. //add cp. pr. //set a font for text Font f = new Font(“Arail”). //Create Print check box as a menu item pr = new JCheckBoxMenuItem(“Print”). //add op. pt to edit menu edit.com . pt. cl.add(cl). cp = new JMenuItem(“Copy”).add(cp). file. edit. cp.add(pr).add(f1).addActionListener(this). //Create a font as a sub menu font = new JMenu(“Font”). Page 129 of 148 rambabumandalapu@yahoo. cl to file menu file. //add font to file menu file.add(op).addActionListener(this).addActionListener(this).add(font).add(pt).addActionListener(this). pt = new JMenuItem(“Paste”). //add listeners to menu items op. cl = new JMenuItem(“Close”).addActionListener(this). font.setEnabled(false). Font f1 = new Font(“Times New Roman”). //disable close item cl.Advanced Java op = new JMenuItem(“Open”). //add menu items to font font.add(f2).addSeparator().

showOpenDialog(this).out.out.APPROVE _ OPTION) System.getModel. if(cl.400). mm.isArmed()) this.getSelectedFile(). } public void actionPerformed(ActionEvent ae) { //Know which item is selected by user if(op.println(“Printer On”).setSize(500.com .println(“Close Selected”). } } Page 130 of 148 rambabumandalapu@yahoo.println(“Paste Selected”).isSelected()) System.out.Advanced Java //Clsoe the frame setDefaultCloseOperaton(JFrame.setVisible(true). if(cp.isArmed()) System.println(“Copy Selected”). if(pt.openFile().out. { //display file Selection box JFileChooser fc = new JFileChooser().isArmed()) System.out. } public static void main(String args[ ]) { //Create a frame MyMenu mm = new MyMenu(). if(pt.EXIT_ON_CLOSE).getName()). //See the file is selected or not if(i == JFileChooser.println(“U Select: ”+fc. mm. } void openFile().isArmed()) System. int i = fc.

int cols. component). int vgap) CardLayout: . import javax. b2 = new JButton(“Button2”).A layout manager arranges the components in a container. class GridLayoutDemo extends JFrame { //Constructor GridLayoutDemo() { //Go to the content pane Container c = getContenPane(). 2. To add the component: add(“cardname”. To retrieve the cards void first(container) void last(container) void next(container) void previous(container) void show(container. b4 = new JButton(“Button4”). CardLayout() CardLayout(int hgap. b2.It arranges the components in the form of deck of cards. int vgap) 1.swing. c.Advanced Java In java internally all constant numbers are represents as integer numbers. b4. “Card Name”). GridLayout() GridLayout(int rows. GridLayout grid = new GridLayout(). Page 131 of 148 Card 3 Card 2 Card 1 rambabumandalapu@yahoo. int cols) GridLayout(int rows. Ex: .//GridLayout Demo import java.com .*. b3.setLayout(grid).awt.It arranges the components in a 2D grid. JButton b1. LayoutManagers: . GridLayout: . b3 = new JButton(“Button3”).*. b1 = new JButton(“Button1”). int hgap.

b1). c. c. b2 = new JButton(“Button2”).event.com . JButton b1. c. CardLayout card. b2.400). b3 = new JButton(“Button3”).setVisible(true). demo.add(“Fisrt Card”. c.setSize(500. demo. b1 = new JButton(“Button1”).awt. import java.add(b1). c.add(“Second Card”.add(b2).add(b3).awt. c. //Constructor CardLayoutDemo() { //Go to the content pane c = getContenPane().*. Page 132 of 148 rambabumandalapu@yahoo.add(b4). b3.//CardLayout Demo import java. card = new CardLayout().Advanced Java c.*.b2). } public static void main(String args[ ]) { //Create a frame GridLayoutDemo demo = new GridLayoutDemo().setLayout(card).*. } } Ex: . import javax.swing. class CardLayoutDemo extends JFrame implements ActionListener { Container c.

GridBagLayout() 1.com . gridheight: . in which some Button 1 Button 2 Button 4 Button 3 components span more than one row or column. b1.addActionListener(this). It specify constraints for positioning of the components.addActionListener(this).Specify the row and column at the upper left of the y=2 component. Page 133 of 148 rambabumandalapu@yahoo.addActionListener(this).b3). y=1 2.Specify the number of colums (for gridwidth) or rows (for gridheight) in the components display area. } } GridBagLayout: . We can use GridBagConstraints class object.setSize(500. b3.400). The efault value is 1. { card.It specifies the components in a grid like fashion. } public void actionPerformed(ActionEvent ae). b2.Advanced Java c.next(c). gridy: .add(“Third Card”. demo. demo.setVisible(true). } public static void main(String args[ ]) { //Create a frame CardLayoutDemo demo = new CardLayoutDemo(). 1 y=0 x=0 x=1 Button 5 x=2 gridwidth. GridBagConstriants() gridx.

HORIZONTAL. JButton b5 = new JButton(“Button5”). weighty: . Generally weights are specified between 0.It is used when the componet is smaller than its display area to determine where (within the area) to place the component.com .0.setLayout(gbag).0 tells that the components size will not change when resized.It is used the components display area is larger than the component’s size to determine whether and how to resize the componet.0 (0.To specify whether the component can be stretched horizontally or vertically. JButton b2 = new JButton(“Button2”).awt. class GridBagLayoutDemo extends JFrame { GridBagLayout gbag.*. BOTH.insets(0.swing.0 and 1.To specify internal padding (widthwise or heightwise) to be added to the component. //Constructor GridBagLayoutDemo() { //Go to the content pane Container c = getContenPane().Space around the component (external padding) in four corners.None(default). c. gbag = new GridBagLayout(). Page 134 of 148 rambabumandalapu@yahoo. Valid values are shown below. inset: . Ex: //GridBagLayout Demo import java. GridBagConstraints cons. Default is 0. JButton b1 = new JButton(“Button1”). Ex: .0) //default ipadx.Advanced Java weightx. FIRST_START LINE_START LAST_LINE_END PAGE_START CENTER PAGE_END FIRST_LINE_END LINE_END LAST_LINE_END fill: . Ex: . import javax. VERTICAL. JButton b4 = new JButton(“Button4”). when resized. anchor: .0.*. ipady: . JButton b3 = new JButton(“Button3”).

cons. gbag.anchor = GridBagConstraints. cons).ipady = 100.setConstraints(b1. gbag. cons. c. cons. cons).setConstraints(b5.0. } Page 135 of 148 //cons.0.HORIZONTAL. cons. 0. //aligned with button2 //third row //reset to default //request any extra vertical space rambabumandalapu@yahoo.Advanced Java cons.gridx = 1.gridx = 1. gbag.7. cons. cons.setConstraints(b2.weightx = 0. cons. gbag.weighty = 1. //top padding cons. cons. cons). c.setConstraints(b4. cons.gridWidth = 2. //make this component tall cons.gridx = 1. cons. cons. c.gridy = 0. cons).add(b5).gridx = 0.gridy = 0.gridx = 1.add(b1).add(b2).PAGE_END. //button of space cons. 0.add(b3). cons). 0). cons.insets = new Insets(10. gbag. cons. cons.gridy = 0.0. //2 columns wide cons.weightx = 0.fill = GridBagConstraints.setConstraints(b3.gridy = 0.add(b4).weightx = 0.gridwidth = 3.gridy = 2. cons.com . c.ipady = 0. c.

An applet is a program which comes from server travels on the internet and executes in the client machine Applet is also java program. 14. Take a student class with H. } } H. display their sum in the third textfiled.show().400). Create a calculator using textfield and pushbuttons also ass the functionality to it.W: 12.No: Retreive Marks in Physcics: Marks in Chemistry: Marks in Maths: Applet: . Create the following screen which accepts H.No. Name and Marks in the Physcics.com . When the push button is clicked. Maths and Chemistry. Applet = Java Code + HTML Page //(or) demo.No. Enter First No: Enter Second No: The Sum is: Find Sum 13.Advanced Java public static void main(String args[ ]) { //Create a frame GridBagLayoutDemo demo = new GridBagLayoutDemo().setVisible(true). Create 2 text filelds to enter 2 numbers into them. demo. Page 136 of 148 rambabumandalapu@yahoo. Enter Hall Ticket. demo.setSize(500. and ddisplay the rest of details in text fileld.

In an Applet we will have following methods.yahoo. What is the Applet Life Cycle? ***** Ans: .Always the stop() method is executed before the destroy() method is called. 2. It is also useful to create components and attach to frame.com . Coe related to opening files. start().start() method is executed after init() method.It is useful to initialize variables and any parameters. 3. 1. 4.This method is executed when the applet loses the focus (When the application is minimized) code related closing the files. public void init(): . Internet Explorer File Edit View Favorites Tools Help Back Back Address www.swing package. public void stop(): .Advanced Java An Applet is a java program embded in HTML page. stop() methods are repeatedly executed when the application (maximize. init() or this method is executed immediately when an Applet is loaded into memory.It will terminate the applet from memory this method executed when the web page is closed. public void destroy(): .init() start() stop() destroy() and explain the above steps clearly. This method is executed only once. Page 137 of 148 rambabumandalapu@yahoo. Note: . public void start(): . and any cleanup operations is written in stop() method.applet package or JApplet class of javax. Note: . minimized) receives focuse and loses the focus. This method is executed as long as an applet receives focus. disconnecting from databases. connecting to databases and processing the data is written inside the start() method.com Welcome to Yahoo Request Response Server Done Internet Applet Methods available in Applet Class: .Executed the above methods in that order is called “Applet Life Cycle”. To create Applets in java we can use Applet class of java.

public void paint(Graphics g) we can also use awt swing componets Where are the Applet executed? ***** Ans: .drawString(str.applet. setForeground(Color.*.com .Advanced Java Note: . Font. public void init() { setBackground(Color. public class MyApp extends Applet { String str = “ ”.red).awt. 20). g.*. 50). str +=”init”. Applet will execute in limited memory or in a sand memory. What is the advantage using of Apple? ***** Ans: . Ex: . setFont(f). In web browser (software will contain) a small JVM called applet engine will executes the applets.//A sample Applet import java.yellow). } Page 138 of 148 rambabumandalapu@yahoo. } public void paint(Graphics g) { str +=”paint”. import javax.BOLD. 20.Applets make the webpages to dynamically interact with the users.Applets are executed in the web browser software of the client. } public void init() { str +=”start”. Font f = new Font(“Dialog”.

Advanced Java public void stop() { str +=”stop”. (Θ Where as appletviewer is a tool in J2SDK) } Page 139 of 148 rambabumandalapu@yahoo.swing.//Creating a shooping form import java.awt. F:\rnr>appletviewer x.*. <applet> tag is useful to embded (or) insert applet code into a HTML page. import javax. <! This HTML page embdeds MyApp applet> <html> <applet code = “MyApp.class” width =500. because we have to embded with the HTML of this byte code.awt. Hyper text means the text that uses hyperlink to directly jump to any piece of information. str1 = “ ”. Applet viewer is a tool to test the applet. } public void destroy() { } Save the above code as MyApp.applet. public class MyForm extends JApplet implements ActionListener { String str = “ ”.com . <html> tag specify the text. str2 = “ ”. Attributes provides additional information of the tag.java and compile it but don’t run it.html. Ex: . import java. height =400> </applet> </html> Save it as x. It is developed by the (Software people) Sum Microsystem. import java.event*. Open IntenetExplorer page. that is hyper link.html↵ IIS – Internet Informat Server.*.*.

add(n).setForeground(Color. public void init() { //Create the frame and goto contentpane JFrame jf = new JFrame(). 500. JList lst. I.yellow).setTitle(“My Form”). 200. lbl.getContentPane().setSize(500. jf. JLabel. name. 40). jf.com . c = jf. 40). 30).BOLD. //Heading lbl = new JLabel().setBounds(200. c. Container c. Font. jf.red).setBouns(200. c. 100. c. //name label and text field n = new JLabel(“Enter Name”.400).setBackground(Color. b2.RIGHT).setFont(new Font(“Dailog”.add(lbl).setText(“INetSolv Online Shopping Form”). JButton b1. Page 140 of 148 rambabumandalapu@yahoo.setVisible(true). //add label an text area a = new JLabel(“Enter Address”. 10.setLayout(null). lbl. 50. n. lbl. name = new JTextField(20). lbl. JTextField name. addr = new JTextArea(6.setBounds(50.).Advanced Java JLabel n. object x[ ]. 30). c. c.add(name). a. lbl.RIGHT). 50. JLabel. 40). JTextArea addr.

lst. JLabel. b2. 260. str1 += addr.add(addr).add(b2).getText() + “\n”. 260. 75.addActionListener(this). 40). if(str.add(a).length.setBounds(50. 200. Page 141 of 148 rambabumandalapu@yahoo. 420. “Shorts”}. x = lst. 100. 40).Advanced Java a. b1. i++) str2 += (String)x[ ] + “\n”. c. c. b2 = new JButtons(“Cancel”). 75. 150).add(b1). i<x.setBounds(200. //Create 2 push buttons b1 = new JButtons(“Ok”).getActionCommand().addActionListener(this). 100. lst = new JList(data). } public void actionPerformed(ActionEvent ae) { //Know which button is clicked str = ae. c. 200. addr.equals(“Ok”).com .getSelectedValues(). { str1 += name. //items label and list box i = new JLabel(“Select Items”. 100.setBounds(50.add(i). “Punjabees”. i.setBounds(200.add(lst). for(int i = 0. String data[ ] = {“T.setBounds(200.setBounds(300. “Sarees”. c.getText() + “\n”. 420. b2. 150). 40). c.RIGHT). 50. 40). c.Shirts”. //add action Listeners to buttons b1.

We can compile it.setText(“ ”).com . str2 = “ ”.setText(“ ”). Now create Applet <! This is HTML page that contains MyForm> <html> <applet code = “MyForm.applet.*. We can run this program by JVM.clearSelection().Advanced Java //display user selection in addr box addr. } } } Save it MyForm.html F:\rnr>appletviewer MyForm. addr.//Animation in applets import java.class” width = 500 height = 400> </applet> <html> Save it as MyForm.java. public class Animate extends Applet { public void init() {} public void paint(Graphics g) { Page 142 of 148 rambabumandalapu@yahoo.html↵ Animation: . str1 = ” ”.awt. Ex: .setText(str1 + str2).*. } else{ //Clear the form data name. lst. import java.Moving components/objects from one place to another is called animation.

} catch(InterruptedException ie){ } } } } Save the above code as Animate. x<800.sleep(20). height =400> </applet> </html> Save it as Animate.com . 15.gif using Flash. g. this). x. But we will draw using Ms-Paint/MsPowerPonit.drawImage(i. F:\rnr>appletviewer Animate. Page 143 of 148 rambabumandalapu@yahoo. o.class> <html> <applet code = “Animate. DreamWeaver. Then we have create plane. “plane. { g.gif”).java and compile it but don’t run it. because we have to embded with the HTML of this byte code. H. <! HTML that contains Animate.html.gif in the same irectory “rnr”. Adobe PhotoShop. x++).Advanced Java Image i = getImage(getDocumentBase(). this).java) Image i = getImage(getDocumentBase(). Save it as plane.html↵ In the above code (Applet. this is image present object. Where getImage will loads the image in image object getDocumentBase() method will gives URL of the image (or) current directory path. “plane. x.class” width =500. Create an applet that animates two objects simulataneously on the screen using two threads.W.drawImage(i. try{ Thread. for(int x =0. o.gif”).

This is introduced in Java 1. Generic types or declared as sub types of object class so they act upon any class object. } T. System.obj= obj. Generic class: class MyClass { T obj.out. MyClass obj = new MyClass(). version.com . Generic types can’t act up on primitive types. Ex: . which are type-safe. MyClass() { this. } integer. Generic types represents classes or interfaces.getObj() { return obj. Generic classes and interfaces Generic methods handle any type of data. } Page 144 of 148 rambabumandalapu@yahoo.Advanced Java Generic types are parameteize types: . } } class Gent { public static void main(String args[ ]) { Integer i = new Integer(100).getObj()).obj = obj.println(“U Stored” +obj.getObj() { return obj.5.//A generic class – to store any types of data class MyClass { this.

Advanced Java class Gen1 { public static void main(String args[ ]) { Integer i = new Integer(100). MyClass.getObj()). 4.println(i). } } Ex: .out.out. 5}. } } Page 145 of 148 rambabumandalapu@yahoo.println(i). System. class MyClass { static <GT>void display(GT[ ] arr) { for(GT i:arr) //this is for loop System.//A generic method – to ispaly any type of array elements class MyClass { static void display(int[ ] arr) { for(int i:arr) //this is for loop System.out. } } class Gen2 { public static void main(String args[ ]) { int arr1[ ] = {1. } } 2. 2. 3.display(arr1).com . MyClass< Integer> obj = new MyClass<Integer>().println(“U Stored” +obj.

put(“Sachin”. “Srinu”. “Siva”.5}. ht. Double arr2[ ] = {1. } } import java. Integer>().1. 4. MyClass.println(“Score = ” +score).5 as Hashtable <KV> import java. “Guru”}.//Hashtable OS rewritten in JDK 1. 5}.Advanced Java class Gen2 { public static void main(String args[ ]) { integer arr1[ ] = {1.2. new Integer(50)).put(“Ajay”.put(“Ajay”.display(arr3). class HT { public static void main(String args[ ]) { Hashtable ht = new Hashtable().util. 5.put(“Sachin”.get(s). String arr3[ ] = {“Prasad”. Page 146 of 148 rambabumandalapu@yahoo.. 3. ht.util. class HT { Hashtable<String. System.*. 4. MyClass.4.display(arr1). 2. ht. 100). 2. Integer score = (Integer) ht.display(arr2). MyClass.get(s). String s =”Sachin”.*.3. Integer> ht = new Hashtable<String. 3.com .out. String s =”Sachin”. 50). Integer score = (Integer) ht. } } Ex: .. ht. new Integer(100)).

They cannot act on primitive data type. 3. Generic types are sub types of class object. for-each style for loop Variable-length arguments (varagrs) Static import Formatted I/O Concurrency utilities Upgrades to the API Generic class: 1. generic interface or a generic method can handle any type of data. A generic class or generic interface represents a class or an interface which is type-safe. 4. //Invalid Page 147 of 148 rambabumandalapu@yahoo. When generic type is used.Advanced Java System.com . 9. H. 8. We cannot create an object to generic type. 7. 16. Ex: . Write a generic metho swaps any two data types. So they can act on objects of any class. 2. The class of java.out. consider the following list of its major few features: Genrics Metadata Autoboxing and auto-unboxing Enumerations Enchanced. 5. we can elimainate casting in any class. 6.util have been rewritten using generic types.5: To grasp the magnitude of the changes that J2SE 5 made to Java.println(“Score = ” +score). Java compiler creates a non-generic versions using the specified data type from a generic version. A generic class.class MyClass <T> //Invalid T obj = new T(). } } J2SE 1.W.

Extensibility: Additional features can be easily added.com .e. Availability: Clustering and load balancing can provide availability. business logic and database logic. horizontal scaling).Advanced Java The advantages of a 3-tiered or n-tiered application: 3-tier or multi-tier architectures force separation among presentation logic. tuned and upgraded independently and different people can have clearly defined responsibilities. *****END***** Page 148 of 148 rambabumandalapu@yahoo. Maintainability: Changes and upgrades can be performed without affecting other components. Scalability: More hardware can be added and allows clustering (i. Let us look at some of the key benefits: Manageability: Each tier can be monitored.