Sie sind auf Seite 1von 64

Commonly-Used

Objects

a tour of the standard library


of Java

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

“The Mother of All Classes”

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:

 clone(), equals(), finalize(), getClass(),


hashCode(), notify(), notifyAll(), toString(),
wait()

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

 usually overridden to more appropriate


implementation
 Ex: for String – checks for spelling
 Ex: for BigDecimal – checks if value and scale
are equal

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

String and StringBuffer/StringBuilder

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.

String x = new String("SELECT"); "SELECT"

String y = new String("SELECT"); "SELECT"

String z = new String("SELECT"); "SELECT"

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

String c = new String("SELECT");


String d = new String("SELECT");
c == b  false! c and d point to different instances

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.

String greeting = “happy ” + “birthday”;


greeting += “ to you”;

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,

concat, toUpperCase, toLowerCase


 Methods for searching for characters or patterns in a
String:
 charAt, startsWith, endsWith, indexOf, lastIndexOf

 Methods for comparing Strings


 equals, equalsIgnoreCase, compareTo,

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)

Boolean Character Number

Byte Short Integer Long Float Double BigDecimal

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Primitive Wrappers
 Each primitive datatype has a corresponding
wrapper type.

Boolean Character Number

Byte Short Integer Long Float Double BigDecimal

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.

Boolean Character Number

Byte Short Integer Long Float Double BigDecimal

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);

 Retrieving Primitive Values


 Call one of the methods that end in “___Value”:
int x = i.intValue();
byte y = i.byteValue();
long z = i.longValue();

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:

Integer i = new Integer(5);


Integer j = new Integer(10);
int temp = i.intValue() + j.intVAlue();
Integer answer = new Integer(temp);

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:

Integer i = new Integer(10);


Integer j = new Integer(10);
Integer k = new Integer(25);
Long l = new Long(10);
i.equals(j);  true
i.equals(k);  false
i.equals(l);  false
i.equals(null);  false

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!

 Using floats and doubles are dangerous in


financial applications!

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
BigDecimal
 BigDecimal accurately stores a decimal
number to a specified level of precision.

 Use the constructor that takes in a String to


create precise values:

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

Java Data Structures

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

classes that hold routines for other


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

“For a time-stamp of 'now', use Date. But


for everything else, use Calendar.”
 Sierra & Bates (Head First Java, 2005)

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:

Calendar cal = Calendar.getInstance();

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.

Calendar cal = new 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)

int day = cal.get(Calendar.DAY);

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);

 set(int field, int value)


 Sets the value of a given Calendar field.
 cal.set(Calendar.DATE, 2);

 set(year, month, day, hour, minute)


 A common variety of set to set a complete time.
 cal.set(2008, 0, 17, 15, 30) -> month is zero-
based
Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Commonly Used Calendar
Methods
 setTimeInMillis(long millis)
 Sets a Calendar's time based on a long milli-
time.

long day = cal.getTimeInMillis();


day1 += 1000 * 60 * 60
cal.setTimeInMillis(day1);

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

SimpleDateFormat formatter = new


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

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

SimpleDateFormat formatter = new


SimpleDateFormat("dd/MMM/yyyy");

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

SimpleDateFormat formatter = new


Formats the
SimpleDateFormat("dd/MMM/yyyy");
date to the
specified
formatter.setLenient(false); format.
Date date = formatter.parse("29/Feb/2008");
System.out.println(formatter.format(date));

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

“dd, MMMMMMMMM yyyy” 18. January 2008

“EEEEEEEEE, MMMMMMMMM dd, yyyy” Friday, January 18, 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

was set to null yet there was an attempt to use it


 ClassCastException
 …an attempt was made to cast an object to the wrong

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

Das könnte Ihnen auch gefallen