oop_Exam1

9
The System Class Tutorial 6 - Class Libraries To aid programmer productivity, the Java insta llation 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. Syste m Class Math Class Local e Class Calend ar & Date Exampl e: 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  S  ystem class provides redirectable standard io streams for console read, write and error operations. The  S  ystem class also provides access to the native operat ing system's environment through the use of  static methods. As an

Transcript of oop_Exam1

8/3/2019 oop_Exam1

http://slidepdf.com/reader/full/oopexam1 1/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 

services java.net , new io (ie. memory mapped) java.nio and remote methodinvocation 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 thelibraries (except for java.lang). Unless another library is indicated the following

classes are contained in the java.lang package.

Syste

m

Class 

Math

Class 

Local

e

Class 

Calend

ar &

Date 

Exampl

e:

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 themany 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  S  ystem class provides redirectable standard io streams for console read, write

and error operations.

The  S  ystem class also provides access to the native operating system's environmentthrough the use of  static methods. As an

8/3/2019 oop_Exam1

http://slidepdf.com/reader/full/oopexam1 2/9

example  S  ystem.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  S  ystem.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  S ecurityException 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  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),

8/3/2019 oop_Exam1

http://slidepdf.com/reader/full/oopexam1 3/9

round(x) 

Miscellaneous  IEEEremainder(x,y),

random(),

toDegrees(x),

toRadians(x) 

 N ote: 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: CA N  ADA, CA N  ADA_FRE  N CH, CHI  N  A, CHI  N  E  S  E, E  NGL I  S  H, FRA N CE, FRE  N CH, G  ERMA N  , G  ERMA NY  , ITA L IA N  , ITA LY  ,

 JAPA N  , JAPA N  E  S  E, KOREA, KOREA N  , PRC,  S  IMP  L IFIED_CHI  N  E  S  E,

TAIWA N  , TRADITIO N  A L _CHI  N  E  S  E, UK A N  D U  S . 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 objectformat. get(fld) returns the specific field as a string object. fld can be YEAR,

MONTH, DAY_OF_MONTH, etc. getTime() returns the time in DATEformat. G regorianCalendar is a concrete subclass which adds a boolean isLeapYear()

test.

8/3/2019 oop_Exam1

http://slidepdf.com/reader/full/oopexam1 4/9

Group  Methods 

C onstr uct or   getInstance() 

 Accessor   get(fld),

getAvailableLocales,

getInstance(),

getTime(),

getTimeZone() 

Mutat or   add(whichField,

intVal), clear(),

set(fld,intVal),

setTime(),

setTimeZone() 

C omparison  after(), before(),

equals(), isSet() 

The wrapper class Date is used primarily to convert objects into longs for math

operations with the getTime() method.

 N ote: Calendar.getTime() converts to Date objects, Date.getTime() converts to long

 primitives.

Example: timeSpan()

A common request is for a time S  pan() method that computes the difference betweentwo 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();

8/3/2019 oop_Exam1

http://slidepdf.com/reader/full/oopexam1 5/9

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  S impleDateFormat providesthe ability to format and parse dates and times. The constructor normally takes a

formatting string made from the following symbols:

Char M

eaning 

a  AM or PM 

d  Day of month 

h  Hour (1-12) 

8/3/2019 oop_Exam1

http://slidepdf.com/reader/full/oopexam1 6/9

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[])

8/3/2019 oop_Exam1

http://slidepdf.com/reader/full/oopexam1 7/9

{

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  N umberFormat 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 

8/3/2019 oop_Exam1

http://slidepdf.com/reader/full/oopexam1 8/9

%  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 

C onstr uct or   DecimalFormat (), DecimalFormat(pattern),

DecimalFormat(pattern,symbols) 

 Accessor   getDecimalFormatSymbols (), getGroupingSize(),

getMultiplier(), getNegativePrefix(),,getNegativeSuffix(),

getPositivePrefix(), getPositiveSuffix() 

Mutat or   setDecimalFormatSymbols(newSymbols),

setDecimalSeparatorAlwaysShown(newValue),

setGroupingSize(newValue),

setMaximumFractionDigits(newValue),

setMaximumIntegerDigits(newValue),

setMinimumFractionDigits(newValue),

setMinimumIntegerDigits(newValue), setMultiplier(newValue),

setNegativePrefix(newValue), setNegativeSuffix(newValue),

8/3/2019 oop_Exam1

http://slidepdf.com/reader/full/oopexam1 9/9

setPositivePrefix(newValue), setPositiveSuffix(newValue) 

Boolean  equals(ob j), isDecimalSeparatorAlwaysShown() 

Instance  applyLocalizedPattern(pattern), applyPattern(pattern),

format(number),

String toLocalizedPattern(), String toPattern(),