10 enum and date, calendar, arrays, locale

44
1 Java Miscellaneous

Upload: suresh1130

Post on 13-Nov-2014

125 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 10  Enum and Date, Calendar, Arrays, Locale

1Java

Miscellaneous

Page 2: 10  Enum and Date, Calendar, Arrays, Locale

2Java

Contents

1 static constants

2 Enums

3 enum and class

4 printing enums

5 Members in enum

6 Overriding enum methods

7 java.util.Calendar

8 Get date and time components

9 Set date and time components

10 Other interesting methods

Page 3: 10  Enum and Date, Calendar, Arrays, Locale

3Java

Contents

11 Locale

12 java.util.Date

13 Formatting dates

14 Constructing DateFormat

15 Using DateFormat class

16 Formatting by specifying style

17 Formatting dates using Locale

18 Number formatting

19 Methods to format

20 Few more NumberFormat methods

Page 4: 10  Enum and Date, Calendar, Arrays, Locale

4Java

Contents

21 Java Beans

22 Property data types and methods

23 Coupling and Cohesion

24 Modifiers/Specifiers

25 Native

26 Volatile

27 Strictfp

28 More on garbage collection

29 Requesting GC

30 finalize()

Page 5: 10  Enum and Date, Calendar, Arrays, Locale

5Java

Know

• Enum • Date and Calendar classes• How to format dates and numbers• What Java Beans are• What native, volatile and strictfp access

specifiers• Some facts about garbage collection in Java

and the use of finalize()

Page 6: 10  Enum and Date, Calendar, Arrays, Locale

6Java

Be able to

• Implement Enum, Data and Calendar classes• Format dates and numbers• Write Java Beans • Use native, volatile and strictfp access

specifiers

Page 7: 10  Enum and Date, Calendar, Arrays, Locale

7Java

static constants

class CornCorner{public final static int LARGE=1;public final static int MEDIUM=2;public final static int SMALL=3;public final static int BUTTER=1;public final static int PEPPER=2;public final static int CHILLI=3;private int size;private int flavour;CornCorner(int size, int flavour){this.size=size;this.flavour=flavour;}}

Can you identify the

problems you can have with

this code?

Example 1

Page 8: 10  Enum and Date, Calendar, Arrays, Locale

8Java

enums• New feature in 1.5 that allows us to create type-

safe constants.class CornCorner{enum SIZE {LARGE, MEDIUM, SMALL };enum FLAVOUR {BUTTER, PEPPER, CHILLI };

private SIZE size;private FLAVOUR flavour;CornCorner(SIZE size, FLAVOUR flavour){

this.size=size;this.flavour=flavour}}

new CornCorner(CornCorner.SIZE.LARGE, CornCorner.FLAVOUR.PEPPER);

Example 2

Page 9: 10  Enum and Date, Calendar, Arrays, Locale

9Java

So what will be the data type of SIZE and FLAVOUR ?

Don’t confuse enum with enumeration types of other

languages. In fact when we create enums in java we are sort of creating a

datatype- a class !

Page 10: 10  Enum and Date, Calendar, Arrays, Locale

10Java

enum and class• enums are special type of java classes that are

subclasses of a class java.lang.Enum which implements the interfaces Serializable and Comparable.

• enum can be declared with only the public, private or default modifier. They cannot be declared inside a method and cannot be instantiated.

• For-each can be used with enums for iterating: for(CornCorner.SIZE s: CornCorner.SIZE.values())

• Unqualified enum names can also be used as case labels.

Page 11: 10  Enum and Date, Calendar, Arrays, Locale

11Java

Since enum is a class can I have stand-alone enum … that is

enum declared outside class?

Yes, you can declare enum independent of class. And if you declare it inside a class ‘;’ is optional. It is like an inner class.

class CornCorner{enum SIZE {LARGE, MEDIUM, SMALL}enum FLAVOUR {BUTTER, PEPPER, CHILLI }…} But remember the access-specifier can only be public or default.

Page 12: 10  Enum and Date, Calendar, Arrays, Locale

12Java

printing enumspublic static void main(String str[]){

for(CornCorner.SIZE s: CornCorner.SIZE.values()){

System.out.println(s);

}}

Prints:

LARGE

MEDIUM

SMALL Example 3

Page 13: 10  Enum and Date, Calendar, Arrays, Locale

13Java

Members in enum

class CornCorner{enum SIZE {LARGE(500), MEDIUM(300), SMALL(200);private int size;SIZE(int size){this.size=size;}int getSize(){ return size;}}public static void main(String str[]){SIZE s= SIZE.LARGE;System.out.println(s.getSize());}}

field

constructormethod

Example 4

Page 14: 10  Enum and Date, Calendar, Arrays, Locale

14Java

We have to be very careful about where to place enum constants when we have fields, constructors etc in enum class. For example the code below will not compile:enum SIZE {private int size;SIZE(int size){this.size=size;

}int getSize(){ return size;}LARGE(500), MEDIUM(300), SMALL(200);}Also, invoking enum constructor as follows is also invalid.SIZE s= SIZE.LARGE(900);

Page 15: 10  Enum and Date, Calendar, Arrays, Locale

15Java

Overriding enum methods

class CornCorner{enum SIZE { MEDIUM(300), SMALL(200), LARGE(500){ int getSize(){return super.getSize(); }};private int size;SIZE(int size){this.size=size;}int getSize(){ System.out.print("I am the largest of all and my size is ");return size;} }

public static void main(String str[]){SIZE s= SIZE.LARGE;System.out.print(s.getSize());}}

Necessary here

Example 5

Page 16: 10  Enum and Date, Calendar, Arrays, Locale

16Java

java.util.Calendar

• A utility class used to work with date and time.• Calendar is an abstract class.• To create an instance of Calendar class use getInstance() static method which initializes a Calendar object with the system’s current date and time.

• The getInstance() static method of Calendar class instantiates a local sensitive class.

• Note: System.currentTimeMillis() gets current time in milliseconds.

Page 17: 10  Enum and Date, Calendar, Arrays, Locale

17Java

import java.util.*;class Test{public static void main(String str[]){String month[]={"Jan","Feb","Mar","Apr","May","Jun","Jly","Aug","Sep","Oct","Nov","Dec"};

Calendar c=Calendar.getInstance();String m=month[c.get(Calendar.MONTH)];System.out.print(m);System.out.println(c.get(Calendar.DATE));}}

Static constants that specifies what get() must return.

returns the specified part of the date and time from the calendar instance.

Get date and time componentsExample 6

Page 18: 10  Enum and Date, Calendar, Arrays, Locale

18Java

import java.util.*;

class Test{

public static void main(String str[]){

Calendar c=Calendar.getInstance();

System.out.println("enter year");

int year=new Scanner(System.in).nextInt();

c.set(Calendar.YEAR,year);

System.out.println(c.get(c.DAY_OF_WEEK));}}

Specify the date component and the value. Other version of set methods:set(int year, int month, int date,[int hourOfDay, int minute] [, int second]) )

Set date and time componentsExample 7

Page 19: 10  Enum and Date, Calendar, Arrays, Locale

19Java

Other interesting methods

• void add(int field, int amount)• boolean after(Object when)• boolean before(Object when)• void clear()• void clear(int field) • Static constants from JANUARY to DECEMBER, SATURDAY to FRIDAY

• void roll(int field, int amount)• abstract void roll(int field, boolean up)

Calendar.YEAR, Calendar.MONTH etc.

Page 20: 10  Enum and Date, Calendar, Arrays, Locale

20Java

Locale• A Locale instance is used to specify the formatting

style in a specific region. • Creation -2 ways:• -Locale(String language,[ String

country], [String variant])

ISO 639 language codes- en, ja

-Static constants that returns Locale references defined by this class like CANADA, FRANCE, GERMANY, ITALY , JAPAN, CHINA, ENGLISH, UK ,US

variant - vendor and browser specific code: WIN, MAC etc.

country - uppercase two-letter ISO-3166 code: US, IT etc.

Page 21: 10  Enum and Date, Calendar, Arrays, Locale

21Java

java.util.Date

• Date is a older class in JDK 1.0. A Date object is represented internally a single long number which represents the number of milliseconds since January 1, 1970, 00:00:00 GMT.

• Most of its methods are depreciated because many of them are not amenable to internationalization.

• Date(), Date(long) : constructor that creates an object which represents system's current date and time. The getTime() method of Calendar class returns Date object.

Page 22: 10  Enum and Date, Calendar, Arrays, Locale

22Java

Formatting dates

• DateFormat class and Locale class can be used together to format the date.

• DateFormat is an abstract class.• Formatting is necessary to display the dates with

respect to a specific locality.• DateFormat class is used to format and parse the

date. It provides many class methods for obtaining default date/time formatters based on the default or a given locale (specified by Locale object or by default) and a number of formatting styles.

Page 23: 10  Enum and Date, Calendar, Arrays, Locale

23Java

Constructing DateFormat• getDateInstance([int style],

[Locale aLocale])• getTimeInstance([int style],

[Locale aLocale])• getDateTimeInstance([int datestyle

,int timestyle],[ Locale aLocale]) • getInstance()

date style/ time style static constants: MEDIUM, LONG, SHORT

Page 24: 10  Enum and Date, Calendar, Arrays, Locale

24Java

Using DateFormat class

import java.util.*;import java.text.*;class Test{public static void main(String str[]){Date d= new Date();String dt=DateFormat.getDateInstance().format(d);System.out.println(dt);}}

Output:Aug 2, 2006

package imported for DateFormat

Returns format for the default locale

formats a Date object

Example 8

Page 25: 10  Enum and Date, Calendar, Arrays, Locale

25Java

Formatting by specifying style

• DateFormat.getDateInstance

(DateFormat.SHORT).format(d); • Returns: 8/2/06• Similarly try out for :

•DateFormat.MEDIUM•DateFormat.LONG•DateFormat.FULL

Page 26: 10  Enum and Date, Calendar, Arrays, Locale

26Java

Formatting dates using Locale

Calendar c = Calendar.getInstance();c.set(2006,7, 1); // 1st August 2006Date d = c.getTime();Locale in = new Locale("hi","IN");//indiaLocale ja = new Locale("ja"); //japanSystem.out.println(DateFormat.getDateInstance(DateFormat.SHORT, in).format(d)); System.out.println(DateFormat.getDateInstance(DateFormat.SHORT, ja).format(d));

OrSystem.out.println(DateFormat.getDateInstance(DateFormat.SHORT, Locale.JAPAN).format(d));

Example 9

Page 27: 10  Enum and Date, Calendar, Arrays, Locale

27Java

Number formatting

• Like date formatting, number formatting can also be done using NumberFormat and Locale classes.

• It is an abstract class.• Methods get an NumberFormat instance:

1. getInstance() or getNumberInstance() for current default locale

2. getInstance(Locale l) or getNumberInstance(Locale l)

3. getXxxInstance() and getXxxInstance(Locale l)

where XXX is Integer, Currency, Percent

Page 28: 10  Enum and Date, Calendar, Arrays, Locale

28Java

Methods to format

• From numeric into String form:

-String format(double/long d)

• From String form into Number

- String Number parse(String source) throws ParseException

Page 29: 10  Enum and Date, Calendar, Arrays, Locale

29Java

Number formatting example double d= 12345.6789;Locale l = new Locale("da", "DK"); System.out.println(NumberFormat.getInstance(l).format(d)); System.out.println(NumberFormat.getInstance().format(d)); System.out.println(NumberFormat.getCurrencyInstance(l).format(d)); System.out.println(NumberFormat.getCurrencyInstance().format(d));

Denmark

Example 10

Page 30: 10  Enum and Date, Calendar, Arrays, Locale

30Java

Few more NumberFormat methods

• void setMaximumFractionDigits(int newVal)

• int getMinimumFractionDigits() • void setMaximumIntegerDigits(int newVal)

• int getMinimumIntegerDigits()• void setParseIntegerOnly(boolean value)

• boolean isParseIntegerOnly()• void setCurrency(Currency currency)• Currency getCurrency()

Page 31: 10  Enum and Date, Calendar, Arrays, Locale

31Java

import java.util.*;import java.text.*;class Test{public static void main(String str[]) throws ParseException{

double d=12345.6546;NumberFormat nf = NumberFormat.getInstance();

nf.setMaximumFractionDigits(2);System.out.println(nf.format(d));nf.setParseIntegerOnly(true);System.out.println(nf.parse("45.65"));}} Prints: 12,345.65

45Example 11

Page 32: 10  Enum and Date, Calendar, Arrays, Locale

32Java

I noticed that for both DateFormat and NumberFormat class we use getInstance() method to get instances of their respective types. Are they also abstract like Calendar class?

Yes ! both DateFormat and NumberFormat class are

abstract classes.

Page 33: 10  Enum and Date, Calendar, Arrays, Locale

33Java

Java Beans

• A java bean is a java class with some attributes or properties that meet the following criteria:

• The class must be public.• The class must have a no-arguments constructor.• The class must provide set and get methods to

access variables which follow the JavaBean property naming convention.

Page 34: 10  Enum and Date, Calendar, Arrays, Locale

34Java

Property data types and methods

•public void setXxx(Type t)•public Type getXxx()•where Type is any primitive data type or class and Xxx is the attribute. •For boolean types boolean isXxx() is also valid instead of boolean getXxx().

•The get methods are also called getters or accessor methods.•The set methods are also called setters or mutators methods.

Page 35: 10  Enum and Date, Calendar, Arrays, Locale

35Java

More…• If the bean is a component that generates

event, then it must have addXxxListener() methods to allow other components which are interested in the event.

To understand this better let us get moving to AWT after just one more topic!

Page 36: 10  Enum and Date, Calendar, Arrays, Locale

36Java

Coupling and Cohesion

• Coupling: It is measure of dependence between classes.

• Cohesion: It is a measure of the extent to which the internal constituents of a class are related to each other and to the overall purpose of the class.

• Recommendation for a good OO Design: Low coupling and High Cohesion.

Page 37: 10  Enum and Date, Calendar, Arrays, Locale

37Java

Examples

• A class that accesses data member of another class – High coupling.

• A class that provides only one functionality. – High cohesion.

• Changing implementation of one class does not affect any other class – Low coupling.

• A class that does database operations, report printing and archiving. – Low cohesion

Page 38: 10  Enum and Date, Calendar, Arrays, Locale

38Java

Modifiers/Specifiers

Access specifiers/ modifiers

Non-Access specifiers/ modifiers

public

private

protected

[default]

static

final

abstract

synchronized

transient

native volatilestrictfp

In Threads

Our focus right now

Page 39: 10  Enum and Date, Calendar, Arrays, Locale

39Java

native• native is applicable to methods only.• It indicates that the method is implemented as

native code (machine-dependent code: usually c code).

• So, the native method declaration in a class is like the abstract method.

• Example: • public native void method();

Page 40: 10  Enum and Date, Calendar, Arrays, Locale

40Java

volatile• volatile is applicable to member variables only.

• It is generally used in multithreaded programming where multiple threads share the same member variable which is rapidly changing (ex:-timer variable that changes very second). In such a scenario, it will be time consuming for multiple threads to keep the updating and tracking the change in the value of member variable in the memory.

• If the member variable is declared volatile, then every thread maintains its own copy of the member variable and updation with the actual copy of the member variable happens only periodically.

Page 41: 10  Enum and Date, Calendar, Arrays, Locale

41Java

strictfp• strictfp is applicable to methods and the class only.• strictfp forces floating points (and any floating-point

operations) to adhere to the IEEE 754 standard.• Without this keyword, the floating points are treated in

platform-specific way.• The advantage of using strictfp is that you get the

standard behavior in all the OS where you java code runs.

• But if you want to take advantage of the the underlying platform that supports greater precision then don’t use strictfp .

Page 42: 10  Enum and Date, Calendar, Arrays, Locale

42Java

More on garbage collection• Garbage collection cannot be forced. The JVM

runs the garbage collection (GC) thread a as a low priority thread.

• You can choose to request the JVM to run the garbage collection. Though one cannot guarantee that the GC thread will execute immediately (for the reason you know, now that you are a multithreading savvy!), if you don’t have any high priority threads executing at that point, there is a good chance that GC will execute.

Page 43: 10  Enum and Date, Calendar, Arrays, Locale

43Java

Requesting GC• System.gc()• Runtime.getRuntime().gc()• FROM API: Calling this method suggests that the Java virtual

machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the virtual machine has made its best effort to recycle all discarded objects.

Page 44: 10  Enum and Date, Calendar, Arrays, Locale

44Java

finalize()• The Object class defines a method called • protected void finalize()• This method is called just before an object is garbage

collected.• A class can override this method in case it needs to do

some clean–up like closing the file etc. (though this practice is not recommended).

• This method can also prevent the object from being garbage collected by making the objects available to other threads.

• The finalize method is never invoked more than once by a Java virtual machine for any given object.

• Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored .