HTML Markup | JavaScript | Java | Home & Links

Tutorial 5 - Class Libraries

Java includes several predefined class packages (aka Java class libraries) to aid in programmer productivity. The packages/libraries discussed in my tutorials are: language extensions java.lang, utilities java.util, formatters java.text, file streams, GUIs java.awt and javax.swing, network services, memory mapped io java.nio, remote method invocation java.rmi and applets java.applet. Libraries not covered in my tutorials include beans java.beans, communication ports java.comm, precision math java.math, security and database management java.sql. import is used to access classes from libraries other than java.lang. Class name conflicts can be resolved by prepending the package name. Library packages explains how to create reusable class packages or use 3rd-party libraries.

java.lang java.utiljava.text

System Class

The System class provides access to the operating system's environment through the use of static methods. For example System.currentTimeMillis() retrieves the system clock setting (as a long, in milliseconds starting Jan 1, 1970). Methods include: arraycopy(src[], srcpos, dest[], destpos, len), clearProperty(sName), currentTimeMillis(), exit(exitCode), gc(), getenv(String var), getCWD(), getOSName(), getProperty().

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

  • file.separator
  • line.separator
  • path.separator
  • os.arch
  • os.version
  • user.dir
  • user.home
  • java.class.path
  • java.class.version
  • java.home
  • java.vendor
  • java.vendor.url
  • java.version
  • 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.

Runtime Class

The Runtime class encapsulates the run-time environment. Available methods are: availableProcessors(), exec(String cmd). load(String fileName), loadLibrary(String libName), exit(int status), gc(), halt(int status), runFinalization(), freeMemory(), maxMemory() and totalMemory().

Math Class

The Math class provides the constants E and PI which are of type double as well as many useful methods:

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

Locale Class [java.util library]

Dates, times and numbers are displayed differently internationally depending on geographical, political or cultural region. The Locale class produces language/country related objects Calendar, DateFormat, GregorianCalendar, SimpleDateFormat and SimpleTimeZone are all locale-sensitive. By default the locale is set by the operating system.

Locale objects are created using locale(strLanguage[,strCountry] where strLanguage is ISO-639 and strCountry is ISO-3166.

Some of the more commonly used locale methods are: getAvailableLocales(), getDefault(), getDisplayCountry(), getDisplayLanguage(), getDisplayName() and setDefault(loc_obj). Use my showLocale app to find out what is available on the computer before setting a new locale. showLocale now uses the enhanced for loop.

Calendar & Date Classes [java.util library]

The abstract class Calendar provides methods for formatting and comparing dates. The wrapper class Date is used primarily to convert objects into longs for math operations with the getTime() method. 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.

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

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

The often needed timeSpan(cal1,cal2) function is shown on the java short projects page.

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:

aAM or PM
dDay of month
hHour (1-12)
kHour (1-24)
wWeek of year
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)
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);}

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 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 customized number formatting and parsing. Objects are created by passing a 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)"

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

The DecimalFormat class methods are as follows:

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:2016 02 15]