Wrapper Class & Enumerated

Download Report

Transcript Wrapper Class & Enumerated

CONTENTS
•
•
•
•
Wrapper Class
Enumeration
Garbage Collection
Import static
Wrap – associate with present!
When God want to give us a PRESENT,
He WRAPS it in a CHALLENGE,
the BIGGER is the CHALLENGE,
the is the PRESENT.
Wrapper Classes
• Boolean
• Character
• Integer
• Long
• Short
• Float
• Byte
• Double
(1) The wrapper classes do not have
no-arg constructors.
(2) The instances of all wrapper
classes are immutable, i.e., their
internal values cannot be changed
once the objects are created.
Comparable
-
Object
Number
Character Boolean
-
-
Double
-
Float
-
Long
-
Integer
-
Short
-
Byte
-
The Integer and Double Classes
java.lang.Number
+byteValue(): byte
+shortValue(): short
+intValue(): int
+longValue(): long
+floatValue(): float
+doubleValue():double
java.lang.Comparable
+compareTo(o: Object): int
java.lang.Integer
-value: int
+MAX_VALUE: int
+MIN_VALUE: int
+Integer(value: int)
+Integer(s: String)
+valueOf(s: String): Integer
+valueOf(s: String, radix: int): Integer
+parseInt(s: String): int
+parseInt(s: String, radix: int): int
java.lang.Double
-value: double
+MAX_VALUE: double
+MIN_VALUE: double
+Double(value: double)
+Double(s: String)
+valueOf(s: String): Double
+valueOf(s: String, radix: int): Double
+parseDouble(s: String): double
+parseDouble (s: String, radix: int): double
The Integer and Double Class
• Constructors
• Class Constants MAX_VALUE,
MIN_VALUE
• Conversion Methods
Numeric Wrapper Class Constructors
You can construct a wrapper object either
from a primitive data type value or from a
string representing the numeric value. The
constructors for Integer and Double are:
public Integer(int value)
public Integer(String s)
public Double(double value)
public Double(String s)
Numeric Wrapper Class Constants
Each numerical wrapper class has the constants
MAX_VALUE and MIN_VALUE.
MAX_VALUE represents the maximum value of the
corresponding primitive data type.
For Byte, Short, Integer, and Long, MIN_VALUE
represents the minimum byte, short, int, and long
values.
For Float and Double, MIN_VALUE represents the
minimum positive float and double values.
To access Constant
System.out.println(Integer. MAX_VALUE);
the maximum integer (2,147,483,647),
System.out.println(Float. MIN_VALUE);
the minimum positive float (1.4E-45), and
the maximum double floating-point number
(1.79769313486231570e+308d).
The Static valueOf Methods
The numeric wrapper classes have a
useful class method, valueOf(String s).
This method creates a new object
initialized to the value represented by the
specified string. For example:
Double doubleObject = Double.valueOf("12.4");
Integer integerObject = Integer.valueOf("12");
The Methods for Parsing Strings into
Numbers
parseInt method in the Integer class to
parse a numeric string into an int value
parseDouble method in the Double class
to parse a numeric string into a double
value.
Each numeric wrapper class has two
overloaded parsing methods to parse a
numeric string into an appropriate
numeric value.
Converting Strings to
Numbers
• Integer class
– Part of java.lang
– Automatically imported into programs
– Convert String to integer
– parseInt() method
• Takes String argument
• Returns its integer value
• Wrapper
– Class or object “wrapped around” simpler
element
Converting Strings to
Numbers (continued)
• Integer class valueOf() method
– Convert String to Integer class object
• Integer class intValue() method
– Extract simple integer from wrapper class
• Double class
– Wrapper class
– Imported into programs automatically
– parseDouble() method
• Takes String argument
• Returns its double value
The ConvertStringToInteger
Application
ANSWER EXERCISE 2 NO. 7
import javax.swing.JOptionPane;
public class Addition {
public static void main( String args[] )
{
String first,second,third;
int number1,number2,sum;
final double PI = 3.14;
double radius,area;
first=JOptionPane.showInputDialog("Enter 1st int" );
second=JOptionPane.showInputDialog("Enter 2nd int");
third=JOptionPane.showInputDialog("Enter radius");
number1 = Integer.parseInt(first);
number2 = Integer.parseInt(second);
radius = Double.parseDouble(third);
sum = number1 + number2;
area = PI*radius*radius;
JOptionPane.showMessageDialog(null,"The sum is: " + sum,
"Results", JOptionPane.PLAIN_MESSAGE );
JOptionPane.showMessageDialog(null,"Area is: " + area,
"Area of Circle", JOptionPane.PLAIN_MESSAGE );
System.exit(0);
}
}
convert objects to primitive type values
In class Number, methods;
doubleValue,
floatValue,
intValue,
longValue,
shortValue, and byteValue
“convert” objects into primitive type values.
e.g
//Program 4.13
class Test {
public static void main(String[] args) {
Object x = new Integer(2);
System.out.println(x.intValue());
}
}
toString, equals, and hashCode
Methods - in the Object class
Each wrapper class overrides the
toString, equals, and hashCode
Since all the numeric wrapper classes
and the Character class implement the
Comparable interface, the compareTo
method is implemented in these classes.
e.g
//Program 4.12
class Test {
public static void main(String[] args) {
Object x = new Integer(2);
System.out.println(x.toString());
}
}
enumerated
Enumerated Types
• Known as an enum, requires
declaration and definition like a class
• Syntax:
enum typeName { one or more enum constants }
– Definition:
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, SATURDAY }
– Declaration:
Day WorkDay; // creates a Day enum
– Assignment:
Day WorkDay = Day.WEDNESDAY;
Enumerated Types
• An enum is a specialized
class
Each are objects of type Day, a specialized class
Day.SUNDAY
Day workDay = Day.WEDNESDAY;
Day.MONDAY
The workDay variable holds the address of the
Day.WEDNESDAY object
Day.TUESDAY
address
Day.WEDNESDAY
Day.THURSDAY
Day.FRIDAY
Day.SATURDAY
enum CoffeeSize { BIG, HUGE, OVERWHELMING } ;
class Coffee
semicolon is optional
{
CoffeeSize size;
}
public class CoffeeTest1
{
public static void main(String[] args)
{
Coffee drink = new Coffee();
drink.size = CoffeeSize.BIG;
}
}
class Coffee2
{
enum CoffeeSize {BIG, HUGE, OVERWHELMING }
CoffeeSize size;
}
public class CoffeeTest2
{
public static void main (String[] args) {
Coffee2 drink = new Coffee2();
drink.size = Coffee2.CoffeeSize.BIG; }
}
enclosing
class name
required
public class CoffeeTestl
{
public static void main(String[] args)
{
enum CoffeeSize { BIG, HUGE, OVERWHELMING }
Coffee drink = new Coffee();
drink.size = CoffeeSize.BIG;
}
}
enum CoffeeSize {
private int ounces;
BIG(8), HUGE(10), OVERWHELMING(16);
CoffeeSize(int ounces) {
this.ounces = ounces;
}
public int getOunces() {
return ounces;
}
}
enum CoffeeSize
{
BIG(8),
HUGE(10),
OVERWHELMING(16)
{
public String getLidCode()
{
return "A";
}
};
.
.
}
Enumerated Types - Switch
• Java allows you to test an enum constant with a
switch statement.
Refer example from lab module page 71-71(Program 4.11)
switch (satay) {
case MUTTON: System.out.println("Mutton Satay Fabulous.");
System.out.println("Price is RM0.60/each");
break;
case OSTRICH: System.out.print("Ostrich Satay ");
System.out.println("For Low Cholestrol Diet.");
System.out.println("Price is RM1.00/each");
break;
Enumerated Types - Methods
• toString – returns name of calling constant
• ordinal – returns the zero-based position of the
constant in the enum. For example the ordinal for
Day.THURSDAY is 4
• equals – accepts an object as an argument and returns
true if the argument is equal to the calling enum constant
• compareTo - accepts an object as an argument and
returns a negative integer if the calling constant’s ordinal
< than the argument’s ordinal, a positive integer if the
calling constant’s ordinal > than the argument’s ordinal
and zero if the calling constant’s ordinal == the
argument’s ordinal.
Garbage Collection
Garbage Collection
• When objects are no longer needed they
should be destroyed.
• This frees up the memory that they
consumed.
• Java handles all of the memory operations
for you.
• Simply set the reference to null and Java
will reclaim the memory.
Garbage Collection
• The Java Virtual Machine has a process that
runs in the background that reclaims memory
from released objects.
• The garbage collector will reclaim memory from
any object that no longer has a valid reference
pointing to it.
BankAccount account1 = new BankAccount(500.0);
BankAccount account2 = account1;
• This sets account1 and account2 to point to
the same object.
Garbage Collection
A BankAccount object
account1
Address
account2
Address
Balance:
500.0
Here, both account1 and account2 point to the same
instance of the BankAccount class.
Garbage Collection
A BankAccount object
account1
null
account2
Address
Balance:
However, by running the statement: account1 = null;
only account2 will be pointing to the object.
500.0
Garbage Collection
A BankAccount object
account1
null
account2
null
Balance:
500.0
Since there are no valid references to this
object, it is now available for the garbage
collector to reclaim.
If we now run the statement: account2 = null;
neither account1 or account2 will be pointing to the object.
Garbage Collection
A BankAccount object
account1
null
account2
null
Balance:
500.0
The garbage collector reclaims the
memory the next time it runs in
the background.
The finalize Method
• If a method with the signature:
public void finalize(){…}
is included in a class, it will run just prior to
the garbage collector reclaiming its
memory.
• The garbage collector is a background
thread that runs periodically.
• It cannot be determined when the
finalize method will actually be run.
Refer to page
import static
import static java.lang.Math.*;
public class StaticImportTest
{
public static void main(String args[])
{
System.out.printf("sqrt(9.0)\t= %.1f\n",sqrt(9.0));
System.out.printf("ceil(-9.7)\t= %.1f\n",ceil(-9.7));
System.out.printf("\tlog(E)\t\t= %.1f\n",log(E));
System.out.printf("cos(0.0 \t= %.1f\n",cos(0.0));
}
}