You are on page 1of 65

Chapter 2

Derived Syntactical Constructs in


Java
Marks-18
Constructors
• Objects once created must be given some initial
values.
• It is easy and simple to initialize an object when it is
created using constructor
• A constructor initializes an object immediately upon
creation.
• It has the same name as the class in which it is
defined.
• Constructor is automatically called immediately
after the object is created and before the new
operator completes.
• Constructors have no return type, not even void.
The implicit return type of a constructor is the class
type itself.
Constructors
• Syntax: classname (parameter-list)
{
//body of the constructor
}

• Types of Constructor:
1) Default Constructor
2) Parameterized Constructor
3) Copy Constructor
• Constructor without parameter is known as default
constructor.
• Constructor with parameter is known as
parameterized constructor
• Constructor with object as parameter is known as
copy constructor.
Constructors
• For example:
class Student
{
int rollno;
String name;
Student () //default constructor
{
rollno =10;
name =“xyz”;
}
}
Parameterized Constructors
• Constructor which takes some arguments then it
is called as parameterized constructor.
• For example:
class Student
{
int rollno;
String name;
Student (int r, String n) //parameterized constructor
{
rollno =r;
name =n;
}
}
Copy Constructors
• Constructor which takes object as parameter.
• It is special form of parameterized constructor.
• For example:
class Student
{
int rollno;
String name;
Student (int r, String n) //parameterized constructor
{
rollno =r;
name =n;
}
Student (Student s) //copy constructor
{
rollno =s.rollno;
name =s.name;
}
}
Constructor Overloading
• Overloading refers to the • For example:
use of same name for class Student
different purposes. {
int rollno;
String name;
• A class can have more
Student (int r, String n) //parameterized
than one constructor but {
with different rollno =r;
parameters. This is name =n;
known as constructor }
overloading. Student (Student s) //copy
{
rollno =s.rollno;
name =s.name;
}

}
• For example:
Nesting of Methods class NestMethod
{ int len,bre;
• When a NestMethod(int l, int b)
{
method calls len=l;
another bre=b;
}
method in the void display()
same class, it {
System.out.println(“Length:"+len);
is called System.out.println(“Breadth:"+bre);
}
Nesting of void perimeter()
methods. {
display(); //nested call
int pr = 2 * (len+ bre);

System.out.println("Perimeter:"+pr);

}
}
‘this’ keyword
• To refer to own or current object in a method or a
constructor, Java defines the ‘this’ keyword.
• Uses of this keyword:
1. ‘this’ can be used inside any method to refer to the
current object.
2. ‘this’ to resolve instance variable hiding
3. ‘this’ to call one constructor from another constructor
Uses of ‘this’ keyword
1) ‘this’ can be used 2) ‘this’ to resolve instance
inside any method to variable hiding
refer to the current When a local variable has
object. the same name as an
instance variable, the local
Box(double w, double h) variable hides the instance
{ variable.
this. width = w; Box(double width, double
height)
this. height = h;
{
}
this. width = width;
this. height = height;
}
Uses of ‘this’ keyword
3) ‘this’ to call one constructor from another
constructor within a class
class Student
{
int roll,marks; String name;
Student () //constructor1
{
roll=1;
name=“xyz”;
}
Student(int m) //constructor2
{
this();
marks = m;
}
}
Methods overloading
• defining two or more methods within the
same class that are having the same name,
but with different parameter
• implementation of compile time
polymorphism.
• Java uses the type and/or number of
arguments to determine which version of the
overloaded method to actually call.
Methods overloading
class Area class Shape
{ {
int area(int side) public static void main(String args[])
{ {
Area s = new Area();
return(side * side);
}
int x=s.area(10);
float area(float radius)
System.out.println ("Area of square : "+x);
{
return(3.14f * radius * radius); int y=s.area(10,20);
} System.out.println ("Area of rect: "+y);
int area(int len, int wid)
{ float z = s.area(5.5f);
return(len * wid); System.out.println ("Area of circle : "+z);
} }
} }
Command line argument
• Sometimes we need to pass information into a program
when we run it. This is accomplished by
passing command-line arguments to main( ).
• Command-line argument is the information that directly
follows the program’s name on the command line when
it is executed.
• Can be used to specify configuration information while
launching application.
• There is no restriction on the number of java command
line arguments. We can specify any number of
arguments
• Information is passed as Strings.
• They are captured into the String args of your main
method
Command line argument
• The first command-line argument is stored at args[0],
the second at args[1], and so on
• For Example:
class CommandLine
{
public static void main(String args[])
{
for (int i = 0; i < args.length; i++)
{
System.out.println(args[i]);
}
}
}
Varargs: Variable-Length Arguments
• It simplifies the creation of methods that need to take a
variable number of arguments. This feature is called
varargs and it is short-form for variable-length
arguments.
• A method that takes a variable number of arguments is a
varargs method.
• A variable-length argument is specified by three
periods(…).
• Syntax of varargs :
public static void fun(int ... a)
{
// method body
}
Varargs: Variable-Length Arguments
• Rules for varargs:
1. There can be only one variable argument in the
method.
2. Variable argument (varargs) must be the last
argument.

• Foll. Methods will give compile time errors


– void method(String... a, int... b){}//Compile time error
– void method(int... a, String b){}//Compile time error
Varargs: Variable-Length Arguments
• Example:
class VarargsEx
{
void display(String... values)
{
System.out.println("Number of arguments: " + values.length);
for(String s:values)
{ System.out.println(s);
}
}
public static void main(String args[])
{ VarargsEx v=new VarargsEx();
v.display();//zero argument
v.display("hello");//one argument
v.display("my","name","is","varargs");//four arguments
}
}
Garbage Collection
• garbage means unreferenced objects.
• Garbage Collection is process of reclaiming the runtime
unused memory automatically.
• It is a way to destroy the unused objects.
• To destroy unused object, we were using free() function in C
language and delete() and destructor() in C++. But, in java it is
performed automatically. So, java provides better memory
management.
• In Java, the programmer need not to care for all those objects
which are no longer in use. The garbage collector finds these
unused objects and deletes them to free up memory.
• We can also request JVM to run Garbage Collector. There are
two ways to do it :
– Using System.gc() method
– Using Runtime.getRuntime().gc() method
Garbage Collection
• Garbage Collector is one of the module of JVM.
• Main objective of Garbage Collector is to free heap memory
by destroying unreachable objects. Unreachable object
doesn’t contain any reference to it.
• Object can be unreferenced in 3 ways :
1. By nulling the reference
Employee e=new Employee();
e=null;
2. By assigning a reference to another
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//e1 is available for garbage collection
3. By anonymous object
new Employee();
finalize() method
• The finalize() method is invoked each time before destroying
an object.
• finalize() method is defined in Object class.
• calls finalize() method on the object to perform cleanup
activities.
• Once finalize() method completes, Garbage Collector destroys
that object.
• The finalize() method called by Garbage Collector not JVM.
• Syntax:
protected void finalize()
{
}
Object class
• Defined in java.lang package
• It is the parent class of all the classes in java by
default.
• It is beneficial if we want to refer any object whose
type we don't know.
• Declaration for Object class foll. constructor is used −
Object()
• Methods of Object class

Method Description

returns the Class class object of this object. The


public final Class getClass() Class class can further be used to get the
metadata of this class.
public int hashCode() returns the hashcode number for this object.
Object class
public boolean equals(Object
compares the given object to this object.
obj)
protected Object clone()
throws creates and returns the exact copy (clone) of
CloneNotSupportedExceptio this object.
n
public String toString() returns the string representation of this object.
wakes up single thread, waiting on this object's
public final void notify()
monitor.
wakes up all the threads, waiting on this
public final void notifyAll()
object's monitor.
causes the current thread to wait, until another
public final void wait()throws
thread notifies (invokes notify() or notifyAll()
InterruptedException
method).
protected void invoked by the garbage collector before object
finalize()throws Throwable is being garbage collected.
Visibility Control
• Visibility modifiers also known as access modifiers
• Used to restrict the scope of a class, constructor ,
variable , method or data member.
• Java provides a number of access modifiers to set
access levels for classes, variables, methods, and
constructors.
• There are four types of access modifiers available in
java:
1. Default – No keyword required
2. Private
3. Protected
4. Public
Visibility Control
1. default:
• When no access modifier is specified for a class ,
method or data member – It is said to be having the
default access modifier by default.
• accessible only within the same package.
• Also known as package access or friendly access
• For example,
int val;
void display();
Visibility Control
2. public
• specified using the keyword public.
• The public access modifier has the widest scope
among all other access modifiers.
• accessible from every where in the program. There
is no restriction on the scope of a public data
members.
• For example,
public int val;
public void display();
Visibility Control
3. private
• specified using the keyword private.
• The methods or data members declared as private
are accessible only within the class in which they are
declared.
• Any other class of same package will not be able to
access these members.
• For example,
private int val;
private void display();
Visibility Control
4. protected
• specified using the keyword protected
• The methods or data members declared as protected
are accessible within same package or sub classes in
different package.
• For example,
protected int val;
protected void display();
5. private protected access
• This modifier makes the fields visible in all subclasses
regardless of package.
• For example: private protected int val;
• private protected void display();
Visibility Control

Access Modifier
Public Protected Default Private
Access Location

Same Class Yes Yes Yes Yes

Subclass in same
Yes Yes Yes No
package

Non Subclasses in same


Yes Yes Yes No
package

Subclass in other
Yes Yes No No
package

Non Subclasses in other


Yes No No No
package
Arrays
• Array is a collection of similar type of elements
that have contiguous memory location.
• Array provides a convenient means of grouping
related information.
• We can store only fixed elements in an array.
• Array is index based, first element of the array is
stored at 0 index.
• Advantages of Arrays:
1. An array supports efficient random access to the
members.
2. It is easy to sort an array.
3. They are more appropriate for storing fixed number of
elements
• Disadvantages of Arrays:
1. Insertion and Deletion operation is difficult.
2. Size of array is fixed.
3. Dynamic creation of arrays is not possible.
4. Multiple data types cannot be stored.
• Types of Arrays:
• One dimensional array
• Two dimensional array or Multidimensional array
One Dimensional Array
• A list of items are given in one variable name
using only one subscript.
• Syntax to Declare an Array in java
dataType[ ] arrayVar; (or)
dataType [ ]arrayVar; (or)
dataType arrayVar[ ];

• Instantiation of an Array in java


– arrayVar=new datatype[size];
Example of one dimensional array
class A
{
public static void main(String args[])
{
int a[]=new int[5]; //declaration and instantiation
a[0]=10; //initialization
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;
//printing array
for(int i=0; i<a.length; i++) //length is the property of array
System.out.println(a[i]);
}
}
Array initialization
• Putting the values inside the array is called as array
initialization.
• Two ways:
1. Direct Initialization:
– We can declare, instantiate and initialize the java array
in single statement together.
– Syntax: datatype arrayname[ ] = {list of values
separated by
commas};
– For Ex: int num[ ] = { 45, 12, 56, 10, 20, 86, 19, 46, 30 } ;
Array initialization
2. Initialization using index:
– Individual elements can be initialized as
arrayname[index] = value;
– For example:
val [0] = 36;
val [1] = 26;
val [2] = 78;
val [3] = 3;
val [4] = 95;
Array length
• All arrays store the allocated size in an attribute named
length.
• size or length or number of elements of the array can be
obtained using attribute ‘length’.
• Syntax:
arrayname.length;
• For example:
int arr[ ] = {8, 6, 2, 4, 9, 3, 1};
int size = arr.length;
Two dimensional array
• Sometimes it is required to manipulate the data in table
format or in matrix format
• In these cases, we have to give two dimensions to the array.
• Syntax:
datatype arrayname[ ][ ] = new datatype[row][column];
• For example:
• int table[ ][ ] = new int[3][3]; //3 rows and 3 columns

• We can also initialize array at compile time.


int table[][] = {{1,2,3},{4,5,6},{7,8,9}};
String class
• String is a sequence of characters
• defined in the java.lang package
• When creating a String object, we are creating a string
that cannot be changed. That is Strings are immutable.
• For mutable Strings, use the StringBuffer class
• It is not NULL terminated.
• Creating strings: two ways:
1) Direct initialization:
String s=“Hello”;
2)Using constructor
2)Using constructor
i)String() - creates empty string
ex: String str=new String();

ii)String (char ch[]) - Initializes a new String from the given Character array.
ex: char ch[]={‘j’,’a’,’v’,’a’};
String s1=new String(ch);

iii)String (char ch[],int startindex,int n) –Initialized with ‘n’ no. of characters from
a given character array started from the start_index.
ex: char ch[]={‘J’,’a’,’v’,’a’};
String s1=new String(ch,2,2);

iv)Sring(StringBuffer buffer) -Initializes a new string from the string in buffer.


ex: StringBuffer buffer = new StringBuffer(“Java");
String s = new String(buffer);

v) Sring(String s) :-Initializes a new string from the string


ex: String s= new String(“Java");
String Methods
1) length() - Returns the number of characters in the
string.
• Syntax: int length()
• Example: String s = “abc”;
int len = s.length();
2) charAt()- Returns the char at specified position .
• Syntax: char charAt(int index)
• For Example: String s = “Indian”;
char ch = s.charAt(2); //ch will be ‘d’
String Methods
3) concat( ) -This is used to join two strings.
• Syntax: String concat(String str)
• Example:
String s1 = “First”;
String s2 = “Second”;
String s3=s1.concat (s2); //string ‘s3’ will be “FirstSecond”
• The operator + can also be used to join two strings together.
• For example:
String x = “Number = ” + 2;

4) toCharArray()- It converts all the characters of the string into the


character array.
• Syntax: char[ ] toCharArray( )
• For example , String s = “Programming”;
• char ch[ ] = s.toCharArray();
String Methods
5) equals() -Used to check two strings for equality and returns the
boolean value true if they are equal else false.
• The equals( ) is case sensitive.
• Syntax: boolean equals(String str)
• Example: String a = “Hello”;
String b = “HELLO”;
boolean res=a. equals(b); //false

6)equalsIgnoreCase()
• It is used to check two strings for equality and returns the boolean
value true if they are equal else false.
• The equalsIgnoreCase( ) is not case sensitive method.
• Syntax: boolean equalsIgnoreCase(String str)
• Example: String a = “Hello”;
String b = “HELLO”;
boolean res=a. equalsIgnoreCase(b) ; //true
String Methods
7) compareTo( ) and compareToIgnoreCase( )
• used to check whether one string is greater than, less than or equal to
another string or not.
• returns the “difference” string1 and string2
• compareTo( ) is case-sensitive and compareToIgnoreCase( ) is case
insensitive.
• Syntax: int compareTo(String str)
int compareToIgnoreCase(String str)
• It will return

value < then invoking string is Example:


0 less than str String str1 = “catch”;
String str2 = “match”;
value > then invoking string is if(str1.compareTo(str2)<0) //true
0 greater than str System.out.println(“str2 is greater”);
value = then both the strings else
0 System.out.println(“str1 is greater”);
are equal
String Methods
8) indexOf() and lastIndexOf()
• Used to search a particular character or substring in the string .
• indexOf() method returns first occurrence of the character or
substring from the string.
• lastIndexOf() method returns last occurrence of the character or
substring from the string.
• Syntax:
int indexOf(char ch)
• Example:
int indexOf(String str)
String s = “Maharashtra”;
int indexOf(char ch, int startIndex)
int n = s.indexOf(‘a’);
int indexOf(String str, int startIndex)
//n will be 1
• Syntax:
int x = s.indexOf(“tra”);
int lastIndexOf(char ch) //x will be 8
int lastIndexOf(String str) int m = s.lastIndexOf(‘a’);
//m will be 10
String Methods
9) substring( )
• used to extract a substring from the string.
• Syntax:
– String substring(int start)
– String substring(int start, int end)
• For ex: String str = “Are you a Marathi guy”;
• String s = s.substring (10); //s will be “Marathi guy”

10) replace( )
• used to replace all the occurrences of a character with another
character
• Syntax: String replace(char original, char replacement)
• For ex: String s = “mama”;
String s1=s.replace(‘m’,’k’);
String Methods
11) toLowerCase( ) and toUpperCase( )
• These methods will convert the strings into lower case and upper case
respectively
• Syntax:
String toLowerCase( )
String toUpperCase( )
• For ex: String str = “Solapur City”;
String t = str.toUpperCase();
String u = str.toLowerCase();
12) trim()
• removing white space at both ends
• does not affect whites space in the middle
• Example:
String s = “ What is this? “;
String k = s.trim();
StringBuffer class
• StringBuffers are mutable that is we can modify the
characters of the string.
• We can insert new characters, modify them delete them at any
location of string of can append another string to other end.
• So StringBuffer provides the flexible string.
• Constructors:
1. StringBuffer(): creates an empty string buffer with the initial
capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified
string and reserves room for 16 more characters without
reallocation.
3. StringBuffer(int capacity): creates an empty string buffer with
the specified capacity as length.
• For ex StringBuffer sb = new StringBuffer("India");
StringBuffer Methods
1) length( )
• Returns total number of characters stored in StringBuffer object
• Syntax: int length( )
• Example:
StringBuffer sb = new StringBuffer("India");
int len = sb.length());

2) capacity( )
• Returns total allocated capacity
• Syntax: int capacity( )
• Example:
StringBuffer sb = new StringBuffer("India");
int cap = sb.capacity());
• Here the variable cap will contain capacity 21 i.e. actual length +
additional room for 16 characters.
StringBuffer Methods
3) setLength( )
• used to set the length of the buffer.
• Syntax: void setLength(int len)
• Example:
StringBuffer sb=new StringBuffer(“Solapur”);
sb.setLength(3); // now sb object contains only 3 chars

4) setCharAt( )
• Used to set the character at certain index in the StringBuffer
• Syntax:
void setCharAt(int index, char ch)
• Example:
StringBuffer sb = new StringBuffer(“Kolkata”);
sb.setCharAt(0,‘C’);
• After execution of these statements, ‘sb’ will be “Colkata”.
StringBuffer Methods
5) append( )
• Used to concatenates any other type of data to the end of the invoking
StringBuffer object.
• Syntax: StringBuffer append(datatype var)
• Example:
StringBuffer sb = new StringBuffer(“Parle");
int x = 20;
StringBuffer a = sb.append(x); //a will be “Parle20”

6) insert( )
• used to insert one string, character or object into another string.
• Syntax:
• StringBuffer insert(int index, String str)
• StringBuffer insert(int index, char ch)
• Example:
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "love ");
• After this, the contents of ‘sb’ will be “I love Java!”
StringBuffer Methods
5) append( )
• Used to concatenates any other type of data to the end of the invoking
StringBuffer object.
• Syntax: StringBuffer append(datatype var)
• Example:
StringBuffer sb = new StringBuffer(“Parle");
int x = 20;
StringBuffer a = sb.append(x); //a will be “Parle20”

6) insert( )
• used to insert one string, character or object into another string.
• Syntax: StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
• Example:
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "love ");
• After this, the contents of ‘sb’ will be “I love Java!”
StringBuffer Methods
7) reverse( )
• To reverse the characters inside the StringBuffer
• Syntax: StringBuffer reverse()
• Example: StringBuffer s = new StringBuffer(“Yellow”);
s.reverse(); //s will be “wolleY”

8)delete() and deleteCharAt( )


• used to delete a single character or a sequence of characters
from the StringBuffer.
• Syntax:
• StringBuffer delete(int startIndex, int endIndex)
• StringBuffer deleteCharAt(int loc)
• Example:
StringBuffer sb = new StringBuffer("This is a test.");
sb.delete(4, 7); //sb will be “This a test”
Vector Class
• Vector implements a DYNAMIC ARRAY.
• grows or shrinks as required.
• Vector object is synchronized.
• Vectors can hold objects of any type and any number.
• Vector class is contained in java.util package
• Advantages of vector over arrays:
1. Vectors store objects.
2. used to store a list of objects that may vary in size.
3. We can add and delete objects from the list as when required.
4. The objects do not have to be homogeneous.
5. Vector implements dynamic array.
6. Dynamically grows or shrinks as required
• Disadvantages of vector :
1. A vector is an object, memory consumption is more.
Creation of Vector
Vector list = new Vector(); Creates a default vector, which has
an initial size 10.
Vector list = new Vector(int size);
Creates a vector, whose initial
capacity is specified by size.
Vector list = new Vector(int size, int incr);

Creates a vector, whose initial capacity is specified


by size and whose increment is specified by incr.

Vector v=new Vector (5);


Vector operations and methods
Method Description
Adds the item specified to the vector list at
the end.
void addElement(Object item)
Ex: v.addElement(10);
v.addElement(10.6);
Returns the object stored at specified index.
Object elementAt(int index)
Ex: Object ob=v.elementAt(4);

Returns the number of elements currently in


int size()
the vector. Ex: int s=v.size();

Returns the capacity of the vector.


int capacity()
Ex: int c=v.capacity();

void removeElement(Object Removes the specified item from the vector.


item) Ex: v.removeElement(10);

Removes the item stored at the specified


void removeElementAt(int
index position from the vector.
index)
Ex: v.removeElementAt(2);
Vector operations and methods
Remove all the elements from the vector.
void removeAllElements()
Ex: v.removeAllElement();
Copies all the elements from vector to
void copyInto(datatype array[]) array.
Ex: v.copyInto(array);
Inserts the element in vector at specified
void insertElementAt(Object item, int
index position.
index)
Ex: v.insertElementAt(20,2);
Returns the first element of the vector.
Object firstElement()
Ex: Object f=v.firstElement();

Returns the last element of the vector.


Object lastElement()
Ex: Object l=v.lastElement();
Returns true if the vector is empty, and
returns false if it contains one or more
boolean isEmpty()
elements.
Ex: boolean b=v.isEmpty();
Returns true if element is contained by the
boolean contains(Object item) vector, and returns false if it is not.
Ex: boolean b=v.contains(10);
Difference between Array and vector
Sr.
Array Vector
No.
Array is the static memory Vector is the dynamic memory
1
allocation allocation.
Array allocates the memory for Vector allocates the memory
2 the fixed size. dynamically means according to the
requirement.
3 wastage of memory, No wastage of memory.
4 Array is not synchronized Vector is synchronized.
5 Array cannot be re-sized Vector can be re-sized.
Array can store primitive data Vector stores objects.
6
types
Elements in the array cannot be Vector is efficient in insertion,
7 deleted. deletion and to increase the size.
Syntax : datatype[] arraname= Syntax:
8 new datatype[size]; Vector obj= new Vector();
Ex: int Ex: Vector v=new Vector();
9 num[]={10,20,30,40,50}; v.addElement(10);
Wrapper Class
• Primitive data types such as int,long,float, etc cannot hold
the objects of that type.
• Sometimes we need to convert these primitive types into
object and object into primitive type.
• Each of Java's 8 primitive data types has a class dedicated
to it, known as wrapper classes, because they "wrap" the
primitive data type into an object of that class.
• Defined in java.lang package
• Wrapper class also allows to convert object into primitive
type.
Wrapper Class

For ex:
int x = 25;
Integer y = new Integer(33);
Integer Wrapper Class
• An Integer object encapsulates a simple int value.
• Integer is a wrapper class for int.
• Constructors:
• Integer(int i) : constructs an Integer object equivalent to
the integer i . Eg: Integer it1=new Integer(25);
• Integer(String s) : constructs an Integer object equivalent
to the numeric string s. Eg: Integer it1=new Integer(“25”);
Integer Wrapper Class
• Methods of Integer Wrapper class:
static int parseInt(String s) Converts numeric string to signed
decimal int value
Ex: int a=Integer.parseInt(“25”);
static String toString(int i) Converts int value into a String object
Ex: String s=Integer.toString(25);
byte byteValue() Converts Integer object into primitive
type. These methods unwraps object.
short shortValue()
Integer it1=new Integer(25);
int intValue()
long l=it1.longValue();
long longValue() int i=it1.intValue()
float floatValue()

double doubleValue()
Integer Wrapper Class
• Methods of Integer Wrapper class:
static String toBinaryString(int Used to convert decimal into binary,
i) octal and hex respectively.
static String toOctalString(int i) Ex:
String s=Integer.toBinaryString(10);
static String toHexString(int i) String s=Integer.toOctalString(10);
String s=Integer.toHexString(10);

static Integer valueOf(String s, int Used to convert binary, octal and hex
base) into decimal.
Ex:
int dec=Integer.valueOf(“1010”,2);
int dec=Integer.valueOf(“10”,8);
int dec=Integer.valueOf(“a”,16);
Enumerated Types
• used to define collections constants
• To define enumerated types enum keyword is used.
• Syntax:
enum collectionname { list of elements separated by comma};

• It can be used in s
• witch.
• It can be traversed
• It can have fields, methods as well as constructors.
Enumerated Types
class EnumDemo
{ enum color{Red,Green,Black,Yellow,White}
public static void main(String args[])
{

for(color s:color.values())
{
System.out.println(s);
}
}
}

You might also like