36
String Classes & Wrapper Classes Lecture 5

String Classes & Wrapper Classes

  • Upload
    others

  • View
    7

  • Download
    1

Embed Size (px)

Citation preview

Page 1: String Classes & Wrapper Classes

String Classes & Wrapper

Classes

Lecture 5

Page 2: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 2

The String class

• An object of the String class represents a

string of characters.

• The String class belongs to the java.lang

package, which is built into Java.

• Like other classes, String has constructors

and methods.

• Unlike other classes, String has two

operators, + and += (used for

concatenation).

Page 3: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 3

Literal Strings

• Literal strings are anonymous constant objects of the String class that are defined as text in double quotes.

• Literal strings don’t have to be constructed: they are “just there.”

– \\ stands for \

– \n stands for the newline character

String s1 = "Biology”;

String s2 = "C:\\jdk1.4\\docs";String s3 = "Hello\n";

Page 4: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 4

Immutability

• Once created, a string cannot be changed:

none of its methods changes the string.

• Such objects are called immutable.

• Immutable objects are convenient because

several references can point to the same

object safely: there is no danger of changing

an object through one reference without the

others being aware of the change.

Page 5: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 5

Immutability (cont’d)

• Advantage: more efficient, no need to copy.

String s1 = "Sun";

String s2 = s1; String s1 = "Sun";

String s2 = new String(s1);

s1

s2

s1

s2

OK Less efficient:

wastes memory

"Sun"

"Sun"

"Sun"

Page 6: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 6

Empty Strings

• An empty string has no characters; its

length is 0.

• Not to be confused with an uninitialized

string:

String s1 = "";

String s2 = new String();

private String errorMsg; errorMsg

is null

Empty strings

Page 7: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 7

Constructors

• String’s no-args and copy constructors are

not used much.

• Other constructors convert arrays into

strings

String s1 = new String ();

String s2 = new String (s1);

String s1 = "";

String s2 = s1;

Page 8: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 8

Methods — length, charAt

int length ();

char charAt (k);

• Returns the number of

characters in the string

• Returns the k-th char

6

’n'

”Flower".length();

”Wind".charAt (2);

Returns:

Character positions in strings

are numbered starting from 0

Page 9: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 9

Methods — substring

String s2 = s.substring (i, k);

returns the substring of chars in positions from i to k-1

String s2 = s.substring (i);

returns the substring from the i-

th char to the end

"raw"

"happy"

"" (empty string)

”strawberry".substring (2,5);

"unhappy".substring (2);

"emptiness".substring (9);

Returns:

strawberry

i k

strawberry

i

Page 10: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 10

Methods — Concatenation

String result = s1 + s2;concatenates s1 and s2

String result = s1.concat (s2);the same as s1 + s2

result += s3;concatenates s3 to result

result += num;converts num to String and concatenates it to

result

Page 11: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 11

Methods — Find (indexOf)

String date ="July 5, 2012 1:28:19 PM";

date.indexOf ('J'); 0

date.indexOf ('2'); 8

date.indexOf ("2012"); 8

date.indexOf ('2', 9); 11

date.indexOf ("2020"); -1

date.lastIndexOf ('2'); 15

Returns:

(not found)

(starts searching

at position 9)

0 8 11 15

Page 12: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 12

Methods — Comparisons

boolean b = s1.equals(s2);

returns true if the string s1 is equal to s2

boolean b = s1.equalsIgnoreCase(s2);

returns true if the string s1 matches s2, case-blind

int diff = s1.compareTo(s2);returns the “difference” s1 - s2

int diff = s1.compareToIgnoreCase(s2);returns the “difference” s1 - s2, case-blind

Page 13: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 13

Methods — Replacements

String s2 = s1.trim ();

returns a new string formed from s1 by removing

white space at both ends

String s2 = s1.replace(oldCh, newCh);

returns a new string formed from s1 by replacing all

occurrences of oldCh with newCh

String s2 = s1.toUpperCase();

String s2 = s1.toLowerCase();

returns a new string formed from s1 by converting

its characters to upper (lower) case

Page 14: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 14

Replacements (cont’d)

• Example: how to convert s1 to upper case

• A common bug:

s1 = s1.toUpperCase();

s1.toUpperCase();s1 remains

unchanged

Page 15: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 15

Character Methods

• java.lang.Character is a “wrapper” class that

represents characters as objects.

• Character has several useful static methods

that determine the type of a character (letter,

digit, etc.).

• Character also has methods that convert a

letter to the upper or lower case.

Page 16: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 16

Character Methods (cont’d)

if (Character.isDigit (ch)) ...

.isLetter...

.isLetterOrDigit...

.isUpperCase...

.isLowerCase...

.isWhitespace...

return true if ch belongs to the corresponding

category

Whitespace is

space, tab,

newline, etc.

Page 17: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 17

Character methods (cont’d)

char ch2 = Character.toUpperCase (ch1);

.toLowerCase (ch1);

if ch1 is a letter, returns its upper (lower)

case; otherwise returns ch1

int d = Character.digit (ch, radix);

returns the int value of the digit ch in the

given int radix

char ch = Character.forDigit (d, radix);

returns a char that represents int d in a given

int radix

Page 18: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 18

The StringBuffer Class

• Represents a string of characters as a mutable

object

• Constructors:StringBuffer() // empty StringBuffer of the default capacity

StringBuffer(n) // empty StringBuffer of a given capacity

StringBuffer(str) // converts str into a StringBuffer

• Adds setCharAt, insert, append, and delete

methods

• The toString method converts this StringBuffer

into a String

Page 19: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 19

the String class

Copy chars or bytesinto an external array.

The beginning and end from which to copy, the array to copy into, an index into the destination array.

getChars( ), getBytes( )

Produces a char[]containing the characters in the String.

toCharArray( )

The char at a location in the String.

int IndexcharAt()

Number of characters in String.

length( )

Creating String objects.Overloaded: Default, String, StringBuffer, char arrays, byte arrays.

Constructor

UseArguments, OverloadingMethod

Page 20: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 20

the String class

boolean result indicates whether the argument is a suffix.

String that might be a suffix of this String.

endsWith( )

boolean result indicates whether the String starts with the argument.

String that it might start with. Overload adds offset into argument.

startsWith( )

boolean result indicates whether the region matches.

Offset into this String, the other String and its offset and length to compare. Overload adds “ignore case.”

regionMatches( )

Result is negative, zero, or positive depending on the lexicographical ordering of the String and the argument. Uppercase and lowercase are not equal!

A String to compare with.compareTo( )

An equality check on the contents of the two Strings.

A String to compare with.equals( ), equals-IgnoreCase( )

Page 21: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 21

the String class

Returns a new String object with the replacements made. Uses the old String if no match is found.

The old character to search for, the new character to replace it with.

replace( )

Returns a new String object containing the original String’s characters followed by the characters in the argument.

The String to concatenateconcat( )

Returns a new String object containing the specified character set.

Overloaded: Starting index, starting index, and ending index.

substring( )

Returns -1 if the argument is not found within this String, otherwise returns the index where the argument starts. lastIndexOf( )searches backward from end.

Overloaded: char, char and starting index, String, String, and starting index

indexOf( ), lastIndexOf( )

Page 22: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 22

the String class

Produces one and only one Stringreference for each unique character sequence.

intern( )

Returns a String containing a character representation of the argument.

Overloaded: Object, char[], char[] and offset and count, boolean, char, int, long, float, double.

valueOf( )

Returns a new String object with the white space removed from each end. Uses the old String if no changes need to be made.

trim( )

Returns a new String object with the case of all letters changed. Uses the old String if no changes need to be made.

toLowerCase( ) toUpperCase( )

Page 23: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 23

the StringBuffer class

Makes the StringBuffer hold at least the desired number of spaces.

Integer indicating desired capacity.

ensure-Capacity( )

Returns current number of spaces allocated.

capacity( )

Number of characters in the StringBuffer.

length( )

Creates a String from this StringBuffer.

toString( )

Create a new StringBuffer object.Overloaded: default, length of buffer to create, Stringto create from.

Constructor

UseArguments, overloading

Method

Page 24: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 24

the StringBuffer class

Copy chars into an external array. There’s no getBytes( )as in String.

The beginning and end from which to copy, the array to copy into, an index into the destination array.

getChars( )

Modifies the value at that location.

Integer indicating the location of the desired element and the new char value for the element.

setCharAt( )

Returns the char at that location in the buffer.

Integer indicating the location of the desired element.

charAt( )

Truncates or expands the previous character string. If expanding, pads with nulls.

Integer indicating new length of character string in buffer.

setLength( )

Page 25: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 25

the StringBuffer class

The order of the characters in the buffer is reversed.

reverse( )

The second argument is converted to a string and inserted into the current buffer beginning at the offset. The buffer is increased if necessary.

Overloaded, each with a first argument of the offset at which to start inserting: Object, String, char[], boolean, char, int, long, float, double.

insert( )

The argument is converted to a string and appended to the end of the current buffer, increasing the buffer if necessary.

Overloaded: Object, String, char[], char[] with offset and length, boolean, char, int, long, float, double.

append( )

Page 26: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 26

From Objects to Strings

• The toString method is called:

public class Fraction

{

private int num, denom;

...

public String toString ()

{

return num + "/" + denom;

}

}

Fraction f = new Fraction (2, 3);

System.out. println (f) ;

Output: 2/3

f.toString() is called

automatically

Page 27: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 27

Wrapper Classes

•• A wrapper class is a class that encapsulates a A wrapper class is a class that encapsulates a single, immutable value.single, immutable value.

•• All the wrapper classes can be constructed by All the wrapper classes can be constructed by passing the value to be wrapped into the passing the value to be wrapped into the appropriate constructor.appropriate constructor.

•• The purpose of a wrapper class is to The purpose of a wrapper class is to encapsulate (wrap up) dataencapsulate (wrap up) data

•• Wrapper classes are useful whenever it Wrapper classes are useful whenever it would be convenient to treat primitive data would be convenient to treat primitive data as if it were an object.as if it were an object.

Page 28: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 28

Wrapper Classes

• The abstract class Number is the superclass that

is implemented by the classes that wrap the

numeric types byte, short, int, long, float and

double.

• Number has abstract methods that return the

value of the object in each of the different

number formats.

Eg: intValue(), doubleValue(), floatValue().

• The concrete subclasses that hold explicit values

of each numeric type are: Double, Float, Byte,

Short, Integer, Long.

Page 29: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 29

Wrapper Classes

•• The values wrapped inside two wrappers of The values wrapped inside two wrappers of

the same type can be checked for equality the same type can be checked for equality

by using the equals() method.by using the equals() method.

•• Java has the following predefined wrapper Java has the following predefined wrapper

classes:classes:

–– IntegerInteger

–– FloatFloat

–– DoubleDouble

–– CharacterCharacter

–– BooleanBoolean

Page 30: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 30

Class Integer

• Can create an object that encapsulates an int

using Java’s Integer class

Page 31: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 31

Method intValue

• Can retrieve the int value by calling the

intValue method

Page 32: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 32

Other Integer Methods

• public String toString();

– returns the integer value as a string value

• public long longValue();

– returns the integer as a long value

• public double doubleValue();

– returns the integer as a double value

Page 33: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 33

Wrapper Classes

• The constructors of the Byte, Short, Integer and Long are:

Byte(byte num)

Byte(String str) throws NumberFormatException

Short(short num)

Short(String str) throws NumberFormatException

Integer(int num)

Integer(String str) throws NumberFormatException

Long(long num)

Long(String str) throws NumberFormatException

Page 34: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 34

Wrapper Class Methods

• isInfinite() - Returns true if this Double value is

infinitely large in magnitude, false otherwise.

• isNaN() - Returns true if this Double value is a

Not-a-Number (NaN), false otherwise.

• The Byte, Short, Integer, Long classes provide the

parseByte(), parseShort(), parseInt() and

parseLong() methods, to return the byte, short, int,

long equivalent of the numeric string with which

they are called.

Eg: int i = Integer.parseInt(str);

Page 35: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 35

Wrapper Class Methods

• The Byte, Short, Integer, Long classes provide

the toString() method to convert a number to a

string.

• The Integer and Long classes provide the

toBinaryString(), toHexString(), and

toOctalString() to convert a value into a binary, hexadecimal or octal string.

Page 36: String Classes & Wrapper Classes

28 March 2007 Java : Lecture 5 36

Wrapper Class Methods

• Character has the constructor Character(char ch)

and wraps a character.

• The charValue() method returns the char value

contained in a Character object.

• Boolean is a wrapper around boolean values.

Boolean defines the constructors:

– Boolean(boolean boolValue)

– Boolean(String boolString)