Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4...

38
Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance [email protected] http://home.comcast.net/~glance44/ microhard/java2.html

Transcript of Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4...

Page 1: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

Sun Certified Java 1.4 ProgrammerChapter 6 Notes

Gary Lance

[email protected]://home.comcast.net/~glance44/microhard/java2.html

Page 2: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

Strings are Immutable

• What is all the fuss about? So what if String objects are immutable.

• Well, everytime an anonymous String object is created, is it using up memory that must wait for garbage collection to reclaim it.

• When you concatenate a String with another String, the old String object may be abandoned.

• Let’s consider a few examples

Page 3: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

String Concatenation Example

What is printed out, and how many String objects have been created in memory? How many String objects have no references to them?

Create a class Practice, and put this code in main().

String m = “M”;m.concat(“i”);m.concat(“c”);m.concat(“r”);m += “o”;System.out.println(m);

Page 4: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

String Concatenation Example

Five String objects were created, and the location of only one is accessible by String variable “m”.

String m = “M”; // Creates memory to hold “M”, stores ref in mm.concat(“i”); // Creates anonymous String object “mi”m.concat(“c”); // Creates anonymous String object “mic”m.concat(“r”); // Creates anonymous String object “micr”m += “o”; // Creates String object “Mo”, stores ref in mSystem.out.println(m); // Prints “mo”

Page 5: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

String method concat

concatpublic String concat(String str)

– Concatenates the specified string to the end of this string. If the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string.

SO, if str refers to a String object that has at least one character, a new String object is created by this method. But we MUST assign this to a String variable if we want to access it.

In the last example, we did not do this. New String objects were created, but the references to those Strings was never assigned to a variable.

m.concat(“i”) does NOT change m, because String objects are immutable.

Page 6: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

String toUpperCase()toUpperCasepublic String toUpperCase()

Converts all of the characters in this String to upper case using the rules of the default locale.

Returns:

the String, converted to uppercase.

What is printed? How many Strings have been created, and how many are unreachable?

String str = “abc”str.toUpperCase();“abc”.toUpperCase();System.out.println(str);

Page 7: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

String toLowerCase()toUpperCasepublic String toUpperCase()

Converts all of the characters in this String to lower case using the rules of the default locale.

Returns:

the String, converted to uppercase.

What is printed? How many Strings have been created, and how many are unreachable?

String str = “abc”str.toLowerCase();“abc”.toLowerCase();System.out.println(str);

Page 8: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.
Page 9: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

String equals()

equalspublic boolean equals(Object anObject)

Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

Overrides: equals in class Object

Parameters: anObject - the object to compare this String against.

Returns: true if the String are equal; false otherwise.

Page 10: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

new String(“abc”)

This is interesting. Note that an anonymous String “abc” is created, and that is used to instantiate another String.

But what if a String identical to one being created already has a reference to it?

Then a new String may be created, according to the text. I am not sure this is correct. Why? Because of the existence of the String method intern().

All String objects end up in the “String constant pool”.

The constant pool may be searched to find a String object with the exact character sequence as the new String being created. But it will definitely be searched if the new String is created NOT by an constructor, but by the method intern().

Page 11: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

String constant pool – not on exam

http://mindprod.com/jgloss/interned.html

interned Strings Interned strings avoid duplicate strings. There is only one copy of each String that

has been interned, no matter how many references point to it. Since Strings are immutable, if two different methods "incidentally" use the same String, (even if they concocted the same String by totally independent means, e.g. one might use the string "sin" in the context of Moses and another in the context of trigonometry.) they can share a copy of the same string. The process of converting duplicated strings to shared ones is called interning. String.intern() gives you the address of the canonical master String. You can compare interned Strings with simple == (which compares pointers) instead of .equals which compares the characters of the String one by one. Because Strings are immutable, the intern process is free to further save space, for example, by not creating a separate string literal for "pot" when it exists as a substring of some other literal such as "hippopotamus" There there are two reasons for interning Strings:

To save space, by removing String literal duplicates. To speed up String equality compares.

Page 12: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

Not on exam – but it is interesting. The only way to guarantee that two String objects refer to the same object in the String constant pool is to use the intern() method in String to create the duplicate.

Clearly, this implies that there is no guarantee that two String objects that satisfy (s1.equals(s2) = = true) are really referring to the same String object in memory.

I don’t believe this! See example, page 19.

Page 13: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

String length()

length

public int length() Returns the length of this string.

Returns: the length of the sequence of characters

represented by this object.

Page 14: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

Think of Strings as arrays, as arrays and Strings are zero-based.

String str = “abcdefgh”;

System.out.println(str.charAt(1)); // returns ‘b’

Page 15: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

Compare two Strings, but ignore case.

String str = “abcdefgh”;

String str2 = “AbCdEfG”;

System.out.println( str2.equalsIgnoreCase(str) );

Page 16: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.
Page 17: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.
Page 18: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.
Page 19: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

public class Practice {public static void main(String[] args){

String str = "Now is the time";String str1 = str;String str2 = str.substring(4, 6); // "is"String str3 = str.substring(3,7); // " is "String str4 = str2.intern(); // NOT ON EXAM

System.out.println("str == str1 is " + (str == str1));System.out.println("str.equals(str1) is " + str.equals(str1));

System.out.println("str2 == str3 is " + (str2 == str3));System.out.println("str2.equals(str3) is " + str2.equals(str3));

str3 = str3.trim();System.out.println("str2 == str3 is " + (str2 == str3));System.out.println("str2.equals(str3) is " + str2.equals(str3));

System.out.println("str2 == str4 is " + (str2 == str4));System.out.println("str2.equals(str4) is " + str2.equals(str4));

}}

Know the difference

between == and equals. You will be tested on it.

Also, make sure you

know how both

overloaded substring methods

work!

Page 20: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

java.lang.StringBuffer class

A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

String buffers are used by the compiler to implement the binary string concatenation operator +. For example, the code:

x = "a" + 4 + "c"

is compiled to the equivalent of:

x = new StringBuffer().append("a").append(4).append("c") .toString()

which creates a new string buffer (initially empty), appends the string representation of each operand to the string buffer in turn, and then converts the contents of the string buffer to a string. Overall, this avoids creating many temporary strings.

Page 21: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

StringBuffer

There is one thing to keep in mind. There IS a difference between:

String x = “a” + “b” + “c”;

and

String x = “a”;x += “b”;x += “c”;

The first does not create temporary String objects. But the second one does.

Page 22: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

Overloading of insert() in StringBuffer class

Page 23: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

Overloaded StringBuffer Constructors

Note that you can create a StringBuffer object from a String.

This means that you can use the methods of StringBuffer on Strings.

The toString() method of StringBuffer can then convert the StringBuffer object back to a String.

Page 24: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

StringBuffer reverse()

Reverses the characters in the StringBuffer object.

TASK: Create a String, and then make another String with the characters reversed. How would you do this, using the StringBuffer class?

Page 25: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

StringBuffer insert()

StringBuffer sb = new StringBuffer("aefg");

sb.insert(1,"bcd");

System.out.println(sb);

System.out.println( sb.reverse() );

Page 26: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

Chained Methods

Recall the append() example for String concatenation:

x = new StringBuffer().append("a").append(4).append("c") .toString()

This is an example of chained methods. You are always to start from the left, and handle this one message at a time.

Page 27: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

java.lang.Math constants E and PI

Page 28: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

Math.abs(): Absolute Value

static double abs(double a)           Returns the absolute value of a double value.

static float abs(float a)           Returns the absolute value of a float value.

static int abs(int a)           Returns the absolute value of an int value.

static long abs(long a)           Returns the absolute value of a long value.

Page 29: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

Math.floor()public static double floor(double a)

Returns the largest (closest to positive infinity) double value that is not greater than the argument and is equal to a mathematical integer. Special cases:

• If the argument value is already equal to a mathematical integer, then the result is the same as the argument.

• If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.

Parameters:

a - a value.

Returns:

the largest (closest to positive infinity) floating-point value that is not greater than the argument and is equal to a mathematical integer.

4.0

3.0

2.0

1.0

0.0

-1.0

-2.0

-3.0

-4.0

4.0 <= x < 5.0

Page 30: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

Math.ceil()

public static double ceil(double a) Returns the smallest (closest to negative infinity) double value that is

not less than the argument and is equal to a mathematical integer. Special cases:

• If the argument value is already equal to a mathematical integer, then the result is the same as the argument.

• If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.

• If the argument value is less than zero but greater than -1.0, then the result is negative zero.

Note that the value of Math.ceil(x) is exactly the value of -Math.floor(-x).

Parameters: a - a value.

Returns: the smallest (closest to negative infinity) floating-point value that

is not less than the argument and is equal to a mathematical integer.

4.0

3.0

2.0

1.0

0.0

-1.0

-2.0

-3.0

-4.0

3.0 < x <= 4.0

Page 31: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

Math.max(), Math.min()

Page 32: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

Math.random()

• public static double random() – Returns a double value with a positive sign, greater than or

equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.

Note the upper value is less than 1.0

0.0 <= Math.random() < 1.0

TASK: Show the code that will generate random numbers that are between 1 and 50 for the lotto.

Page 33: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

Math.round()

roundpublic static long round(double a)

Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long.

Math.round(1.5) Math.floor(2.0) 2LMath.round(1.6) Math.floor(2.1) 2LMath.round(-3.4) Math.floor(-2.9) -3L

Page 34: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

Wrapper Classes

Makes objects out of primitivesInteger intObj = new Integer(5); // intInteger intObj2 = new Integer(“6”); // StringDouble dblObj = new Double(9.5);Boolean boolObj = new Boolean(true);Boolean boolObj2 = new Boolean(“false”);Long longObj = new Long(5);Long longObj2 = new Long(6L);Byte byteObj = new Byte( (byte)1 );Character charObj = new Character(‘a’);Short shortObj = new Short( (short)45 );

Page 35: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

valueOf() methodUse the static valueOf() method to convert a String to a wrapper (eg,

Integer). Holds for all wrapper classes except Character.Both throw NumberFormatException. Use either one, if base 10. Use

valueOf() when other than base 10, since the Integer constructors do not take a parameter of the radix.

It actually does this:new Integer( Integer.parseInt(s) )

Integer intObj = Integer.valueOf(“123”);Integer intObj2 = Integer.valueOf(“fff”, 16); // radix = base = 16

Page 36: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

xxxValue()

Allows you to get the primitive value that is wrapped in the object:

Integer intObj = Integer.valueOf(“abc”, 16); // hexint value = intObj.intValue();System.out.println(value);

intObj = Integer.valueOf(“abc”, 15); // base 15value = intObj.intValue();System.out.println(value);

Page 37: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

parseXXX()

Very similar to valueOf(), except parseXXX returns the primitive (eg, int), and valueOf() returns the wrapper object (eg, Integer).

int value = Integer.parseInt(“123”); // 123value = Integer.parseInt(“123”, 16); // 291

Page 38: Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance glance44@comcast.net glance44/microhard/java2.html.

End of Chapter 6