ENUMERATIONS
“Enumeration means a list of named constant, enum in java is a data type that contains fixed set of
constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc.
It is available from JDK 1.5.
An Enumeration can have constructors, methods and instance variables. It is created using enum keyword.
Each enumeration constant is public, static and final by default.
Even though enumeration defines a class type and have constructors, you do not instantiate an enum using
new.
Enumeration variables are used and declared in much a same way as you do a primitive variable.
ENUMERATION FUNDAMENTALS
How to Define and Use an Enumeration
An enumeration can be defined simply by creating a list of enum variable. Let us take an example for list
of Subject variable, with different subjects in the list.
enum Subject //Enumeration defined
{
JAVA, CPP, C, DBMS
}
Identifiers JAVA, CPP, C and DBMS are called enumeration constants. These are public, static and
final by default.
Variables of Enumeration can be defined directly without any new keyword.
Ex: Subject sub;
Variables of Enumeration type can have only enumeration constants as value.
We define an enum variable as: enum_variable = enum_type.enum_constant;
Ex: sub = [Link];
Two enumeration constants can be compared for equality by using the = = relational operator.
Example:
if(sub == [Link])
{
...
}
Program 1: Example of Enumeration
enum WeekDays
{
sun, mon, tues, wed, thurs, fri, sat
}
class Test
{
public static void main(String args[])
{
WeekDays wk; //wk is an enumeration variable of type WeekDays
wk = [Link]; //wk can be assigned only the constants defined under enum type Weekdays
[Link]("Today is "+wk);
}
}
Output : Today is sun
values() and valueOf() Methods
The java compiler internally adds the values() method when it creates an enum.
The values() method returns an array containing all the values of the enum.
Its general form is,
public static enum-type[ ] values()
valueOf() method is used to return the enumeration constant whose value is equal to the string passed in as
argument while calling this method.
It's general form is,
public static enum-type valueOf (String str)
enum SpecialStud
{
ABI, GAUTHAM, NANDA, SOURABH, SUHAS, SHARATH
}
class Test
{
public static void main(String args[])
{
SpecialStud s;
[Link]("All constants of enum type Students are:");
SpecialStud sArray[] = [Link]();
for(SpecailStud a : sArray) //using foreach loop
[Link](a);
s = [Link]("SUHAS");
[Link]("TALKITIVE BOY " + s);
}
}
Output:
All constants of enum type students are: ABI GAUTHAM NANDA SOURABH SUHAS SHARATH
TALKITIVE BOY SUHAS
JAVA ENUMERATIONS ARE CLASS TYPES
Enumeration with Constructor, instance variable and Method
Java Enumerations Are Class Type.
It is important to understand that each enum constant is an object of its enumeration type.
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
Example of Enumeration with Constructor, instance variable and Method
enum Apple2
{
Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15), Cortland(8);
// variable
int price;
// Constructor
Apple2(int p)
{
price = p;
}
//method
int getPrice()
{
return price;
}
}
public class EnumConstructor
{
public static void main(String[] args)
{
Apple2 ap;
// Display price of Winesap.
[Link]("Winesap costs " + [Link]() + " cents.\n");
[Link]([Link]);
// Display all apples and prices.
[Link]("All apple prices:");
for(Apple2 a : [Link]())
[Link](a + " costs " + [Link]() + " cents.");
}
}
Output
Winesap costs 15 cents.
9
All apple prices:
Jonathan costs 10 cents.
GoldenDel costs 9 cents.
RedDel costs 12 cents.
Winesap costs 15 cents.
Cortland costs 8 cents.
In this example as soon as we declare an enum variable(Apple2 ap ) the constructor is called once, and it
initializes value for every enumeration constant with values specified with them in parenthesis.
TYPE WRAPPERS
Java uses primitive data types such as int, double, float etc. to hold the basic data types for the sake of
performance.
Despite the performance benefits offered by the primitive data types, there are situations when you will
need an object representation of the primitive data type.
For example, many data structures in Java operate on objects. So you cannot use primitive data types with
those data structures.
To handle such type of situations, Java provides type Wrappers which provide classes that encapsulate a
primitive type within an object.
Character : It encapsulates primitive type char within object.
Character (char ch)
To obtain the char value contained in a Character object, call charValue( ), shown here:
char charValue( ): It returns the encapsulated character.
Boolean : It encapsulates primitive type boolean within object.
Boolean (boolean boolValue) : boolValue must be either true or false
Boolean(String boolString): if boolString contains the string ―true‖
(in uppercase or lowercase), then the new Boolean object will be true. Otherwise, it will be false.
Numeric type wrappers : It is the most commonly used type wrapper.
byte byteValue( )
double doubleValue( )
float floatValue( )
int intValue( )
long longValue( )
short shortValue( )
Example:
The following program demonstrates how to use a numeric type wrapper to encapsulate a value and then
extract that value.
class Wrap {
public static void main(String args[]) {
Integer iOb = new Integer(100);
int i = [Link]();
[Link](i + " " + iOb); // displays 100 100
}
}
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.
String Handling
The String Constructors
The String class supports several constructors. To create an empty String, you call the default
constructor. For example,
String s = new String();
To create a String initialized by an array of characters, use the constructor shown here:
String(char chars[ ])
Example:
char chars[] = { 'm', 'a', 'n' };
String s = new String(chars);
This constructor initializes s with the string ―man‖.
You can specify a subrange of a character array as an initializer using the following constructor:
String(char chars[ ], int startIndex, int numChars);
startIndex specifies the index at which the subrange begins, and numChars specifies the number of
characters to use.
Example:
char chars[] = { 'h', 'e', 'l', 'l', 'o' };
String s = new String(chars, 2, 3);
This initializes s with the characters llo.
You can construct a String object that contains the same character sequence as another String object
using this constructor:
String(String strObj)
Example:
class MakeString {
public static void main(String args[]) {
char c[] = {'r', 'a', 'm', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
[Link](s1);
[Link](s2);
}
}
Output:
rama
rama
Even though Java‘s char type uses 16 bits to represent the basic Unicode character set, the typical format for
strings on the Internet uses arrays of 8-bit bytes constructed from the ASCII character set.
The byte formats are Their forms are shown here: String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int numChars)
Example:
class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
[Link](s1);
String s2 = new String(ascii, 2, 3);
[Link](s2);
}
}
Output ABCDEF
CDE
String Constructors Added by J2SE 5
J2SE 5 added two constructors to String. The first supports the extended Unicode character set and is
shown here:
String(int codePoints[ ], int startIndex, int numChars);
String Length
The length of a string is the number of characters that it contains. To obtain this value, call the length( )
method, shown here:
int length( );
Example:
char chars[] = {‗k‘, ‗r‘, ‗i‘, ‗s‘, ‗h‘};
String s = new String(chars);
[Link]([Link]());// displays 5
String Concatenation
Java does not allow operators to be applied to String objects.
The one exception to this rule is the + operator, which concatenates two strings, producing a String object
Example:
String marks = "35";
String s = "He scored " + marks+ " in internals.";
[Link](s);// He scored 35 in internals
Character Extraction
charAt( ):
To extract a single character from a String, you can refer directly to an individual character via the
charAt( ) method. It has this general form:
char charAt(int where);
Example:
char ch;
ch = "abc".charAt(1);// ch contains b
getChars( )
If you need to extract more than one character at a time, you can use the getChars( )
method. It has this general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
Example:
String s = "Abhimanyu is a good cricket player"; int start = 16;
int end = 20;
char buf[] = new char[end - start];
[Link](start, end, buf, 0);
[Link](buf);
Output:
Good
getBytes( )
There is an alternative to getChars( ) that stores the characters in an array of bytes. This method is called
getBytes( ), and it uses the default character-to-byte conversions provided by the platform.
Here is its simplest form:
byte[ ] getBytes( )
toCharArray( )
If you want to convert all the characters in a String object into a character array, the easiest way is to call
toCharArray( ). It returns an array of characters for the entire string. It has this general form:
char[ ] toCharArray( )
String Comparison
equals( ) and equalsIgnoreCase( )
To compare two strings for equality, use equals( ). It has this general form: boolean equals(Object str)
To perform a comparison that ignores case differences, call equalsIgnoreCase( ). It has this general form:
boolean equalsIgnoreCase(String str)
Example:
class equalsDemo {
public static void main(String args[])
{ String s1 = "Sourabh";
String s2 = "Sourabh"; String s3 = "Nikil";
String s4 = "SOURABH";
[Link](s1 + " equals " + s2 + " -> " + [Link](s2));
[Link](s1 + " equals " + s3 + " -> " + [Link](s3));
[Link](s1 + " equals " + s4 + " -> " + [Link](s4));
[Link](s1 + " equalsIgnoreCase " + s4 + " -> " + [Link](s4));
}
}
regionMatches( )
The regionMatches( ) method compares a specific region inside a string with another specific region in
another string
Here are the general forms for these two methods:
boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numChars)
boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int numChars)
For both versions, startIndex specifies the index at which the region begins within the invoking String
object.
The index at which the comparison will start within str2 is specified by str2StartIndex
The length of the substring being compared is passed in numChars.
In the second version, if ignoreCase is true, the case of the characters is ignored.
startsWith( ) and endsWith( )
String defines two routines that are, more or less, specialized forms of
regionMatches( ).
The startsWith( ) method determines whether a given String begins with a specified string.
The endsWith( ) determines whether the String in question ends with a specified string. They have the
following general forms:
boolean startsWith(String str)
boolean endsWith(String str)
Example: "Nandasagar".endsWith("gar") and
"Nandasagar".startsWith("Nan") are both true.
A second form of startsWith( ), shown here, lets you specify a starting point: boolean startsWith(String str,
int startIndex);
"Nandasagar".startsWith("gar", 7) returns true.
equals( ) Versus ==
It is important to understand that the equals( ) method and the == operator perform two different
operations.
The equals( ) method compares the characters inside a String object
The == operator compares two object references to see whether they refer to the same instance.
Example:
String s1 = "Sunaina"; String s2 = new String(s1);
[Link](s1 + " equals " + s2 + " -> " + [Link](s2));// true
[Link](s1 + " == " + s2 + " -> " + (s1 == s2)); // false