0% found this document useful (0 votes)
6 views21 pages

Module 5 Part 2

Module 5 covers enumerations, type wrappers, and autoboxing in Java. It explains how to create and use enums, the methods associated with them, and the concept of type wrappers for primitive types. Additionally, it discusses autoboxing and unboxing, highlighting their importance in simplifying code and preventing errors.

Uploaded by

ahavish9924
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views21 pages

Module 5 Part 2

Module 5 covers enumerations, type wrappers, and autoboxing in Java. It explains how to create and use enums, the methods associated with them, and the concept of type wrappers for primitive types. Additionally, it discusses autoboxing and unboxing, highlighting their importance in simplifying code and preventing errors.

Uploaded by

ahavish9924
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

MODULE-5 ENUMERATIONS

MODULE 5

Chapter-2
Enumerations, Type Wrappers and Autoboxing

➢ Enumerations(Enumeration Fundamentals,
The values() and valueOf() Methods),

➢ Type Wrappers (Character, Boolean, The


ENUMERATIONS, Numeric Type Wrappers),

TYPE ➢ Autoboxing (Autoboxing and Methods,


Autoboxing/Unboxing Occurs in Expressions,
WRAPPERS AND
AUTOBOXING: ➢ Autoboxing/Unboxing Boolean and Character
Values).
MODULE-5 ENUMERATIONS

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.

➢ Note that they should be in uppercase letters:

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

• To create an enumeration list we need to import java.util.Enumeration

• An enumeration is created using the enum keyword followed by the variable


Name we want associated with the list

Syntax:

public enum variableName

ITEM1
ITEM2
ITEMN
}

Example: enum Colors {

RED,
BLUE,
YELLOW,
GREEN
}

➢ You can access enum constants with the dot syntax:

Colors myVar = Colors.RED;

Simple Program:

enum Colors {
MODULE-5 ENUMERATIONS

RED,
BLUE,
YELLOW,
GREEN
}
public class Main
{

public static void main(String[] args)


{
Colors red = Colors.RED;
System.out.println(red); // RED
}
}
OUTPUT

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

we can create our enum inside the Main class


public class Main
{
enum Colors
{
RED,
BLUE,
YELLOW,
GREEN
}
public static void main(String[] args)

{
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
{

public static void main(String[] args)


{
Colors red = Colors.RED;
System.out.println(red.ordinal());
}
}
OUTPUT: returns 0(index of red).

2. Java Enumerations Are Class Types

• Enumerations in Java can have methods, members and constructors just as any other class
can have.

• Each enumeration constant is an object of its enumeration type.

• 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

ITEM1(1), ITEM2(20), ITEM3(30);//objects of enum


data-typevariableName; //instance variable

data-type methodName()//method
{ statement;}

enumName (parameter-list) // constructors.


{
statements;
}
}

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());
}
}

output: Value of A Is= 10

3. the values() and valueOf() Methods:

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():

• Method returns an array that contains a list of the enumeration constants

• 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( )

Progarm 1: To print the list of day of enumeration class

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:

today day is=mon


today day is=tue
today day is=wed
today day is=thu
today day is=fri
today day is=sat
today day is=sun

program 2:TO find no of days in month


MODULE-5 ENUMERATIONS

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.

4. Enumerations Inherit Enum:


All enumerations in Java inherit the Enum class, java.lang.Enum, which provide a set of
methods for all enumerations. The four mentioned here are ordinal( ) and
compareTo(),equals() and toString().

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());

program: To find index of Enum List.

enum Days {
mon,tue,wed;
}
class cont
{

public static void main( String args[] )


{
Days wd = Days.mon;
System.out.println("Index of list:"+wd.ordinal());
}
}
output: Index of list:0

Program 2: Using foreach loop

enum Days {
class cont
MODULE-5 ENUMERATIONS

{
mon,tue,
wed;
}
MODULE-5 ENUMERATIONS

public static void main( String args[] )

Days wd[] = Days.values();

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():

• compares the ordinal value of the two enumeration objects.

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

Syntax: int num = enumObject1.compareTo(enumObject2);

program: To find order of day

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)

System.out.println("mon comes befor tue");

if(d2.compareTo(d3)<0)
System.out.println("Tue comes befor wed");

System.out.println("wed comes after tue");

}
}

output:

mon comes befor tue


Tue comes befor wed
wed comes after tue

3. equals():

• method returns true if the specified object is equal to this enum constant.

public final boolean equals(Object other)

• 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():

➢ method returns the name of this enum constant, as contained in the


declaration. public String toString()

➢ This method returns the name of this enum constant.

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.

➢ So to avoid this java had used primitive types.


➢ So primitive types do not inherit Object class
➢ But there are times when you will need an object representation for primitives
like int and char.

➢ Example, you can’t pass a primitive type by reference to a method.


➢ Many of the standard data structures implemented by Java operate on objects, which
mean that you can’t use these data structures to store primitive types.
MODULE-5 ENUMERATIONS

➢ To handle these (and other) situations, Java provides type wrappers, which
are classes that encapsulate a primitive type within an object.

The type wrappers are :

Double, Float, Long, Integer, Short, Byte,


Character, and Boolean.
Character:
• Character is a wrapper around a char.
• The constructor for Character is Character(char ch) here ch is a character
variable whose values will be wrapped to character object by the wrapper class

• To obtain the char value contained in a Character object, call charValue( ), shown
here:

char charValue( )
It returns the encapsulated character.

Boolean

• Boolean is a wrapper around boolean values. It defines these constructors:


Boolean(boolean boolValue)
Boolean(String boolString)

• 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( )

• It returns the boolean equivalent of the invoking object.

The Numeric Type Wrappers

• 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( )

doubleValue( ): returns the value of an object as a double


floatValue( ): returns the value as a float, and so on.

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

• For example, here are the constructors defined for Integer:

Integer(int num) Integer(String str)

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

Program : All wrapper class


class Wrap
{
public static void main(String args[])
{
Character c=new Character('@'); // character type char c1=c.charValue();
System.out.println("Character wrapper class"+c1);
Boolean b=new Boolean(true);
boolean b1=b.booleanValue(); System.out.println("Boolean wrapper class"+b1);
MODULE-5 ENUMERATIONS

Integer i1 = new Integer(100); // integre type


int i = i1.intValue();
System.out.println("Integer wrapper class"+i); // displays 100 100

Float f1 = new Float(12.5); // Float type

float f = f1.floatValue();
System.out.println("Float wrapper class"+f);

output:

Character wrapper class@


Boolean wrapper classtrue
Integer wrapper class100 Float
wrapper class12.5

Autoboxing

• Autoboxing is the process by which a primitive type is automatically encapsulated


(boxed) into its equivalent type wrapper whenever an object of that type is needed.
There is no need to explicitly construct an object.

• For example, converting int to Integer class. The Java compiler applies autoboxing when
a primitive value is:

• Passed as a parameter to a method that expects an object of the corresponding


wrapper class.

• Assigned to a variable of the corresponding wrapper class.

• Auto-unboxing is the process by which the value of a boxed object is automatically


extracted(unboxed) from a type wrapper when its value is needed. There is no need to
call a method such as intValue( ) or doubleValue( ).

• For example conversion of Integer to int. The Java compiler applies unboxing when an
object of a wrapper class is:

• Passed as a parameter to a method that expects a value of the corresponding


primitive type.

• Assigned to a variable of the corresponding primitive type.


MODULE-5 ENUMERATIONS

Uses of Autoboxing and Unboxing

➢ Useful in removing the difficulty of manually boxing and unboxing values


in several algorithms.

➢ it is very important to generics, which operates only on objects.


➢ It also helps prevent errors.

➢ autoboxing makes working with the Collections Framework

here is the modern way to construct an Integer object that has the value 100:

Integer iOb = 100; // autobox an int

➢ 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:

int i = iOb; // auto-unbox

Program: Simple program for autoboxing and autoUnboxing

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

int i = iob; //Auto-unboxing of Integer i.e converting Wrapper class Integer to a


primitve type int
System.out.println("integer type="+i+" "+iob);
Character cob = 'a'; //Auto-boxing of char i.e converting primitive data
type char to a Wrapper class Character
char ch = cob; //Auto-unboxing of Character i.e converting Wrapper class Character to a
primitive type char
MODULE-5 ENUMERATIONS

System.out.println("character type="+cob+" "+ch);


}

output:

integer type=100 100 character


type=a a

Autoboxing and Methods:

• Thus, autoboxing/unboxing might occur when an argument is passed to a


method, or when a value is returned by a method.

• autoboxing automatically occurs whenever a primitive type must be converted


into an object.autounboxing takes place whenever an object must be converted
into a primitive type

Program :

class auto {
static int m(Integer v) {
return v ; // auto-unbox to int

public static void main(String args[])

Integer iOb = m(100); // Auto Boxing

System.out.println("Integertype="+iOb);

output:

Integer type=100
MODULE-5 ENUMERATIONS

Autoboxing/Unboxing Occurs in Expressions:

• autoboxing and unboxing take place whenever a conversion into an object or from
an object is required.

• This applies to expressions. Within an expression, a numeric object is


automatically unboxed.

• The outcome of the expression is reboxed, if necessary

Program:

class auto

public static void main(String args[])

Integer iOb, iOb2; int i;

iOb = 100;

System.out.println("Original value of iOb: " + iOb);//The following


automatically unboxes iOb, performs the increment, and
then reboxes the result back into iOb.
++iOb;
System.out.println("After ++iOb: " + iOb); iOb2 = iOb + (iOb / 3);

System.out.println("iOb2 after expression: " + iOb2); i = iOb + (iOb / 3);

System.out.println("i after expression: " + i);


}
}

output: Original value of iOb: 100


After ++iOb: 101
iOb2 after expression: 134
i after expression: 134
MODULE-5 ENUMERATIONS

Autoboxing/Unboxing Boolean and Character Values:


Java also supplies wrappers for boolean and char. These are Boolean and Character.
Autoboxing/unboxing applies to these wrappers, too

• Character ch = 'x'; // box a char

• char ch2 = ch; // unbox a char

• Boolean b = true; here the value true is boxed in b

• if(b) System.out.println("b is true"); // here b is unboxed

Program:
class auto {
public static void main(String args[]) {
//Autobox/unbox a boolean.
Boolean b = true; if(b)

System.out.println("b is true");//Autobox/unbox a char.

Character ch = 'x'; // box a char


char ch2 = ch; // unbox a char
System.out.println("ch2 is " + ch2);
}
}
output:
b is true
ch2 is x

You might also like