MELJUN CORTES Java Lecture Commonly Used Objects

Post on 13-May-2015

172 views 0 download

Tags:

description

MELJUN CORTES Java Lecture Commonly Used Objects

Transcript of MELJUN CORTES Java Lecture Commonly Used Objects

Commonly-Used Commonly-Used ObjectsObjects

a tour of the standard librarya tour of the standard library

of Javaof Java

MELJUN CORTESMELJUN CORTES

MELJUN CORTESMELJUN CORTES

ContentsContents

I.I. The Object ClassThe Object Class

II.II. The String ClassesThe String ClassesI.I. String, StringBuilder, etc.String, StringBuilder, etc.

III.III. Wrapper Classes *todo:updateWrapper Classes *todo:update

IV.IV. Utility Classes Utility Classes

V.V. CollectionsCollections

VI.VI. ExceptionsExceptions

The Object ClassThe Object Class

““The Mother of All Classes”The Mother of All Classes”

The Object ClassThe Object Class

All classes are subclasses of ObjectAll classes are subclasses of Object

The Object ClassThe Object Class

All classes inherit these methods:All classes inherit these methods:

clone(), equals(), finalize(), getClass(), clone(), equals(), finalize(), getClass(), hashCode(), notify(), notifyAll(), toString(), hashCode(), notify(), notifyAll(), toString(), wait()wait()

toString()toString()

public String toString()public String toString() returns a String representation of the objectreturns a String representation of the object in the Object class, returns a concatenation of in the Object class, returns a concatenation of

the runtime class name and the hashcodethe runtime class name and the hashcode usually overridden to return something more usually overridden to return something more

appropriateappropriate

equals()equals()

public boolean equals(Object obj)public boolean equals(Object obj) in the Object class, returns true when the in the Object class, returns true when the

parameter obj is parameter obj is the same instance as the the same instance as the current objectcurrent object

Same as == operator

usually overridden to more appropriate usually overridden to more appropriate implementationimplementation

Ex: for String – checks for spelling Ex: for BigDecimal – checks if value and scale

are equal

hashCode()hashCode()

public int hashCode()public int hashCode() returns an integer value that is the object’s returns an integer value that is the object’s

“hashcode”“hashcode” used in “hashing” algorithms used in “hashing” algorithms

such as in HashSet and HashMap rarely called directlyrarely called directly Best Practice: if you override equals, you Best Practice: if you override equals, you

must override hashcodemust override hashcode otherwise, hashing algorithms fail

The String ClassesThe String Classes

String and StringBuffer/StringBuilderString and StringBuffer/StringBuilder

String and String and StringBuffer/StringBuilderStringBuffer/StringBuilder

Java actually has TWO types of strings!Java actually has TWO types of strings! StringString

Immutable – once you create it, you can never Immutable – once you create it, you can never change its value.change its value.

StringBuffer/StringBuilderStringBuffer/StringBuilder Mutable – these are the classes you should Mutable – these are the classes you should

use if you need to do a lot of string use if you need to do a lot of string manipulation.manipulation.

StringBuffer – before Java 1.5 StringBuilder – preferred option for Java 1.5 and

above

String x = "SELECT";"SELECT"

String y = "SELECT";

StringString

The JVM maintains a pool of String The JVM maintains a pool of String objects. Each newly created String is objects. Each newly created String is stored in the pool. The instance lingers stored in the pool. The instance lingers even if no references are pointing to it.even if no references are pointing to it.

StringString

Great performance if there is no need to Great performance if there is no need to modify, since you don’t incur the cost of modify, since you don’t incur the cost of instantiation.instantiation.

String a = "SELECT";"SELECT"

String c = "SELECT";

String b = "SELECT";

StringString

Otherwise, performance is terrible. Each Otherwise, performance is terrible. Each “modification” actually creates a new “modification” actually creates a new String.String.

String greeting = “happy”;greeting += “ ”;greeting += “birth”;greeting += “day”;

“birth”

“day”

“happy”

“happy birthday”

“ ” “happy ”

“happy birth”

StringString

The string pool is also the reason why you The string pool is also the reason why you should should nevernever initialize a string with the initialize a string with the “new” operator if the literal will do.“new” operator if the literal will do.

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

String y = new String("SELECT");

String z = new String("SELECT");

"SELECT"

"SELECT"

StringString

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

StringString

Strings are the only objects that can be used with the “+” and “+=” operators.

String greeting = “happy ” + “birthday”;greeting += “ to you”;

StringString

String MethodsString Methods @see@see the API documentation for String the API documentation for String Notice that all methods for “string manipulation” will not Notice that all methods for “string manipulation” will not

modify the String instance. They will only return a new modify the String instance. They will only return a new String.String.

substring, trim, split, replace, replaceFirst, replaceAll, concat, toUpperCase, toLowerCase

Methods for searching for characters or patterns in a Methods for searching for characters or patterns in a String:String:

charAt, startsWith, endsWith, indexOf, lastIndexOf Methods for comparing StringsMethods for comparing Strings

equals, equalsIgnoreCase, compareTo, compareToIgnoreCase

StringBuffer/StringBuilderStringBuffer/StringBuilder

Maintains an internal character array, Maintains an internal character array, contents can be modified.contents can be modified.

Great performance when modifications are Great performance when modifications are needed.needed.

@see API documentation for StringBuilder@see API documentation for StringBuilder append, delete, insert, replace, setCharAt, append, delete, insert, replace, setCharAt,

length, toStringlength, toString

Primitive WrappersPrimitive Wrappers

Java Fundamentals and Object-Oriented Java Fundamentals and Object-Oriented ProgrammingProgramming

The Complete Java Boot CampThe Complete Java Boot Camp

Number

Short IntegerByte Long Float Double BigDecimal

Boolean Character

Primitive WrappersPrimitive Wrappers

Allow primitive values to participate in the world Allow primitive values to participate in the world of objects.of objects. For example, allows primitives to be stored in For example, allows primitives to be stored in

“Collections” (Java data structures)“Collections” (Java data structures)

Number

Short IntegerByte Long Float Double BigDecimal

Boolean Character

Primitive WrappersPrimitive Wrappers

Each primitive datatype has a corresponding Each primitive datatype has a corresponding wrapper type.wrapper type.

Number

Short IntegerByte Long Float Double BigDecimal

Boolean Character

Primitive WrappersPrimitive Wrappers

ImmutableImmutable Just like String, once value is set, it cannot be Just like String, once value is set, it cannot be

changed.changed.

Primitive WrappersPrimitive Wrappers

Creating a Primitive WrapperCreating a Primitive Wrapper Primitive wrappers are Primitive wrappers are usually*usually* created simply by created simply by

calling the constructor and feeding the primitive value calling the constructor and feeding the primitive value as a constructor:as a constructor:

Integer i = new Integer(14);Integer i = new Integer(14);

Retrieving Primitive ValuesRetrieving Primitive Values Call one of the methods that end in “___Value”:Call one of the methods that end in “___Value”:

int x = i.intValue();int x = i.intValue();

byte y = i.byteValue();byte y = i.byteValue();

long z = i.longValue();long z = i.longValue();

Primitive WrappersPrimitive Wrappers

Before Java 1.5, you can’t use primitive Before Java 1.5, you can’t use primitive wrappers directly in arithmetic nor wrappers directly in arithmetic nor comparison operators. You have to extract comparison operators. You have to extract the primitive values first: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);

Primitive WrappersPrimitive Wrappers

Autoboxing and Unboxing in Java 1.5Autoboxing and Unboxing in Java 1.5 Java 1.5 automatically converts primitives to Java 1.5 automatically converts primitives to

wrappers and wrappers to primitives:wrappers and wrappers to primitives:

Integer i = 5;Integer j = 10;Integer answer = i + j;

Primitive WrappersPrimitive Wrappers

equals() methodequals() method Returns true if the object passed is of the same type Returns true if the object passed is of the same type

and has the same value: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); truei.equals(k); falsei.equals(l); falsei.equals(null); false

Primitive WrappersPrimitive Wrappers

Primitive Wrappers as Utility ClassesPrimitive Wrappers as Utility Classes Primitive Wrappers also serve as Primitive Wrappers also serve as “Utility “Utility

Classes”*.Classes”*. They contain static methods and static fields They contain static methods and static fields

that are useful for the type of primitive that that are useful for the type of primitive that each of them wraps.each of them wraps.

Primitive WrappersPrimitive Wrappers

Primitive Wrappers as Utility ClassesPrimitive Wrappers as Utility Classes @see the API documentation for the ff:@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

BigDecimalBigDecimal

Computers cannot accurately store Computers cannot accurately store decimal values!decimal values!

Using floats and doubles are dangerous Using floats and doubles are dangerous in financial applications!in financial applications!

BigDecimalBigDecimal

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

BigDecimalBigDecimal

BigDecimal has methods for arithmetic operations. add, subtract, multiply, divide, min, max,

negate, pow, abs, remainder, round @see API Documentation for BigDecimal

CollectionsCollections

Java Data StructuresJava Data Structures

CollectionsCollections

Objects used to hold other objects (data Objects used to hold other objects (data structures).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

CollectionsCollections

Collections will be discussed in more Collections will be discussed in more detail in a succeeding lecture.detail in a succeeding lecture.

Utility ClassesUtility Classes

classes that hold routines for other classes that hold routines for other classesclasses

Utility ClassesUtility Classes

Classes that just hold useful routines.Classes that just hold useful routines. All methods and fields are static.All methods and fields are static. Never instantiated.Never instantiated. To be discussed:To be discussed:

1.1. SystemSystem

2.2. MathMath

3.3. ArraysArrays

4.4. CollectionsCollections

Utility ClassesUtility Classes

SystemSystem Used to get some access the underlying Used to get some access the underlying

operating system.operating system. Fields: out, err, in Methods: arraycopy, currentTimeMillis, exit,

getProperties, getProperty, gc @see API Documentation for System

Utility ClassesUtility Classes

MathMath Contains methods for mathematical operationsContains methods for mathematical operations

abs, round, min, max, sin, cos, tan, floor, ceil, exp, log, random

@see API Documentation for Math

Utility ClassesUtility Classes

ArraysArrays Contains methods for working with arraysContains methods for working with arrays

sort, binarySearch, equals, asList, toString @see API Documentation for Arrays

Utility ClassesUtility Classes

CollectionsCollections Contains methods for working with CollectionsContains methods for working with Collections

sort, binarySearch, addAll, copy, min, max, frequency, unmodifiable____

@see API Documentation for Collections

ExceptionsExceptions

Java Fundamentals and Object-Oriented Java Fundamentals and Object-Oriented ProgrammingProgramming

The Complete Java Boot CampThe Complete Java Boot Camp

ExceptionsExceptions

Special objects used to indicate that an Special objects used to indicate that an exceptional (usually undesirable) event exceptional (usually undesirable) event has occurred.has occurred.

Will abruptly end execution, unless Will abruptly end execution, unless handled.handled. A “stack trace” will be written to the standard A “stack trace” will be written to the standard

error stream to help you debug your problem.error stream to help you debug your problem. The stack trace will contain all the methods The stack trace will contain all the methods

that were in execution, and the line number of that were in execution, and the line number of the code being called in each method, at the the code being called in each method, at the time the exception occurred.time the exception occurred.

The EndThe End

Java Fundamentals and Object-Oriented Java Fundamentals and Object-Oriented ProgrammingProgramming

The Complete Java Boot CampThe Complete Java Boot Camp