HTML Markup | JavaScript | Java | Home & Links

Tutorial 5 - Class Libraries

To aid programmer productivity, the Java Standard Edition (JSE) 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, precision math java.math, 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, database management java.sql and security java.security. The import reserved word is used to access classes from libraries other than java.lang.

java.lang java.utiljava.text

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

arraycopy(src[], srcpos, dest[], destpos, len)
currentTimeMillis()
gc()
exit(int exitCode)
getenv(String var)
getCWD()
getOSName()

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

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

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

The Runtime Class

The Runtime class encapsulates the run-time environment. Some of the available methods are:

availableProcessors()
exec(String cmd)
load(String fileName)
loadLibrary(String libName)
exit(int status)
gc()
halt(int status)
runFinalization()
freeMemory()
maxMemory()
totalMemory()

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 objects that represent a geographical, political or cultural region. 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: getAvailableLocales(), getDefault(), getDisplayCountry(), getDisplayLanguage(), getDisplayName() and setDefault(loc_obj). Use seeLocale to find out what is available on the running computer before setting a new locale.

Locale objects are created using locale(strLanguage[,strCountry]. where strLanguage and strCountry are ISO codes. Default Locale language constants include: CANADA_FRENCH, CHINESE, ENGLISH, FRENCH, GERMAN, ITALIAN, JAPANESE, KOREAN, SIMPLIFIED_CHINESE and TRADITIONAL_CHINESE. Default locale country constants include: CANADA, CHINA, FRANCE, GERMANY, ITALY, JAPAN, KOREA, PRC, TAIWAN, UK and US.

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 to convert a String to a Date:

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");
    try {rptDate=sdf.format(date); System.out.println(rptDate+"\n");}
    catch (ParseException e)
	      {System.out.println("Exception :"+e);}
  }
}

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 [jatutor5.htm:2014 04 04]