Beruflich Dokumente
Kultur Dokumente
Objects
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Contents
I. The Object Class
II. The String Classes
• String, StringBuilder, etc.
III. Wrapper Classes
IV. Utility Classes
V. Collections
VI. Exceptions
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
The Object Class
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
The Object Class
All classes are subclasses of Object
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
The Object Class
All classes inherit these methods:
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
toString()
public String toString()
returns a String representation of the object
in the Object class, returns a concatenation of
the runtime class name and the hashcode
usually overridden to return something more
appropriate
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
equals()
public boolean equals(Object obj)
in the Object class, returns true when the
parameter obj is the same instance as the
current object
Same as == operator
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
hashCode()
public int hashCode()
returns an integer value that is the object’s
“hashcode”
used in “hashing” algorithms
such as in HashSet and HashMap
rarely called directly
Best Practice: if you override equals, you
must override hashcode
otherwise, hashing algorithms fail
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
The String Classes
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
String and
StringBuffer/StringBuilder
Java actually has TWO types of strings!
String
Immutable – once you create it, you can never
change its value.
StringBuffer/StringBuilder
Mutable – these are the classes you should
use if you need to do a lot of string
manipulation.
StringBuffer – before Java 1.5
StringBuilder – preferred option for Java 1.5 and
above
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
String
The JVM maintains a pool of String
objects. Each newly created String is
stored in the pool. The instance lingers
even if no references are pointing to it.
String x = "SELECT";
"SELECT"
String y = "SELECT";
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
String
Great performance if there is no need to
modify, since you don’t incur the cost of
instantiation.
String a = "SELECT";
"SELECT"
String b = "SELECT";
String c = "SELECT";
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
String
Otherwise, performance is terrible. Each
“modification” actually creates a new
String.
“happy”
String greeting = “happy”; “ ” “happy ”
greeting += “ ”;
greeting += “birth”; “birth”
greeting += “day”;
“happy birth”
“day”
“happy birthday”
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
String
The string pool is also the reason why you
should never initialize a string with the
“new” operator if the literal will do.
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
String
String a = "SELECT";
String b = "SELECT";
a == b true! a and b point to the same instance
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
String
Strings are the only objects that can be used
with the “+” and “+=” operators.
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
String
String Methods
@see the API documentation for String
Notice that all methods for “string manipulation” will not
modify the String instance. They will only return a new
String.
substring, trim, split, replace, replaceFirst, replaceAll,
compareToIgnoreCase
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
StringBuffer/StringBuilder
Maintains an internal character array,
contents can be modified.
Great performance when modifications are
needed.
@see API documentation for StringBuilder
append, delete, insert, replace, setCharAt,
length, toString
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Primitive Wrappers
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Primitive Wrappers
Allow primitive values to participate in the world
of objects.
For example, allows primitives to be stored in
“Collections” (Java data structures)
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Primitive Wrappers
Each primitive datatype has a corresponding
wrapper type.
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Primitive Wrappers
Immutable
Just like String, once value is set, it cannot be
changed.
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Primitive Wrappers
Creating a Primitive Wrapper
Primitive wrappers are usually* created simply by
calling the constructor and feeding the primitive value
as a constructor:
Integer i = new Integer(14);
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Primitive Wrappers
Before Java 1.5, you can’t use primitive
wrappers directly in arithmetic nor
comparison operators. You have to extract
the primitive values first:
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Primitive Wrappers
Autoboxing and Unboxing in Java 1.5
Java 1.5 automatically converts primitives to
wrappers and wrappers to primitives:
Integer i = 5;
Integer j = 10;
Integer answer = i + j;
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Primitive Wrappers
equals() method
Returns true if the object passed is of the same type
and has the same value:
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Primitive Wrappers
Primitive Wrappers as Utility Classes
Primitive Wrappers also serve as “Utility
Classes”*.
They contain static methods and static fields
that are useful for the type of primitive that
each of them wraps.
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Primitive Wrappers
Primitive Wrappers as Utility Classes
@see the API documentation for the ff:
Integer: parseInt, toString. MAX_VALUE,
MIN_VALUE
Float: parseFloat, NaN, POSITIVE_INFINITY,
NEGATIVE_INFINITY, isNaN, isInfinite
Character: isDigit, isLetter, isLetterOrDigit,
isLowerCase, isUpperCase, isSpace,
isWhitespace
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
BigDecimal
Computers cannot accurately store
decimal values!
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
BigDecimal
BigDecimal accurately stores a decimal
number to a specified level of precision.
new BigDecimal(“1.25”);
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
BigDecimal
BigDecimal has methods for arithmetic
operations.
add, subtract, multiply, divide, min, max,
negate, pow, abs, remainder, round
@see API Documentation for BigDecimal
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Collections
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Collections
Objects used to hold other objects (data
structures).
Lists – like arrays, only size can grow
Sets – like lists, only all elements have to be unique
SortedSets – sets that hold elements in a sorted
order
Maps – maintains a set of key-value pairs
Queues (Java 1.5) – used to hold objects prior to
processing, usually in a FIFO* manner, sometimes in
some sort of “priority” ordering
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Collections
Collections will be discussed in more
detail in a succeeding lecture.
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Utility Classes
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Utility Classes
Classes that just hold useful routines.
All methods and fields are static.
Never instantiated.
To be discussed:
1. System
2. Math
3. Arrays
4. Collections
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Utility Classes
System
Used to get some access the underlying
operating system.
Fields: out, err, in
Methods: arraycopy, currentTimeMillis, exit,
getProperties, getProperty, gc
@see API Documentation for System
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Utility Classes
Math
Contains methods for mathematical operations
abs, round, min, max, sin, cos, tan, floor, ceil,
exp, log, random
@see API Documentation for Math
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Utility Classes
Arrays
Contains methods for working with arrays
sort, binarySearch, equals, asList, toString
@see API Documentation for Arrays
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Utility Classes
Collections
Contains methods for working with Collections
sort, binarySearch, addAll, copy, min, max,
frequency, unmodifiable____
@see API Documentation for Collections
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Commonly Used
Classes for Dates
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Date
Encapsulates a long value representing a
specific moment in time.
Used for getting a “time-stamp”
An object that represents the current date and
time.
Depends on System.currentTimeMillis() in
obtaining the time.
To use Date, import java.util.Date
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Calendar
Represents a point in time interpreted
appropriately for some locale and
timezone.
Used for date manipulation.
To use Calendar, import java.util.Calendar
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Date vs Calendar
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Instantiating a Calendar
Since Calendar is an abstract class, it cannot
be instantiated.
Static methods of Calendar, however, can still
be called.
To instantiate a Calendar, use the
getInstance() method:
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Instantiating a Calendar
getInstance() method will return an instance of
a concrete subclass of Calendar.
By default, it will return a GregorianCalendar
instance.
GregorianCalendar is part of the standard Java
API.
There are existing Java libraries for handling
other types of calendars such as Buddhist,
Islamic or Japanese.
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Instantiating a Calendar
Another way is to instantiate a
GregorianCalendar directly.
@see API Documentation for constructing a
GregorianCalendar with parameters.
@see API Documentation for additional methods
of GregorianCalendar.
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Getting Information from the
Calendar
A Calendar object holds fields for
representing its ultimate state, its date and
time.
These fields can be accessed via the get()
method (which then returns an int)
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Commonly Used Calendar
Fields
DATE / DAY_OF_MONTH
DAY_OF_WEEK
HOUR/ HOUR_OF_DAY
MILLISECOND
MINUTE
MONTH
YEAR
ZONE_OFFSET
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Commonly Used Calendar
Methods
add(int field, int amount)
Adds or subtracts time from the calendar's field.
cal.add(Calendar.Date, 20);
get(int field)
Returns the value of the given calendar field.
int date = cal.get(Calendar.Date);
getTimeInMillis()
Returns this Calendar's time in millis as a long.
long day1 = cal.getTimeInMillis();
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Commonly Used Calendar
Methods
roll(int field, boolean up)
Adds or subtracts time without changing larger
fields.
cal.roll(Calendar.DATE, 35);
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
SimpleDateFormat
Used for handling the most common
requirements related to displaying and
converting dates to specific storage
formats.
Constructor accepts a String containing the
intended format for display.
Format String can contain additional
formatting characters
space, forward slash, and dash.
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
SimpleDateFormat Sample
formatter.setLenient(false);
Date date = formatter.parse("29/Feb/2008");
System.out.println(formatter.format(date));
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
SimpleDateFormat Sample
The format
SimpleDateFormat formatter = new
to);be used.
SimpleDateFormat("dd/MMM/yyyy"
formatter.setLenient(false);
Date date = formatter.parse("29/Feb/2008");
System.out.println(formatter.format(date));
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
SimpleDateFormat Sample
formatter.setLenient(false); Specify
whether or not
Date date = formatter.parse("29/Feb/2008");
date/time
System.out.println(formatter.format(date));
parsing is to be
lenient.
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
SimpleDateFormat Sample
This is used
SimpleDateFormat formatter = new
for converting
SimpleDateFormat("dd/MMM/yyyy");
a valid String
date to a Date.
formatter.setLenient(false);
Date date = formatter.parse("29/Feb/2008");
System.out.println(formatter.format(date));
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
SimpleDateFormat Sample
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Common Display Formats
Sample
Format Example
“dd/MMM/yyyy” 18/Jan/2008
“dd-MM-yyyy” 18-03-2008
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Abbreviated List of
SimpleDateFormat Parameters
y year
M month in year
d day in month
D day in year
w week in year
W week in month
E day in week
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Exceptions
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Exceptions
Special objects used to indicate that an
exceptional (usually undesirable) event
has occurred.
Will abruptly end execution, unless
handled.
A “stack trace” will be written to the standard
error stream to help you debug your problem.
The stack trace will contain all the methods
that were in execution, and the line number of
the code being called in each method, at the
time the exception occurred.
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Exceptions
Exceptions that indicate a bug in your program:
NullPointerException
thrown by JVM to indicate that one of your variables
type
ArrayIndexOutOfBounds
…an index was passed to an array that is out of
bounds
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
The End
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved