1 / 72

Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas

C. ertificación en. J. AVA. Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas. Objectives The Object Class The Math class The Wrapper classes Strings The Collections API. 8. THE java.lang AND java.util PACKAGES. Objectives.

teddy
Télécharger la présentation

Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C ertificación en J AVA Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas

  2. Objectives • The Object Class • The Math class • The Wrapper classes • Strings • The Collections API 8. THE java.lang AND java.util PACKAGES

  3. Objectives • Determine the result of applying the boolean equals(Object) • method to objects of any combination of the classes • java.lang.String, java.lang.Boolean, and java.lang.Object •  Write code using the following methods of the • java.lang.Math class: abs, ceil, floor, max, min, random, • round, sin, cos, tan, sqrt

  4. Objectives •   Determine the result of applying any operator, including • assignment operators and instanceof, to operands of any • type, class, scope, or accessibility, or any combination of these • Describe the significance of the immutability of String • Objects •  Make appropriate selection of collection classes/interfaces • to suit specified behavior requirements.

  5. Some of the most important classes of the • java.lang package: • Object • Math • The wrapper classes • String • StringBuffer Introduction

  6. All the methods of Object are inherited by every class 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 bu¡lds a class that extends directly from Object.

  7. equals method provides "deep" comparison, in contrast to the "shallow" comparison provided by the == operator public boolean equals(Object object)

  8. java.util.Date Date: d1 and d2; if (d1 == d2) true if the reference in d1 is equal to the reference in d2: that is, if both variables contain identical Patterns this is only the case when both variables refer to the same object

  9. if (d1.equals(d2)) The version of equals() provided by the Object class is not very useful; in fact, it just does an == comparison All classes should override equals() so that it performs a useful comparison That is just what most of the standard Java classes do: they compare the relevant instance variables of two objects.

  10. toString method provides a String representation of an object's state This is especially useful for debugging The version provided by the Object class is not especially useful. (It just prints out the object's class name, followed by a hash code)

  11. The Math class contains a collection of methods and two constants that support mathematical computation The class is final, so you cannot extend it!! The constructor is private, so you cannot create an instance The methods and constants are static

  12. The two constants are Math.PI Math.E public, static, final and double

  13. Methods of the Math class int abs(int l): returns the absolute value of l long abs(long l): returns the absolute value of l float abs(float f): returns the absolute value of f double abs(double d): returns the absolute value of d double ceil(double d): returns as a double the smallest integer that is not less than d double floor(double d): returns as a double the largest integer that is nor greater than d int max(int i1, int i2): returns the greater of i1 and i2 long max(long l1, long l2): returns the greater of l1 and l2 float max(float f1, float f2): returns the greater of f1 and f2 double max(double d1, double d2): returns the greater of d1 and d2

  14. Methods of the Math class ... intint min(int i1, int i2): returns the smaller of i1 and i2 long min(long l1, long l2): returns the smaller of l1 and l2 float min(float f1, float f2): returns the srnaller of f1 and f2 double min(double d1, double d2): returns the smaller of d1 and d2 double random(): returns a random number between 0.0 and 1.0 int round(float f): returns the closest int to f long round(double f): returns the closest long to d double sin(double d): rerurns the sine of d double cos(double d): returns the cosine of d double tan(double d): returns the tangent of d double sqrt(double d): returns the square root of d

  15. The Integer class wraps upon int value • The Float class wraps up a float value The Wrapper Classes A wrapper class is simply a class that encapsulates a single, inmutable value

  16. Each Java primitive data type has a corresponding wrapper class

  17. Primitive Data Type Wrapper Class boolean Boolean byte Byte char Character short Short Integer int long Long float Float double Double The wrapper class names do not perfectly match the corresponding primitive data type names.

  18. All the wrapper classes can be constructed by passing the value to be wrapped into the appropiate constructor

  19. 1. boolean primitiveBoolean = true; 2. Boolean wrappedBoolean = new Boolean(primitiveBoolean); 3. 4. byte primitiveByte = 41; 5. Byte wrappedByte = new Byte(primitiveByte); 6. 7. char primitiveChar = ‘M’; 8. Character wrappedChar = new Character(primitiveChar); 9. 10. short primitiveShort = 31313; Short wrappedShort = new Short(primitiveShort); 12.

  20. 13. int primitiveInt = 12345678; 14. Integer wrappedlnt = new Integer(primitiveInt); 15. 16. long primitiveLong = 12345678987654321L; 17. Long wrappedLong = new Long(primitiveLong); 18. 19. float primitiveFloat = 1.11f 20. Float wrappedFloat = new Float(primitiveFloat); 21. 22. double primitiveDouble = 1.11111111; 23. Double wrappeddouble = new Double(primitiveDouble); 

  21. There is another way to construct any of these classes, with the exception of Character You can pass into the constructor a string that represents the value to be wrapped Most of these constructors throw NumberFormatException, because there is always the possibility that the string will not represent a valid value Only Boolean does not throw this exception: the constructor accepts any String input, and wraps a true value if the string (ignoring case) is "true"

  22. Boolean wrappedBoolean = new Boolean("True"); • try{ • Byte wrappedByte = new Byte("41"); • Short wrappedShort = new Short("31313"); • Integer wrappedInt = new Integer("12345678"); • Long wrappedLong = new Long("12345678987654321"); • Float wrappedFloat = new Float("1.11f"); • Double wrappedDouble = new Double("1.11111111"); • } • catch (NumberFormatException e) { • System.out.println("Bad Number Format"); • }

  23. Double d1 = new Double(1.01055); • Double d2 = new Double("1.11348"); • if (d1.equals(d2)) { • // Do something. • } The values wrapped inside two wrappers of the same type can be checked for equality by using the equals() method

  24. After a value has been wrapped, it may eventually be necessary to extract it For an instance of Boolean, you can call booleanValue() For an instance of Character, you can call charValue() The other six classes extend from the abstract superclass Number, which provides methods to retrieve the wrapped value as a byte, a short, an int, a long, a float, or a double.

  25. public byte byteValue() • public short shortValue() • public int intValue() • public long longValue() • public float floatValue() • public double doubleValue() The value of any wrapped number can be retrieved as any numeric type

  26. public void addElement(Object ob) The wrapper classes are useful whenever it would be convenient to treat a piece of primitive data as if it were an object. Example: the Vector class, a dynamically growing collection of objects of arbitrary type

  27. 1. Vector vec = new Vector(); 2. boolean boo = false; 3. vec.addElement(boo); // Illegal Vector vec = new Vector(); boolean boo = false; Boolean wrapper = new Boolean(boo); vec.addElement(wrapper); // Legal The following code will not compile!! Solution:

  28. Character.isDigit(char ch) The wrapper classes also provide a variety of utility methods, most of which are static. returns a boolean that tells whether the character represents a base-10 digit.

  29. Long.valueof("23L") All the wrapper classes except Character have a static method called valueOf(String s), which parses a string and constructs and returns a wrapper instance of the same type as the class whose method was called constructs and returns an instance of the Long class that wraps the value 23.

  30. About primitive wrapper classes (summary) • 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() methods which parse an input string

  31. Strings Java uses the String and StringBuffer classes to encapsulate strings of characters Java uses 16-bit Unicode characters in order to support a broader range of international alphabets than would be possible with traditional 8-bit characters. Both strings and string buffers contain sequences of 16-bit Unicode characters.

  32. The String Class The String class represents an immutable string Once an instance is created, the string it contains cannot be changed!!.

  33. There are numerous forms of constructor, allowing you to build an instance out of • an array of bytes or chars, • a subset of an array of bytes or chars, • another string, or • a string buffer Many of these constructors give you the option of specifying a character encoding, specified as a string;

  34. String s1 = new String("immutable"); String s1 = "immutable"; Probably the most common string constructor simply takes another string as its input. This is useful when you want to specify a literal value for the new string: or

  35. Every string literal is represented internally by an instance of String Java classes may have a pool of such strings. When a literal is compiled, the compiler adds an appropriate string to the pool If the same literal already appeared as a literal elsewhere in the class, the compiler does not create a new copy; instead, it uses the existing one from the pool This saves on memory and can do no harm.

  36. String s1 = "Compare me"; • String s2 = "Compare me"; • if ( s1.equals(s2) ) { • // whatever • } • String s1 = "Compare me"; • String s2 = "Compare me"; • if ( s1 == s2 ) { • // whatever • } Clearly, it succeeds!! Still succeeds!!

  37. String s1 = "Compare me"; • String s2 = "Compare me"; • if ( s1.equals(s2) ) { • // whatever • } line 1 s1 “Compare me” line 2 s2 Pool of literal strings

  38. String s2 = new String("Constructed") String s2= new String( ) “Constructed” “Constructed” Pool of literal strings At runtime, the new String() statement is executed and a fresh instance of String is constructed, duplicating the String in the literal pool

  39. char charAt(int index): • returns the indexed character of a string, where the index of the initial character is 0 • String concat(String addThis): • returns a new string consisting of the old string followed by addThis • int compareTo(String otherString): • perfoms a lexical comparison; it returns an int that is less than O if the current string is less than otherString, equal to O if the strings are identical, and greater than O if the current string is greater than otherString • boolean endsWith(String suffix): • returns true if the current string ends with suffix; otherwise it returns false

  40. boolean equals(object ob): • returns true if ob instanceof String and the string encapsulared by ob matches the string encapsulated by the executing object • boolean equalsIgnoreCase(): • like equals()  the argument is a String and the comparison ignores case • int indexOf( int ch): • returns the index within the current string of the first occurrence of ch. Alternative forms return the index of a string and begin searching from a specified offset • int lastlndexOf(int ch): returns the index within the current string of the last occurrence of ch. Alternative forms return the index of a string and end searching at a specified offset from the end of the string

  41. int length(): returns the number of characters in the current string • replace(char oldChar, char newChar): returns a new string, generated by replacing every occurrence of oldChar witn newChar • boolean startswlth(String prefix): • returns true if the current string begins with prefix; otherwise it returns false • String substring(int startlndex): returns the substring, beginning at startIndex of the current string and extending to the end of the current string. An altemate form specifies string and ending offsets

  42. String toLowerCase(): • converts the executing object to Lower­case and returns a new string • String toUpperCase(): • converts the executing object to upper­case and returns a new string • String toString(): • returns the executing object • String trim(): • returns the string that results from removing whitespace characters from the beginning and ending of the current string

  43. String 5 = " 5 + 4 = 20”; • s = s.trim(); // "5 + 4 = 20” • s = s.replace('+' , ‘x’); // "5 x 4 = 20” Of course, the modification does not take place within the original string Both the trim() call in line 2 and the replace() call of line 3 construct and return new strings; the address of each new string in turn gets assigned to the reference variable s.

  44. String 5 = " 5 + 4 = 20”; • s = s.trim(); // "5 + 4 = 20” • s = s.replace('+' , ‘x’); // "5 x 4 = 20” s After line 3 s=s.replace(“+”,x’); After line 3 s=“5+4=20” After line 3 s=s.trim( ); “5+4=20” “5x4=20” “5+4=20”

  45. The StringBuffer Class An instance of Java’s StringBuffer class represents a string 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

  46. All of the following methods return the original string buffer itself!! • StringBuffer append(String str): appends str to the current string buffer. Alternative forms support appending primitives and character arrays; these are converted to strings before appending. • StringBuffer append(Object ob): • 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

  47. 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

  48. 1. StringBuffer sbuf = new StringBuffer( “12345”); 2. sbuf.reverse(); // “54321” 3. sbuf.insert(3, “aaa”); // “543aaa21” 4. sbuf.append( "zzz"); // “543aaa21zzz” The method calls above actually modify the string buffer they operate on (unlike the String class example)

  49. 1. StringBuffer sbuf = new StringBuffer( “12345”); 2. sbuf.reverse(); // “54321” 3. sbuf.insert(3, “aaa”); // “543aaa21” 4. sbuf.append( "zzz"); // “543aaa21zzz” sbuf “12345” “54321” “543aaa21” “543aaa21zzz” line 2 line3 line 4

  50. toString() the string buffer's version just returns the encapsulated string

More Related