Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance"— Presentation transcript:

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 http://home.comcast.net/~glance44/microhard/java2.html

2 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 2 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

3 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 3 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);

4 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 4 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 m m.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 m System.out.println(m);// Prints “mo”

5 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 5 String method concat concat public 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.

6 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 6 String toUpperCase() toUpperCase public 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);

7 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 7 String toLowerCase() toUpperCase public 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);

8 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 8

9 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 9 String equals() equals public 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.

10 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 10 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().

11 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 11 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.

12 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 12 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.

13 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 13 String length() length public int length() Returns the length of this string. Returns: the length of the sequence of characters represented by this object.

14 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 14 Think of Strings as arrays, as arrays and Strings are zero-based. String str = “abcdefgh”; System.out.println(str.charAt(1));// returns ‘b’

15 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 15 Compare two Strings, but ignore case. String str = “abcdefgh”; String str2 = “AbCdEfG”; System.out.println( str2.equalsIgnoreCase(str) );

16 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 16

17 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 17

18 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 18

19 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 19 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!

20 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 20 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.

21 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 21 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.

22 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 22 Overloading of insert() in StringBuffer class

23 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 23 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.

24 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 24 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?

25 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 25 StringBuffer insert() StringBuffer sb = new StringBuffer("aefg"); sb.insert(1,"bcd"); System.out.println(sb); System.out.println( sb.reverse() );

26 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 26 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.

27 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 27 java.lang.Math constants E and PI

28 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 28 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.

29 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 29 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 -2.0 -3.0 -4.0 4.0 <= x < 5.0

30 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 30 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 -2.0 -3.0 -4.0 3.0 < x <= 4.0

31 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 31 Math.max(), Math.min()

32 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 32 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.

33 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 33 Math.round() round public 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)  2L Math.round(1.6)  Math.floor(2.1)  2L Math.round(-3.4)  Math.floor(-2.9)  -3L

34 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 34 Wrapper Classes Makes objects out of primitives Integer intObj = new Integer(5);// int Integer intObj2 = new Integer(“6”);// String Double 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 );

35 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 35 valueOf() method Use 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

36 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 36 xxxValue() Allows you to get the primitive value that is wrapped in the object: Integer intObj = Integer.valueOf(“abc”, 16);// hex int value = intObj.intValue(); System.out.println(value); intObj = Integer.valueOf(“abc”, 15); // base 15 value = intObj.intValue(); System.out.println(value);

37 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 37 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”);// 123 value = Integer.parseInt(“123”, 16);// 291

38 Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 38 End of Chapter 6


Download ppt "Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 6, page 1 Sun Certified Java 1.4 Programmer Chapter 6 Notes Gary Lance"

Similar presentations


Ads by Google