Sie sind auf Seite 1von 9

The System Class

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 servicesjava.net, new io (ie. memory mapped) java.nio and remote method invocation java.rmi. Other libraries include beansjava.beans, communication ports java.comm, precision math java.math, database management java.sql and securityjava.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.
y

y y

Syste y m Class Math y Class Local e Class

Calend y ar & Date y Exampl e: y timeSp an()

DateFormat Class NumberForm at Class DecimalForm at Class

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 redirectable standard io streams for console read, write and error operations. The System class also 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 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 Transcendental Methods acos(x), asin(x), atan(x), atan2(x,y), cos(x), sin(x), tan(x) exp(x), log(x), pow(x,y), sqrt(x) abs(x), ceil(x), floor(x), max(x,y), min(x,y), rint(x),

Exponential

Rounding

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 ocale 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.

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.

Group Constructor Accessor

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

Mutator

Comparison

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:
Char a d h AM or PM Day of month Hour (1-12) Meaning

k m s w y z : Char D E F G H K M S W /

Hour (1-24) Minute Second Week of year Year Timezone Separator Meaning Day of year Day of week Day of week in month Era (AD or BC) Hour in Day (0-23) Hour in Day (0-11) Month Millisecond 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 0 # . , Interpretation 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 Constructor Methods DecimalFormat (), DecimalFormat(pattern), DecimalFormat(pattern,symbols) getDecimalFormatSymbols (), getGroupingSize(), getMultiplier(), getNegativePrefix(),,getNegativeSuffix(), getPositivePrefix(), getPositiveSuffix() setDecimalFormatSymbols(newSymbols), setDecimalSeparatorAlwaysShown(newValue), setGroupingSize(newValue), setMaximumFractionDigits(newValue), setMaximumIntegerDigits(newValue), setMinimumFractionDigits(newValue), setMinimumIntegerDigits(newValue), setMultiplier(newValue), setNegativePrefix(newValue), setNegativeSuffix(newValue),

Accessor

Mutator

setPositivePrefix(newValue), setPositiveSuffix(newValue) Boolean Instance equals(obj), isDecimalSeparatorAlwaysShown() applyLocalizedPattern(pattern), applyPattern(pattern), format(number), String toLocalizedPattern(), String toPattern(),

Das könnte Ihnen auch gefallen