Module 5 Part 2
Module 5 Part 2
MODULE 5
Chapter-2
Enumerations, Type Wrappers and Autoboxing
➢ Enumerations(Enumeration Fundamentals,
The values() and valueOf() Methods),
Enumeration fundamentals :
➢ An enum is a special "class" that represents a group of constants (unchangeable variables,
like final variables).
➢ To create an enum, use the enum keyword (instead of class or interface), and separate the
constants with a comma.
Creating Enumerations
• When creating an enumeration list, we don't use the keyword class and when you
create a enumeration object, we don't use the keyword new
Syntax:
ITEM1
ITEM2
ITEMN
}
RED,
BLUE,
YELLOW,
GREEN
}
Simple Program:
enum Colors {
MODULE-5 ENUMERATIONS
RED,
BLUE,
YELLOW,
GREEN
}
public class Main
{
RED
we initialized a Colors variable and assigned one of the values of an enum to it using the dot syntax:
Colors red = Colors.RED;.
{
Colors red = Colors.RED;
System.out.println(red);
}
MODULE-5 ENUMERATIONS
}
MODULE-5 ENUMERATIONS
If we want to get the index number of any of the values, we would have to use the ordinal() method.
Here is an example:
enum Colors {
RED,
BLUE,
YELLOW,
GREEN
}
public class Main
{
• Enumerations in Java can have methods, members and constructors just as any other class
can have.
• Thus, when you define a constructor for an enum, the constructor is called when each
enumeration constant is created.
• Also, each enumeration constant has its own copy of any instance variables defined by
the enumeration.
• the enum constants have initial value that starts from 0, 1, 2, 3 and so on. But we can
initialize the specific value(default value) to the enum constants by defining fields and
constructors.
Syntax:
enum variableName
{
MODULE-5 ENUMERATIONS
data-type methodName()//method
{ statement;}
Progarm:
enum Value
{
A(10), B(20), C(30); //objects of enum
int a; //instance variable
int getValue(){ return a;} //method
Gender(int value) // constructors.
{
this.a=value;
}
}
class Enu
{
public static void main( String args[] )
{
System.out.println(" value of A IS="+Value.A.getValue());
}
}
There are some methods that you can use that are part of the enumeration class, these methods
include :
MODULE-5 ENUMERATIONS
1. values()
2. valueOf()
1. Values():
• values() returns the values in the enumeration and stores them in an array. We can
process the array with a foreach loop.
Syntax:
public static enum-type[ ] values( )
enum Days {
mon,tue,wed,thu,fri,sat,sun;
}
class cont
{
public static void main( String args[] )
{
Days d[]=Days.values();
for(Days d1:d)
System.out.println("today day is:"+d1);
}
}
output:
enum month {
January(31),
February(28),
March(31),
April(30),
May(31),
June(30),
July(31),
August(31),
September(30),
October(31),
November(30),
December(31);
private final int days;
month(int days)
{
this.days = days;
}
public static void main(String[] args)
{
for(month month1 : month.values( ))
{
System.out.println(month1+":"+month1.days);
}
}
}
output:
January:31
February:28
March:31
April:30
May:31
June:30
July:31
August:31
September:30
October:31
MODULE-5 ENUMERATIONS
November:30
December:31
2. ValueOf():
• method returns the enumeration constant whose value corresponds to the string
passed in str.
• method takes a single parameter of the constant name to retrieve and returns the constant
from the enumeration, if it exists.
Syntax: enumerationVariable = enumerationName.valueOf("EnumerationValueInList");
Example
WeekDays wd = WeekDays.valueOf("MONDAY");
System.out.println(wd);
program:
enum Days {
monday,tuesday;
}
class cont
{
public static void main( String args[] )
{
Days d=Days.valueOf("monday");
System.out.println("day selected is:"+d);
}
}
output: day selected is:Monday
MODULE-5 ENUMERATIONS
Note: An enumeration cannot inherit another class and an enum cannot be a superclass for other
class.
1. ordinal():
➢ Returns the value of the constant's position in the list (the first constant has a position of
zero).
➢ The ordinal value provides the order of the constant in the enumeration, starting with 0
Example
WeekDays wd = WeekDays.MONDAY;
System.out.println(wd.ordinal());
enum Days {
mon,tue,wed;
}
class cont
{
enum Days {
class cont
MODULE-5 ENUMERATIONS
{
mon,tue,
wed;
}
MODULE-5 ENUMERATIONS
for(Days w:wd)
System.out.println("Index of list:"+w.ordinal());
}
}
output:
Index of list:0
Index of list:1
Index of list:2
2. compareTo():
• If the object invoking the method has a value less than the object being passed, a negative
number is returned.
• It the two objects have the same oridnal number, a zero is returned.
• If the invoking object has a greater value than the one being passed, a positive number is
returned.
enum Days {
class cont
{
mon,tue,wed;
public static void main( String args[] )
Days d1,d2,d3;
d1=Days.mon;
d2=Days.tue;
MODULE-5 ENUMERATIONS
d3=Days.wed;
if(d1.compareTo(d2)<0)
if(d2.compareTo(d3)<0)
System.out.println("Tue comes befor wed");
}
}
output:
3. equals():
• method returns true if the specified object is equal to this enum constant.
• where other − This is the object to be compared for equality with this object.
• This method returns true if the specified object is equal to this enum constant
• Example:
enum Days {
mon,tue,wed;
}
class cont
{
Output:
public static void main( String args[] )
{ False
Days d1,d2,d3; False
d1=Days.mon; d2=Days.tue; d3=Days.wed; true
System.out.println(d1.equals(d2));
System.out.println(d2.equals(d3));
System.out.println(d2.equals(d2));}
}
MODULE-5 ENUMERATIONS
4. toString():
Example:
enum Days {
mon,tue,wed;
}
class cont
{
public static void main( String args[] )
{
Days d1,d2,d3;
d1=Days.mon;
d2=Days.tue;
d3=Days.wed;
System.out.println(d1.toString());
System.out.println(d2. toString());
System.out.println(d3. toString());
}
}
Output: mon tue wed
4. Type wrappers:
➢ Java uses primitive types (also called simple types), such as int or double, to hold the
basic data types supported by the language.
➢ Instead of primitive types if objects are used everywhere for even simple
calculations then performance overhead is the problem.
➢ To handle these (and other) situations, Java provides type wrappers, which
are classes that encapsulate a primitive type within an object.
• To obtain the char value contained in a Character object, call charValue( ), shown
here:
char charValue( )
It returns the encapsulated character.
Boolean
• In the first version, boolValue must be either true or false. In the second version, if
boolString contains the string "true" (in uppercase or lowercase), then the new Boolean
object will be true. Otherwise, it will be false.
• To obtain a boolean value from a Boolean object, use booleanValue( ), shown here:
boolean booleanValue( )
• The most commonly used type wrappers are those that represent numeric values. These are
Byte, Short, Integer, Long, Float, and Double. All of the numeric type wrappers inherit
the abstract class Number.
MODULE-5 ENUMERATIONS
• Number declares methods that return the value of an object in each of the different number
formats. These methods are shown here:
1. byte byteValue( )
2. double doubleValue( )
3. float floatValue( )
4. int intValue( )
5. long longValue( )
6. short shortValue( )
• All of the numeric type wrappers define constructors that allow an object to be constructed
from a given value, or a string representation of that value.
• If str does not contain a valid numeric value, then a NumberFormatException is thrown.
All of the type wrappers override toString( ). It returns the human-readable form of the
value contained within the wrapper. This allows you to output the value by passing a type
wrapper object to println( ), for example, without having to convert it into its primitive
type.
float f = f1.floatValue();
System.out.println("Float wrapper class"+f);
output:
Autoboxing
• For example, converting int to Integer class. The Java compiler applies autoboxing when
a primitive value is:
• For example conversion of Integer to int. The Java compiler applies unboxing when an
object of a wrapper class is:
here is the modern way to construct an Integer object that has the value 100:
➢ Notice that no object is explicitly created through the use of new. Java handles this for
you,automatically.
➢ To unbox an object, simply assign that object reference to a primitive-type
variable.
➢ For example, to unbox iOb, you can use this line:
class auto
{
public static void main(String[] args)
{
Integer iob = 100; //Auto-boxing of int i.e converting primitive data type int to a Wrapper class
Integer
output:
Program :
class auto {
static int m(Integer v) {
return v ; // auto-unbox to int
System.out.println("Integertype="+iOb);
output:
Integer type=100
MODULE-5 ENUMERATIONS
• autoboxing and unboxing take place whenever a conversion into an object or from
an object is required.
Program:
class auto
iOb = 100;
Program:
class auto {
public static void main(String args[]) {
//Autobox/unbox a boolean.
Boolean b = true; if(b)