HTML Markup | JavaScript | Java | Home & Links

Tutorial 6 - Class Libraries

To aid programmer productivity, the Java installation includes several predefined class packages (aka Java class libraries). Packages/libraries discussed in this set of tutorials are: applets java.applet, language extensions java.lang, utilities java.util, formatters java.text, file streams java.io, GUIs java.awt and javax.swing, network services java.net, new io (ie. memory mapped) java.nio and remote method invocation java.rmi. Other libraries include beans java.beans, communication ports java.comm, precision math java.math, database management java.sql and security java.security. The import reserved word is used to access classes from the libraries (except for java.lang). Unless another library is indicated the following classes are contained in the java.lang package.

Note 1: For information on creating your own class packages or using 3rd-party libraries see the Java Appendix.

Note 2: Some programmers find that using an interactive development environment (IDE) such as NetBeans to be very helpful in accessing and using the many extended features that these class libraries provide. Others stay with a basic text editor and develop a more complete understanding of the libraries. It is your call but I recommend a basic text editor for beginning programmers.

The System Class

The System class provides redirectable standard io streams for console read, write and error operations.

The System class also provides access to the native operating system's environment through the use of static methods. As an example System.currentTimeMillis() retrieves the system clock setting (as a long, in milliseconds counted from January 1, 1970). Some of the available methods are:

currentTime()
freeMemory()
gc()
totalMemory()
exit(int status)
exec(String cmd)
execin(String cmd)
getenv(String var)
getCWD()
getOSName()
arraycopy(src[], srcpos, dest[], destpos, len)

Another method called System.getProperty("property_name") allows access to the following system properties:

  • file.separator
  • line.separator
  • path.separator
  • os.arch
  • os.name
  • os.version
  • user.dir
  • user.home
  • user.name
  • java.class.path
  • java.class.version
  • java.home
  • java.vendor
  • java.vendor.url
  • java.version
  • java.vm.name
  • java.vm.vendor
  • java.vm.version

Note: Many System class methods can throw a SecurityException exception error for safety reasons.

The Math Class

The Math class provides the important mathematical constants E and PI which are of type double. It also provides many useful math functions as methods.

GroupMethods
Transcendental acos(x), asin(x), atan(x), atan2(x,y), cos(x), sin(x), tan(x)
Exponential exp(x), log(x), pow(x,y), sqrt(x)
Rounding abs(x), ceil(x), floor(x), max(x,y), min(x,y), rint(x), round(x)
Miscellaneous IEEEremainder(x,y), random(), toDegrees(x), toRadians(x)

Note: random() generates double in range of 0 to < 1.

intRnd=(int) (Math.random() * x) + 1; // from 1 to x
intRnd=(int) (Math.random() * 10); // random digit

The Locale Class [java.util library]

The Locale class produces object that describe a geographical or cultural region. For example dates, times and numbers are displayed differently through the world. Calendar, GregorianCalendar, DateFormat, SimpleDateFormat and SimpleTimeZone are all locale-sensitive. By default the locale is determined by the operating system.

Some of the more commonly used locale methods are: setDefault(loc_obj), getDefault(), getDisplayCountry(), getDisplayLanguage() and getDisplayName().

Locale constants include: CANADA, CANADA_FRENCH, CHINA, CHINESE, ENGLISH, FRANCE, FRENCH, GERMAN, GERMANY, ITALIAN, ITALY, JAPAN, JAPANESE, KOREA, KOREAN, PRC, SIMPLIFIED_CHINESE, TAIWAN, TRADITIONAL_CHINESE, UK AND US. Locale.CANADA would give the loc_obj for Canada.

Calendar & Date Classes [java.util library]

The abstract class Calendar provides methods for formatting and comparing dates. getInstance() returns the current date/time in Calendar object format. get(fld) returns the specific field as a string object. fld can be YEAR, MONTH, DAY_OF_MONTH, etc. getTime() returns the time in DATE format. GregorianCalendar is a concrete subclass which adds a boolean isLeapYear() test.

GroupMethods
Constructor getInstance()
Accessor get(fld), getAvailableLocales, getInstance(), getTime(), getTimeZone()
Mutator add(whichField, intVal), clear(), set(fld,intVal), setTime(), setTimeZone()
Comparison after(), before(), equals(), isSet()

The wrapper class Date is used primarily to convert objects into longs for math operations with the getTime() method.

Note: Calendar.getTime() converts to Date objects, Date.getTime() converts to long primitives.

Example: timeSpan()

A common request is for a timeSpan() method that computes the difference between two Date or Calendar objects. Since Date has been downgraded to a wrapper with no setField operations, my example uses Calendar objects. The user will have to provide his own input (either sio or file) and output reporter.

import java.util.*;
public class Timer
{
  public static void main(String args[])
  {
// create start and end calendar objects
    Calendar sTime=Calendar.getInstance();
    Calendar eTime=Calendar.getInstance();
// now set times -- add routines to get from sio or file
// be sure to verify times are in range !!
// adjust times for early start and late finish
    sTime.set(Calendar.HOUR_OF_DAY,8);sTime.set(Calendar.MINUTE,0);
    eTime.set(Calendar.HOUR_OF_DAY,16);eTime.set(Calendar.MINUTE,0);
    long span=timeSpan(sTime,eTime);
// adjust time for lunch hour here
    long secs=span/1000;long mins=secs/60;long hours=mins/60;
    System.out.println(hours);
    System.out.println(mins);
  }
// timeSpan (calendarObject,calendarObject) returns long milliseconds
  public static long timeSpan(Calendar calStart,Calendar calEnd)
  {
    Date sTime1,eTime1;long interval,sTime2,eTime2;
    sTime1=calStart.getTime();eTime1=calEnd.getTime(); // to Date objects
    sTime2=sTime1.getTime();eTime2=eTime1.getTime(); // to long objects
    interval=eTime2-sTime2;return interval;
  }
}

The DateFormat Class [java.text library]

The abstract class DateFormat and its concrete subclass SimpleDateFormat provides the ability to format and parse dates and times. The constructor normally takes a formatting string made from the following symbols:

CharMeaning
aAM or PM
dDay of month
hHour (1-12)
kHour (1-24)
mMinute
sSecond
wWeek of year
yYear
zTimezone
:Separator
CharMeaning
DDay of year
EDay of week
FDay of week in month
GEra (AD or BC)
HHour in Day (0-23)
KHour in Day (0-11)
MMonth
SMillisecond
WWeek of month
/Escape character

Here is an example of how SimpleDateFormat can be used:

import java.text.*; import java.util.*;
public class test
{
  public static void main (String args[])
  {
    Date date=new Date(); String rptDate;
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy MMM dd @ hh:mm aa");
    rptDate=sdf.format(date); System.out.println(rptDate+"\n");
  }
}

The NumberFormat Class [java.text library]

The NumberFormat class is used to display numbers in a locale sensitive fashion. The methods getInstance(), getIntegerInstance(), getCurrencyInstance() and getPercentInstance() create objects formatted using local variants. Other useful methods are setDecimalSeparatorAlwaysOn(bool), setMinimunFractionDigits(i), setMaximunFractionDigits(i), setMinimunIntegerDigits(i), setMaximunIntegerDigits(i) and setParseIntegerOnly(bool).

The DecimalFormat Class [java.text library]

The DecimalFormat class provides highly customized number formatting and parsing. Objects are created by passing a suitable pattern to the DecimalFormat() constructor method. The applyPattern() method can be used to change this pattern. A DecimalFormatSymbols object can be optionally specified when creating a DecimalFormat object. If one is not specified, a DecimalFormatSymbols object suitable for the default locale is used. Decimal format patterns consists of a string of characters from the following table. For example: "$#,##0.00;($#,##0.00)"

CharInterpretation
0A digit // leading zeros show as 0
#A digit // leading zeros show as absent
.The locale-specific decimal separator
,The locale-specific grouping separator (comma)
-The locale-specific negative prefix
%Shows value as a percentage
;Separates a positive number format (on left) from
an optional negative number format (on right)
'Escapes a reserved character so it appears literally in the output

Here is an example of how DecimalFormat can be used:

import java.text.*;
public class test
{
  public static void main (String args[])
  {
    int numb=3; String rptNumb;
    DecimalFormat df=new DecimalFormat("000");
    rptNumb=df.format(numb); System.out.println(rptNumb+"\n");
  }
}

The DecimalFormat class methods are as follows:

GroupMethods
Constructor DecimalFormat (), DecimalFormat(pattern), DecimalFormat(pattern,symbols)
Accessor getDecimalFormatSymbols (), getGroupingSize(), getMultiplier(), getNegativePrefix(),,getNegativeSuffix(), getPositivePrefix(), getPositiveSuffix()
Mutator setDecimalFormatSymbols(newSymbols), setDecimalSeparatorAlwaysShown(newValue), setGroupingSize(newValue), setMaximumFractionDigits(newValue), setMaximumIntegerDigits(newValue), setMinimumFractionDigits(newValue), setMinimumIntegerDigits(newValue), setMultiplier(newValue), setNegativePrefix(newValue), setNegativeSuffix(newValue), setPositivePrefix(newValue), setPositiveSuffix(newValue)
Boolean equals(obj), isDecimalSeparatorAlwaysShown()
Instance applyLocalizedPattern(pattern), applyPattern(pattern), format(number),
String toLocalizedPattern(), String toPattern(),


JR's HomePage | Comments [jatutor6.htm:2011 12 01]