Java Tutorial Part 3
Java Tutorial Part 3
Java uses primitive types, such as int, char, double to hold the basic data types supported by the language. Sometimes it is required to create an object representation of these primitive types. These are collection classes that deal only with such objects. One needs to wrap the primitive type in a class.
To satisfy this need, Java provides classes that correspond to each of the primitive types. Basically, these classes encapsulate, or wrap, the primitive types within a class. Thus, they are commonly referred to as type wrapper. Type wrapper are classes that encapsulate a primitive type within an object. The wrapper types are Byte, Short, Integer, Long, Character, Boolean, Double, Float. These classes offer a wide array of methods that allow to fully integrate the primitive types into Java's object hierarchy.
Wrapper Classes are based upon the well-known software engineering design pattern called the Wrapper pattern.
A design pattern is a template solution to a common problem. It describes the problem and identifies the recommended solution(s) to that problem. Because design patterns deal with common problems, they are often quite abstract!
The Solution:
We create another class that wraps the underlying class/type and provides an appropriate interface for the client. e.g. we create an Integer class that subclasses Object (as all classes do), allowing us to store wrapped ints in Vectors.
Boolean
Void
Number
String
Character
Byte
Short
Integer
Long
Float
Double
int i =integer.parselnt(str); Converts String str into primitive integer i long l = Long.parseLong(str); Converts String str into primitive long l Double d=Double.parseDouble(str); Converting String to primitive double Note: parselnt() and parseLong() methods throw a NumberFormatException if the value of the str does not represent an integer.
sets str to the String 33.34. Getting a wrapper class instance for a value:
e.g. Integer
obj = Integer.getInteger(12);
creates a new Integer object with value 12 and makes obj refer to that object.
Reading a Double
import java.io.*; class MyProgram { public static void main(String[] args) { BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); String line = null; System.out.println("Input Something:" ); try { line = in.readLine(); } catch (IOException ie) { System.out.println("Exception caught: " + ie); } try { double value = Double.parseDouble(line); System.out.println("Value: " + value); } catch (NumberFormatException nfe) { System.out.println("You didn't enter a double number"); } } }
Sample values:
boolObj new Boolean(Boolean.TRUE); charObj = new Character('a'); byteObj = new Byte("100"); shortObj = new Short("32000"); intObj = new Integer(2000000); longObj = new Long(500000000000000000L); floatObj = new Float(1.42); doubleObj = new Double(1.42);
printWrapperInfo(); //method to print objects above
Byte Example
The Byte class encapsulates a byte value. It defines the constants MAX_VALUE and MIN_VALUE and provides these constructors: Byte(byte b) Byte(String str) Here, b is a byte value and str is the string equivalent of a byte value.
Byte Example
Short Example
The Short class encapsulates a short value. It defines the constants MAX_VALUE and MIN_VALUE and provides the following constructors: Short(short s) Short(String str)
Short Example
Integer Example
The Integer class encapsulates an integer value. This class provides following constructors: Integer(int i) Integer(String str) Here, i is a simple int value and str is a String object.
Integer Example
Character Example
The Character class encapsulates a char value. This class provides the following constructor. Character(char ch) Here, c is a char value. charValue() method returns the char value that is encapsulated by a Character object and has the following form: char charValue()
Character Example
Boolean Example
The Boolean class encapsulates a Boolean value. It defines FALSE and TRUE constants. This class provides following constructors: Boolean(Boolean b) Boolean(String str) Here, b is a Boolean value and str is the string equivalent of a Boolean value. The methods associated with Boolean Class are as follows: 1. Boolean booleanValue() 2. Boolean equals(Boolean b) 3. String toString(Boolean b)
Boolean Example
java2all
Clone Method
Recall that the = operator simply copies Object references. e.g., >> Student s1 = new Student(Smith, Jim, 3.13); >> Student s2 = s1; >> s1.setName(Sahil); >> System.out.println(s2.getName()); OP:- Sahil What if we want to actually make a copy of an Object? Most elegant way is to use the clone() method inherited from Object. Student s2 = (Student) s1.clone();
First, note that the clone method is protected in the Object class. This means that it is protected for subclasses as well. Hence, it cannot be called from within an Object of another class and package. To use the clone method, you must override in your subclass and upgrade visibility to public. Also, any class that uses clone must implement the Cloneable interface. This is a bit different from other interfaces that weve seen. There are no methods; rather, it is used just as a marker of your intent. The method that needs to be implemented is inherited from Object.
Deep Copies
For deep copies that recurse through the object ivs, you have to do some more work. super.clone() is first called to clone the first level of ivs. Returned cloned objects object fields are then accessed one by one and clone method is called for each. See DeepClone.java example
Finally, though no one really cares, Object does not support clone();
toString() method
The Object method
String toString();
is intended to return a readable textual representation of the object upon which it is called. This is great for debugging! Best way to think of this is using a print statement. If we execute:
System.out.println(someObject);
we would like to see some meaningful info about someObject, such as values of ivs, etc.
default toString()
By default toString() prints total garbage that no one is interested in
getClass().getName() + '@' + Integer.toHexString(hashCode())
and values (or some important subset). The intent is not to overformat. Typically used for debugging. Always override toString()!
equals() method
Recall that boolean == method compares when applied to object compares references. That is, two object are the same if the point to the same memory. Since java does not support operator overloading, you cannot change this operator. However, the equals method of the Object class gives you a chance to more meaningful compare objects of a given class.
equals subtleties
As with any method that you override, to do so properly you must obey contracts that go beyond interface matching. With equals, the extra conditions that must be met are discussed on the next slide:
equals contract
It is reflexive: for any reference value x, x.equals(x) should
return true. It is symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified. For any non-null reference value x, x.equals(null) should return false.
hashcode() method
Java provides all objects with the ability to generate a hash code. By default, the hashing algorithm is typically based on an integer representation of the java address. This method is supported for use with java.util.Hashtable Will discuss Hashtable in detail during Collections discussion.
once, the hashCode method must return the same integer, provided no information used in equals comparisons on the object is modified. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
finalize() method
Called as final step when Object is no longer used, just before garbage collection Object version does nothing Since java has automatic garbage collection, finalize() does not need to be overridden reclaim memory. Can be used to reclaim other resources close streams, database connections, threads. However, it is strongly recommended not to rely on this for scarce resources. Be explicit and create own dispose method.