Utility class Presented by:Lovely June Nasrin Lawanshwa Gayatry.

Slides:



Advertisements
Similar presentations
Java Programming: Advanced Topics 1 Collections and Utilities.
Advertisements

AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
Sequence of characters Generalized form Expresses Pattern of strings in a Generalized notation.
The Dictionary ADT Definition A dictionary is an ordered or unordered list of key-element pairs, where keys are used to locate elements in the list. Example:
Lecture 11 oct 6 Goals: hashing hash functions chaining closed hashing application of hashing.
Skip List & Hashing CSE, POSTECH.
Hashing as a Dictionary Implementation
Hashing Chapters What is Hashing? A technique that determines an index or location for storage of an item in a data structure The hash function.
Using arrays – Example 2: names as keys How do we map strings to integers? One way is to convert each letter to a number, either by mapping them to 0-25.
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
Sets and Maps Chapter 9. Chapter 9: Sets and Maps2 Chapter Objectives To understand the Java Map and Set interfaces and how to use them To learn about.
Hash Tables1 Part E Hash Tables  
1 Dynamic Arrays  Why Dynamic Arrays?  A Dynamic Array Implementation  The Vector Class  Program Example  Array Versus Vector.
23-Jun-15 Strings, Etc. Part I: String s. 2 About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects,
Hash Tables1 Part E Hash Tables  
StringBuffer class  Alternative to String class  Can be used wherever a string is used  More flexible than String  Has three constructors and more.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
Strings, Etc. Part I: Strings. About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects, have a defined.
Lecture 11 oct 7 Goals: hashing hash functions chaining closed hashing application of hashing.
Hashing General idea: Get a large array
Introducing Hashing Chapter 21 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
Maps A map is an object that maps keys to values Each key can map to at most one value, and a map cannot contain duplicate keys KeyValue Map Examples Dictionaries:
Session 5 java.lang package Using array java.io package: StringTokenizer, ArrayList, Vector Using Generic.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities Chapter 4.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities.
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
CS212: DATA STRUCTURES Lecture 10:Hashing 1. Outline 2  Map Abstract Data type  Map Abstract Data type methods  What is hash  Hash tables  Bucket.
Data structures and algorithms in the collection framework 1 Part 2.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt * Object-Oriented Software Development Unit 8.
Geoff Holmes Palindrome solutions Overview Arrays Collections Enumerators Vector BitSet Stack Dictionary Hashtable Collection Classes (Chapter 19) import.
Hash Tables1   © 2010 Goodrich, Tamassia.
Chapter 18 Java Collections Framework
Data structures Abstract data types Java classes for Data structures and ADTs.
Built-in Data Structures in Python An Introduction.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
© 2004 Goodrich, Tamassia Hash Tables1  
Hashing as a Dictionary Implementation Chapter 19.
1 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain:
Chapter 12 Hash Table. ● So far, the best worst-case time for searching is O(log n). ● Hash tables  average search time of O(1).  worst case search.
Chapter 10 Hashing. The search time of each algorithm depend on the number n of elements of the collection S of the data. A searching technique called.
Garside, JAVA: First Contact, 2ed Java First Contact – 2 nd Edition Garside and Mariani Chapter 6 More Java Data Types.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1.
Hashtables. An Abstract data type that supports the following operations: –Insert –Find –Remove Search trees can be used for the same operations but require.
Copyright (c) Systems and Computer Engineering, Carleton University * Object-Oriented Software Development Unit 13 The Collections Framework.
Java Util Package Prepared by, S.Amudha AP/SWE. Calendar 1.The abstract Calendar class provides a set of methods that allows you to convert a time in.
Hash Tables Ellen Walker CPSC 201 Data Structures Hiram College.
Sets and Maps Chapter 9. Chapter Objectives  To understand the Java Map and Set interfaces and how to use them  To learn about hash coding and its use.
Collections Dwight Deugo Nesa Matic
C19: Collection Classes (don’t forget to look at all the online code examples)
Hashing By Emily Nelson. The Official Definition Using a hash function to turn some kind of data in relatively small integers or Strings The “hash code”
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Building Java Programs Generics, hashing reading: 18.1.
Hashing Alexandra Stefan.
Searching.
CS313D: Advanced Programming Language
L5. Necessary Java Programming Techniques
Hashing in java.util
CS210- Lecture 16 July 11, 2005 Agenda Maps and Dictionaries Map ADT
A type is a collection of values
Lecture-Hashing.
Presentation transcript:

Utility class Presented by:Lovely June Nasrin Lawanshwa Gayatry

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

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.

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.

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.

. 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);

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.

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]) ;

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

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

Output C:\>javac VectorDemo.java C:\>java VectorDemo Vector Elements: Elements using ListIterrator: In forward direcrtor: In Backward direction:

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:

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

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.

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) ;

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);

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));

//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());

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);

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

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]

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

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

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.

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

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

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.

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.

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.

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.

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( )); balance.put("Mahnaz", new Double(123.22)); balance.put("Ayan", new Double( )); 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")); }

Output This would produce the following result: Qadir: Zara: Mahnaz: Daisy: Ayan: Zara's new balance:

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.

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.

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.

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.

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.

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.

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.

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.

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

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: {}

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

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

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

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);

//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 :49

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.

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

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 Calendar.MINUTE gives the minute number from 0 to Calendar.SECOND gives the second number from 0 to Calendar.AM or PM gives 0 if it is AM. Give 1 if it is PM.

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);

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.

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;

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: Current Time Good Evening

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.

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.

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.

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

// 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));

// 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 Time: 6:44:14 The current year is not a leap year

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

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.

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 );

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.

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.

Example program import java.util.Random; /* Generate 10 random integers in the range */ public final class RandomInteger { public static final void main(String... aArgs) { log("Generating 10 random integers in range "); //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); }

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

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.

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

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.

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

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

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