0% found this document useful (0 votes)
20 views

Unit 1

Oops java unit 1

Uploaded by

23r11a05x8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Unit 1

Oops java unit 1

Uploaded by

23r11a05x8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 123

OBJECT ORIENTED PROGRAMMING

THROUGH JAVA

A.Sree Lakshmi
Professor & HOD,
Dept of CSE
Course Outcomes (COs):
After completion of the course, student would be able to
CO1: Use concepts of OOPs such as data abstraction, inheritance, polymorphism,
encapsulation and method overloading principles in structuring computer
applications for solving problems.
CO2: Identify classes, objects, members of a class and relationships among them
needed for a specific problem.
CO3: Use Java Collection of Application Programming Interface (API) as well as
the Java standard class library with necessary exception handling mechanisms in
constructing computer applications.
CO4: Develop java programs using multi-threading, files and database
concepts and their connectivity.
CO5: Design and develop Graphical User Interface applications using Abstract
Window Toolkit (AWT), Swings and Applets.
History of Java

The Java platform and language began as an internal project at Sun


Microsystems in December 1990, providing an alternative to the C++/C
programming languages. Engineer Patrick Naughton, James Gosling and
Mike Sheridan were attempting to develop a new platform independent
language that can be used to create software to be embedded in various
consumer electronic devices i.e. Programming for next generation smart
appliances (like microwave ovens, remote controls, set-top boxes), which Sun
expected to be a major new opportunity. It was called the Green project.

3
Year Progress

1990 Sun decided to developed software that could be used for


electronic devices. And the project called as Green Project
head by James Gosling.

1991 Announcement of a new language named ―Oak‖

1992 The team verified the application of their new language to


manage a list of home appliances using a hand held device.

1993 The WWW appeared on the Internet and transformed the


text-based interface to a graphical rich environment.

1994 The team developed a new Web browsed called ―Hot


Java‖ to locate and run Applets

1995 Oak was renamed to Java, as it did not survive ―legal‖


registration. Many companies such as Netscape and
4
Microsoft announced their support for Java.
Features of Java
1. Simple

2. Secure

3. Object Oriented

4. Robust

5. Platform Independent

6. Multi Threaded

7. Architectural Neutral

8. Portable

9. High Performance

10. Ease of Use 5


Java Features
1) Simple
Java is easy to learn and its syntax is quite simple, clean and easy to understand. The confusing and
ambiguous concepts of C++ are either left out in Java or they have been re-implemented in a
cleaner way.
Eg : Pointers and Operator Overloading are not there in java but were an important part of C++.
2) Secure
Java is very secure language . With java secure features it enable us to develop virus free, temper
free system. Java program always runs in Java runtime environment with almost null interaction
with system OS, hence it is more secure.
Java Security measures
a)) No use of pointers :-
C/C++ language uses pointers, which may cause unauthorized access to memory blocks when other
programs get the pointer values. Unlike conventional C/C++ language, Java never uses any kind of
pointers. Java has its internal mechanism for memory management. It only gives access to the data
to the program if has appropriate verified authorization.

6
Java Features
b)Exception handling concept: The concept of exception handling enables Java to capture
a series of errors that helps developers to get rid of risk of crashing the system.
c) Byte code is another thing that makes Java more secure:-
Every time when a user compiles the Java program, the Java compiler creates a class file
with Byte code, which are tested by the JVM at the time of program execution for viruses
and other malicious files
d)Garbage collection mechanism:-
Garbage collection(gc()) mechanism aids more to the security measures of Java. It provides
a transparent storage allocation and recovering unutilized memory rather than deallocating
memory through manual action. It will help developers to ensure the integrity of the
program during its execution and avoids any JVM crash due to incorrect freeing of
memory.

7
Java Features
4) Robust:-Java makes an effort to eliminate error level codes by highlight mainly on compile
time error checking and runtime checking. But the main areas which Java improved were
Memory Management and mishandled Exceptions by introducing automatic Garbage
Collector and Exception Handling.
5) Platform Independent:- All programming languages such as C, C++ etc which are
compiled into platform specific machines. Java is guaranteed to be write-once, run-anywhere
language.
 A Java program is compiled into byte code. This byte code is platform independent and can
be run on any machine, plus this byte code format also provide security. Any machine with Java
Runtime Environment can run Java Programs.
Java Features
6) Multi Threaded
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other resources to
execute multiple threads at the same time, like While typing, grammatical errors are checked
along.
7) Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a particular computer architecture,
hence a Java program is easy to interpret on any machine.
8) Portable
Java Byte code can be carried to any platform. Java code is compiled into intermediate format
(bytecode), which can be executed on any systems for which Java virtual machine is ported. That
means you can write a Java program once and run it on Windows, Mac, Linux or Solaris without
re-compiling. Thus the slogan “Write once, run anywhere” of Java.

9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language like C or C++.
9
But, Java enables high performance with the use of just-in-time compiler.
Interpreter Compiler

Translates program one statement at a Scans the entire program and


translates it as a whole into machine
time. code.

It takes less amount of time to analyze It takes large amount of time to


the source code but the overall analyze the source code but the
execution time is slower. overall execution time is
comparatively faster.

No intermediate object code is Generates intermediate object code


generated, hence are memory which further requires linking, hence
efficient. requires more memory.

Continues translating the program It generates the error message only


until the first error is met, in which after scanning the whole program.
case it stops. Hence debugging is Hence debugging is comparatively
easy. hard.

Programming language like Programming language like C, C++


HTML,JAVA Script , Python, Ruby use compilers. 10
use interpreters.
Is Java a Compiler or Interpreter based language??

 Java is both compiled and interpreted language. A java program is


first compiled into bytecode which JRE can understand. ByteCode is
then interpreted by the JVM making it as interpreted language
 When JVM interprets Java byte code, it also gathers useful statistics, like which
part of code is hot and always run. Once JVM has enough data to make such
decision, JIT can compile that part of code e.g. method or block into native code.
 This native code will then directly be executed by machine, without interpreting
by JVM
 In short, Java is both compiled and interpreted language. It compiles using javac
and JIT, and interprets using Java virtual machine.
Object-Oriented Programming Concepts

The concepts used in OOPs are

❖Classes

❖ Objects

❖ Abstraction

❖ Encapsulation

❖ Inheritance

❖Polymorphism
Procedure Oriented Programming/
Structured Programming
In structured programming , a complex programming is broken into sets of
smaller, understandable tasks, however the drawbacks of structured
programming soon became clear.
The data and task independently were too hard to maintain
Programmers were reinventing new solutions to old problems
As the length of the program increases , its complexity increases making
it difficult to maintain a very large program
The functions have unrestricted access to global data
They provide poor mapping to real world
Object Oriented Programming(OOP)
 This provides a technique for managing huge complexity , achieving
reuse of software components and coupling data with the tasks that
manipulate data
 OOP deals with things called objects.
 Objects are just extremely functional way of organizing information.
 In the complex real world we have objects which has some attributes
and behavior. WE deal with similar objects in OOP
 Objects are defined by their unique identity, state and behavior.
 The state of an object is identified by the value of its attributes and
behavior by methods
Object-Oriented Programming Concepts
Class:-
A class is a set of objects with similar properties (attributes), common
behavior (operations), and common link to other objects.
The complete set of data and code of an object can be made a user defined
data type with the help of class.
The objects are variable of type class. A class is a collection of objects of
similar type.
A class defines the structure and behavior that will be shared by a set of
objects. Once the class has been defined, we can make any number of objects
belonging to that class. Each object of a given class contains the structure and
behavior defined by the class.
The classification of objects into various classes is based on its properties
(States) and behavior (methods). The important thing about the class is to
identify the properties and procedures and applicability to its instances.
Object-Oriented Programming Concepts

 Object:- Objects are important runtime entities in object oriented


programming. It has components representing the present state of the object
as well as functions(methods) which describe the behavior of the object and
allow the other programming entities to interact with the object.
OOP Concepts

Abstraction:-
Abstraction is a process where you show only “relevant” data and “hide”
unnecessary details of an object from the user.
It refers to the act of representing important description without including the
background details or explanations.
Ex: person driving a car need not know the internal working of the car
OOP Concepts
Encapsulation:-
Data Encapsulation means wrapping of data and functions into a single unit (i.e. class). It is
most useful feature of class.
It provides us the power to restrict anyone from directly altering the data. An access to the data
has to be through the methods of the class. This insulation of data from direct access by the
program is called as Data hiding. It prevents users from seeing the internal working of an object.
Java basic unit of encapsulation is class. The code and data that constitute a class are called
members of the class. Specifically the data defined by the class are referred to as members
variables or instance variables. The code that operates on that data is referred to as member
methods.
Benefits of Encapsulation
Improves program readability
Reduces maintenance
Lends reusability
Facilitates information hiding
Improves modularity
Makes coding easier
OOP Concepts
 Inheritance: It is a way to adopt the characteristics of one class into another class,
called the child or derived class. When a class inherits another class, it has all the
properties of the base class and it adds some new properties of its own.
 The principle of dividing a class into subclass is that each subclass shares common
characteristics with the class from where they are inherited or derived.
 Inheritance can reduce the amount of coding by letting any derived class use the base
class’s functionality when it needs to, thus simplifying implementation of similar
classes and structures.
 Benefits of inheritance:
1. Increased productivity
2. Reduced maintenance
3. Standardization
4. reusability
OOP Concepts
Polymorphism:
‘HAVING MANY FORMS is know as Polymorphism. It can be defined as same
thing being used in different forms. It refers to the ability of an object to respond
differently to the same message.
Behavior of an object can be varied depending on the message passed to it
without worrying about the way the kind of message was passed.
Object can exhibit different behaviors in different situations. The behavior
depends on the data types and number of parameters used in the operation.
Polymorphism is achieved in java using method overloading and method
overriding
Procedure Oriented Programming (POP) Object Oriented Programming (OOP)
1 Decompose the main problem in small parts called Decompose the main problem in small parts called
functions. objects.

2 Employs top-down approach for designing programs. Employs bottom-up approach for designing.

3 Emphasizes on functions. Emphasizes on data.


4 In large programs, most functions use global data. Each object controls data under it.

5 Appropriate & effective techniques are unavailable to Data security can be obtained using different access
secure the data. specifiers.

6 Modification of a completed program is very difficult Modifications are easy as objects stay independent to
and it may affect the whole program. declare and define.

7 In large programs, it is very difficult to find what data As data and functions stay close, it is easy to identify
has been used by which function. data.

8 Less reusable More reusable

9 Languages like C, FORTRAN, COBOL etc. use POP. Languages like C++, JAVA etc. use OOP.
Compiling the program
 To compile a java program we execute the compiler javac, specifying the name of
the source file.
javac << java file name>>
ex: javac test.java
 Javac compiler creates a class file that contains the byte code.(This byte code can
execute on any machine of any architecture and any platform)
 To run the program , we use java interpreter called java
java <<class file that contains main method>> <<command line arguments if
required>>
ex: java test
java test sai // passing one command line argument
java test sai siva // passing two command line arguments
Note: If eclipse IDE is used all these steps are done internally by IDE itself. We need to
just click on run. We can specify command line arguments using Run Configurations.
Data types

 Java is a strongly typed language


 Java defines eight simple types of data byte, short, int, long, char, float, double, boolean
 They can be grouped into four categories
❖ Integers: byte, short, int, long
❖ Floating point numbers: float and double
❖ Characters: char ( uses Unicode)
❖ Boolean : boolean data type with values true/false
Data Type Size Range

boolean 1 bit true or false

char 2 byte 0 to 65,536 (unsigned)

byte 1 byte -128 to 127

short 2 byte -32,768 to 32,767

int 4 byte -2,147,483,648 to 2,147,483, 647

long 8 byte -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807

float 4 byte approximately ±3.40282347E+38F


(6-7 significant decimal digits)
Java implements IEEE 754 standard

double 8 byte approximately ±1.79769313486231570E+308


(15 significant decimal digits)

24
Literals
A constant value in java is created by using a literal representation of it.
Ex: “my java prog”, 10, ‘s’, 16.5

 Integer Literal: Any whole number is a integer literal. These are all decimal
numbers with base 10. There are other bases which can be used in integer
literals, octal(base 8) and hexadecimal (base 16). Octal values are denoted by
a leading zero. Hexadecimal constants are denoted with leading zero-x(0x, or
0X)
 Examples:
❖ int i=5
❖ Int i= 012 // considers as octal and with value of 10
❖ Int i= 09 // error as 9 is out of range of octal( only 0-7)
❖ int i=0X11; // considers as hexadecimal with value of 17
❖ Int i=0XA1 ; // considers as hexadecimal with value of 161
Literals
 When a integer literal value is assigned to byte or short variable , no
error is generated if the literal value is within the range of the target
type.
byte b=10;
byte b=128 // error as 128 is out of range of byte
short s=278;
 By default, integer literals are of type int. If you want to specify a
long literal, append an l or an L. For example, 12 is an int, but 12Lis a
long
long l=1098765353545L
Literals
Floating-point literal:
 By default double data type is considered for a decimal number with a
fractional component.
double d=10.5;
float f=10.5; // error as it is narrowing conversion from double literal
to // float variable
 To specify a float literal, append an F or f to the constant. For example,
10.19F is of type float.
float f=10.5F
Literals
 Boolean literals: literals true or false
boolean b=true;
 Character literals: Uses unicode, expressed in single codes. Escape sequences
can also be used
char c=‘a’ //’a’ is char literal
char c=‘\n’
 String literals:
String S=“hello”
String s1=“Hello \n World”
Character Escape sequences
Variables

Variables: Variables can be defined for all the data types and can be assigned with
appropriate literal. Variable name cannot start with a number:
Scope and Lifetime of Variables in Java:-
❖ The scope of a variable defines the section of the code in which the variable is visible. As
a general rule, variables that are defined within a block are not accessible outside that
block. The lifetime of a variable refers to how long the variable exists before it is
destroyed.
❖ Java allows variables to be declared within any block. A block defines scope.
❖ Java allows another category of scope called as class scope(---Will be dealt later---)
Type conversion and casting:-
 Java Automatic Conversions: When one type of data is assigned to
another type of variable, an automatic type conversion takes place if
the following two conditions are met.
❖ The two types are compatible
❖ The destination type is larger than the source type
 Automatic type conversion is called as Widening
 Narrowing conversions can be done only by typecasting
(target-type) variable
Type conversion and casting:-Assigning a value of one type to a variable of another type is known
as Type Casting.
Eg:- int x = 10;
byte y = (byte)x;
Type casting is classified into two types

1. Widening Casting(Implicit)
2. Narrowing Casting(Explicitly done)

1. Widening Casting(Implicit) :-It is also called Automatic Type casting in this type the target type is
larger than the source type.

32
public class Testcasting1
{
public static void main(String[] args)
{
int i = 25;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}}
OUTPUT:-

java Testcasting1
Int value 25
Long value 25
Float value 25.0
33
2. Narrowing Casting(Explicitly done) :- larger type value to a variable of smaller type is called explicit type
casting.

public class Testcasting2


{
public static void main(String[] args)
{
double d = 300.25;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required

System.out.println("Double value "+d); C:\>java Testcasting2


System.out.println("Long value "+l); Double value 300.25
System.out.println("Int value "+i); Long value 300
}} Int value 300
34
Type promotion rules in expressions

 Type promotion rules:


❖ All byte, short and char values are promoted to int
❖ If one operand is long, the whole expression is promoted to long
❖ If one operand is float, entire expression is promoted to float
❖ If one operand is double, entire expression is promoted to double

 byte b=50;
 b=b*2; // error as b is promoted to int by default and cannot fit into byte
 b=(byte) b*2 // need to explicitly type cast
Operators:- Operator in java is a symbol that is used to perform special operations. For example: +, -, *, / etc.
There are basically two types of Operators
1) Unary Operator
2)Binary Operator
1)Unary Operator:- This operator perform operation on single operand (Variable);
eg:-a++;
2) Binary Operator:- This operator perform operation on more than ne operands
Eg:- c=a+b;

operators in java:- java support following operators


1.Arithmetic Operator,
2.Logical Operator,
3.Relational Operator,
4.Assignment Operator.
5.Increment / decrement Operator
6.shift Operator,
•Bitwise Operator,
•Ternary Operator and

36
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Shift operators

General form

Value<< num-bits
Value>> num-bits
Value>>> num-bits
Conditional Operator ( ? : )
Syntax:
variable x = (expression) ? value if true : value if false
Example:

public class Test {


public static void main(String args[]){
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
}
Java Operator Precedence

Operator Type Category Precedence


Increment/Decrement postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !
Arithmetic multiplicative */%
additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
44
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>=
>>>=
Java Command Line Arguments:-The java command-line argument is an argument i.e. passed at the time of
running the java program
The arguments passed from the console can be received in the java program and it can be used as an input,
and it provides a convenient way to check the behavior of the program for the different values. W e can
pass N (1,2,3 and so on) numbers of arguments from the command prompt.
class Cmd
{
public static void main(String ar[])
{

System.out.print(ar[0]);
System.out.print(ar[1]);
System.out.print(ar[2]);
System.out.print(ar[3]);
}}

OUTPUT:-
C:\java Cmd Geethanjali College of Engineering

Geethanjali College of Engineering 45


class Cmd2
OUTPUT:-
{ C:\javac Cmd2.java
public static void main(String ar[]) C:\java Cmd2 2 12 JAVA CLASS
{ 2
int a,b; 12
a=Integer.parseInt(ar[0]); JAVACLASS
b=Integer.parseInt(ar[1]);
System.out.println(a); class Cmd1
System.out.println(b); {
System.out.print(ar[2]); public static void main(String ar[])
System.out.print(ar[3]); { int a,b,c;
}} a=Integer.parseInt(ar[0]);
b=Integer.parseInt(ar[1]);
Output:- System.out.println(a);
C:\javac Cmd1.java System.out.println(b);
C:\java Cmd1 12 13 GCET ITDEPT c=(a+b);
12 System.out.print(ar[2]);
13 System.out.println(ar[3]);
GCET ITDEPT System.out.println("SUM IS:"+c);
SUM IS:25
}} 46
CONTROL STRUCRURES

 LOOPS
❖ while Loop
❖ do...while Loop
❖ for Loop
 Conditional statements
❖ If statements
❖ Switch statements
❖ Break
❖ Continue
For each loop

Syntax:
for (type var : array)
{
statements using var;
}
Break with Label
public class LabelledBreak
{
public static void main(String args[])
{
loop2:
for(int i=0;i<5;i++)
for(int k=0;k<5;k++)
{
if(k==2) Output:
break loop2; i=0
System.out.println("i = "+i); k=0
System.out.println(“k = "+k); i=0
} k= 1
System.out.println("Out of the loop"); Out of the loop
} //main method ends
} //class ends
Continue with Label
public class LabelledContinue
{
public static void main(String args[]) Output:
{ i=0
loop2: k=0
for(int i=0;i<3;i++) i=0
for(int k=0;k<3;k++) k=1
{ i=1
if(k==2) k=0
continue loop2; i=1
System.out.println("i = "+i); k=1
System.out.println(“k = “+k); i=2
} k=0
System.out.println("Out of the loop"); i=2
} //main method ends k=1
} //class ends Out of the loop
If-else Statement:- if statement is used to test the condition. It checks boolean condition: true or false. There
are various types of if statement in java.
1)if statement 2) if-else statement 3) nested if statement
IF Statement:- The Java if statement tests the condition.
It executes the if block if condition is true.
Syntax:
if(condition){
//code to be executed
}
Example:-
class Con1
{
public static void main(String args[])
{
int n;
n=10;
if(n%5==0)
{
System.out.println("the number "+n+"is divided by 5");
}
51
}}
IF-else Statement:- The Java if-else statement also tests the condition.
It executes the if block if condition is true otherwise else block is
executed.
Syntax:
if(condition){ //code if condition is true }
else{ //code if condition is false }

Eg:- import java.util.Scanner;


class Con2
{
public static void main(String args[])
{
Scanner s1 =new Scanner(System.in);
int n;
n=s1.nextInt();
if(n%5==0)
{
System.out.println("the number "+n+"is divided by 5");
}else
{System.out.println("the number "+n+"is not divided by 5"); 52
}}}
IF-else-if ladder Statement:-The if-else-if ladder statement executes one condition from multiple
statements.
Syntax:
if(condition1)
{
//code to be executed if condition1 is true
}else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
else
{
//code to be executed if all the conditions are false
} 53
54
Switch Statement:-
The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement.

Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}

Note: For versions of Java prior to JDK 7 , the expression controlling the switch must be of type byte,
short, int, char or an enumeration . From JKD 7 , expression can also be of type String.
55
56
Arrays:- “An array is a Indexed collection of fixed number of homogenous data elements”.
An array can be either primitive or reference type. It gets memory in heap area. Index of array starts from zero
to size-1.

Advantage of Java Array:-


i. Indexing:-It is always indexed. Index begins from 0.
ii. Memory allocation:-It occupies a contiguous memory location.
iii. Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
iv. Random access: We can get any data located at any index position.
Disadvantage of Java Array:-
i. Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To
solve this problem, collection framework is used in java.
57
Array Declaration:-
Syntax :
datatype[ ] identifier; (or) datatype identifier[ ];
Both are valid syntax for array declaration.

Example :
int[ ] a ; Declares an array variable but no array actually exists. It
int b[ ] ; is set to null i.e. An array with no value

Initialization of Array:-

➢ new operator is used to initialize an array.


int a[ ] = new int[10]; //this creates an empty array named a of integer type whose size is 10 and with
default values 0. values can be assigned later.

➢ An array can be directly initialized without using new keyword.


int b[ ] = {10,20,30,40,50}; //this creates an array named b and assign elements are given.
58
import java.util.Scanner;
class test1
{
public static void main(String args[])
{
int a[]=new int[5],i;
Scanner s=new Scanner(System.in);
System.out.println("enter 5 elements");
for(i=0;i<=4;i++)
a[i]=s.nextInt();
System.out.println("elements in the array are");
for(i=0;i<=4;i++)
System.out.print(a[i]+"\t");
}}
Multidimensional array:- A multi-dimensional array is very much similar to a single dimensional array. It can
have multiple rows and multiple columns unlike single dimensional array.
Array Declaration:-
dataType[][] identifier; (or) = int [][] a
dataType [][] identifier ; (or) = int [][]a
dataType identifier[][]; (or) =int a[][]

Initialization of Array:-
int[ ][ ] arr = new int[size-m][size-n];

int[ ][ ] M = new int[5][5];

int[ ][ ] K= {{11,22,13,14},{6,8,9,10},{12,13,14,15}};// 3 by 4 is the size of the array.

60
class Twoarray
{
public static void main(String args[]){

//declaring and initializing 2D array


int a[][]={{1,2,3,4},{11,12,14,15},{14,24,34,44}};

//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<4;j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}}

OUTPUT:-
C:\praveen>java Twoarray
1234
61
11 12 14 15
14 24 34 44
Irregular arrays
 When defining an multidimensional array we need to specify the memory for
the first(leftmost dimension). The remaining dimensions can be allocated
separately
int a[][]=new int[3][];
a[0]=new int[4];
a[1]=new int[4];
a[2]=new int[4];
 We can also have different dimensions
int a[][]=new int[3][];
a[0]=new int[4];
a[1]=new int[3];
a[2]=new int[2];
 int b[][]={{1,2,3,4},{5,6,7},8,9}};// array initialized with different dimensions
Assigning Array references
When one array reference variable is assigned to another , it does not cause a
copy of the array nor the contents of one array is copied to the other, but the
object that the variable refers to is changed. This is because arrays are
treated as objects in java.

int a=new int[3];


a[0]=1;a[1]=2;a[2]=3 a 1 2 3
int b=new int[3];
b 5 6 7
b[0]=5;b[1]=6;b[2]=7
a=b a
5 6 7
b
Length member of array
Arrays are implemented s objects and each array is associated with length
instance variable that contains the number of elements that the array can hold.
Example:
int a[]={1,2,3,4}
System.out.println(a.length); // prints 4 as length
for(int i=0;i<a.length;i++)
System.out.println(a[i]);

int a[][]={{1,2,3},{4,5},{6,7},{7,3,5}}
System.out.println(a.length) // prints 4 as a has 4 rows
System.out.println(a[0].length) // prints 3 as row 0 has 3 cols
System.out.println(a[1].length) // prints 2 as row 1 has 2 cols
System.out.println(a[2].length) // prints 2 as row 2 has 2 cols
System.out.println(a[3].length) // prints 3 as row 3 has 3 cols
Enhanced for loop: for-each loop
 Enhanced for loop (for-each) can be used to access each element sequentially
from a collection like array.
 Syntax:
for(type itr-var:collection) statement block
❖ type specifies the type of the elements stored in the collection
❖ itr-var is the iteration variable that receives values from collection one at a
time from beginning to endexample
Example 1: to find sum of all elements in array
int[] num={1,2,3,4,5,6,7,8,9}
int sum=0
for(int x:nums) sum+=x;
Example2:
double [] num={1.5,2.6,3.8,4.2,5.7,6.0}
for(float x:nums) System.out.println(x);
Assignment

 Write a program to perform linear search and display the element position
 Write a program to perform binary search and display the element position
 Write a program to read two matrices and perform matrix addition
67
OUTPUT:-
C:\java Matadd
enter no of rows matrix A
2
enter no of cols matrix A
2
enter no of rows matrix B
2
enter no of cols matrix B
2
enter elements in to matrix A
2 2 2 2
enter elements in to matrix B
22 2 2
sum matrix is:
4 4
4 4

68
Classes and Objects
Class:- A class is a collection of fields (data members) and methods (procedure or
function) that operate on that data.
(or)
A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity.
A class in Java can contain:
fields
methods
constructors
blocks
nested class and interface
Syntax to declare a class:
class ClassName [extends SuperClassName]
{
[fields declaration]
[methods declaration]
}

70
Classes and Objects
class <classname>>
{
//declare instance variables
<<type>> var1;
<<type>> var2;
// declare methods
<<return type>> method1(<<parameters>>)
{
// body of the method
}
<<return type>> method1(<<parameters>>)
{
// body of the method
}
}
Classes and Objects

 Creating an object
<<classname>> <<obj var>>=new <<classname>>()
 To access the members we use ‘.’ operator
Object.member
Classes and Objects
class Student class test
{ {
int sno; public static void main(String args[])
String name; {
void set(int r,String n) Student s1 = new Student();
{ Student s2 = new Student();
sno = r; s1.set(1201,“sai");
name = n; s2.set(1202,“siva");
} s1.display();
void display () s2.display();
{ }
System.out.println(sno+" "+name); }
}
}
class Rectangle Class Rectdemo
{ public static void main(String args[])
int length; {
int breadth; Rectangle r1=new Rectangle();
void setSize(int l,int b) r1.setSize(10,20);
{ r1.dispSize();
length=l; r1.printArea();
breadth=b; Rectangle r2=new Rectangle();
} r2.setSize(15,25);
void dispSize() r2.dispSize();
{ r2.printArea();
System.out.println("Length of the rect="+ length); }
System.out.println("Breadth of the rect="+ breadth); }
}
void printArea() Output:
{ Length of the rect=10
System.out.println(“Area of the Breadth of the rect=20
rect=“+(length*breadth)); Area of the rect=200
} Length of the rect=15
} Breadth of the rect =25
Area of the rect =375
Constructor :- Constructor is a special type of method , method name is same as class name is called
constructor. It is used to initialize memory to the method at object creation. Java constructor is invoked at the
time of object creation.
It constructs the values i.e. provides data for the object that is why it is known as constructor.

Rules for creating java constructor


There are basically two rules defined for the constructor.
I.Constructor name must be same as its class name
II.Constructor must have no explicit return type

Types of java constructors


There are 3 types of constructors:
1.Default constructor (no-arg constructor)
2.Parameterized constructor
3.Copy Constructor

75
Default Constructor:- A constructor that have no parameter is known as default constructor.
Syntax:-
<classname>
{
……
}
Eg:- class exp()
{
int a,b;
exp()
{ }
parameterized constructor:- A constructor that have parameters is known as parameterized constructor.
Syntax:-
<classname>
{
……
}
Eg:- class exp()
{
int a,b;
exp(int i, int b)
{
76
a= i; b=j;
}
class Rectangle
class test
{
{
int len;
public static void main(String args[])
int bred;
{
Rectangle(int l,int b)// parameterised construtor
Rectangle r1=new Rectangle(10,20);
{
r1.printArea();
len=l;
r1.getPerimeter();
bred=b;
Rectangle r2=new Rectangle(5,10);
}
r2.printArea();
void printArea()
r2.getPerimeter();
{
Rectangle r3=new Rectangle()// gives error
System.out.println("Area="+(len*bred));
}
}
}
void getPerimeter()
{
System.out.println("Perimeter="+(2*(len+bred)));
}
}
 A class can be written with multiple constructors differentiating in number of parameters
passed.
 Ex:
➢ Rectangle(){---}// default constructor
➢ Rectangle(int l){---}// parameterized constructor with one parameter
➢ Rectangle(int l,int b){---}// parameterized constructor with two parameters
 If no constructor is written in a class, JVM provides a default constructor which initializes
data members to default values. But if any constructor is written in a class JVM does not
provide default constructor.
 In the previous example the third object creation gives an error as it is invoking a default
constructor and Rectangle class is written with only parameterized constructor.
Rectangle r3=new Rectangle()// gives error
(Note: If no constructor is written then it does not give error as JVM provides a default
constructor for every class with no constructors written)
Constructor Overloading
class Rectangle Void getPerimeter()
{ {
int len; System.out.println("Perimeter="+(2*(len+bred)));
int bred; }
Rectangle() }
{ class ConstOverload
len=1; {
bred=1; public static void main(String args[])
} {
Rectangle(int l) Rectangle r1=new Rectangle(10,20);
{ r1.getArea();
len=l; r1.getPerimeter();
bred=l;} Rectangle r2=new Rectangle(5);
Rectangle(int l,int b) r2.getArea();
{ r2.getPerimeter();
len=l; Rectangle r3=new Rectangle();
bred=b;} r3.getArea();
Void getArea() r3.getPerimeter();
{ }
System.out.println("Area="+(len*bred)); }
}
this keyword

 this is a keyword in Java which is used as a reference to the object of the


current class, with in an instance method or a constructor. Using this we can
refer the members of a class such as constructors, variables and methods.
 Java syntax permits the name of a parameter or a local variable to be same as
the name of an instance variable(data member). When this happens, the local
name hides the instance variable. We can give access to hidden instance
variable by referring to it through this keyword.
 this keyword can be used for multiple purposes, we will see it in coming
classes……
class thisdemo
class Rectangle Same name given for {
{ data members and public static void main(String args[])
int len; arguments. this {
int bred; keyword can be used Rectangle r1=new Rectangle(10,20);
Rectangle(int len,int bred) to differentiate as this r1.getArea();
{ keyword refers to
current object r1.getPerimeter();
this.len=len; Rectangle r2=new Rectangle(5,10);
this.bred=bred; r2.getArea();
} r2.getPerimeter();
void getArea() }
{ }
System.out.println("Area="+(len*bred));
}
void getPerimeter()
{
System.out.println("Perimeter="+(2*(len+bred)));
}
}
Method Overloading
 In Java, two or more methods within the same class can share the same name as long as
their parameter declarations are different. This process is called as method overloading
and is one of the way that Java implements polymorphism.
 Rules:
1. Method name is same
2. Type and/or number of parameters of each overloaded method should differ
(ex1: int add(int i, int j)
Add method is overloaded and differentiated by
int add( int a, int b, int c) number of arguments
ex2: int add(int i, int k)
Add method is overloaded and differentiated by
double add(double d1, double d2) type of arguments
3. It is not sufficient that two methods to differ only in return type
(ex: int add(int i, int j)
double add(int a,int b) are not considered as overloaded and gives error
(as they differ only in return types)
Method Overloading Example
class addition
{ class methodover
void add(int i, int j) {
{ public static void main(String args[])
System.out.println("Add result of 2 integers="+(i+j)); {
} addition a=new addition();
void add(int i,int j, int k) a.add(10,20);
{ a.add(10,20,30);
System.out.println("Add result of 3 integers="+(i+j+k)); a.add(10.5,12.5);
} a.add(15.5f,13.8f);
void add(double d1,double d2) }
{ }
System.out.println("Add result of double nos="+(d1+d2));
Output:
}
Add result of 2 integers=30
void add(float f1,float f2) Add result of 3 integers=60
{ Add result of double nos=23.0
System.out.println("Add result of float nos="+(f1+f2)); Add result of float nos=29.3
}
}
class addition
{
void add(int i, int j)
{
System.out.println("Add result of 2 integers="+(i+j));
}
Yes it works as automatic type conversion is
void add(int i,int j, int k)
applicable for methods also. If a method with the
{
required data types is not available, it searches
System.out.println("Add result of 3 integers="+(i+j+k));
for appropriate method that can be used with
}
automatic type conversion for the given data
void add(double d1,double d2)
type.
{
System.out.println("Add result of double nos="+(d1+d2));
In the given example add method with double
}
arguments can be used for float parameters as
}
float can be automatically converted to double.
public class test {
public static void main(String args[])
{
addition a=new addition();
a.add(10,20);
a.add(10,20,30);
a.add(10.5,12.5); Will this work as no add method
a.add(15.5f,13.8f); with float argument is written. Test
} it??????
}
Passing objects to methods
boolean equals(Circle c)
class Circle {
{ if(rad==c.rad) Passing Circle
int rad; return true; object as Output:
else parameter Area=314.0
Circle(int r) return false;
{ perimeter=62.800000000000004
}
rad=r; circle c1 equals circle c2 : false
}
} class test1 circle c1 equals circle c3 : true
Circle() { circle c1 equals circle c4 : false
{ public static void main(String args[])
rad=1; {
} Circle c1=new Circle(10);
double getArea() System.out.println("Area="+c1.getArea());
{ System.out.println("perimeter="+c1.printPerimeter());
return (3.14*rad*rad); Circle c2=new Circle(20);
} Circle c3=new Circle(10); Actual
double printPerimeter() Circle c4=new Circle(); //rad=1 as per default constructor argument=c2
{ System.out.println("circle c1 equals circle c2 : "+c1.equals(c2)); object
return(2*3.14*rad); System.out.println("circle c1 equals circle c3 : "+c1.equals(c3));
} System.out.println("circle c1 equals circle c4 : "+c1.equals(c4));
Actual
}
}
argument=c3
Actual object
argument=
c4 object
Passing parameters
 Pass-by-Value: When the formal parameter is a primitive type , the formal
parameter acts as a local variable i.e. the changes made to the formal
parameter inside the method do not affect the actual parameter. Hence
primitive type argument is passed by value in Java

 Pass-by-Reference: When a formal parameter is an object, it is not the value


that is copied but the address i.e. the changes made to the formal parameter
object inside the method affects the actual parameter object. Hence objects
are passed by reference in Java.
Pass by Value Output:
b=10
a=11
public class PassByValDemo b=10
{
void incr(int a)// a is formal parameter
{
a++;
System.out.println("a="+a);
}
public static void main(String args[])
{
PassByValDemo d1=new PassByValDemo();
int b=20;
System.out.println("b="+b);
d1.incr(b);// b is actual parameter
System.out.println("b="+b);
//var b(actual param)is not changed on changing
//var a(formal param)
}
}
Pass by Reference Output:
before method invocation
class myclass a=10
{ after method invocation
int a;// data member a=11
myclass(int a1)// constructor to initialize data member a
{ a=a1; }
void display()// method to display state of object
{
System.out.println("a="+a);
}
}
public class PassByRefDemo {
void incr(myclass m)// m is formal parameter
{
m.a++;// incr the data member ‘a ‘ i.e. changing the state of object m
}
public static void main(String args[])
{
PassByRefDemo d1=new PassByRefDemo();// to invoke incr
myclass m1=new myclass(20); // to pass as an argument to incr method
System.out.println("before method invocation");
m1.display();
d1.incr(m1);// actual parameter=m1
System.out.println("after method invocation");
m1.display();
}}
Static keyword
 We can have a class member that will be used independently of any
object of that class. As we know normally a class member must be
accessed through an object of its class, but it is possible to create a
member that can be used without reference to a specific instance.To
create such member , we precede its declaration with the keyword
static.
 When a member is declared as static , it can be accessed before any
objects of its class are created and without reference to any object.
 We can declare both variables(data members) or methods( member
methods) as static
 Blocks can also be declared as static
Static Variables
 The static keyword is used to create variables that will exist independently of any instances
created for the class( global for all objects). Only one copy of the static variable exists regardless
of the number of instances of the class i.e. A static variable is common to all the instances (or
objects) of the class.
 Memory allocation for such variables only happens once when the class is loaded in the memory
 Static variables are also known as class variables. Local variables cannot be declared static.
 Syntax:
static <<data_type>> <<variable_name>>;
 Static variable initialization:
❖ Static variables are initialized when class is loaded.
❖ Static variables are initialized before any object of that class is created.
❖ Static variables are initialized before any static method of the class executes.

91
Output:
Static variable Obj1: count is=1
Obj2: count is=1
Obj1: count is=2
class staticdemo Obj2: count is=2
{
static int count=0;
public void increment()
{
count++;
}
public static void main(String args[])
{
staticdemo obj1=new staticdemo();
staticdemo obj2=new staticdemo();
obj1.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
obj2.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
}
}
Static variable (example2)
class staticdemo
{ Output:
static int a=0; obj1:a=1 obj2.a=1
int b=0; obj1:b=1 obj2.b=0
public void increment()
{
a++;
b++;
}
public static void main(String args[])
{
staticdemo obj1=new staticdemo();
staticdemo obj2=new staticdemo();
obj1.increment();
System.out.println(“obj1:a="+obj1.a+"\t"+"obj2.a="+obj2.a);
System.out.println(“obj1:b="+obj1.b+"\t"+"obj2.b="+obj2.b);
}
}
Static methods

Static Methods:-
 The static keyword is used to create methods that will exist independently of any
instances created for the class. Methods declared static are essentially global methods.
 They are called independently of any object. Instead a static method is called through
its class name.
 Class variables and methods can be accessed using the class name followed by a dot
and the name of the variable or method.
 Static methods are particularly used for creating utility methods that perform useful
functions not related to a specific object . Ex: Math class has many static methods like
cos(), sin()……..
 They have restrictions:
❖ Then can directly call only other static methods
❖ They can directly access only static data
❖ They do not have a this reference
Static methods
class demo class staticdemo
{ {
static int increment(int a) public static void main(String args[])
{ {
a++; int r;
return(a); r=demo.increment(10);// as increment is static can be directly accessed
} System.out.println("increment res="+r);
int decrement(int a) demo s=new demo();
{ r=s.decrement(10);// decrement can only be accessed using object
a--; System.out.println("decrement res="+r);
return(a); }
} }
}
Static methods
class demo public static void main(String args[])
{ {
static int increment(int a) int r;
{ r=increment(10);// as increment is static in same class can be directly
a++; //accessed inside main which is static
return(a); System.out.println("increment res="+r);
} demo s=new demo();
int decrement(int a) r=s.decrement(10);// decrement can only be accessed using object
{ System.out.println("decrement res="+r);
a--; }
return(a); }
}
}
Static blocks
 Sometimes a class will require some type of initialization before it is ready to
create objects
 (ex: it might need to establish a connection to a remote site, it might also
need to initialize certain static variables before any of the class static
methods are used)
 A static block is executed only once when the class is first loaded. i.e. it is
executed before the class can be used for any other purpose.
 Non-static variables can’t be accessed with in a Java static block.
 A static initialization block is a normal block of code enclosed in braces { },
and preceded by the static keyword.
 Syntax: static { // code for initialization goes here }
Static block
class StaticBlockDemo {
class STest { public static void main(String args[]) {
static int i; // though two objects are created static block is
executed only once.
int j; STest t1 = new STest();
static { STest t2 = new STest();
i = 10; }
}
//j=20;// gives error as j is non static
member
System.out.println("static block called ");
Output:
} static block called
STest(){ Constructor called
System.out.println("Constructor called"); i=10
j=0
System.out.println("i="+i);
Constructor called
System.out.println("j="+j); i=10
} j=0
}
Strings
➢ Series of characters treated as single unit
➢ May include letters, digits, etc.
➢ String class is present in java.lang package which is a default package imported to
every java class
➢ Like other classes, String has constructors and methods
➢ There are two ways to create String object:
1. By string literal
2. By new keyword
Strings
1) String Literal:-Java String literal is created by using double quotes.
Eg:- String s1=“Java”;
Each time we 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 string doesn't exist in the pool, a new string instance is created and
placed in the pool.
2.By new keyword:-
String s=new String(“Java");
By using new keyword, JVM will create a new string object though Java literal
exists in pool
String literals

String word1 = "Java"; String word1 = “Java";


String word2 = “Java”; String word2 = new String(“Java”);

word1 word1 “Java"

“Java" word2 “Java"


word2
Immutability

Strings are immutable i.e. we cannot manipulate a string instead a new string
will be created

String word1 = "Java"; word2=word2+” course”;


String word2 = “Java”;

word1 word1 “Java"

“Java" word2 “Java course"


word2
String Constructors
1. String(): To create an empty String, we will call a default constructor.
For example:
String s = new String();
It will create a string object in the heap area with no value.
2. String(String str): It will create a string object with the content of given string
argument in the heap area.
For example:
String s2 = new String(“Hello Java“);
Now, the object s2 contains Hello Java.
3. String(char chars[ ]): It will create a string object and stores the array of
characters in it.
For example:
char chars[ ] = { ‘a’, ‘b’, ‘c’, ‘d’ };
String s3 = new String(chars);
String Constructors
4. String(char chars[ ], int startIndex, int count): It will create and initializes a string
object with a subrange of a character array. The argument startIndex specifies the
index at which the subrange begins and count specifies the number of characters to
be copied.
For example:
char chars[ ] = { ‘w’, ‘i’, ‘n’, ‘d’, ‘o’, ‘w’, ‘s’ };
String str = new String(chars, 2, 3);
The object str contains the address of the value ”ndo” stored in the heap area
because the starting index is 2 and the total number of characters to be copied is 3.
5. String(byte byteArr[ ]): It constructs a new string object by decoding the given array
of bytes (i.e, by decoding ASCII values into the characters) according to the system’s
default character set.
byte b[] = { 97, 98, 99, 100 };
String s = new String(b); //s=abcd
97 is the Unicode value of a, 98 ➨ b, 99 ➨ c, 100 ➨ d.
String Constructors

6. String(byte byteArr[ ], int startIndex, int count): This constructor also


creates a new string object by decoding the ASCII values using the system’s
default character set.
byte b[] = { 65, 66, 67, 68, 69, 70 }; // Range of bytes: -128 to 127.
String s = new String(b, 2, 4); // CDEF
String class methods
String class methods
String class methods
String class methods

String class has a method length() which returnsnumber of


characters in the string
int length()
Note: for arrays length is a data member
a.length (where a ia array)
For string length is a method
a.length() ( if a is a string)
Please refer to
https://docs.oracle.com/javase/7/docs/api/java/lang/String.ht
ml
String class methods
Why does String define the equals( ) method? Can’t I just use ==?
A : The equals( ) method compares the character sequences of two String objects
for equality. Applying the == to two String references simply determines whether
the two references refer to the same object.
Ex:
String s1=”java”
String s2=”java”
String s3=new String(“java”);
System.out.println(s1==s2)// true
System.out.println(s1==s3) // false though value is same as s1 and s3 point to
//different references
System.out.println(s1.equals(s2)) //true
System.out.println(s1.equals(s3) //true
Garbage Collection

Garbage means unreferenced objects. Garbage Collection is process of retrieve


the runtime unused memory automatically. i.e. it is a way to destroy the
unused objects.
It works like this: When no references to an object exist, that object is assumed to
be no longer needed, and the memory occupied by the object is released. This
recycled memory can be used for a subsequent allocation.
Advantage of Garbage Collection
It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
It is automatically done by the garbage collector(a part of JVM) so we don't
need to make extra efforts.
Garbage Collection

object can be unreferenced by following ways


1. When object is out of scope
By nulling the reference
Student s1 = new Student(); S1=null;
2. By assigning a reference to another
Student s1=new Student(); Student s2=new Student();
e1=e2;//now the first object referred by e1 is available for garbage collec
tion
Garbage Collection

finalize() method:-
The Java run-time system calls finalize( ) method whenever it is about to recycle an object
of that class. Inside the finalize( ) method, you will specify those actions that must be
performed before an object is destroyed. This method is defined in Object class as:
protected void finalize()
{ // finalize code here
}

⚫ It is important to understand that finalize( ) is called just before garbage collection. It is


not called when an object goes out of scope, for example. This means that you cannot
know when—or even if finalize( ) will be executed. For example, if your program ends
before garbage collection occurs, finalize( ) will not execute.
Garbage Collection

We can also request JVM to run Garbage Collector. There are two ways to
do it :
1. Using System.gc() method : System class contain static method gc() for
requesting JVM to run Garbage Collector.
2. Using Runtime.getRuntime().gc() method : Runtime class allows the
application to interface with the JVM in which the application is running.
Hence by using its gc() method, we can request JVM to run Garbage
Collector.
class Demo {
Demo() {
System.out.println("Object created: Constructed invoked");
}

void sayHello() {
System.out.println("Hello java programmer");
}

protected void finalize() {


System.out.println("Object getting destroyed: finalize invoked");
}
} Output
public class finalizedemo { Object created: Constructed invoked
Hello java programmer
public static void main(String args[]) { Object getting destroyed: finalize invoked
Demo d = new Demo();
d.sayHello();
d = null;// to allow GC to deallocate memory for d
System.gc();// invoking GC focibily through program
}
}
ENUMERATIONS

⚫ An enumeration is a list of named constants that define a new data type. An


object of an enumeration type can hold only the values that are defined by
the list.
⚫ An enumeration gives you a way to precisely define a new type of data that
has a fixed number of valid values.
⚫ An enumeration of the days of the week is Sunday, Monday, Tuesday,
Wednesday, Thursday, Friday, and Saturday.
⚫ An enumeration is created using the enum keyword.
ENUMERATIONS

⚫ The identifiers CAR, TRUCK, and so on, are called enumeration


constants. Each is implicitly declared as a public, static member of
Transport.
⚫ Variable declaration:
Transport tp;
tp=Transport.AIRPLANE;
⚫ Two enumeration constants can be compared for equality by using the
= = relational operator
if(tp==Transport.TRAIN)
ENUMERATIONS
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.
ENUMERATIONS

⚫ All enumerations automatically have two predefined methods: values(


) and valueOf( ).
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.
ENUMERATIONS

⚫ An enumeration can define constructors, add methods, and


have instance variables. When you define a constructor for an
enum, the constructor is called when each enumeration
constant is created.
⚫ Each enumeration constant can call any method defined by the
enumeration. Each enumeration constant has its own copy of
any instance variables defined by the enumeration.

You might also like