Nothing Special   »   [go: up one dir, main page]

0% found this document useful (0 votes)
26 views67 pages

Unit-2 Java

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 67

Unit 2 Derived Syntactical Construct in Java

Constructors
❑ Constructors are used to assign initial values to instance variables of the class.
❑ A default constructor with no arguments will be called automatically by the
Java Virtual Machine (JVM).
❑ Constructor is always called by new operator.
❑ Constructors are declared just like as we declare methods
❑ The constructors don’t have any return type, not even void because they return
the instance of the class itself.
❑ Constructors have the same name as the class itself.
Constructors

Rules for creating Java constructor

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Note: We can use access modifiers while declaring a constructor. It controls the
object creation. In other words, we can have private, protected, public or default
constructor in Java.
Types of Constructor

Constructor

Default Parameterized Copy


Default Constructor

❑ When no constructor has been explicitly defined then java creates a default
constructor.
❑ Default constructor automatically initializes all instance variables to zero.

Syntax:
class classname
{
classname()
{
}
}
❑ Class name will be the same name of class in which constructor is declared.
Example of Default Constructor

class sample
{
int num;
sample()
{
num=10;
System.out.println(“Constructor OUTPUT

called”); Constructor called


}
public static void main(String[]
args)
{
sample s=new sample();
}
}
Parameterized Constructor

❑ Constructor is a special type of method.


❑ It accept argument.
❑ We require a constructor which assigns the different values to variable when
different objects are created.
❑ So we make some constructor which takes some argument whose value will be
assigned to variable.
❑ Constructors which have arguments are known as parameterized constructor.
Example of Parameterized Constructor

class Rectangle
{ int length;
int breadth;
Rectangle(int l, int b)
{ length = l;
breadth= b;
}
int area()
{ return (length * breadth); }
}
class ParameterizedConstructor
{
public static void main(String[] args)
{ Rectangle firstRect = new Rectangle(5,6);
Rectangle secondRect = new Rectangle(7,8);
System.out.println("Area of First Rectangle : " +firstRect.area());
System.out.println("Area of Second Rectangle : "+secondRect.area());
}
Copy Constructor

❑ A copy constructor is a special type of constructor that creates an object using another object of the
same Java class.
❑ It returns a duplicate copy of an existing object of the class.
public class Fruit fprice = fruit.fprice;
{ fname = fruit.fname;
private double fprice; }
private String fname; double showPrice()
//constructor to initialize roll number and name of the student {
Fruit(double fPrice, String fName) return fprice;
{ }
fprice = fPrice; String showName()
fname = fName; {
} return fname;
//creating a copy constructor }
Fruit(Fruit fruit) public static void main(String args[])
{ {
System.out.println("\nAfter invoking the Copy Constructor:\n"); Fruit f1 = new Fruit(399, "Ruby Roman Grapes");
System.out.println("Name of the first fruit: "+ f1.showName());
System.out.println("Price of the first fruit: "+ f1.showPrice());
Fruit f2 = new Fruit(f1);
System.out.println("Name of the second fruit: "+ f2.showName());
System.out.println("Price of the second fruit: "+ f2.showPrice()); }}
Difference between Constructor and Method

Sr.No Constructor Method


1 A constructor is used to A method is used to expose the behavior
initialize the state of an object of an object.

2 A constructor must not have a A method must have a return type.


return type.
3 The constructor is invoked The method is invoked explicitly
implicitly
4 The Java compiler provides a The method is not provided by the
default constructor if you don't compiler in any case.
have any constructor in a class.
5 The constructor name must be The method name may or may not be
same as the class name. same as the class name
Constructor Overloading

❑ Constructor overloading in java allows having more than one constructor inside
one Class.
❑ Constructor with same name and different arguments then it’s called constructor
overloading.
❑ Overload constructors - define multiple constructors which differ in number
and/or types of parameters.
Example of Constructor Overloading

class Student{
int id;
String name;
int age;
Student(int i,String n){
id = i;
name = n;
}
Student(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student s1 = new Student(111,“Vihan");
Student s2 = new Student(222,“Rudra",25);
s1.display();
s2.display(); } }
Nesting of Methods
❑ A method of a class can be called only be an object of that class using the dot operator.
❑ Exception to this is a method can be called by using only its name by another method of the same class.
❑ This is known as nesting of methods.
class Nesting
{ int m, n; constructor
Nesting (int x, int y)
{ m=x; n=y; }
int largest()
{ if (m >= n)
return (m);
Nesting of
else return(n); }
Methods
void display ()
{ int large = largest();
System.out.println(“Largest value = “ + large); } }
public void static main(String args[ ])
{ Nesting nest = new Nesting (50, 40);
nest.display();
}
This Keyword

❑ There can be a lot of usage of java this keyword.


❑ In java, this is a reference variable that refers to the current object.
❑ this can be used to refer current class instance variable.
❑ this can be used to invoke current class method (implicitly)
❑ this() can be used to invoke current class constructor.
❑ this can be passed as an argument in the method call.
❑ this can be passed as argument in the constructor call.
❑ this can be used to return the current class instance from the method.
this: to refer current class instance variable

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Note: 1.We are using this keyword to distinguish local variable and instance variable.
2. If local variables(formal arguments) and instance variables are different, there is no need to use this keyword
Command Line Argument

❑ When we provided the input at the time of execution, it is known as command line arguments.
❑ Command line arguments are parameters that are supplied to the application program at the
time of invoking it for execution.
❑ Args is declared as an array of strings. Any arguments provided in the command line are passed
to the array args as its elements.
❑ Example
class testarg
{ public static void main(String args[])
{ for(int i=0;i<args.length;i++)
{ System.out.println("Args[" + i + "] is " + args[i] );
}
}
Steps to run program Javac testarg
Java testarg C C++ Java
Output
Args[0] is C
Args[1] is C++
Args[2] is Java
Var args: Variable length arguments

❑ Variable argument in Java allows you to write more flexible methods which can accept as many
argument as you need.
❑ If we don't know how many argument we will have to pass in the method, var args is the better
approach.
❑ Var args is a helper syntax and it enables use of variable number of arguments in a method call.
❑ Syntax: type … variable Name.

class Example
{
void display(String... values)
{ System.out.println("display method invoked ");
for(String s:values)
{ System.out.println(s); } }
public static void main(String args[])
{ display(); //zero argument
display("hello"); //one argument
display("One","Two","Three","Four"); //four arguments } }
Garbage Collector

1. The memory to the object are dynamically allocated by using “new” operator.
2. Objects are destroyed and there memory release for later reallocation
3. In some language such as c++,dynamically allocated object must be manually
release by use of “delete” operator.
Java takes different approaches it handles the allocation of object automatically.
When no reference exits ,that object is assume to no longer needed and the memory
occupied by the object can be released.
There is no need to destroy the object explicitly.
Garbage Collector only occurs at irregular interval during the execution of program.
Garbage Collector

❑ When the object is not needed any more, the space occupied by such objects can be collected
and use for later reallocation.
❑ Java performs release of memory occupied by unused objects automatically, it is called garbage
collection.
❑ JVM runs the garbage collector (gc) when it finds time. Garbage collector will be run
periodically but you can not define when it should be called. We can not even predict when this
method will be executed.
❑ It will get executed when the garbage collector, which runs on its own, picks up the object.
class X
{ int a; X() { a=0; } }
class Y
{ public static void main(String args[])
{ X ob1 = new X();
X ob2 = new X(); Ob1 = ob2; } }
Two objects are created which are referenced by ob1 and ob2
Garbage Collector

Both ob1 and ob2 points to the same object.


Here the object which was previously pointed by the ob1 is not having any reference to point it.
So it will be now candidate for garbage collector.
A garbage collector can be invoked explicitly by writing statement.
System.gc();
Advantages of Garbage Collection
1. Garbage Collection eliminates the need for the programmer to deallocate memory blocks
explicitly.
2. Garbage collection helps ensure program integrity.
3. Garbage collection can also dramatically simplify programs.
Disadvantages of Garbage Collection:
1. Garbage collection adds an overhead that can affect program performance.
2. Garbage Collection requires extra memory.
3. Programmers have less control over the scheduling of CPU time.
Finalize Method

❑ The finalize() method of Object class is a method that the Garbage Collector always calls just
before the deletion/destroying the object which is eligible for Garbage Collection, so as to perform
clean-up activity.
❑ Since Object class contains the finalize method hence finalize method is available for every java
class
❑ Object is the superclass of all java classes. Since it is available for every java class hence Garbage
Collector can call the finalize method on any java object
Visibility Control in Java

Visibility Control

Private
Public Private Protected friendly
Protected

Java provides a number of access modifiers to set access levels classes, variables , methods and
constructors.

The access specifiers available in Java are

1. Public 2. Private 3. Protected 4. Friendly 5. Private Protected


Public access specifier

❑ Public modifier achieves the highest level of accessibility.


❑ A class, method, constructor, interface, etc. declared public can be accessed from any other class.
❑ Therefore, fields, methods, blocks declared inside a public class can be accessed from any class
belonging to the Java Universe.
❑ The most know public method in Java is the main function.
❑ Any variable or methods declared inside the class is visible to the entire class.
❑ To make variable and method is visible to all the classes outside this class by declaring the
variables or methods as public.
Private Access Specifier

► Private fields enjoy the highest degree of protection.


► Methods, variables, and constructors that are declared private can only be accessed within the
declared class itself.
► They are accessible only with their own class.
► They cannot be inherited by sub classes and therefore not accessible in sub classes.
► A method declared as private behaves like a method declared as final.
It prevents the method from being sub classes.
Private Access specifier example

class A
{
private int data = 40;
private void msg()
{ System.out.println(“Hello Java”);} }
class Test
{
public static void main(String args[])
{
A obj=new A();
system.out.println(“Data is :”+obj.data); //Compile Time Error
Obj.msg(); //Compile Time Error
}
}
Friendly access specifier
❑ When no access modifier is specified
❑ The member defaults to a limited version of public accessibility known as “friendly” level of access.
❑ The difference between the public access and friendly access is that the public modifier makes
fields visible in all classes, regardless of their packages while the friendly access makes fields
visible only in the same package, but not in other packages.
class BaseClass
{ void display()
{ System.out.println("BaseClass::Display with 'dafault' scope"); } }
class Main
{ public static void main(String args[]) { //access class with default scope BaseClass obj = new
BaseClass();
obj.display();
}
}
Protected & Private Protected

The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't
be applied on the class.
It provides more accessibility than the default modifer.
Private Protected Access
► The visibility level lies between private and protected access.
► This modifier makes fields visible in all subclasses regardless of what package they are in.
► These fields are not accessible by other classes in the same package.
Array in Java

Arrays in Java are homogeneous data structures implemented in Java as objects.


Arrays store one or more values of a specific data type and provide indexed access to store the same.
A specific element in an array is accessed by its index.
Arrays offer a convenient means of grouping related information.
Obtaining an array is a two-step process.
1. First, you must declare a variable of the desired array type
2. Second, you must allocate the memory that will hold the array, using new, and assign it to the
array variable
One Dimensional Array

► A list of items can be given one variable name using only one subscript and such a variable is

called a single-subscripted variable or a one –dimensional array.


Creating an array
► Array must be declared and created in the computer memory before they are used.
► Creation of array involves three steps:
► declare the array ► create memory locations ► put values into the memory locations
Declaration of an Array Array can be declared in two forms Syntax:
1) Type arrayname [ ];
2) data type [ ]arrayname;
Example: int number [ ]; int [ ] numbers;
Creation of array

► After declaring the variable for the array, the array needs to be created in the memory.
► This can be done by using the new operator in the following way:
Arrayname = new type[size];
numbers = new int [10];
► This statement assigns ten contiguous memory locations of the type int to the variable numbers.
The array can store ten elements.
int number [] = new int[10];
Initialization of array

The final step is to put values into the array created.


This process is known as initialization .
Syntax: Arrayname[subscript] = value;
Example: number[0] = 50; number[1] = 60;
we can also initialize array automatically in the same way as ordinary variable when they are
declared.
type arrayname[] = { list of values};
int number[] = { 35,40,50,45,95 };
Array length

In java all array store the allocated size in a variable named length.
❑ We can access the length of the array using a.length
❑ int asize = a.length;

Program
class arraytest
{ public static void main(String args[])
{ int [] a1;
a1=new int[3];
a1[0]=11;
a1[1]=22;
a1[2]=33;
System.out.println("first element= "+a1[0]);
System.out.println("first element= "+a1[1]);
System.out.println("first element= "+a1[2]);
}
}
Two Dimensional Arrays

A two dimensional array can be thought of as a table of rows and columns


Syntax: data type [] [] variablename;
Example: int [] [] numbers;
To create the array in the memory, following statement can be use numbers = new int [3][3];
This will create two dimensional array of 9 elements – three rows and three columns.
String in Java

What is String in java ?


➢ String is a sequence of characters.
➢ But in Java, string is an object that represents a sequence of characters.
➢ The java.lang.String class is used to create a string object.

How to create a string object?


There are two ways to create String object:
1. By string literal
2. By new keyword
String Literal

Java String literal is created by using double quotes.

For Example:
String s="welcome";

Each time you create a string literal, the JVM checks the "string constant pool" first.
If the string already exists in the pool, a reference to the pooled instance is returned.
If the string doesn't exist in the pool, a new string instance is created and placed in the pool.

For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
By new keyword
String s=new String("Welcome");

public class StringExample{


public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Important operations of Strings

► String Concatenation
► String Comparison
► Substring
► Length of string and etc.

String Concatenation
There are two methods to concatenate two or more strings.
Concatenate two or more strings
1. Using concate() method
2. Using + Operator
String Concatenation Example

Public class stringexample


{ public static void main(String args[])
{ String s = “Hello”;
String str = “World”;
String str1 = s.concat(str);
String str2 = “Hello”.concat(“World”);
String str3 = s + str;
String str4 = “Hello” + ”World”;
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
}}
String Comparison

String Comparison is done using 3 methods:

1.Using equals() method


2.Using == Operators Using compareTo() method
3. Using CompareTo method
class stringexample
{ String s = “Hi”;
String s1 = “Hello”;
String s2 = “Hello”;
String s3 = “Java”;
System.out.println(s1.equals(s2)); //true
System.out.println(s.equals(s1)); //false
String s4 = new String(“Java”) ;
System.out.println(s1==s2); //true
System.out.println(s3==s4); //false
System.out.println(s.compareTo(s2)); //returns-1 because s<s2
System.out.println(s1.compareTo(s2)); //returns 0 because s1=s2
System.out.println(s2.compareTo(s)); //returns 1 because s2>s }
}
Substring in Java

A part of String is called substring.


In other words, substring is a subset of another string.
We can get substring from the given string object by one of the two methods:
1. public String substring(int startindex);
2. public String substring(int startindex, int endIndex);
Example:
public class StringExample
{ public static void main(String args[])
{ String s = “Hello World”;
System.out.println(s.substring(6));
System.out.println(s.substring(0,5));
}}
Length of String

The java string length() method find the length of the string.
It returns the count of total number of characters.
Example:
public class lengthexample
{ public static void main(String args[])
{ String s1 = “Hello World”;
System.out.println(“String length is:” + s1.length());
}
}
More Methods on String

1)charAt()
2)contains()
3)getChars()
4)indexOf()
5)replace()
6)toLowerCase()
7)toUpperCase
charAt() and contains()

► charAt(): Returns a char value at the given index number.


The index number starts from 0.
► Contains(): searches the sequence of characters in this string.
It returns true if sequence of char values are found in this string otherwise returns false.
Example:
class method
{ public static void main(String args[])
String name=“Hello World!”;
char ch=name.charAt(4);
System.out.println(ch);
System.out.println(name.contains(“Hello”));
System.out.println(name.contains(“hello”));
}
}
indexOf()

► Return index of given character value or substring.


► If it is not found it returns -1. the index count starts from 0.
Example:
Class methods
{ Public static void main(String args[])
{ String s1=“Hello World”;
int index1 = s1.indexOf(‘o’);
System.out.println(index1);
int index2 = s1.indexOf(‘l’,4);
System.out.println(index2);
}
}
replace()

► Returns a string replacing all the old char to new char.


Example:
class Methods
{ public static void main(String args[])
{ String s1 = “Computer”;
String s2 = s1.replace(‘o’,’e’);
System.out.println(s2);
}
}
toLowerCase() and toUpperCase()

► toLowerCase(): it converts all the characters of the string into lowercase letter.
► toUpperCase(): it converts all the characters of the string into uppercase letter.
Example:
class methods
{ public static void main(String args[])
{ String s1 = “Hello World”;
String lowercase = s1.toLowerCase();
System.out.println(lowercase);
String uppercase = s1.toUpperCase();
System.out.println(uppercase);
}
}
Immutable String in Java

In java, string objects are immutable.


❑ Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
Output:
Sachin
Immutable String in Java

class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
StringBuffer Class

The StringBuffer class is used to represent characters that can be modified.


This is simply used for concatenation or manipulation of the strings.
We can insert characters and substring in the middle of a string or append another string to the
end.
Methods of StringBuffer class:
1) append()
2) insert()
3) delete()
4) deleteCharAt()
5) reverse()
6) setChartAt()

In java strings are class objects and implemented using two classes namely, String and StringBuffer.
append()

Appends the string s2 to s1 at the end.

Example:
Class a
{ public static void main(String args[])
{ StringBuffer s1 = new StringBuffer(“Welcome");
StringBuffer s2 = new StringBuffer(“ GHRIET");
s1.append(s2);
System.out.println(s1);
}
}
Insert()

It insert the string at the given position.

Example:
Class a
{ public static void main(String args[])
{ StringBuffer s1 = new StringBuffer(“Welcome");
StringBuffer s2 = new StringBuffer(“ World");
S1.insert(3,s2);
System.out.println(s1);
}
}
delete()

This is the delete() function is used to delete multiple character at once from n
position to m position (n and m are will be fixed by you.) in the buffered string.

Example:
Class a
{ public static void main(String args[])
{
StringBuffer s1 = new StringBuffer(“College");
s1.delete(1,3);
System.out.println(s1);
}
}
deleteCharAt()

This is the deleteCharAt() function which is used to delete the specific character
from the buffered string by mentioning that's position in the string.

Example:
class a
{ public static void main(String args[])
{ StringBuffer s1 = new StringBuffer(“Morning");
s1.deleteCharAt(2);
System.out.println(s1);
}
}
reverse()

This is the reverse() function used to reverse the string present in string buffer.

Example:
Class a
{
public static void main(String args[])
{ StringBuffer s1 = new StringBuffer(“GHRIET");
s1.reverse();
System.out.println(s1);
}
}
setCharAt()

It modifies the character at the specified position by the given character.

Example:
Class a
{
public static void main(String args[])
{
StringBuffer s1 = new StringBuffer(“College");
s1.setCharAt(3,’e’);
System.out.println(s1);
}
}
Vector

❑ Vector class is in java.util package of java.


❑ Vector is dynamic array which can grow automatically according to the requirement.
❑ Vector does not require any fix dimension like String array and int array.
❑ Vectors are used to store objects that do not have to be homogeneous.
Declaring Vector

❑ Vectors are created like arrays.


❑ Vector can be created using constructor of Vector class.
❑ Vector cannot directly store simple data types, so objects are created to store in a Vector class.
❑ The objects stored in Vector can be retrieved using an index value.

Vector class defines three different constructors:

1) Vector list = new Vector();


This constructor creates a default vector, which has an initial size of 10.
2) Vector list = new Vector(int size);
This constructor accepts an argument that equals to the required size, and creates a vector whose
initial capacity is specified by size.
3) Vector list = new Vector(int size, int incr);
create vector with initial size and whenever it need to grows; it grows by value specified by
increment capacity. If Vector has to grow and increment is not specified, Vector doubles its capacity
when it grows.
Java Vector Example

import java.util.*;
public class VectorExample {
public static void main(String args[]) {
//Create a vector
Vector<String> vec = new Vector<String>();
//Adding elements using add() method of List
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
//Adding elements using addElement() method of Vector
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");

System.out.println("Elements are: "+vec);


}
}
Methods of Vector Class
Methods Task performed

firstElement() It returns the first element of the vector.


lastElement() It returns last element.
addElement(item) Adds the item specified to the list at the end.
elementAt(int index) Gives the name of the object present at index position.
size() Gives the number of objects present
setSize(int newSize) Sets the size of this vector.
Set(int index, object element) Replaces the element at the specified position in the
vector with the specified element
capacity() Returns the current capacity of this vector
Boolean Contains(object elem) Tests if the specified object is a component in the vector
clear() Removes all of the elements from this vector
remove(int index) Removes the element at the specified position in this
vector
Example of Vector
import java.util.*;
import java.io.*;
class RemovingElementsFromVector {
public static void main(String[] arg)
{
// create default vector of capacity 10
Vector v = new Vector();
// Add elements using add() method
v.add(1);
v.add(2);
v.add(“Computer");
v.add(“Engg.");
v.add(4);
// removing first occurrence element at 1
v.remove(1);
// checking vector
System.out.println("after removal: " + v);
}
}
Wrapper class
❑ A Wrapper class is a class which contains the primitive data types (int, char, short, byte, etc).
❑ Wrapper classes provide a way to use primitive data types (int, char, short, byte, etc) as objects.
These wrapper classes come under java.util package.

Why we need Wrapper Class


❑ Wrapper Class will convert primitive data types into objects.
❑ The objects are necessary if we wish to modify the arguments passed into the method (because
primitive types are passed by value).
❑ The classes in java.util package handles only objects and hence wrapper classes help in this case
also.
❑ Data structures in the Collection framework such as ArrayList and Vector store only the objects
(reference types) and not the primitive types.
❑ The object is needed to support synchronization in multithreading.
8 primitive types has corresponding wrapper classes.

Primitive Type Wrapper Class

byte Byte

boolean Boolean

char Character

double Double

float Float

int Integer

long Long

short Short
Autoboxing

❑ The automatic conversion of primitive data type into its corresponding wrapper class is known as
autoboxing
❑ Example, byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to
Boolean, double to Double, and short to Short.

//Java program to convert primitive into objects


//Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}
}
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing.
It is the reverse process of autoboxing.
Since Java 5, we do not need to use the intValue() method of wrapper classes to convert the
wrapper type into primitives.

Wrapper class Example: Wrapper to Primitive

//Java program to convert object into primitives


//Unboxing example of Integer to int
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
}}
Java Enums

❑ The Enum in Java is a data type which contains a 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),
season (SPRING, SUMMER, WINTER, and AUTUMN or FALL), colors (RED, YELLOW,
BLUE, GREEN, WHITE, and BLACK) etc. According to the Java naming conventions, we
should have all constants in capital letters. So, we have enum constants in capital letters.
❑ Enums are used to create our own data type like classes.
❑ The enum data type (also known as Enumerated Data Type) is used to define an enum in
Java.
❑ Unlike C/C++, enum in Java is more powerful. Here, we can define an enum either inside the
class or outside the class.
Simple Example of Java Enum

class EnumExample1{
//defining the enum inside the class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//main method
public static void main(String[] args) {
//traversing the enum
for (Season s : Season.values())
System.out.println(s);
}}
values(), valueOf(), and ordinal() methods of Java enum.

class EnumExample1{
//defining enum within class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//creating the main method
public static void main(String[] args) {
//printing all enum
for (Season s : Season.values()){
System.out.println(s);
}
System.out.println("Value of WINTER is: "+Season.valueOf("WINTER"));
System.out.println("Index of WINTER is: "+Season.valueOf("WINTER").ordinal());
System.out.println("Index of SUMMER is: "+Season.valueOf("SUMMER").ordinal());
}
}

You might also like