Monday, August 25, 2008

SCJP-WRAPPER

Wrapper Class Summary - Methods of interest for SCJP
Class Name parseXXX getXXX toString toHexString
Boolean static boolean getBoolean(String) String toString()
static String toString(boolean)*
Character String toString()
static String toString(char)*
Byte static byte parseByte(String)
static byte parseByte(String, int) String toString()
static String toString(byte)
Short static short parseShort(String)
static short parseShort(String, int) toString()
static String toString(short)
Integer static int parseInt(String)
static int parseInt(String, int) static Integer getInteger(String)
static Integer getInteger(String, int)
static Integer getInteger(String, Integer) String toString()
static String toString(int)
static String toString(int, int) static String toHexString(int)
Long static long parseLong(String)
static long parseLong(String, int) static Long getLong(String)
static Long getLong(String, long)
static Long getLong(String, Long) String toString()
static String toString(long)
static String toString(long, int) static String toHexString(long)
Float static float parseFloat(String) String toString()
static String toString(float)
Double static double parseDouble(String) String toString()
static String toString(double)
* indicates that the method is new to JDK 1.4

.equals() for Wrapper classes

So how about Wrapper classes - when are they "equal"? In particular, we want to focus on the .equals method. The Sun Certified Programmer for the Java 2 Platform 1.4 Exam state that you must know the following methods
doubleValue, floatValue, intValue, longValue, parseXxx, getXxx, toString, and toHexString.
Ah, but where is the equals() method you might ask? It's not there, so I don't need to worry about it! That would be wrong! There are several items of confluence for the SCP for Java 2 Platform 1.4 - we previously had .equals() required knowledge based on other objectives. Second, the new hashCode method objective has the hashCode() and equals() methods of utmost importance. Even if the equals() method is not covered, knowing how to test the equality of two Wrapper classes is an important interview question or on the job scenario.
Let us use the Float and Double classes as examples. A value of 5.0 wrapped by a Double and a value 5.0 wrapped by a Float are the same, no? After all, is not 5.0 the same as 5.0? The answer is no when defined by the equals() method.
Let's take a look at the following code snippet:
Double aDouble = new Double (5.0);
Float aFloat = new Float(5.0);
if ( aFloat.equals(aDouble) )
System.out.println("equals");
The result is true if and only if the argument is not null and is a Float object that represents a float that has the identical bit pattern to the bit pattern of the float represented by this object. For this purpose, two float values are considered to be the same if and only if the method floatToIntBits(float) returns the same int value when applied to each. Note that in most cases, for two instances of class Float, f1 and f2, the value of f1.equals(f2) is true if and only if
f1.floatValue() == f2.floatValue()
also has the value true.
Thus, in the above code snippet, the aDouble object needs to be of type Float, not Double, to be considered "equal" by the equals() method.
There are two exceptions for the Float equals() method:
 If f1 and f2 both represent Float.NaN, then the equals method returns true, even though Float.NaN==Float.NaN has the value false.
 If f1 represents +0.0f while f2 represents -0.0f, or vice versa, the equal test has the value false, even though 0.0f==-0.0f has the value true. This definition allows hashtables to operate properly.

toHexString
The toHexString method does approximately what you expect in that it returns a string which is a hex string version of the number. It has a natural partner in the toBinaryString method which returns a string that represents the number in its binary version. The following example code will output the strings 100 followed by 10.
public class NumberFormats{
public static void main(String argv[]){
System.out.println(Integer.toBinaryString(4));
System.out.println(Integer.toHexString(16));

}
}

• Wrapper class names differ from the primitives only in the initial upper case letter.
Exceptions are Integer, which wraps int and Character, which wraps char values.
• All wrapper objects can be constructed by passing a string EXCEPT Character wrapper class for char data type. Most of these constructor throws NumberFormatException, which is a runtime exception.
• Wrapper classes override equals() method. equals() on wrappers return false if both the objects are not instances of the same class. This statement is true even when the value they are wrapping has the same numerical value.
• All wrapper objects are immutable. Once an object is created, the wrapped primitive value cannot be changed.
• Wrapper classes are final and hence cannot be sub classed.
• Byte, Double, Float, Integer and Short extend the abstract Number class
• all are public final ie cannot be extended
• get around limitations of primitive types
• allow objects to be created from primitive types
• all the classes have two constructor forms
• a constructor that takes the primitive type and creates an object eg Character(char), Integer(int)
• a constructor that converts a String into an object eg Integer("1"). Throws a NumberFormatException if the String cannot be converted to a number
Note
• The Character class does not have a constructor that takes a String argument
• all, except Character, have a valueOf(String s) method which is equivalent to new Type(String s)
• all have a typeValue() method which returns the value of the object as it's primitive type. These are all abstract methods defined in Number and overridden in each class
• public byte byteValue()
• public short shortValue()
• public int intValue()
• public long longValue()
• public float floatValue()
• public double doubleValue()
• all the classes override equals(), hashCode() and toString() in Object
• equals() returns true if the values of the compared objects are the same
• hashCode() returns the same hashcode for objects of the same type having the same value
• toString() returns the string representation of the objects value
• all have a public static final TYPE field which is the Class object for that primitive type
• all have two static fields MIN_VALUE and MAX_VALUE for the minimum and maximum values that can be held by the type
Void
• There is also a wrapper class for Void which cannot be instantiated.
• The constructors and methods described above do NOT exist for the Void class although it does have the TYPE field.
Character
• contains two methods for returning the numeric value of a character in the various number systems
• public static int digit(char ch, int radix)
• public static int getNumber(char ch)
• and one method to return the character value of a number
• public static char forDigit(int digit, int radix)
• has two case conversion methods
• public static char toLowerCase(char ch)
• public static char toUpperCase(char ch)
• also contains a variety of other methods to test whether a character is of a specific type eg isLetter(), isDefined(), isSpaceChar(), etc
• getType() returns an int that defines a character's Unicode type
Integer, Short, Byte and Long
• all have parseType methods e.g. parseInt(), parseShort, etc that take a String and parse it into the appropriate type
• the Integer and Long classes also have the static methods toBinaryString(), toOctalString() and toHexString() which take an integer value and convert it to the appropriate String representation
Float and Double
• both classes have static fields which define POSITIVE_INFINITY, NEGATIVE_INFINITY, and NaN
• and the following methods to test a value
• public boolean isNan()
• public static boolean isNaN(type value)
• public boolean isInfinite()
• public static boolean isInfinite(type value)
• Float also has a constructor that takes a double value
• both classes have methods to convert a value into a bit pattern or vice versa
• public static int floatToIntBits(float value)
• public static float intBitsToFloat(int bits)
• public static long doubleToLongBits(double value)
• public static double longBitsToDouble(long bits)
parseInt
public static int parseInt(String s) throws NumberFormatException
 Parses the string argument as a signed decimal integer.
 The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value.
 The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method

public static int parseInt(String s, int radix) throws NumberFormatException
 Parses the string argument as a signed integer in the radix specified by the second argument.
 The characters in the string must all be digits of the specified radix (as determined by whether Character.digit(char, int) returns a nonnegative value), except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value.
 The resulting integer value is returned.
An exception of type NumberFormatException (during RUNTIME )is thrown if any of the following situations occurs:
• The first argument is null or is a string of length zero.
• The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX. ( radix >= 2 , <=36 )
• Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') provided that the string is longer than length 1.
• The value represented by the string is not a value of type int.
Examples:
parseInt("0", 10) returns 0
parseInt("473", 10) returns 473
parseInt("-0", 10) returns 0
parseInt("-FF", 16) returns -255
parseInt("1100110", 2) returns 102
parseInt("2147483647", 10) returns 2147483647
parseInt("-2147483648", 10) returns -2147483648
parseInt("2147483648", 10) throws a NumberFormatException // size is more than integer
parseInt("99", 8) throws a NumberFormatException // 9 is not there in octal system
parseInt("99", 37) throws a NumberFormatException // radix is > 36
parseInt("99", 1) throws a NumberFormatException // radix is <2
parseInt("Kona", 10) throws a NumberFormatException
parseInt("Kona", 27) returns 411787 // please note this..
getBoolean
public static boolean getBoolean(String name)
 Returns true if and only if the system property named by the argument exists and is equal to the string "true".
 (Beginning with version 1.0.2 of the JavaTM platform, the test of this string is case insensitive.)
 A system property is accessible through getProperty, a method defined by the System class.
 If there is no property with the specified name, or if the specified name is empty or null, then false is returned.
 Parameters: name - the system property name.
 Returns: the boolean value of the system property.
getInteger
 public static Integer getInteger(String nm, int val)
 Determines the integer value of the system property with the specified name.
 The first argument is treated as the name of a system property. System properties are accessible through the System.getProperty(java.lang.String) method. The string value of this property is then interpreted as an integer value and an Integer object representing this value is returned. Details of possible numeric formats can be found with the definition of getProperty.
 The second argument is the default value. An Integer object that represents the value of the second argument is returned if there is no property of the specified name, if the property does not have the correct numeric format, or if the specified name is empty or null.
 Parameters: nm - property name. val - default value.
 Returns: the Integer value of the property.



===============IMP POINTS FROM JAVARANCH==================================

 Boolean b1 = new Boolean("123");
Boolean b2 = new Boolean("123");
b1.toString() == b2.toString() // - Returns true
 Byte by = new Byte(“123”)
by.toString() == by.toString() // - Returns false . Same for other wrapper classes except boolean
Byte class ( and Other wrappers except Boolean )
----------
.toString() method creates a new String object and returns this every time you call this method.
Boolean class
-------------
.toString() method returns a String literal "true" or "false" depending upon the value of this Boolean object. This String literal will be in String pool and every time you call, the same ref. value (memory address) is returned
 Primitive type wrapper classes
a)allow primitive types to behave as reference types.
Some loose language here but the intention is TRUE, IMO.
b)allow operator overloading to be implemented for primitive numeric types.
NO!!
c)provide string parsing and conversion methods
YES as in Integer.parseInt(String s)
d)provide arithmetic operators such as '+','-'
NO!!
 Float f1 = new Float("10.0f"); //fine
Double f2 = new Double("10.0d"); // fine
Long f2 = new Long("10L"); //  NumberFormatException at RUNTIME
 "Neither L nor l is permitted to appear at the end of the string as a type indicator, as would be permitted in Java programming language source code".

No comments: