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: 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.
Type Wrapper Classes
Type wrappers are classes used to enclose a simple datatype or a primitive object into an object. This is sometimes necessary because:
- Simple datatypes are not part of the object hierarchy.
- Simple datatypes are passed by value and not by reference.
- Two methods can't refer to the same instance of a simple type.
- Some classes can only use members of another class and not a simple type.
- The wrapped object lacks advanced methods needed for object manipulation
The Number class wrapper has subclasses of Byte, Short, Integer, Long, Double and Float. Each of these subclasses have constants MAX_VALUE and MIN_VALUE and methods for converting from and to strings such as: parseInt(str[, radix]), valueOf(str[, radix]), and toString(value).
The Boolean class wrapper allows passing Boolean values (true and false) by reference.
The Character class wrapper has many methods available, some of which are:
|
|
|
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:
| 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:
|
|
|
Note: Many System class methods can throw a SecurityException exception error for safety reasons.
The System class also provides standard io redirectable print streams for console read, write and error operations. System.in and System.out refer to the user console by default but can be redirected by the operating system to files using the symbols < and >. System.err always refers to the console (no redirection allowed). The method read() returns an integer value. It can also throw an IOException exception error. The methods print(string), println(string) and printf(format, object_list) display strings [with line return] [using c-like syntax formatting] to the console. There are much better ways for user interactions. Refer to file io for basic file management or to file choosers for visual file interfaces using Swing objects.
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.
| Group | 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: To generate a random integer between 1 and x you can use the following.
intRnd=(int) (Math.random() * x) + 1;
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.
Date & Calendar Classes [java.util library]
The Date class represents date objects in a long integer format. The Date class methods are as follows:
| Group | Methods |
|---|---|
| Constructor | Date(), Date (longMillisec) |
| Accessor | getTime() |
| Mutator | setTime(longTime), Date.toString() |
| Comparison | after(d), before(d), compareTo(d), equals(d) |
The Calendar class provides methods for formatting dates based on an object in milliseconds. getInstance() returns the current date/time as a Calendar object. get(locObj) returns the specific parameter as a string object. locObj can be YEAR, MONTH, DAY_OF_MONTH etc. An important subclass is GregorianCalendar which adds a boolean isLeapYear() test.
| Group | Methods |
|---|---|
| Constructor | none |
| Accessor | get(locObj), getAvailableLocales, getInstance(), getTime(), getTimeZone() |
| Mutator | add(whichField, intVal), clear(), set(), setTime(), setTimeZone() |
| Comparison | after(), before(), equals(), isSet() |
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:
| Char | Meaning |
|---|---|
| a | AM or PM |
| d | Day of month |
| h | Hour (1-12) |
| k | Hour (1-24) |
| m | Minute |
| s | Second |
| w | Week of year |
| y | Year |
| z | Timezone |
| : | Separator |
| Char | Meaning |
|---|---|
| D | Day of year |
| E | Day of week |
| F | Day of week in month |
| G | Era (AD or BC) |
| H | Hour in Day (0-23) |
| K | Hour in Day (0-11) |
| M | Month |
| S | Millisecond |
| W | Week 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)"
| Char | Interpretation |
|---|---|
| 0 | A 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:
| Group | Methods |
|---|---|
| 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(), |