Using Predefined Classes Core Java

Because you can’t do anything in Java without classes, you have already seen severalclasses at work. However, not all of these show off the typical features of object orientation.Take, for example, the Math class. You have seen that you can use methods of the Mathclass, such as Math. random, without needing to know how they are implemented—all youneed to know is the name and parameters (if any). That is the point of encapsulationand will certainly be true of all classes. But the Math class only encapsulates functionality;it neither needs nor hides data. Because there is no data, you do not need to worry aboutmaking objects and initializing their instance fields—there aren’t any!

Objects and Object Variables

To work with objects, you first construct them and specify their initial state. Then youapply methods to the objects.

NOTE: You may be wondering: Why use classes to represent dates rather than (as in some languages) a built-in type? For example, Visual Basic has a built-in date type and programmers can specify dates in the format #6/1/1995#. On the surface, this sounds convenient— programmers can simply use the built-in date type rather than worrying about classes. But actually, how suitable is the Visual Basic design? In some locales, dates are specified as month/day/year, in others as day/month/year. Are the language designers really equipped to foresee these kinds of issues? If they do a poor job, the language becomes an unpleasant muddle, but unhappy programmers are powerless to do anything about it. With classes, the design task is off loaded to a library designer. If the class is not perfect, other programmers can easily write their own classes to enhance or replace the system classes. (To prove the point: The Java date library is a bit muddled, and a major redesign is underway.)

In the Java programming language, you use constructors to construct new instances. Aconstructor is a special method whose purpose is to construct and initialize objects.

Constructors always have the same name as the class name. Thus, the constructor forthe Date class is called Date. To construct a Date object, you combine the constructor with the new operator, as follows:

This expression constructs a new object. The object is initialized to the current date andtime. If you like, you can pass the object to a method:

Alternatively, you can apply a method to the object that you just constructed. One of themethods of the Date class is the toString method. That method yields a string representationof the date. Here is how you would apply the toString method to a newly constructed Date object:

In these two examples, the constructed object is used only once. Usually, you will wantto hang on to the objects that you construct so that you can keep using them. Simplystore the object in a variable:

Creating a new object

Creating a new object

There is an important difference between objects and object variables. For example,the statement

defines an object variable, deadline, that can refer to objects of type Date. It is important torealize that the variable deadline is not an object and, in fact, does not yet even refer to anobject. You cannot use any Date methods on this variable at this time. The statement

would cause a compile-time error.

You must first initialize the deadline variable. You have two choices. Of course, you caninitialize the variable with a newly constructed object:

Or you can set the variable to refer to an existing object:

Now both variables refer to the same object.

It is important to realize that an object variable doesn’t actually contain an object. It onlyrefers to an object.

In Java, the value of any object variable is a reference to an object that is stored elsewhere. The return value of the new operator is also a reference. A statement such as

has two parts. The expression new Date() makes an object of type Date, and its value is a referenceto that newly created object. That reference is then stored in the deadline variable.

Object variables that refer to the same object

Object variables that refer to the same object

You can explicitly set an object variable to null to indicate that it currently refers to noobject.

If you apply a method to a variable that holds null, then a runtime error occurs.

Variables are not automatically initialized to null. You must initialize them, either bycalling new or by setting them to null.

C++ NOTE: Many people mistakenly believe that Java object variables behave like C++ references. But in C++ there are no null references, and references cannot be assigned. You should think of Java object variables as analogous to object pointers in C++. For example,

is really the same as

Once you make this association, everything falls into place. Of course, a Date* pointer isn’t initialized until you initialize it with a call to new. The syntax is almost the same in C++ and Java.

If you copy one variable to another, then both variables refer to the same date—they are pointers to the same object. The equivalent of the Java null reference is the C++ NULL pointer.

All Java objects live on the heap. When an object contains another object variable, that variable still contains just a pointer to yet another heap object.

In C++, pointers make you nervous because they are so error prone. It is easy to create bad pointers or to mess up memory management. In Java, these problems simply go away. If you use an uninitialized pointer, the runtime system will reliably generate a runtime error instead of producing random results. You don’t worry about memory management, because the garbage collector takes care of it.

C++ makes quite an effort, with its support for copy constructors and assignment operators, to allow the implementation of objects that copy themselves automatically. For example, a copy of a linked list is a new linked list with the same contents but with an independent set of links. This makes it possible to design classes with the same copy behavior as the built-in types. In Java, you must use the clone method to get a complete copy of an object.

The GregorianCalendar Class of the Java Library

In the preceding examples, we used the Date class that is a part of the standard Javalibrary. An instance of the Date class has a state, namely a particular point in time.

Although you don’t need to know this when you use the Date class, the time is representedby the number of milliseconds (positive or negative) from a fixed point, the socalledepoch, which is 00:00:00 UTC, January 1, 1970. UTC is the Coordinated Universal Time, the scientific time standard that is, for practical purposes, the same as the more familiar GMT or Greenwich Mean Time.

But as it turns out, the Date class is not very useful for manipulating dates. The designers ofthe Java library take the point of view that a date description such as “December 31, 1999,23:59:59” is an arbitrary convention, governed by a calendar. This particular description follows the Gregorian calendar, which is the calendar used in most places of the world.The same point in time would be described quite differently in the Chinese or Hebrewlunar calendars, not to mention the calendar used by your customers from Mars.

NOTE: Throughout human history, civilizations grappled with the design of calendars that attached names to dates and brought order to the solar and lunar cycles. For a fascinating explanation of calendars around the world, from the French Revolutionary calendar to the Mayan long count, see Calendrical Calculations, Second Edition by NachumDershowitz and Edward M. Reingold (Cambridge University Press, 2001).

The library designers decided to separate the concerns of keeping time and attachingnames to points in time. Therefore, the standard Java library contains two separate classes: the Date class, which represents a point in time, and the GregorianCalendar class,which expresses dates in the familiar calendar notation. In fact, the GregorianCalendar classextends a more generic Calendar class that describes the properties of calendars in general.In theory, you can extend the Calendar class and implement the Chinese lunar calendaror a Martian calendar. However, the standard library does not contain any calendar implementations besides the Gregorian calendar.

Separating time measurement from calendars is good object-oriented design. In general,it is a good idea to use separate classes to express different concepts.

The Date class has only a small number of methods that allow you to compare two pointsin time. For example, the before and after methods tell you if one point in time comesbefore or after another:

NOTE: Actually, the Date class has methods such as getDay, getMonth, and getYear, but these methods are deprecated. A method is deprecated when a library designer realizes that the method should have never been introduced in the first place.

These methods were a part of the Date class before the library designers realized that it makes more sense to supply separate calendar classes. When the calendar classes were introduced, the Date methods were tagged as deprecated. You can still use them in your programs, but you will get unsightly compiler warnings if you do. It is a good idea to stay away from using deprecated methods because they may be removed in a future version of the library.

The GregorianCalendar class has many more methods than the Date class. In particular, it hasseveral useful constructors. The expression

constructs a new object that represents the date and time at which the object was constructed.

You can construct a calendar object for midnight on a specific date by supplying year,month, and day:

Somewhat curiously, the months are counted from 0. Therefore, 11 is December. Forgreater clarity, there are constants like Calendar.DECEMBER:

You can also set the time:

Of course, you will usually want to store the constructed object in an object variable:

The GregorianCalendar has encapsulated instance fields to maintain the date to which it isset. Without looking at the source code, it is impossible to know the representation that the class uses internally. But, of course, the point of encapsulation is that this doesn’t matter. What matters are the methods that a class exposes.

Mutator and Accessor Methods

At this point, you are probably asking yourself: How do I get at the current day ormonth or year for the date encapsulated in a specific Gregorian Calendar object? And howdo I change the values if I am unhappy with them? You can find out how to carry outthese tasks by looking at the on -line documentation or the API notes at the end of this section. We go over the most important methods in this section.

The job of a calendar is to compute attributes, such as the date, weekday, month, oryear, of a certain point in time. To query one of these settings, you use the get methodof the GregorianCalendar class. To select the item that you want to get, you pass a constantdefined in the Calendar class, such as Calendar.MONTH or Calendar .DAY _OF _WEEK:

The API notes list all the constants that you can use. You change the state with a call to the set method:

There is also a convenience method to set the year, month, and day with a single call:

Finally, you can add a number of days, weeks, months, and so on, to a given calendar object:

If you add a negative number, then the calendar is moved backwards.

There is a conceptual difference between the get method on the one hand and the set andadd methods on the other hand. The get method only looks up the state of the object andreports on it. The set and add methods modify the state of the object. Methods that change instance fields are called mutator methods, and those that only access instance fields withoutmodifying them are called accessor methods.

C++ NOTE: In C++, the const suffix denotes accessor methods. A method that is not declared as const is assumed to be a mutator. However, in the Java programming language, no special syntax distinguishes between accessors and mutators.

A common convention is to prefix accessor methods with the prefix get and mutator methods with the prefix set. For example, the Gregorian Calendar class has methods get Timeand set Time that get and set the point in time that a calendar object represents:

These methods are particularly useful for converting between the GregorianCalendar and Dateclasses. Here is an example. Suppose you know the year, month, and day and you want tomake a Date object with those settings. Because the Date class knows nothing about calendars, first construct a Gregorian Calendar object and then call the getTime method to obtain a date:

Conversely, if you want to find the year, month, or day of a Date object, you construct aGregorian Calendar object, set the time, and then call the get method:

We finish this section with a program that puts the GregorianCalendar class to work. Theprogram displays a calendar for the current month, like this:

Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19* 20 21 22 23 24 25 26 27 28 29 30 31

The current day is marked with an asterisk (*). As you can see, the program needs toknow how to compute the length of a month and the weekday of a given day.
Let us go through the key steps of the program. First, we construct a calendar objectthat is initialized with the current date.

We capture the current day and month by calling the get method twice.

Then we set d to the first of the month and get the weekday of that date.

The variable weekday is set to Calendar .SUNDAY if the first day of the month is a Sunday, to Calendar.MONDAY if it is a Monday, and so on. (These values are actually the integers 1, 2, . . . , 7,but it is best not to write code that depends on that knowledge.)

Note that the first line of the calendar is indented, so that the first day of the month fallson the appropriate weekday. This is a bit tricky since there are varying conventionsabout the starting day of the week. In the United States, the week starts with Sundayand ends with Saturday, whereas in Europe, the week starts with Monday and endswith Sunday.

The Java virtual machine is aware of the locale of the current user. The locale describeslocal formatting conventions, including the start of the week and the names of the weekdays.

TIP: If you want to see the program output in a different locale, add a line such as the following as the first line of the main method:


The getFirstDayOfWeek method gets the starting weekday in the current locale. To determinethe required indentation, we subtract 1 from the day of the calendar object untilwe reach the first day of the week.

Next, we print the header with the weekday names. These are available from the class Date Format Symbols.

The get Short Weekdays method returns a string with short weekday names in the user’slanguage (such as "Sun", "Mon", and so on in English). The array is indexed by weekdayvalues. Here is the loop to print the header:

Now, we are ready to print the body of the calendar. We indent the first line and set the date object back to the start of the month. We enter a loop in which d traverses the days of the month.

In each iteration, we print the date value. If d is today, the date is marked with an *. If wereach the beginning of each new week, we print a new line. Then, we advance d to thenext day:

d.add(Calendar.DAY_OF_MONTH, 1);

When do we stop? We don’t know whether the month has 31, 30, 29, or 28 days. Instead,we keep iterating while d is still in the current month.

Once d has moved into the next month, the program terminates.

As you can see, the GregorianCalendar class makes it possible to write a calendar programthat takes care of complexities such as weekdays and the varying month lengths. Youdon’t need to know how the Gregorian Calendar class computes months and weekdays. Youjust use the interface of the class—the get, set, and add methods.

The point of this example program is to show you how you can use the interface of a classto carry out fairly sophisticated tasks without having to know the implementation details.
Listing below shows the complete program.

java.util.GregorianCalendar 1.1 GregorianCalendar()

constructs a calendar object that represents the current time in the default timezone with the default locale.

  • GregorianCalendar(int year, int month, int day)
  • GregorianCalendar(int year, int month, int day, int hour, int minutes, int seconds)constructs a Gregorian calendar with the given date and time.
  • Parameters: year the year of the date monththe month of the date. day the day of the month hour the hour (between 0 and 23) minutes the minutes (between 0 and 59) seconds the seconds (between 0 and 59)
  • int get(int field)
    gets the value of a particular field.
  • Parameters: field one of Calendar.ERA,Calendar.YEAR, Calendar.MONTH, Calendar.WEEK_OF_YEAR,Calendar.WEEK_OF_MONTH, Calendar.DAY_OF_MONTH,Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK,Calendar.DAY_OF_WEEK_IN_MONTH, Calendar.AM_PM,Calendar.HOUR, Calendar.HOUR_OF_DAY, Calendar.MINUTE,Calendar.SECOND, Calendar.MILLISECOND, Calendar.ZONE_OFFSET,Calendar.DST_OFFSET
  • void set(int field, int value)
    sets the value of a particular field.
  • Parameters: field one of the constants accepted by get value the new value
  • void set(int year, int month, int day)
  • void set(int year, int month, int day, int hour, int minutes, int seconds)
  • sets the fields to new values.
    Parameters: year the year of the date Month the month of the date. day the day of the month hour the hour (between 0 and 23) minutes the minutes (between 0 and 59) seconds the seconds (between 0 and 59)
  • void add(int field, int amount)
    is a date arithmetic method. Adds the specified amount of time to the given time field. For example, to add 7 days to the current calendar date, call c.add(Calendar.DAY_OF_MONTH,7).
  • Parameters: field the field to modify amount the amount by which the field should be changed
  • intgetFirstDayOfWeek()
    gets the first day of the week in the locale of the current user, for example, Calendar.SUNDAY in the United States.
  • void setTime(Date time)
    sets this calendar to the given point in time.
  • Parameters: time a point in time
  • Date getTime()
    gets the point in time that is represented by the current value of this calendar object

java.text.DateFormatSymbols 1.1

  • String[] getShortWeekdays()
  • String[] getShortMonths()
  • String[] getWeekdays()
  • String[] getMonths()

gets the names of the weekdays or months in the current locale. Uses Calendar weekday and month constants as array index values.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Core Java Topics