chap 8 : the java.lang and java.util packages (scjp/ocjp)

118
The java.lang and java.util Packages Ben Abdallah Helmi Architect J2EE

Upload: it-academy

Post on 28-Oct-2014

416 views

Category:

Technology


2 download

DESCRIPTION

JAVA CERTIFICATION EXAM OBJECTIVES COVERED IN THIS CHAPTER: 3.1 Develop code that uses the primitive wrapper classes (such as Boolean, Character, Double, Integer, etc.) and/or autoboxing and unboxing. Discuss the differences between the String, StringBuilder, and StringBuffer classes. 3.4 Use standard J2SE APIs in the java.text package to correctly format or parse dates, numbers, and currency values for a specific locale, and, given a scenario, determine the appropriate methods to use if you want to use the default locale or a specific locale. Describe the purpose and use of the java.util.Locale class. 3.5 Write code that uses standard J2SE APIs in the java.util and java.util.regex packages to format or parse strings or streams. For strings, write code that uses the Pattern and Matcher classes and the String.split method. Recognize and use regular expression patterns for matching (limited to . (dot), * (star), + (plus), ?, \d, \s, \w, [], ()). The use of *, +, and ? will be limited to greedy quantifiers, and the parenthesis operator will be used only as a grouping mechanism, not for capturing content during matching. For streams, write code using the Formatter and Scanner classes and the PrintWriter.format/printf methods. Recognize and use formatting parameters (limited to %b, %c, %d, %f, %s) in format strings. 6.1 Given a design scenario, determine which collection classes and/or interfaces should be used to properly implement that design, including the use of the Comparable interface.

TRANSCRIPT

  • 1. The java.lang and java.util PackagesBen Abdallah Helmi Architect J2EE

2. The Object Class The Object class is the ultimate ancestor of all Java classes. If a class does not contain the extends keyword in its declaration, the compiler builds a class that extends directly from Object if (d1 == d2) The comparison will be true if the reference in d1is equal to the reference in d2 . Of course, this is the case only when both variables refer to the same object. public boolean equals(Object object) Ben Abdallah Helmi Architect J2EE 3. The Object class provides a clone() method, which returns a copy of the current object. In other words, the clone has the same class as the original, and all its data values are identical. Thus all references in the clone point to the same objects as those pointed to in the original.Objects version of clone() is protected, so a class clone() may not be called by any code anywhere. If you want a class clone() to be public, you need to insert something like the following: public Object clone() throws CloneNotSupportedException { return super.clone(); } Notice the CloneNotSupportedException. It is not a runtime exception, so it must be dealt with. Classes that override clone() generally declare that they implement java.lang.Cloneable, which defines the single clone() method. Ben Abdallah Helmi Architect J2EE 4. 13. Which of the following are legal clone() methods in a class called Q13 that extends Object? A. public Object clone() { return super.clone(); } B. public Object clone() throws CloneNotSupportedException { return super.clone(); } C. public Q13 clone() { return (Q13)super.clone(); } D. public Q13 clone() throws CloneNotSupportedException { return (Q13)super.clone(); } Ben Abdallah Helmi Architect J2EE 5. 13. B, D. The CloneNotSupportedException must be dealt with, so A and C are wrong. The version being overridden (in Object) has return type Object, so prior to release 5.0 the return type in D would be illegal; however, now that covariant returns are legal, D is allowed.Ben Abdallah Helmi Architect J2EE 6. The Math Class Javas Math class contains a collection of methods and twoconstants that support mathematical computation. The class is declared final, so you cannot extend it. The constructor is private, so you cannot create an instance.Fortunately, the methods and constants are static, so they can be accessed through the class name without having to construct a Math object.The two constants of the Math class are Math.PI and Math.E. They are declared to be public, static, final, and double. Ben Abdallah Helmi Architect J2EE 7. Ben Abdallah Helmi Architect J2EE 8. Ben Abdallah Helmi Architect J2EE 9. 3. Suppose you want to write a class that offers static methods to compute hyperbolic trigonometric functions. You decide to subclass java.lang.Math and provide the new functionality as a set of static methods. Which one statement is true about this strategy? A. The strategy works. B. The strategy works, provided the new methods are public. C. The strategy works, provided the new methods are not private. D. The strategy fails because you cannot subclass java.lang.Math. E. The strategy fails because you cannot add static methods to a subclass. Ben Abdallah Helmi Architect J2EE 10. 3. D. The java.lang.Math class is final, so it cannot be subclassed.Ben Abdallah Helmi Architect J2EE 11. 4. Which one statement is true about the following code fragment?1. import java.lang.Math; 2. Math myMath = new Math(); 3. System.out.println(cosine of 0.123 = + 4. myMath.cos(0.123)); A. Compilation fails at line 2. B. Compilation fails at line 3 or 4. C. Compilation succeeds, although the import on line 1 is not necessary. During execution, an exception is thrown at line 3 or 4. D. Compilation succeeds. The import on line 1 is necessary. During execution, an exception is thrown at line 3 or 4. E. Compilation succeeds and no exception is thrown during execution.Ben Abdallah Helmi Architect J2EE 12. 4. A. The constructor for the Math class is private, so it cannot be called. The Math class methods are static, so it is never necessary to construct an instance. The import at line 1 is not required, because all classes of the java.lang package are automatically imported.Ben Abdallah Helmi Architect J2EE 13. Strings 1. String s1 = Compare me; 2. String s2 = Compare me; 3. if (s1.equals(s2)) { 4. // whatever 5. } Not surprisingly, the test at line 3 succeeds. Given what you know about how string literals work, you can see that if line 3 is modified to use the == comparison, as shown here, the test still succeeds: 1. String s1 = Compare me; 2. String s2 = Compare me; 3. if (s1 == s2) { 4. // whatever 5. } The == test is true because s2 refers to the String in the pool that was created in line 1. String s2 = new String(Constructed);Ben Abdallah Helmi Architect J2EE 14. You just saw that if you create a new String instance at runtime, it will not be in the pool but will be a new and distinct object. You can arrange for your new String to be placed into the pool for possible re-use, or to re-use an existing identical String from the pool, by using the intern() method of the String class. In programs that use a great many similar strings, this approach can reduce memory requirements. More important, in programs that make a lot of String equality comparisons, ensuring that all strings are in the pool allows you to use the == reference comparison in place of the equals() method. The equals() method runs slower because it must do a character-by-character comparison of the two strings, whereas the == operator compares only the two memory addresses.The String class includes several convenient methods, some of which transform a string. For example, toUpperCase() converts all the characters of a string to uppercase. It is important to remember that the original string is not modified. That would be impossible, because strings are immutable. What really happens is that a new string is constructed and returned. Generally, this new string will not be in the pool unless you explicitly call intern() to put it there.Ben Abdallah Helmi Architect J2EE 15. 1. String s = 5 + 4 = 20; 2. s = s.trim(); // 5 + 4 = 20 3. s = s.replace(+, x); // 5 x 4 = 20If much modification is required, then this process becomes very inefficientit stresses the garbage collector cleaning up all the old strings, and it takes time to copy the contents of the old strings into the new ones. The next section discusses two classes that alleviate these problems by representing mutable strings. These are the StringBuffer and StringBuilder classes. Ben Abdallah Helmi Architect J2EE 16. The StringBuffer and StringBuilder Classes Javas StringBuffer and StringBuilder classes represent strings that can be dynamically modified StringBuffer() Constructs an empty string buffer. StringBuffer(int capacity) Constructs an empty string buffer with the specified initial capacity. StringBuffer(String initialString) Constructs a string buffer that initially contains the specified string. Ben Abdallah Helmi Architect J2EE 17. StringBuffer append(String str) Appends str to the current string buffer. Alternative forms support appending primitives and character arrays, which are converted to strings before appending. StringBuffer append(Object obj) Calls toString() on obj and appends the result to the current string buffer. StringBuffer insert(int offset, String str) Inserts str into the current string buffer at position offset. There are numerous alternative forms. StringBuffer reverse() Reverses the characters of the current string buffer. StringBuffer setCharAt(int offset, char newChar) Replaces the character at position offset with newChar. StringBuffer setLength(int newLength) Sets the length of the string buffer to newLength. If newLength is less than the current length, the string is truncated. If newLength is greater than the current length, the string is padded with null characters. Ben Abdallah Helmi Architect J2EE 18. 1. StringBuffer sbuf = new StringBuffer(12345); 2. sbuf.reverse(); // 54321 3. sbuf.insert(3, aaa); // 543aaa21 4. sbuf.append(zzz); // 543aaa21zzzBen Abdallah Helmi Architect J2EE 19. The StringBuffer class does not override the version of equals() that it inherits from Object. Thus the method returns true only when comparing references to the same single object. If two distinct instances encapsulate identical strings, equals() will return false. Stringbuffers are threadsafe. The StringBuilder class was introduced in 5.0. It is nearly identical to StringBuffer, but with one major difference: string builders are not threadsafe. Both StringBuffer and StringBuilder implement the java.lang.Appendable interface, which specifies several overloaded forms of an append() method Ben Abdallah Helmi Architect J2EE 20. String Concatenation the Easy Way The concat() method of the String class and the append() method of the StringBuffer class glue two strings together. Another way to concatenate strings is to use Javas overloaded + operator. Similarly, another way to append a string is to use Javas overloaded += operator. However, dont forget that you, the programmer, cannot define additional operator overloads. Ben Abdallah Helmi Architect J2EE 21. It is important to understand how the technique works. At compile time, if either operand of a + operator (that is, what appears on either side of a + sign) is a String object, then the compiler recognizes that it is in a string context. In a string context, the + sign is interpreted as calling for string concatenation rather than arithmetic addition. a+b+c NewStringBuffer().append(a).append(b).append(c).toString(); 1. An empty string buffer is constructed. 2. Each argument in turn is concatenated to the string buffer, using the append() method. 3. The string buffer is converted to a string with a call to toString(). Ben Abdallah Helmi Architect J2EE 22. 1. Given a string constructed by calling s = new String(xyzzy), which of the calls modifies the string? A. s.append(aaa); B. s.trim(); C. s.substring(3); D. s.replace(z, a); E. s.concat(s); F. None of the above Ben Abdallah Helmi Architect J2EE 23. 1. F. Strings are immutable.Ben Abdallah Helmi Architect J2EE 24. 2. Which one statement is true about the following code? 1. String s1 = abc + def; 2. String s2 = new String(s1); 3. if (s1 == s2) 4. System.out.println(== succeeded); 5. if (s1.equals(s2)) 6. System.out.println(.equals() succeeded); A. Lines 4 and 6 both execute. B. Line 4 executes and line 6 does not. C. Line 6 executes and line 4 does not. D. Neither line 4 nor line 6 executes. Ben Abdallah Helmi Architect J2EE 25. 2. C. Because s1 and s2 are references to two different objects, the == test fails. However, the strings contained within the two String objects are identical, so the equals() test passes.Ben Abdallah Helmi Architect J2EE 26. 5. Which one statement is true about the following code fragment? 1. String s = abcde; 2. StringBuffer s1 = new StringBuffer(abcde); 3. if (s.equals(s1)) 4. s1 = null; 5. if (s1.equals(s)) 6. s = null; A. Compilation fails at line 1 because the String constructor must be called explicitly. B. Compilation fails at line 3 because s and s1 have different types. C. Compilation succeeds. During execution, an exception is thrown at line 3. D. Compilation succeeds. During execution, an exception is thrown at line 5. E. Compilation succeeds. No exception is thrown during execution. Ben Abdallah Helmi Architect J2EE 27. 5. E. A is wrong because line 1 is a perfectly acceptable way to create a String and is actually more efficient than explicitly calling the constructor. B is wrong because the argument to the equals() method is of type Object thus any object reference or array variable may be passed. The calls on lines 3 and 5 return false without throwing exceptions because s and s1 are objects of different types. Ben Abdallah Helmi Architect J2EE 28. 6. In the following code fragment, after execution of line 1, sbuf references an instance of the StringBuffer class. After execution of line 2, sbuf still references the same instance. 1. StringBuffer sbuf = new StringBuffer(abcde); 2. sbuf.insert(3, xyz); A. True B. False Ben Abdallah Helmi Architect J2EE 29. 6. A. The StringBuffer class is mutable. After execution of line 2, sbuf refers to the same object, although the object has been modified.Ben Abdallah Helmi Architect J2EE 30. 8. In the following code fragment, line 4 is executed. 1. String s1 = xyz; 2. String s2 = xyz; 3. if (s1 == s2) 4. System.out.println(Line 4); A. True B. False Ben Abdallah Helmi Architect J2EE 31. 8. A. Line 1 constructs a new instance of String and stores it in the string pool. In line 2, xyz is already represented in the pool, so no new instance is constructed.Ben Abdallah Helmi Architect J2EE 32. 9. In the following code fragment, line 4 is executed. 1. String s1 = xyz; 2. String s2 = new String(s1); 3. if (s1 == s2) 4. System.out.println(Line 4); A. True B. False Ben Abdallah Helmi Architect J2EE 33. 9. B. Line 1 constructs a new instance of String and stores it in the string pool. Line 2 explicitly constructs another instance.Ben Abdallah Helmi Architect J2EE 34. The Wrapper Classes A wrapper class is simply a class that encapsulates a single, immutable value. For example, the Integer class wraps up an int value, and the Float class wraps up a float value.Ben Abdallah Helmi Architect J2EE 35. 1. boolean primitiveBoolean = true; 2. Boolean wrappedBoolean = 3. new Boolean(primitiveBoolean); 4. 5. byte primitiveByte = 41; 6. Byte wrappedByte = new Byte(primitiveByte); 7. 8. char primitiveChar = M; 9. Character wrappedChar = new Character(primitiveChar); 11. short primitiveShort = 31313; 12. Short wrappedShort = new Short(primitiveShort); 13. 14. int primitiveInt = 12345678; 15. Integer wrappedInt = new Integer(primitiveInt); 16. 17. long primitiveLong = 12345678987654321L; 18. Long wrappedLong = new Long(primitiveLong); 19. 20. float primitiveFloat = 1.11f; 21. Float wrappedFloat = new Float(primitiveFloat); 22. 23. double primitiveDouble = 1.11111111; 24. Double wrappedDouble = Ben Abdallah Helmi Architect J2EE 25. new Double(primitiveDouble); 36. Only Boolean does not throw this exception 1. Boolean wrappedBoolean = new Boolean(True); 2. try { 3. Byte wrappedByte = new Byte(41); 4. Short wrappedShort = new Short(31313); 5. Integer wrappedInt = new Integer(12345678); 6. Long wrappedLong = new Long(12345678987654321); 7. Float wrappedFloat = new Float(1.11f); 8. Double wrappedDouble = new Double(1.11111111); 9. } 10. catch (NumberFormatException e) { 11. System.out.println(Bad Number Format); Ben Abdallah Helmi Architect J2EE 12. } 37. In other words, the value of any wrapped number can be retrieved as any numeric type.public byte byteValue() public short shortValue() public int intValue() public long longValue() public float floatValue() public double doubleValue() Ben Abdallah Helmi Architect J2EE 38. 1. Vector vec = new Vector(); 2. boolean boo = false; 3. vec.add(boo); // Illegal The solution is to wrap the boolean primitive, as shown here: 1. Vector vec = new Vector(); 2. boolean boo = false; 3. Boolean wrapper = new Boolean(boo); 4. vec.add(wrapper); // Legal Ben Abdallah Helmi Architect J2EE 39. Every primitive type has a corresponding wrapper class type. All wrapper types can be constructed from primitives. All except Character can also be constructed from strings. Wrapped values can be tested for equality with the equals() method. Wrapped values can be extracted with various XXXValue() methods. All six numeric wrapper types support all six numeric XXXValue() methods. Wrapper classes provide various utility methods, including the static valueOf() and parseXXX() methods, which parse an input string. parseXXX() throw NumberFormatException Wrapped values cannot be modified. the wrapper classes are final. Ben Abdallah Helmi Architect J2EE 40. There is no way to modify the contents of the object, because wrapped values are final. if you wanted to perform calculations on wrapped values you had to do something like this(prior to release 5.0) : Double area(Double radius) { double r = radius.doubleValue(); double a = Math.PI * r * r; return new Double(a); } Ben Abdallah Helmi Architect J2EE 41. Boxing is the automatic assignment of a primitive value to a compatible wrapper type. You can think of the primitive value as being stored in a box (the wrapper object). For example, as of release 5.0 2xs you can make the following assignment: Integer wrappedInt = 25; You can think of the line above as an abbreviation for Integer wrappedInt = new Integer(25); The wrapper on the left-hand side of the equals sign must correspond exactly to the primitive type on the right-hand side. Thus all of the following assignments are legal: Boolean wboo = false; Character wc = 'L'; Byte wb = 1; Short ws = 1000; Integer wi = 123456; Long wl = 12345678L; Float wf = 123.45f; Double wd = 123.45; However, the following assignment is illegal: Double wd = 123; The primitive value 123 is an int. It doesnt matter that ints can be assigned to doubles (in accordance with the primitive assignment conversion rules discussed in Chapter 4), because boxing requires an exact match between the wrapper class and the primitive type. The line of code above can be fixed by changing it to Double wd = 123d; Ben Abdallah Helmi Architect J2EE 42. The Java 5.0 compiler also allows you to unbox a wrapped value. Unboxing is the automatic extraction of a wrapped value. Unboxing happens when a wrapper object appears as an operand in a boolean or numerical operation, as shown in the example below: 1. Integer wi = 234; 2. int times9 = wi * 9; We can now rewrite the area() method as follows: Double area(Double radius) { return Math.PI * radius * radius; } Ben Abdallah Helmi Architect J2EE 43. They just hide these operations from the untrained eye.Double rad; for (rad=0d; rad