Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Java Programming Notes 7

The document provides an overview of enumerations in Java, introduced in JDK 5, which are class types that can have constructors, methods, and instance variables. It explains how to create and use enumerations, including the use of predefined methods like values() and valueOf(), and discusses the inheritance of the Enum class. Additionally, it covers type wrappers that encapsulate primitive types into objects and their usage in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java Programming Notes 7

The document provides an overview of enumerations in Java, introduced in JDK 5, which are class types that can have constructors, methods, and instance variables. It explains how to create and use enumerations, including the use of predefined methods like values() and valueOf(), and discusses the inheritance of the Enum class. Additionally, it covers type wrappers that encapsulate primitive types into objects and their usage in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Enumerations

​ In its simplest form, an enumeration is a list of named constants

​ Beginning with JDK 5, enumerations were added to the Java language, and they are now
an integral and widely used part of Java.
​ In Java, enumeration defines a class type.

​ An Enumeration can have constructors, methods and instance variables

​ In the simplest form, Java enumerations appear similar to enumerations in other


languages, except that the classes play a significant role in this concept.

Enumeration Fundamentals
An enumeration is created using the enum keyword. For example, here is a simple enumeration
that lists various apple varieties:

→ The identifiers Jonathan, GoldenDel, and so on, are called enumeration constants.

→ Each enumeration constant is public, static and final by default.

→ Thus, in the language of Java, these constants are called self-typed, in which “self” refers
to the enclosing enumeration.
→ Once you have defined an enumeration, you can create a variable of that type.

→ However, even though enumerations define a class type, you do not instantiate an enum
using new. Instead, you declare and use an enumeration variable in much the same way
as you do one of the primitive types. For example, this declares ap as a variable of

enumeration type Apple:


🖎 Because ap is of type Apple, the only values that it can be assigned (or can contain) are
those defined by the enumeration. For example, this assigns ap the value RedDel:

Notice that the symbol RedDel is preceded by Apple.

🖎 Two enumeration constants can be compared for equality by using the = = relational
operator. For example, this statement compares the value in ap with the GoldenDel

constant:
🖎 An enumeration value can also be used to control a switch statement. Of course, all of the
case statements must use constants from the same enum as that used by the switch
expression. For example, this switch is perfectly valid:

🖎 enum can be declared inside the class or outside the class but not inside the method.

🖎 Semicolon is optional at the end of enumerated constants during declarations if enum


contains only constants. Both of the following declarations are valid.
enum Level{
HIGH,MEDIUM,LOW
}
enum Level{
HIGH,MEDIUM,LOW;
}
But if the enum is containing list of constants with other members like methods then list of
constants should be in the first line and should end with semicolon.
Follwonig are invalid :

Example:

enum Level{
public void meth(){
// method body
} HIGH,MEDIUM,LOW;

}
enum
Level{
HIGH,MEDIU
M,LOW
public void meth(){
// method body
}
}
The values( ) and valueOf( ) Methods
🖎 All enumerations automatically contain two predefined methods: values( ) and valueOf(
). Their general forms are shown here:
public static enum-type [ ] values( ) public
static enum-type valueOf(String str )
The values( ) method returns an array that contains a list of the enumeration constants
The valueOf( ) method returns the enumeration constant whose value corresponds to the
string passed in str. In both cases, enum-type is the type of the enumeration.
For example, in the case of the Days enumeration shown below, the return type of
Days.valueOf("TUESDAY") is TUESDAY.

//using built-in enumeration methods


package examples;
//an enumeration of days in a week
enum Days{

SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY;
}
public class EnumDemo {
public static void main(String[] args) {
Days ds;
System.out.println("Here are all Days constants ");
//using values()
Days allDays[]=Days.values();
for(Days d:allDays){
System.out.println(d);
}
System.out.println("###################");
//using valueOf()
ds=Days.valueOf("TUESDAY");
System.out.println("ds contains:"+ds);
}
}
Java Enumerations Are Class Types
🖎 As explained, a Java enumeration is a class type. Although you don’t instantiate an enum
using new, it otherwise has much the same capabilities as other classes.
🖎 The fact that enum defines a class gives the Java enumeration extraordinary power. For
example, you can give them constructors, add instance variables and methods, and
even implement interfaces.
🖎 It is important to understand that 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 to the enum constants by defining fields and constructors. As
specified earlier, enum can have fields, constructors and methods.

//using enum constructor,instance variable and method


package examples;
enum NewsPaper{

GorkhaPatra(9.5),Kantipur(10.0),Nagarik(11.5),AnnaPurna(8.5),
NayaPatrika(5.0);
private double price; //price of each newspaper

//constructor
NewsPaper(double p){
price =p;
}
//method
double getPrice(){
return price;
}
}

public class EnumTest {


public static void main(String[] args) {
//displaying the price of Kantipur

System.out.println("Kantipur costs

"+NewsPaper.Kantipur.getPrice()+" Rupees");

//displaying all newspapers and their prices


NewsPaper np[]=NewsPaper.values();
System.out.println("*********************");

System.out.println("Here is the list of newspapers with price");


System.out.println("\n");
for(NewsPaper n:np){

System.out.println("Price of "+n+"-----"+ "Rs.


"+n.getPrice());

System.out.println(". ");
}
}
}
Enumerations Inherit Enum
🖎 Although you can’t inherit a superclass when declaring an enum, all enumerations
automatically inherit one: java.lang.Enum.
🖎 This class defines several methods that are available for use by all enumerations.

🖎 Inside enum order of constants is important and we can represent this order by using
ordinal values. We can find ordinal values of enum constants by ordinal() method
🖎 You can obtain a value that indicates an enumeration constant’s position in the list of
constants. This is called its ordinal value, and it is retrieved by calling the ordinal( )
method, shown here:
final int ordinal( )
It returns the ordinal value of the invoking constant. Ordinal values begin at zero.
Thus, in the Apple enumeration, Jonathan has an ordinal value of zero, GoldenDel has
an ordinal value of 1, RedDel has an ordinal value of 2, and so on.

🖎 You can compare the ordinal value of two constants of the same enumeration by using the
compareTo( ) method. It has this general form:
final int compareTo(enum-type e)
Here, enum-type is the type of the enumeration, and e is the constant being compared to
the invoking constant. Remember, both the invoking constant and e must be of the same
enumeration.
If the invoking constant has an ordinal value less than e’s, then compareTo() returns a
negative value. If the two ordinal values are the same, then zero is returned. If the
invoking constant has an ordinal value greater than e’s, then a positive value is returned.

🖎 You can compare for equality an enumeration constant with any other object by using
equals( ), which overrides the equals( ) method defined by Object. Although equals( )
can compare an enumeration constant to any other object, those two objects will be equal
only if they both refer to the same constant, within the same enumeration. Simply having
ordinal values in common will not cause equals( ) to return true if the two constants are
from different enumerations.
🖎 Remember, you can compare two enumeration references for equality by using = =.

🖎 We cannot use extends keyword for enums. (Inheritance is not possible for enum) .But
internally every enum is inheriting java.lang.Enum class.
//to demonstrate ordinal(),compareTo() and equals() method
package examples;
//an enumeration
enum DaysOfWeek{
SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY;

}
public class Ordinal_CompareTo_Eqals {
public static void main(String[] args)
{
DaysOfWeek dow,dow2,dow3;
//getting ordinal values using ordinal() method

System.out.println("Here are all DaysOfWeek constants

with ordinal values");

System.out.println(" ");
DaysOfWeek allDays[]=DaysOfWeek.values();
for(DaysOfWeek d:allDays){
System.out.println(d+" >"+d.ordinal());

}
System.out.println(" ");
dow = DaysOfWeek.SATURDAY;
dow2=DaysOfWeek.MONDAY;
dow3=DaysOfWeek.SATURDAY;
System.out.println("#########################");

//using compareTo() method

System.out.println("dow.compareTo(dow2)==>"+dow.compareTo(dow2))

;
System.out.println("dow2.compareTo(dow)==>"+dow2.compareTo(dow))
;
System.out.println("#########################");
if(dow.compareTo(dow2)<0)
System.out.println(dow +" comes before "+dow2);
if(dow.compareTo(dow2)>0)
System.out.println(dow2 +" comes before "+dow);
if(dow.compareTo(dow3)==0)
System.out.println(dow +" equals "+dow3);

//using equals() method


System.out.println("#########################");

System.out.println("dow.equals(dow2)==>"+dow.equals(dow2));

System.out.println("dow.equals(dow3)==>"+dow.equals(dow3));
System.out.println("#########################");
if(dow.equals(dow2))
System.out.println("Error!");
if(dow.equals(dow3))
System.out.println(dow+" equals "+dow3);

//using ==
if(dow == dow3)
System.out.println(dow+" == "+dow3);

}
}
Type Wrappers
​ As you know, Java uses primitive types (also called simple types), such as int or double,
to hold the basic data types supported by the language. Primitive types, rather than
objects, are used for these quantities for the sake of performance. Using objects for these
values would add an unacceptable overhead to even the simplest of calculations. Thus,
the primitive types are not part of the object hierarchy, and they do not inherit Object
​ Despite the performance benefit offered by the primitive types, there are times when you
will need an object representation. For example, you can’t pass a primitive type by
reference to a method. Also, many of the standard data structures implemented by Java
operate on objects, which means that you can’t use these data structures to store primitive
types. To handle these (and other) situations, Java provides type wrappers, which are
classes that encapsulate a primitive type within an object.
​ A Wrapper class is a class whose object wraps or contains a primitive data types.
When we create an object to a wrapper class, it contains a field and in this field, we
can store a primitive data types. In other words, we can wrap a primitive value into
a wrapper class object.
​ Wrapper class in java provides the mechanism to convert primitive into object and
object into primitive.
​ The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and
Boolean. These classes offer a wide array of methods that allow you to fully integrate the
primitive types into Java’s object hierarchy.

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double
Character
🖎 Character is a wrapper around a char. The constructor for Character is

Character(char ch)
Here, ch specifies the character that will be wrapped by the Character object being
created.

🖎 To obtain the char value contained in a Character object, call charValue( ), general
form of this method is 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( ), general form of
this method is shown here:
boolean booleanValue( )
It returns the boolean equivalent of the invoking object.
The Numeric Type Wrappers
🖎 By far, 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. Number declares
methods that return the value of an object in each of the different number formats. These
methods are shown here:
byte byteValue( )
double doubleValue( )
float floatValue( )
int intValue( )
long longValue( )
short shortValue( )

🖎 For example, doubleValue( ) returns the value of an object as a double, floatValue( )


returns the value as a float, and so on. These methods are implemented by each of the
numeric type wrappers.
🖎 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.
🖎 The following program demonstrates how to use a numeric type wrapper to encapsulate a
value and then extract that value.
🖎 This program wraps the integer value 100 inside an Integer object called iOb. The
program then obtains this value by calling intValue( ) and stores the result in i.

You might also like