Sie sind auf Seite 1von 44

Miscellaneous

1
Java
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

2
Java
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

3
Java
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()

4
Java
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()

5
Java
Be able to
• Implement Enum, Data and Calendar classes
• Format dates and numbers
• Write Java Beans
• Use native, volatile and strictfp access
specifiers

6
Java
static constants
class CornCorner{
public final static int LARGE=1; Can you
public final static int MEDIUM=2; identify the
problems you
public final static int SMALL=3;
can have with
public final static int BUTTER=1; this code?
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;}}
Example 1
7
Java
enums Example 2

• 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); 8
Java
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 !

9
Java
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. 10
Java
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.
11
Java
printing enums
public static void main(String
str[]){
for(CornCorner.SIZE s:
CornCorner.SIZE.values()){
System.out.println(s);
}}
Prints:
LARGE
MEDIUM
SMALL Example 3

12
Java
Members in enum
class CornCorner{
enum SIZE {
LARGE(500), MEDIUM(300), SMALL(200);
private int size; field
SIZE(int size){this.size=size;}
int getSize(){ return size;} constructor
} method
public static void main(String str[]){
SIZE s= SIZE.LARGE;
System.out.println(s.getSize());}}
Example 4
13
Java
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);
14
Java
Overriding enum methods
class CornCorner{
enum SIZE {
MEDIUM(300), SMALL(200), Necessary here
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; Example 5
System.out.print(s.getSize());}} 15
Java
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.

16
Java
Get date and time components
import java.util.*; Example 6

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));
} returns the specified
} part of the date and
time from the calendar Static constants that specifies what get()
instance. must return. 17
Java
Set date and time components
import java.util.*; Example 7

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]) )
18
Java
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.


19
Java
Locale
• A Locale instance is used to specify the formatting
style in a specific region.
• Creation -2 ways: ISO 639 language codes- en, ja
• -Locale(String language,[ String
country], [String variant])
country - uppercase two-letter ISO-3166 code: US, IT etc.
variant - vendor and browser specific code: WIN, MAC
etc.
-Static constants that returns Locale
references defined by this class like
CANADA, FRANCE, GERMANY, ITALY ,
JAPAN, CHINA, ENGLISH, UK ,US
20
Java
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.
21
Java
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.

22
Java
Constructing DateFormat
• getDateInstance([int style],[Local
e aLocale])
• getTimeInstance([int style],[Local
e aLocale])
• getDateTimeInstance([int datestyle
,int timestyle],[ Locale aLocale])
• getInstance()

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

23
Java
Using DateFormat class
import java.util.*;
import java.text.*; package imported for DateFormat
class Test{
public static void main(String str[]){
Date d= new Date(); formats a Date object
String dt=
DateFormat.getDateInstance().format(d);
System.out.println(dt);}}

Output: Returns format for the default locale


Aug 2, 2006
Example 8
24
Java
Formatting by specifying style

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

25
Java
Formatting dates using Locale
Calendar c = Calendar.getInstance();
c.set(2006,7, 1); // 1st August 2006
Date d = c.getTime();
Locale in = new Locale("hi","IN");//india
Locale ja = new Locale("ja"); //japan
System.out.println(
DateFormat.getDateInstance
(DateFormat.SHORT, in).format(d));
System.out.println(DateFormat.getDateInstance(Da
teFormat.SHORT, ja).format(d));
Or
System.out.println(DateFormat.getDateInstance(Da
teFormat.SHORT, Locale.JAPAN).format(d)); 26
Example 9 Java
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:

 getInstance() or
getNumberInstance() for current default
locale
 getInstance(Locale l) or
getNumberInstance(Locale l)
 getXxxInstance() and
getXxxInstance(Locale l) 27
where XXX is Integer, Currency, Percent Java
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

28
Java
Number formatting example
double d= 12345.6789; Denmark
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)); Example 10
29
Java
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()
30
Java
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
45
Example 11 31
Java
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.

32
Java
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.

33
Java
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.
34
Java
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!
35
Java
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.

36
Java
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

37
Java
Modifiers/Specifiers

Access specifiers/ Non-Access specifiers/


modifiers modifiers
public static
native
private final volatile
abstract strictfp
protected
[default] synchronized
In Threads
transient
Our focus right now
38
Java
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();

39
Java
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.
40
Java
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 .

41
Java
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.

42
Java
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.

43
Java
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 . 44
Java

Das könnte Ihnen auch gefallen