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.

Slides:



Advertisements
Similar presentations
Sequence of characters Generalized form Expresses Pattern of strings in a Generalized notation.
Advertisements

Slide 10.1 Advanced Programming 2004, based on LY Stefanus’s Slides Object Serialization Object serialization: the process of converting an object into.
Chapter - 12 File and Streams (continued) This chapter includes -  DataOutputStream  DataInputStream  Object Serialization  Serializing Objects 
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
Enhancing classes Visibility modifiers and encapsulation revisited
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Time & Date Representation in Java. Date class An object of type Date represents an instance in time Part of java.util.* (requires import statement) A.
Advanced Java and Android Day 1 Object-Oriented Programming in Java Advanced Java and Android -- Day 11.
CSC – Java Programming II Lecture 9 January 30, 2002.
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
CIS 644 Aug. 25, 1999 tour of Java. First … about the media lectures… we are experimenting with the media format please give feedback.
The Java Programming Language
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
Chapter 14 Internationalization F Processing Date and Time –Locale –Date –TimeZone –Calendar and GregorianCalendar –DateFormat and SimpleDateFormat F Formatting.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 26 Internationalization.
Chapter 12: Internationalization Processing Date and Time Processing Date and Time  Locale  Date  TimeZone  Calendar and GregorianCalendar  DateFormat.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Neal Stublen Computer Memory (Simplified)  Remember, all programming decisions came down to a true or false evaluation  Consider.
JAC444: Dates Tim McKenna Dates, Calendars, and what year is this? §Java tries to take an OOD approach to “when is now?” §import java.util.*;
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
1.  At the end of this slide, student able to:  Object-Oriented Programming  Research on OOP features.  Do a code walkthrough to examine the implementation.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 14 Internationalization F Processing Date and Time –Locale –Date –TimeZone –Calendar and GregorianCalendar –DateFormat and SimpleDateFormat F Formatting.
Garside, JAVA: First Contact, 2ed Java First Contact – 2 nd Edition Garside and Mariani Chapter 6 More Java Data Types.
RMI , Naming Service, Serialization and Internationalization Chapter 4
Lab 1 Logbook ADT. OVERVIEW A monthly logbook consists of a set of entries, one for each day of the month.
Object Serialization.  When the data was output to disk, certain information was lost, such as the type of each value.  If the value "3" is read from.
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
© Wang Bin 2004 Java Threads. © Wang Bin 2004 In this lesson, you will learn to: u Define the concepts of threads and multithreading  Identify the functions.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Objects and Classes.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
1 Chapter 20 Internationalization. 2 Objectives F To describe Java's internationalization features (§ 20.1). F To construct a locale with language, country,
BPJ444: Dates Peter Liu Tim McKenna Dates, Calendars, and what year is this? §Java tries to take an OOD approach to “when is now?” §import.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
Chapter - 11 Introduction to File and Streams This chapter includes -  Defining a File  Testing and Checking File Objects  Accessing File Objects.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
String handling. when you create a String object, you are creating a string that cannot be changed. That is, once a String object has been created, you.
Introduction to Collections. Collections Collections provide a way of organizing related data in a model Different types of collections have different.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 20.
Introduction To Objects Oriented Programming Instructor: Mohammed Faisal.
14 BirthMonth1February BirthMonth CE : Fundamental Programming Techniques.
1 Copyright © 2011 Tata Consultancy Services Limited TCS Internal.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 4 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
What do I need to Know For My Assignment?. C Pointer Review To declare a pointer, we use the * operator. This is similar to but different from using *
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
1 CSE 331 Memento Pattern and Serialization slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Comp1004: Environments The Java Library. Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Sequential files creation & writing
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
Chapter 14 Internationalization
StringTokenizer The processing of text often consists of parsing a formatted input string. Parsing is the division of text into a set of discrete parts,
I/O Basics.
Accessing Files in Java
Formatting Output.
Prepared by, S.Amudha AP/SWE
The Building Blocks Classes: Java class library, over 1,800 classes:
2017 Jan Sun Mon Tue Wed Thu Fri Sat
Chapter 35 Internationalization
Jan Sun Mon Tue Wed Thu Fri Sat
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
Chapter 13 Abstract Classes and Interfaces Part 01
The command invocation protocol
TIMELINE NAME OF PROJECT Today 2016 Jan Feb Mar Apr May Jun
Java Date ISYS 350.
Presentation transcript:

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 milliseconds to a number of useful components. 2.Some examples of the type of information that can be provided are: year, month, day, hour, minute, and second. 3.It is intended that subclasses of Calendar will provide the specific functionality to interpret time information according to their own rules. 4.This is one aspect of the Java class library that enables you to write programs that can operate in several international environments. 5.An example of such a subclass is GregorianCalendar. 6.Calendar provides no public constructors. 7.Calendar defines several protected instance variables. 8.areFieldsSet is a boolean that indicates if the time components have been set. 9.fields is an array of ints that holds the components of the time. 10.isSet is a boolean array that indicates if a specific time component has been set. 11.time is a long that holds the current time for this object. 12.isTimeSet is a boolean that indicates if the current time has been set.

Calendar defines the following int constants, which are used when you get or set components of the calendar:

// Demonstrate Calendar import java.util.Calendar; class CalendarDemo{ public static void main(String args[]) { String months[] = {"Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul", "Aug“, "Sep", "Oct", "Nov", "Dec"}; Calendar calendar = Calendar.getInstance(); System.out.print("Date: "); System.out.print(months[calendar.get(Calendar.MONTH)]); System.out.print(" " + calendar.get(Calendar.DATE) + " "); System.out.println(calendar.get(Calendar.YEAR)); System.out.print("Time: "); System.out.print(calendar.get(Calendar.HOUR) + ":"); System.out.print(calendar.get(Calendar.MINUTE) + ":"); System.out.println(calendar.get(Calendar.SECOND)); calendar.set(Calendar.HOUR, 10); calendar.set(Calendar.MINUTE, 29); calendar.set(Calendar.SECOND, 22); System.out.print("Updated time: "); System.out.print(calendar.get(Calendar.HOUR) + ":"); System.out.print(calendar.get(Calendar.MINUTE) + ":"); System.out.println(calendar.get(Calendar.SECOND)); } }

GregorianCalendar 1.GregorianCalendar is a concrete implementation of a Calendar that implements the normal Gregorian calendar with which you are familiar. 2.The getInstance( ) method of Calendar returns a GregorianCalendar initialized with the current date and time in the default locale and time zone. 3.GregorianCalendar defines two fields: AD and BC. 4.These represent the two eras defined by the Gregorian calendar. 5.There are also several constructors for GregorianCalendar objects. 6.The default, GregorianCalendar( ), initializes the object with the current date and time in the default locale and time zone. 7.Three more constructors offer increasing levels of specificity: GregorianCalendar(int year, int month, int dayOfMonth) GregorianCalendar(int year, int month, int dayOfMonth, int hours, int minutes) GregorianCalendar(int year, int month, int dayOfMonth, int hours, int minutes, int seconds) All three versions set the day, month, and year. Here, year specifies the number of years that have elapsed since The month is specified by month, with zero indicating January. The day of the month is specified by dayOfMonth. The first version sets the time to midnight. The second version also sets the hours and the minutes. The third version adds seconds.

You can also construct a GregorianCalendar object by specifying either the locale and/or time zone. The following constructors create objects initialized with the current date and time using the specified time zone and/or locale: GregorianCalendar(Locale locale) GregorianCalendar(TimeZone timeZone) GregorianCalendar(TimeZone timeZone, Locale locale) GregorianCalendar provides an implementation of all the abstract methods in Calendar. It also provides some additional methods. Perhaps the most interesting is isLeapYear( ), which tests if the year is a leap year. Its form is boolean isLeapYear(int year) This method returns true if year is a leap year and false otherwise.

import java.util.*; 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"); } } }

Java Date Class Java provides the Date class available in java.util package, this class encapsulates the current date and time. Constructors Date( ) – Default Date(long millisec) - accepts one argument that equals the number of milliseconds

Getting Current Date & Time import java.util.Date; public class DateDemo { public static void main(String args[]) { Date date = new Date(); System.out.println(date.toString()); } Output: Mon May 04 09:51:52 CDT 2009

Example2 import java.util.*; public class CurrentDate{ public static void main(String[] args){ Calendar cal = new GregorianCalendar(); int month = cal.get(Calendar.MONTH); int year = cal.get(Calendar.YEAR); int day = cal.get(Calendar.DAY_OF_MONTH); System.out.println("Current date : " + day + "/" + (month + 1) + "/" + year); } }

Getting Current Time import java.util.*; public class CurrentTime{ public static void main(String[] args){ Calendar calendar = new GregorianCalendar(); String am_pm; int hour = calendar.get(Calendar.HOUR); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); if(calendar.get(Calendar.AM_PM) == 0) am_pm = "AM"; else am_pm = "PM"; System.out.println("Current Time : " + hour + ":" + minute + ":" + second + " " + am_pm); } }

Date Formatting using SimpleDateFormat SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. Example import java.util.*; import java.text.*; public class DateDemo { public static void main(String args[]) { Date dNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); System.out.println("Current Date: " + ft.format(dNow)); } } Result: Current Date: Sun at 04:14:09 PM PDT

TimeZone Another time-related class is TimeZone. The TimeZone class allows you to work with time zone offsets from Greenwich mean time (GMT), also referred to as Coordinated Universal Time (UTC). It also computes daylight saving time. TimeZone only supplies the default constructor.

Parsing Strings into Dates import java.util.*; import java.text.*; public class DateDemo { public static void main(String args[]) { SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd"); String input = args.length == 0 ? " " : args[0]; System.out.print(input + " Parses as "); Date t; try { t = ft.parse(input); System.out.println(t); } catch (ParseException e) { System.out.println("Unparseable using " + ft); } } } Result: $ java DateDemo Parses as Wed Nov 11 00:00:00 GMT 1818 $ java DateDemo Parses as Sat Dec 01 00:00:00 GMT 2007

Creating a Hash Table : Java Util Hash Table holds the records according to the unique key value. It stores the non-contiguous key for several values. Hash Table is created using an algorithm (hashing function) to store the key and value regarding to the key in the hash bucket

Descriptions hashtable hashTable = new Hash table (): - Creates the instance of the Hashtable class. This code is using the type checking of the elements which will be held by the hash table. hashTable.put(key, in.readLine()): - puts the values in the hash table regarding to the unique key. Map map = new TreeMap (hashTable): - Creates an instance of the TreeMap for the hash table which name is passed through the constructor of the TreeMap class. Example Example

Java Serialization Object can be represented as sequence of byte which have data as well as information about states of object. Information about states of objects includes type of object and the data types stored in the object. Representing object into this form is known as Object Serialization.

EXAMPLE 1: Serializing an object & storing it into a file public class Student implements java.io.Serializable{ public String name; public String address; public transient int rollno; public int roomNo; }

import java.io.*; public class SerializeExample { public static void main(String[] args) { Student e = new Student(); e.name = "Kapil k Singh"; e.address = "E-247,Beta-1,Noida"; e.rollno = ; e.roomNo = 111; try { FileOutputStream fileOut = new FileOutputStream("student.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(e); out.close(); fileOut.close(); System.out.println("Object is serialized & stored in 'student.ser'"); } catch (IOException ie) { ie.printStackTrace(); } } }

Deserializing an Object import java.io.*; public class DeserializeExample { public static void main(String[] args) { Student e = null; try { FileInputStream fileIn = new FileInputStream("Student.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); e = (Student) in.readObject(); in.close(); fileIn.close(); } catch (IOException i) { i.printStackTrace(); return; } catch (ClassNotFoundException c) { System.out.println("Student class not found"); c.printStackTrace(); return; } System.out.println("Deserialized Student..."); System.out.println("Name: " + e.name); System.out.println("Address: " + e.address); System.out.println("Roll no: " + e.rollno); System.out.println("Room No: " + e.roomNo); } }

Assignment Questions 1) Determining the actual age from date of birth in Java 2) Determining If a Year is a Leap Year in Java 3) Determining the Day-of-Week for a Particular Date