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.
|
|
|
|
|
Class Libraries:
- A class library is collection of classes
- Example : System, Scanner, String
- Java Standard class library is comes as a part of java instillation.
- You can create your custom libraries
Packages
- The classes of Java Standard class library are organized into
packages.
- Few Important packages are :
- java.lang :General support
- java.applet :Web pages
- java.awt. : Graphics
- java.net : Networking
- java.util :Utilities
- java.swing : Additional graphic capabilities
|
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()
- 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 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. It can also throw
an IOException
exception
error. System.out.println(string) displays a string to the
current output device. There are much better ways for user interaction.
Refer to io streams
for methods of reading more than one keystroke at a time or refer to
file choosers
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. 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 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 varients. 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.*; 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");
}
}
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(), |
|
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 and
SimpleDateFormat are locale-sensitive. By default the locale is determined
by the operating system.
Some of the more commonly used locale methods are: setDefault(loc_obj),
getDisplayCountry(), getDisplayLanguage() and getDisplayName().
Local 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.
|
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.
Group |
Methods |
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:
Group |
Methods |
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:
|
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 |
|