Sunday, March 18, 2007

Class Libraries

To help programmers be more productive, Java includes predefined class packages (aka Java class libraries) as part of the installation. Some specific package/libraries are: applets java.applet, language extensions java.lang, utilities java.util, formatters java.text, io java.io, GUI java.awt and javax.swing, network services java.net, precision math java.math, database management java.sql, security java.security.

Note: Some programmers find that using an interactive development environment (IDE) such as NetBeans, JCreator or JBuilder 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.

Note: Unless another library is indicated the following classes are contained in the java.lang package.

Packages

One of the goals of Java is code reusability. The library keeping function for code reuse is enabled through the use of packages of precompiled classes that can be imported into other projects. This allows developers to distribute their work as toolkits without distributing the source code. Programmers can use these classes as easily as using the classes distributed as part of the developers kit.

All that is required to package a group of classes for reuse in other projects or for distribution is to include the package directive in your source file prior to any executable code. An example might be: package toolkit; where toolkit refers to the folder that the class(es) will be stored in. Sublevels of folder are supported through dot notation. The convention for package names which ensures uniqueness is to reverse the order of your domain name. For example ACME.com would set up its toolkit as com.acme.toolkit.

The import directive is used to incorporate packaged classes within a new project. It is placed prior to any executable code (but after any package directive if there is one). For the above examples of packages, the corresponding import statements would be

import toolkit.*; import com.acme.toolkit.*;

The package location's root is determined by an operating system environment variable called classpath. It can have multiple entries which are used in sequence as search paths. The first matching entry is used. As an example of a WindowsXP classpath here is mine:

classpath=.;C:\Program Files\Java\jdk1.5.0_10\bin;

This says to first look in the current directory and if a class file isn't there look inside the bin folder of the installed distribution package.

Type Wrappers

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

  • isLowerCase(char c)
  • isUpperCase(char c)
  • isDigit(char c)
  • isLetter(char c)
  • isLetterOrDigit(char c)
  • isWhitespace(char c)
  • toLowerCase(char c)
  • toUpperCase(char c)
  • compareTo(String g)

Note: Java 1.5 has introduced automatic type conversion (casting) between primitives and wrapper objects. For example the following are equivalent:

Integer num = 17;
Integer num = new Integer(17);

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()
  • 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 throw a SecurityException error for safety reasons.

The System class also provides very basic io streams for console read, write and error operations. System.in.read() reads a keystroke and returns an integer value. System.out.println(string) displays a string to the current output device.

Note: There are much better ways for user interaction. You can refer to io streams for methods of reading more than a keystroke at a time or refer to GUI stuff for visual interfaces using AWT and Swing objects.

The Math Class

The Math class provides the important mathematical constants E and PI which are of type double.

The Math class 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: To generate a random integer between 1 and x you can use the following.

intRnd = (int) (Math.random() * x) + 1;

The DecimalFormat Class [java.text library]

Applications that require highly customized number formatting and parsing may create custom DecimalFormat class objects 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), String toLocalizedPattern(), String toPattern(),

The Calendar Class [java.util library]

The Calendar class provides a set of methods for formatting dates. getInstance() returns the current date/time as a Calendar object. get(param) returns the specific parameter as a string object. Param can be YEAR, MONTH, DAY_OF_MONTH etc.

GroupMethods
Constructor none
Accessor get(), getAvailableLocales, GetInstance(), getTimeZone()
Mutator set(), setTime(), setTimeZone()
Boolean equals(), isSet()

The Date Class [java.util library]

The Date class provides a standard format for any member of the class.The Date class methods are as follows:

GroupMethods
Constructor Date()
Accessor long getTime()
Mutator String Date.toString()
Boolean before(Date when), after(Date when), equals(Date when)

The Date Format 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");
rptDate = sdf.format(date); System.out.println(rptDate+"\n");
}
}

Project: Math Problems

Here are a few problems that involve passing object references as parameters. You may want to review tutorial 2 on arrays, the new operator and assigning variable values. Formatted output requires DecimalFormat class and keyboard input requires file io class!

  1. Write a method to interchange any two rows of a two-dimensional array passed to it.
  2. Write a method to determine if a two-dimensional array passed to it is symmetric, that is A[i][j]==A[j][i] for all valid i and j.
  3. Write method to transpose, a matrix, that is your method should make its rows into columns, and vice-versa.
  4. Write a method to multiply two conformable matrices. Use your method to find the product P=M x M x M for the matrix M given by {{4,9,2},{3,5,7},{8,1,6}}
  5. Write a program that allows you to input 10 numbers into an array. Then create a method that will return and print the average, sum, smallest value, largest value and printout those below the average and values above average.
  6. Write a program allows you to create the following methods [Assume that your array has 10 elements]:
      A). A method to input the content of an array.
    B). A method to return the sum.
    C). A method to return the average
    D). A method to return the average of negative numbers.
    E). A method to return the average of positive numbers.
    F). A method to return the average, smallest and largest.
  7. Write a program that allows you fill a tabulated 3x3 matrix with random numbers range from 0 to 50. Write a method that will display a message BINGO if the array element has at least 2 numbers divisible by 5.

No comments: