Presentation is loading. Please wait.

Presentation is loading. Please wait.

Utility class Presented by:Lovely June Nasrin Lawanshwa Gayatry.

Similar presentations


Presentation on theme: "Utility class Presented by:Lovely June Nasrin Lawanshwa Gayatry."— Presentation transcript:

1 Utility class Presented by:Lovely June Nasrin Lawanshwa Gayatry

2 Presented by: Lovely June (DC2012MCA0013) Contents: 1. Vector 2.Stack

3 Utility Class A utility class is a class that defines a set of methods that perform common, often re-used functions. Most utility classes define these common methods under static scope. Examples of utility classes include java.util.Collections These classes supplement the classes found in java.util and in the JDK collections classes.

4 The Java Utility Package The final Java package, java.util, contains a collection of utility classes. Data Structure Classes A variety of useful classes implementing standard computer science data structures: including BitSet, Dictionary, Hashtable, Stack and Vector. The java.util package also defines the Enumeration interface which provides a protocol for classes to count through a set of values. Date Use the Date class to create and manipulate calendar dates in a system- independent fashion. StringTokenizer This class converts a String of text into its tokens. Properties This class implements persistent properties. The properties table contains key/value pairs where both the key and the value are Strings. This class is used by the System class to implement System properties. Observer and Observable Classes that implement the Observer interface can "watch" Observable objects for state changes. When an Observable object changes it notifies all of its Observers of the change. Random-Number Generator The Random class implements a random-number generator. Enumeration The Enumeration interface defines a generic programming interface for iterating through a set of values.

5 Vector class method: We can write Vector class as: class Vector – here, E represents the type of elements stored into the vector. Example: 1)Vector v=new Vector (); 2)Vector v=new Vector (101); The default capacity will be 10. Here the capacity of Vector is given 101.

6 . Another way of creating a Vector object is by specifying a ‘Capacity Increment’ which specifies how much the capacity should be increment when the Vector is full with elements. Vector v=new Vector (101,20);

7 Vector class methods: 1) boolean add(element obj) : This methods appends the specified elements to the end of the Vector. If the element is added successfully then the preceding method returns true. 2) void add(int position,element obj) : This methods inserts the specified element at the specified position in the Vector. 3) element remove(int position) : This method removes the element at the specified element at the vector.It also returns the elements which was removed from the Vector. 4) Boolean remove(Object obj) : This method removes the first occurrence of the specified element obj from tghe Vector, if it is present. 5) void clear() : This method removes all the elements from the vector. 6) ) element get(int position) : This method returns the element available at the specified position in theVector.

8 Example: Taking a Vector to store Integer Objects as : Vector v=new Vector (); An idea is to take an int type array x[]and store the elements of this array into the vector v.In this case, since x[] has int type elements, we should convert them all to Integer type onjects and then store them into the vector v. This is done by the statement: v.add(x[i]) ;

9 program that shows the use of Vector Class //creating a vector with Integer elements Import java.util.*; class Vector demo { public static void main(String args[]) {Vector v=new Vecter ; //take a vector to store Integer Objects Int x[]={22,20,10,14,15,60}; //take an Int type array //when x[i] is store into v below, x[i] values are converted into Integer objects and store into v.This is auto-boxing. for(int i=0;i<x.length;i++) { v.add(x[i]); System.out.println(“Vector elements”);// retrieve the elemts using the get(); for(int i=0;i<v.size();i++) { System.out.println(v.get(i)); }

10 Cont’d.. //retrieve using ListIterator System.out.println(“elements usings ListIterrator”); ListIterrator lit=v.listIterrator(); System.out.println(“In forward direction”); While(lit.hasNext()) { System.out.print(lit.Next()+”\t”); } System.ot.println(“\n in Backward direction”); While(lit.hasPrevious()) { System.out.prin(lit.Previous()+”\t); }

11 Output C:\>javac VectorDemo.java C:\>java VectorDemo Vector Elements: 22 20 10 40 50 60 Elements using ListIterrator: In forward direcrtor: 22 20 10 40 50 60 In Backward direction: 60 50 40 10 20 22

12 Stack A stack represents a group of elements store in LIFO(Last in First Out )order. This means that the element which is stored as a last element into the stack will be the first element to be remove from the stack. Inserting elements(objects)into the stack is called ‘Push operation’ and removing elements from stack is called ‘Pop operation’. Searching for an element in the stack is called ‘Peep operation’. Insertion and deletion of elements takes place only from one side of a stack, called ‘Top ‘ of the stack,as shown in figure below:

13 We can write a Stack class as : class Stack where E stands for element type.Suppose,we want to create a Stack object that contains Integer objects, we can do so as shown here: Stack obj=new Stack ();

14 Stack class method boolean empty() : This method tests whether the stack is empty or not. If the stack is empty then true is returned otherwise false. element peek() : This method returns the top-most object from the stack without removing it. element pop() : This method pops the top-most element from the stack and returns it. element push(element obj) : This method pushes an element obj onto the top of the stack and returns that element. Interger search(Object obj) : This method returns the position of an element obj from the top of the stack. If the element (or object) is not found in the stack then it returns -1.

15 A program to perform different operation on a stack.First create a stack can store Integer type objects as : Stack st =new Stack (); Suppose, in this stack we want to store some integer elements, we can write a statement as st.push(element) ;

16 To remove the top-most element(or object) from the stack, we can use pop() method, as : Integer obj = st.pop(); The code to search the position of an element in the stack is as : position = st.search(element);

17 Example: A program to perform different operations on a stack through a menu. //PUSHING,POPPING,SEARCHING ELEMENTS IN A STACK import java.io.*; import java.util.*; class StackDemo{ public static void main(String []args)throws Exception { //create an empty stack to contain Integer objects Stack st=new Stack (); //take variables Int choice=0; Int position,element; BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));

18 //Display the menu as long as user choice < 4 while(choice<4) { System.out.println (“STACK OPERATIONS”); System.out.println(“1:Push element”); System.out.println(“2:Pop element”); System.out.println(“3:Search element”); System.out.println(“4:Exit”); System.out.println(“Enter your choice”); choice= Integer.parseInt(br.readLine());

19 switch(choice) //PERFORM A TASK DEPENDING ON USER CHOICE { case1: System.out.print(“Enter element”); element=Integer.parseInt(br.readLine()); //int type element is converted into Integer object and then push into the stack. st.push(element); break; case2 : Integer obj=st.pop(); System.out.println(“popped=”+obj); break; case3: System.out.print(“Which element”); element=Integer.parseInt(br.readLine()); position=st.search(element);

20 if ( position==-1) { System.out.println(“Element not found”); } else System.out.println(“position”+position); break; default: //come out if user choice is other than 1,2 or 3 return; } / /view the contents of stack System.out.println(“Stack contents:”+st); }

21 Output: C:\>javac StackDemo.java C:\>java StackDemo STACK OPERATION 1:Push element 2:Pop element 3:Seach element 4:Exit Enter your choice:1 Enter element:11 Stack contents:[11] STACK OPERATION 1:Push element 2:Pop element 3:Seach element 4:Exit Enter your choice:1 Enter element:20 Stack contents:[11,20]

22 STACK OPERATION 1:Push element 2:Pop element 3:Search element 4:Exit Enter your choice:3 Which element:20 Position:1 Stack contents:[11,20] STACK OPERATION 1:Push element 2:Pop element 3:Search element 4:Exit Enter your choice:4

23 Presented By: Nasrin Ara Rahman(DC2012MCA0026) Contents: 1. Hash Table 2. String Tokenizer 3. Bit Set

24 Hash Table In computing, a hash table (also hash map) is a data structure used to implement an associative array, a structure that can map keys to values. A hash table uses a hash function to compute an index into an array of buckets or slots, from which the correct value can be found. Hashtable is an implementation of a key-value pair data structure in java. You can store and retrieve a ‘value’ using a ‘key’ and it is an identifier of the value stored. It is obvious that the ‘key’ should be unique. Hashtable was part of the original java.util and is a concrete implementation of a Dictionary. java.util.Hashtable extends Dictionary and implements Map.

25 Hashing in General The idea of hashing is to distribute the entries (key/value pairs) across an array of buckets. Given a key, the algorithm computes an index that suggests where the entry can be found: index = Key % array_size

26 Hashing in java Assume that, v is a value to be stored and k is the key used for storage / retrieval, then h is a hash function where v is stored at h(k) of table. h(k) is the hashing function and it is used to find the location to store the corresponding value v. h(k) cannot compute to a indefinite space. Storage allocated for a Hashtable is limited within a program. So, the hashing function h(k) should return a number within that allocated spectrum Java’s hashing uses uses hashCode() method from the key and value objects to compute. Following is the core code from Hashtable where the hashCode ‘h’ is computed. You can see that both key’s and value’s hashCode() method is called. h += e.key.hashCode() ^ e.value.hashCode();

27 Collision in java There is a possibility of a collision. For two different keys k1 and k2, if we have h(k1) = h(k2), then this is called collision in hashtable. What does this mean, our hashing function directs us store two different values (keys are also different) in the same location. When we have a collision, there are multiple methodologies available to resolve it. To name a few hashtable collision resolution technique, ‘separate chaining’, ‘open addressing’, ‘robin hood hashing’, ‘cuckoo hashing’, etc. Java’s hashtable uses ‘separate chaining’ for collision resolution in Hashtable.

28 Collision resolution Java uses separate chaining for collision resolution. In separate chaining, every bucket will store a reference to a linked list. Now assume that we have stored an element in bucket 1. That means, in bucket 1 it will have a reference to a linked list and in that linked list it will have two cells. In those two cells it will have key and its corresponding value.

29 Class Constructors The Hashtable defines four constructors: 1. Hashtable( ) The first version is the default constructor: 2. Hashtable(int size) The second version creates a hash table that has an initial size specified by size 3. Hashtable(int size, float fillRatio) The third version creates a hash table that has an initial size specified by size and a fill ratio specified by fillRatio. This ratio must be between 0.0 and 1.0, and it determines how full the hash table can be before it is resized upward. 4. Hashtable(Map m) The fourth version creates a hash table that is initialized with the elements in m. The capacity of the hash table is set to twice the number of elements in m.

30 Class Methods 1. void clear( ) Resets and empties the hash table. 2. Object clone( ) Returns a duplicate of the invoking object. 3. Object put(Object key,Object value) Inserts a key and a value into the hashtable. 4. boolean containsKey(Object key) Returns true if some key equal to key exists within the hash table. Returns false if the key isn't found. 5. boolean containsValue(Object value) Returns true if some value equal to value exists within the hash table. Returns false if the value isn't found. 6. Enumeration elements( ) Returns an enumeration of the values contained in the hash table.

31 Example import java.util.*; public class HashTableDemo { public static void main(String args[]){ // Create a hash map Hashtable balance = new Hashtable(); Enumeration names; String str; double bal; balance.put("Zara", new Double(3434.34)); balance.put("Mahnaz", new Double(123.22)); balance.put("Ayan", new Double(1378.00)); balance.put("Daisy", new Double(99.22)); balance.put("Qadir", new Double(-19.08)); // Show all balances in hash table. names = balance.keys(); while(names.hasMoreElements()) { str = (String) names.nextElement(); System.out.println(str + ": " + balance.get(str)); } System.out.println(); // Deposit 1,000 into Zara's account bal = ((Double)balance.get("Zara")).doubleValue(); balance.put("Zara", new Double(bal+1000)); System.out.println("Zara's new balance: " + balance.get("Zara")); }

32 Output This would produce the following result: Qadir: -19.08 Zara: 3434.34 Mahnaz: 123.22 Daisy: 99.22 Ayan: 1378.0 Zara's new balance: 4434.34

33 String Tokenizer What is a StringTokenizer? In java, there is a way to break up a line of text into what are called tokens. A token is a smaller piece of a string. This method of breaking up tokens are come from the StringTokenizer class. This class is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. Its methods do not distinguish among identifiers, numbers, and quoted strings. This class methods do not even recognize and skip comments.

34 String Tokenizer(Contd..) Let's say that we wanted to break up the following line of text into smaller pieces: "Hello and welcome to programming" Here, the token we need is just a simple white space. So here is how to declare a StringTokenizer object: StringTokenizer name = new StringTokenizer(variable, Token(s)); where in the above, name is an appropriate name for the tokenizer object; variable is the name of a String variable we are using or even just a simple string; and token(s) is the token we are specifying. In the above definition, if the second argument of the constructor is not specified, the token, by default, is a white space. If the token that is declared does not exist in the String we are searching through, the entire string is returned to us.

35 Class constructors 1. StringTokenizer(String str) This constructor a string tokenizer for the specified string. 2. StringTokenizer(String str, String delim) This constructor constructs string tokenizer for the specified string. 3. StringTokenizer(String str, String delim, boolean returnDelims) This constructor constructs a string tokenizer for the specified string.

36 Class methods 1. int countTokens() This method calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception. 2. boolean hasMoreElements() This method returns the same value as the hasMoreTokens method. 3. boolean hasMoreTokens() This method tests if there are more tokens available from this tokenizer's string. 4. Object nextElement() This method returns the same value as the nextToken method, except that its declared return value is Object rather than String. 5. String nextToken() This method returns the next token from this string tokenizer. 6. String nextToken(String delim) This method returns the next token in this string tokenizer's string.

37 Example import java.util.StringTokenizer; public class StringTokenizerExample{ public static void main(String args[]) { String s = "What on earth is going on here?"; //by default, a white space: StringTokenizer st = new StringTokenizer(s); //when there are still more tokens, print out the //next one: while(st.hasMoreTokens()) System.out.println(st.nextToken()); } //main } //class Output: This program will simply break up the String named s into 7 pieces, each on a new line based on the println statement.

38 Bitset A BitSet class creates a special type of array that holds bit values. The BitSet array can increase in size as needed. This makes it similar to a vector of bits. This is a legacy class but it has been completely re-engineered in Java 2, version 1.4.

39 Constructors BitSet( ) The first version creates a default object: BitSet(int size) The second version allows you to specify its initial size, i.e., the number of bits that it can hold. All bits are initialized to zero.

40 Methods 1. void and(BitSet bitSet) ANDs the contents of the invoking BitSet object with those specified by bitSet. The result is placed into the invoking object. 2. void andNot(BitSet bitSet) For each 1 bit in bitSet, the corresponding bit in the invoking BitSet is cleared. 3. int cardinality( ) Returns the number of set bits in the invoking object. 4. void clear( ) Zeros all bits. 5. void clear(int index) Zeros the bit specified by index. 6. void clear(int startIndex, int endIndex) Zeros the bits from startIndex to endIndex.1.

41 Example import java.util.BitSet; public class BitSetDemo { public static void main(String args[]) { BitSet bits1 = new BitSet(16); BitSet bits2 = new BitSet(16); // set some bits for(int i=0; i<16; i++) { if((i%2) == 0) bits1.set(i); if((i%5) != 0) bits2.set(i); } System.out.println("Initial pattern in bits1: "); System.out.println(bits1); System.out.println("\nInitial pattern in bits2: "); System.out.println(bits2); // AND bits bits2.and(bits1); System.out.println("\nbits2 AND bits1: "); System.out.println(bits2); // OR bits bits2.or(bits1); System.out.println("\nbits2 OR bits1: "); System.out.println(bits2); // XOR bits bits2.xor(bits1); System.out.println("\nbits2 XOR bits1: "); System.out.println(bits2); }

42 Output Initial pattern in bits1: {0, 2, 4, 6, 8, 10, 12, 14} Initial pattern in bits2: {1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14} bits2 AND bits1: {2, 4, 6, 8, 12, 14} bits2 OR bits1: {0, 2, 4, 6, 8, 10, 12, 14} bits2 XOR bits1: {}

43 Lawanshwa Kharsahnoh(DC2012MCA0016) Contents: 1.date class 2.Calendar Class 3. Gregorian Calendar Presented By:

44 Date Class Date class is useful to display the date and time at a particular moment. It contains the system date and time by default To create an object, we write: Date d= new Date();

45 The following shows how the “formatconst” will modify appearance of the Date class object : Formatconst DateFormat.FULL DateFormat.LONG DateFormat.MEDIUM Eg. 03-Sep-07 19:43:14 DateFormat.SHORT Eg. 03/09/07 19:43

46 Example: Program that shows the use of Date class //Display system date and time using Date class import java.util.*; import java.text.*; class MyDate { public static void main(String args[]) { // Create Date class object-this contains system date and time Date d=new Date(); //Format the date to medium format and time to short format DateFormat fmt=DateFormat.getDateTimeInstance (DateFormat.MEDIUM,DateFormat.SHORT, Locale.INDIA);

47 //Apply the DateFormat to the date object String str=fmt.format(d); //Now display the formatted date and time System.out.println(str); } Output: 26-Oct-2013 17:49

48 Calendar Class The Calendar class is an abstract class Method for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR For manipulating the calendar fields, such as getting the date of the next week.

49 Calendar class is useful in two ways: It helps in knowing the system date and time. It helps in storing date and time value so that it can be transported to some other application. To create an object to Calendar class, we write: Calendar cl=Calendar.getInstance();

50 Calendar class Methods int get(int field): This method returns the value of the given calendar field. For eg, 1.Calendar.DATE 2.Calendar.MONTH 3.Calendar.YEAR 4.Calendar.HOUR gives the hour number from 0 to 11. 5.Calendar.MINUTE gives the minute number from 0 to 59. 6.Calendar.SECOND gives the second number from 0 to 59. 7.Calendar.AM or PM gives 0 if it is AM. Give 1 if it is PM.

51 void set(int field, int value): This method sets the given field in Calendar object to the given value. For eg, we can set a date like 15 March 2007 to Calendar object as: cl.set(Calendar.DATE,15); cl.set(Calendar.MONTH,2); cl.set(Calendar.YEAR,2007);

52 StringtoString(): This method returns the string representation of the calendar object. boolean equals(Object obj): This method compares the calendar object with another object obj and returns true if they are same, otherwise false.

53 Example: Program to show the use of Calendar class //To display System date and time import java.util.*; class CalendarDemo { public static void main(String agrs[]) { //Create Calendar class object. By default, it contains the system date and time Calendar cl=Calendar.getInstance(); //Display date separately System.out.println("Current date:"); int dd=cl.get(Calendar.DATE); int mm=cl.get(Calendar.MONTH); ++mm;

54 int yy =cl.get(Calendar.YEAR); System.out.println(dd+ "-" +mm+ "-" +yy); //Display time alone System.out.println("Current Time"); int h=cl.get(Calendar.HOUR); int m=cl.get(Calendar.MINUTE); int s=cl.get(Calendar.SECOND); System.out.println(h+ "-" +m+ "-" +s); int x=cl.get(Calendar.AM); //int y=cl.get(Calendar.PM); if(x==0){ System.out.println("Good Morning"); } else{ System.out.println("Good Evening"); } Output: Current date: 26-10-2013 Current Time 4-47-38 Good Evening

55 Gregorian Calendar Class GregorianCalendar is a concrete implementation of a Calendar class that implement GregorianCalendar defines two fields: AD and BC. These represent the two eras defined by the Gregorian calendar.

56 Constructors for GregorianCalendar objects GregorianCalendar(): Constructs a default GregorianCalendar using the current time in the default time zone with the default locale. GregorianCalendar(int year, int month, int dayOfMonth): Constructs a GregorianCalendar with the given date set in the default time zone with the default locale. GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute): Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale. GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second): Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale. GregorianCalendar(Locale aLocale): Constructs a GregorianCalendar based on the current time in the default time zone with the given locale. GregorianCalendar(TimeZone zone): Constructs a GregorianCalendar based on the current time in the given time zone with the default locale. GregorianCalendar(TimeZone zone, Locale aLocale): Constructs a GregorianCalendar based on the current time in the given time zone with the given locale.

57 Methods provided by GregorianCalendar class void add(int field, int amount): Adds the specified (signed) amount of time to the given time field, based on the calendar's rules boolean equals(Object obj): Compares this GregorianCalendar to an object reference. int get(int field): Gets the value for a given time field. int getMaximum(int field): Returns maximum value for the given field. Date getTime(): Gets this Calendar's current time. Date getGregorianChange(): Gets the Gregorian Calendar change date. boolean isLeapYear(int year): Determines if the given year is a leap year. void setGregorianChange(Date date): Sets the GregorianCalendar change date. void setTime(Date date): Sets this Calendar's current time with the given Date String toString(): Return a string representation of this calendar.

58 Example: Program to show Gregorian calendar import java.util.*; public class GregorianCalendarDemo { public static void main(String args[]) { String months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; int year; // Create a Gregorian calendar initialized with the current date and time in //the default locale and timezone. GregorianCalendar gcalendar = new GregorianCalendar();

59 // Display current time and date information. System.out.print("Date: "); System.out.print(months[gcalendar.get(Calendar.MONTH)]); System.out.print(" " + gcalendar.get(Calendar.DATE) + " "); System.out.println(year = gcalendar.get(Calendar.YEAR)); System.out.print("Time: "); System.out.print(gcalendar.get(Calendar.HOUR) + ":"); System.out.print(gcalendar.get(Calendar.MINUTE) + ":"); System.out.println(gcalendar.get(Calendar.SECOND));

60 // Test if the current year is a leap year if(gcalendar.isLeapYear(year)) { System.out.println("The current year is a leap year"); } else { System.out.println("The current year is not a leap year"); } Output: Date: Oct 26 2013 Time: 6:44:14 The current year is not a leap year

61 Presented By: Gayatry Borboruah(DC2012MCA0011) Contents: 1.Random Class 2. Obvservable Class

62 Random And Observable Class Random-Number Generator The Random class implements a random-number generator. Observer and Observable Classes that implement the Observer interface can "watch" Observable objects for state changes. When an Observable object changes it notifies all of its Observers of the change.

63 The random class Java provides extensive additional random number generation capabilities in class Random. A new random-number generator can be created by using Random r = new Random(); A Random object generates pseudo-random numbers. Class Random is found in the java.util package. import java.util.*; To create a pseudorandom-number generator with “repeatability,” use Random r = new Random( seedValue );

64 Constructors public Random() Creates a new random number generator. public Random(long seed) Creates a new random number generator using a single long seed: public Random(long seed) { setSeed(seed); } Used by method next to hold the state of the pseudorandom number generator.

65 Methods next(int bits) Generates the next pseudorandom number nextBoolean() Returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence. nextBytes(byte[] bytes) Generates a user specified number of random bytes.

66 Example program import java.util.Random; /* Generate 10 random integers in the range 0..99. */ public final class RandomInteger { public static final void main(String... aArgs) { log("Generating 10 random integers in range 0..99."); //note a single Random object is reused here Random randomGenerator = new Random(); for (int idx = 1; idx <= 10; ++idx) { int randomInt = randomGenerator.nextInt(100); log("Generated : " + randomInt); } log("Done."); } private static void log(String aMessage) { System.out.println(aMessage); }

67 Output Generating 10 random integers in range 0..99. Generated : 44 Generated : 81 Generated : 69 Generated : 31 Generated : 10 Generated : 64 Generated : 74 Generated : 57 Generated : 56 Generated : 93 Done.

68 Observable class This class represents an observable object, or "data" in the model-view paradigm. An observable object can have one or more observers. An observer may be any object that implements interface Observer. After an observable instance changes, an application calling the Observable's notifyObservers method causes all of its observers to be notified of the change by a call to their update method.

69 Constructor public Observable() Construct an Observable with zero Observers.

70 Methods addObserver(Observer o) Adds an observer to the set of observers for this object, provided that it is not the same as some observer already in the set. clearChanged() Indicates that this object has no longer changed, or that it has already notified all of its observers of its most recent change, so that the hasChanged method will now return false. countObservers() Returns the number of observers of this Observable object. hasChanged() Tests if this object has changed.

71 Example program import java.util.Observable; import java.util.Observer; class ObservedObject extends Observable { private String watchedValue; public ObservedObject(String value) { watchedValue = value; } public void setValue(String value) { // if value has changed notify observers if(!watchedValue.equals(value)) { System.out.println("Value changed to new value: "+value); watchedValue = value; // mark as value changed setChanged(); // trigger notification notifyObservers(value); }

72 public class ObservableDemo implements Observer { public static void main(String[] args) { // create watched and watcher objects ObservedObject watched = new ObservedObject("Original Value"); // watcher object listens to object change ObservableDemo watcher = new ObservableDemo(); // trigger value change watched.setValue("New Value"); // add observer to the watched object watched.addObserver(watcher); // trigger value change watched.setValue("Latest Value"); } public void update(Observable obj, Object arg) { System.out.println("Update called with Arguments: "+arg); }

73 Output Value changed to new value: New Value Value changed to new value: Latest Value Update called with Arguments: Latest Value


Download ppt "Utility class Presented by:Lovely June Nasrin Lawanshwa Gayatry."

Similar presentations


Ads by Google