JAVA - All Module Notes
JAVA - All Module Notes
JAVA
(22CDT133)
NCET Page 1
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
MODULE 1
PROCEDURE–ORIENTED PROGRAMMING
NCET Page 2
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Dis-Advantage of POPS:
Since every function has complete access to the global variables, the new programmer can
corrupt the data accidentally by creating function. Similarly, if new data is to be added, all
the function needed to be modified to access the data.
POP doesn’t support object programming features like – abstraction, Encapsulation,
Inheritance etc..,
Advantages
NCET Page 3
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Inheritance
Polymorphism
Class
A Class is a collection of objects (Members and member functions).
Keyword is class.
Class can contain fields, methods, constructors, and certain properties.
Class acts like a blueprint.
When defining class, it should starts with keyword class followed by name of the class;
and the class body, enclosed by a pair of curly braces.
Syntax: Example:
Object
Object is an instance of the class.
Object is used to access members (variables) and member functions (methods).
Example :
public class First
{
public void display( ) // method
{
System.out.println(“NCET”);
}
public static void main(String args[ ] )
{
First obj = new First( ) ; //create object
obj . display( ) ; //access display method using object obj
}
}
Output:
NCET
NCET Page 4
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Data Abstraction
Abstraction is a process where you show only “relevant” data and “hide” unnecessary
details of an object from the user.
In simple words: Display what is necessary. Let other things rest in peace.
For example, when you login to your face book account, you enter your user_id and password
and press login, what happens when you press login; how the input data sent to server, how it
gets verified is all abstracted away from you.
Example:
public class First
{
public static void main(String args[ ] )
{
System.out.println(“My name is Kiran”);
}
}
In the above example we are printing the message “My name is Kiran” using println function but
we are not bothered about how println is working internally to display that message.
Data Encapsulation
Wrapping (combining) of data and functions into a single unit (class) is known as data
encapsulation.
Data is not accessible to the outside world, only those functions which are wrapped in the
class can access it.
We can also call Information hiding.
Java supports the properties of encapsulation and data hiding through the creation of
user-defined types, called classes.
Data Encapsulation can be provided by Access modifiers of the class i.e
public(members of class can be access from anywhere)
private(members of class can be access only within a class )
protected (members of class can be accessible through its child class)
Example: //I shown here only for private; similarly we can write for public and protected also.
class First
{
private int a=10;
}
Output:
class Second extends First a has private access in First
{
public static void main(String args[ ] )
System.out.println( obj.a ) ;
{ ^
Second obj = new Second( );
System.out.println( obj.a ) ;
1 error
}
}
Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors
of a parent object.
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
extends keyword should be used to inherit properties.
Example: Below example shows Second class can access values of a and b from Class One
class One
{
int a=10,b=20;
}
class Second extends One
{
public static void main(String[ ] args)
{
Second obj=new Second( );
System.out.println(obj.a + obj.b);
}
}
Output:
30
Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are related to
each other by inheritance.
Polymorphism uses those methods to perform different tasks. This allows us to perform a single
action in different ways.
Example: Method overloading (same method name but different action ) and method overriding
(same method name override in child class with different action)
NCET Page 6
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Comparison of Object oriented language and Procedure Oriented language
Sl. Object oriented Procedure oriented
1 Program is divided into objects Program is divided into functions
2 Bottom-up approach Top-down approach
3 Inheritance property is supported. Inheritance is not allowed
4 Supports Abstraction Doesn’t Supports Abstraction
5 Polymorphism property is supported. Polymorphism property is not supported.
6 It uses access specifier. It doesn’t use access specifier.
7 Encapsulation is used to hide the data No data hiding.
8 Concept of virtual function No virtual function.
9 It is complex to implement It is simple to implement
10 C++, JAVA C, PASCAL
11 file extension is .java file extension is .c
12 Allows you to use function overloading. C does not allow you to use function overloading.
13 The data is secured. The data is not secured.
14 Supports Multi-Threading. Doesn’t Supports Multi-Threading.
Introduction to JAVA
JAVA was developed by James Gosling at Sun Microsystems Inc in the year 1995, later
acquired by Oracle Corporation.
History:
The history of Java is very interesting. Java was originally designed for interactive television,
but it was too advanced technology for the digital cable television industry at the time.
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team.
Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
After that, it was called Oak and was developed as a part of the Green project.
In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
Java is an island in Indonesia where the first coffee was produced (called Java coffee).
It is a kind of espresso bean. Java name was chosen by James Gosling while having a
cup of coffee nearby his office.
Initially developed by James Gosling at Sun Microsystems and released in 1995.
NCET Page 7
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
JDK 1.0 was released on January 23, 1996. After the first release of Java, there have
been many additional features added to the language. Now Java is being used in
Windows applications, Web applications, enterprise applications, mobile applications,
cards, etc. Each new version adds new features in Java.
Versions
Version Date Version Date
JDK Beta 1995 Java SE 11 2018
JDK 1.0 1996 Java SE 12 2019
JDK 1.1 1997 Java SE 13 2019
J2SE 1.2 1998 Java SE 14 2020
J2SE 1.3 2000 Java SE 15 2020
J2SE 1.4 2002 Java SE 16 2021
Java SE 5 2004 Java SE 17 2021
Java SE 6 2006 Java SE 18 2022
Java SE 7 2011 Java SE 19 (Latest) 2022
Java SE 8 2014
Java SE 9 2017
Java SE 10 2018
JAVA Buzzwords
The features of Java are also known as Java buzzwords.
Java Buzzwords are –
Simple
Secure
Portable
Object-oriented
Platform Independent
Robust
Multithreaded
Architecture-neutral
Interpreted
High performance
Distributed
Dynamic
Simple
Java was designed to be easy for the professional programmer to learn and use
effectively.
If you already understand the basic concepts of object-oriented programming, learning
Java will be even easier. Because Java inherits the C/C++ syntax.
NCET Page 8
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Secure
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
No explicit pointer
Java Programs run inside a virtual machine sandbox
Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is
used to load Java classes into the Java Virtual Machine dynamically.
Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.
Object -Oriented
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language.
A platform is the hardware or software environment in which a program runs.
Java provides a software-based platform.
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e., Write
Once and Run Anywhere.
NCET Page 9
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Robust
The English mining of Robust is strong. Java is robust because:
Multithreaded
Java was designed to meet the real-world requirement of creating interactive, networked programs. To
accomplish this, Java supports multithreaded programming, which allows you to write programs that do
many things simultaneously.
Distributed
Java is designed for the distributed environment of the Internet because it handles TCP/IP
protocols.
In fact, accessing a resource using a URL is not much different from accessing a file. Java also
supports Remote Method Invocation (RMI).This feature enables a program to invoke methods
across a network.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).
NCET Page 10
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
JAVA Byte code
Byte-code is a highly optimized set of instructions designed to be executed by the Java run-time system,
which is called the Java Virtual Machine (JVM).
Java compiler is not executable code.
It required Byte-code to execute java program.
The original JVM was designed as an interpreter for byte-code.
A Java program is executed by the JVM helps solve the major problems associated with web-based
programs.
Translating a Java program into byte-code to run a program in a wide variety of environments because only
the JVM needs to be implemented for each platform.
The JVM will differ from platform to platform; all understand the same Java byte-code.
The execution of byte-code by the JVM is the easiest way to create truly portable programs.
A Java program is executed by the JVM also helps to make it secure.
It can contain the program and prevent it from generating side effects outside of the system.
Source Code
.java file
(Program)
Compiler
Working:
1. First we will write the java code with .java extension using any editor Eclipse IDE(Integrated Development
Environment)
2. Then, compiler will convert the source file to Byte code with .class extension.
3. The Byte code then converts to Machine code by using Java Virtual Machine (JVM).
4. We can run this bytecode on any other platform as well. But the bytecode is a non-runnable code that
requires or relies on an interpreter. This is where JVM plays an important part.
The main difference between the machine code and the bytecode is that the machine code is a set of
instructions in machine language or binary which can be directly executed by the CPU.
While the bytecode is a non-runnable code generated by compiling a source code that relies on
an interpreter to get executed.
1. Install JDK , Set the JDK path in the system environmental variable location.
2. Write program using Notepad editor and save file name as class name with .java extension (First.java)
(Pretend we saving our java file in desktop)
3. Open command prompt , change the directory where the java file present.
C:\> cd desktop
4. Compile the java file using command –
C:\desktop> javac First .java
5. If any errors present compiler will show and programmer should clear those bugs.
6. Run the java file to see output using command
C:desktop> java First
NCET Page 12
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Working
Save file name as First.java (should be same as class name)
In the above program , first line shows the comment
Single line comment starts with the symbol / /
Multi line comment starts with /* and ends with */
Next we used import statement to import an entire package or sometimes import certain
classes and interfaces inside the package. The import statement is written before the class
definition and after the package statement (if there is any). Also, the import statement is
optional.
import java.io.*;
import java.util.Scanner ;
Class definition starts with keyword class followed by name
class First {
The next line of code is shown here:
public static void main(String args[ ] ) {
This line begins the main( ) method at which the program will begin executing.
The public keyword is an access specifier, which allows the programmer to
control the visibility of class members.
The keyword static allows main( ) to be called without having to create object
(instance of the class).
The keyword void simply tells the compiler that main( ) does not return a value.
In main( ), there is only one parameter, String args[ ] declares a parameter named
args, which is an array of instances of the class String. (Arrays are collections of
similar objects.) Objects of type String store character strings. In this case, args
receives any command-line arguments present when the program is executed.
The last character on the line is the{. This signals the start of main( )’s body.
NCET Page 13
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Note: Our program may contain more than one class also but only one class contains main
method to get things started.
The next line of code is shown here. Notice that it occurs inside main( ).
System.out.println("Welcome to NCET ");
This line outputs the string “Welcome to NCET” followed by a new line on the screen.
Output is actually accomplished by the built-in println( ) method. In this case, println( )
displays the string which is passed to it. As you will see, println( ) can be used to display
other types of information, too. The line begins with
System.out. Systemis a predefined class that provides access to the system,
andoutis the output stream that is connected to the console.
The first } in the program ends main( ), and the last } ends the First class definition.
Boolean –
The Boolean data type is used to store only two possible values: true and false.
The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
Example:
Boolean one = false ;
System.out.println(one) ; //false
Byte –
It is an (1 byte)8-bit signed two's complement integer. Its value-range lies between -
128 to 127 (-28 to 28-1).
NCET Page 14
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Its minimum value is -128 and maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings
is most required.
It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.
Example: byte a = 10,b= -20 ;
Short
The short data type is a (2 bytes)16-bit signed two's complement integer. Its value-
range lies between -32,768 to 32,767 (-216 to 216-1). Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short
data type is 2 times smaller than an integer.
Example: short s=10000 , r=-5000;
Int
The int data type is a (4 bytes) 32-bit signed two's complement integer. Its value-range
lies between - 2,147,483,648 (-232) to 2,147,483,647 (232-1) . Its default value is 0.
The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.
Example: int a=10000, b=-5000;
Long
The long data type is a 64-bit(8 bytes) two's complement integer. Its value-range lies
between -264 to 264-1.
Its default value is 0. The long data type is used when you need a range of values more
than those provided by int.
Example: long a=100000L
Float
Variables of type float are useful when we need to store fractional component.
float is a keyword.
Size is 4 bytes (32 bits) and its value range lies between -232 to 232-1
Example: float a=10.6;
Double
The double data type is a 64-bit floating point. Its value range is unlimited.
The double data type is generally used for decimal values just like float.
Example: double a=10.6;
char
The char data type is used to store characters.
The char data type is a single 16-bit Unicode (ASCII) character.
The range of a char is 0 to 65,536. There are no negative chars.
NCET Page 15
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
ASCII(American Standard Code for Information Interchange), a set of digital codes
representing letters, numerals, and other symbols, widely used as a standard format in the
transfer of text between computers.
Example: char a=’K’; //K
char a=’75’; //75
char a=75; //K
Note: in the 3rd example above, 75 is not inside pair of single quotes so we will get answer as
ASCII code of that
Arrays
Array is group of similar type of elements referenced by common name.
Arrays of any type can be created and may have one or more dimensions. A specific element in an array is
accessed by its index.
Arrays in Java work differently than they do in other languages like C,C++.
One-Dimensional Array -
Elements stored either in single row or single column we called 1-dimensional array.
Declaration:
Syntax: type name [ ] ; Example: int a [ ] ;
class First
{
public static void main( String args[ ] )
{
int a[ ] = new int[ 5 ] ; //declaration and instantiation Output:
a[0]=10; //initialization 10
a[1]=20; 20
//printing array 0
for(int i=0 ; i<a.length ; i++) //length is the property of array 0
System.out.println( a[i] ); 0
}
}
NCET Page 16
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Multi-Dimensional Array -
Elements stored in the form of more than one row and more than one column we called multi-dimensional
array.
Declaration:
Syntax: type name [ ] [ ] ; Example: int a [ ] [ ];
Variable
Variable is a name given to memory location to store data while java program executed.
It is a combination of "vary + able" which means its value can be changed.
Types of Variables
local variable
instance variable
static variable
Local Variable
A variable declared inside the body of the method is called local variable.
You can use this variable only within that method and the other methods in the class aren't even
aware that the variable exists.
A local variable cannot be defined with "static" keyword.
NCET Page 17
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
To access instance variable we need to create object of the class.
Static variable
A variable that is declared as static is called a static variable. It cannot be local.
To access static variable no need to create object of the class.
You can create a single copy of the static variable and share it among all the instances of the
class.
Memory allocation for static variables happens only once when the class is loaded in the memory.
Example:
public class A
{
int data=50; //instance variable
static int m=100; //static variable
void demo( )
{
int n=90; //local variable
}
public static void main(String args[])
{
int b=20; //instance variable
}
}
variable ‘data’ is a instance variable because to access ‘data’ variable we should create object of
the class.
variable ‘m’ is declared as static that means, we can access ‘m’ anywhere without creating object.
variable ‘n’ is a local variable that means variable ‘n’ is visible(valid) only inside method demo( )
and we can’t access in other methods.
Display (output) :
To Display value or string or combination of value and string, we will use the statement,
System.out.println(“Kiran”); //prints just a string
System.out.println(a); //prints just value of a string
System.out.println(“Result is”+a); //prints combination of value and string
Where,
println( ) is used to display along with newline . We can also use just print( ) but without newline.
out is an instance of PrintStream type, which is a public and static member field of the System class.
NCET Page 18
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Read (Input):
To Read value of a variable at compile time we will use ,
Example: int a =10,b=20;
To Read value of a variable at Run time (from the keyboard ) we will use Scanner class
Scanner:
Scanner class in Java is found in the java.util package. Java provides various ways to read
input from the keyboard, the java.util.Scanner class is one of them.
The Java Scanner class provides nextXXX( ) methods to return the type of value such as
nextInt( ), nextByte( ), nextShort( ), next( ), nextLine( ), nextDouble( ), nextFloat( ),
nextBoolean( ), etc.
To get a single character from the scanner, you can call next( ).charAt(0) method which
returns a single character.
Example:
Scanner sc = new Scanner(System.in);
System.out.println(“Enter a name” );
String a = sc.next( ) ; //Read a String
System.out.println(“Enter value of n” );
int a = sc.nextInt( ) ; //Read an interger value
System.out.println(“Enter percentage” );
float a = sc.nextFloat( ) ; //Read an floating point number
NCET Page 19
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Operators
Arithmetic Operators
Relational Operators
Logical Operators
Increment/Decrement Operators
Assignment Operators
Conditional Operators
Bitwise Operators
Arithmetic operators
Operator used to perform arithmetic operations.
Type casting
We can called as Explicit type conversion.
Conversion from one data type to other done externally by the programmer.
This occurs when expression contains two operands of same data type and expecting result is other
data type.
Syntax: (type)expression
int / int=float expecting decimal result after dividing two integers then do type casting.
Ex: 2/3=?
(flaot)2/(float)3 2.0 /3.0 0.66answer.
NCET Page 20
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Relational operators
operators used to find relationship between two operands are called relational operator.
Relational operator result is either true or false
Operator Symbol Priority Example Result Associativity
Less than < 1 10 > 20 0 L-R
Greater than > 1 10 < 20 1 L-R
Lesser or Equal <= 1 10 <= 20 1 L-R
Greater orEqual >= 1 10 >= 20 0 L-R
Equal == 2 10 == 10 1 L-R
Not Equal != 2 10 != 10 0 L-R
Logical operators
Operator used to combine 2 or more relational expressions are called logical operators.
Logical operators are used in comparisons and results the boolean value either true or false.
Operator Description Example
&& (AND) This operator returns true if and only if both boolean a=true, b=false;
operands are true otherwise, returns false. a && b // returns false
|| (OR) This operator returns true if and only if any boolean a=true, b=false;
one of the operand is true otherwise, returns a || b // returns true
false.
^ (XOR) This operator returns false if and only if both boolean a=true, b=true;
operands are either true or false otherwise, a || b // returns false
returns true.
! (NOT) As this is unary operator it will returns true if boolean a=true;
the operand is false and vise versa. !a //returns false
Assignment operator
Operator used to assign some values to the variables.
This operator is used to assign some value present in the RHS side to LHS variable.
Types:
Simple Assignment: Assigning RHS value to LHS variable.
Example : C=a+b;
Multiple Assignment: if more than one variable having same value then we will prefer
multiple assignment operator.
Example: C=D=a+b;
Compound Assignemnt: if LHS variable name and RHS first operand name is same then
we will prefer compound assignemnt(+=, -=,*=,/=).
Example: a=a+b; can be rewrite as a += b;
C=C-b; can be rewrite as C -= b;
NCET Page 21
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Increment / Decrement operators
These operators are used to incremnet /decement a value of the variable by one.
Example:
Conditional operator
It is also called ternary operator.
Symbol ? and :
Syntax: (expression1)?expression2:expression3
Ex :(4>5)?4:5
NCET Page 22
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Bit wise operators
Bit wise operators are used to manipulate the bits.
When compared to logical operators, Bit-wise operators are not used for comparisons
rather these operators are used to manipulate the bits.
Operator Symbol Description Example
Bitwise AND & This operator returns result true if and only if int a=5,b=6,c;
both operands are true. c=a&b;
// 50101
60110
c 0100=4
Bitwise OR | This operator returns result true if and only if int a=5,b=6,c;
any one operand is true. c=a|b;
// 50101
60110
c 0111=7
Bitwise XOR ^ This operator returns result false if and only if int a=5,b=6,c;
either both operands are true or both operands c=a^b;
are false. // 50101
60110
c 0011=3
Bitwise ~ As this is unary operator, if operand is true then int a=6,c;
NOT result will be false and vise versa. c=~a;
// 60110
~6 1001=9
Left shift << Shift the user specified number of bits towards int a=6,c ;
left. c=a<<1;
// 6 0110
Shift 1 bit towards left side.
Output:1100=12
Right shift >> Shift the user specified number of bits towards int a=6,c ;
right. c=a>>1;
// 6 0110
Shift 1 bit towards right side.
Output:0011=3
Control statements
Conditional statements
o Conditional Branch statements – if ,if-else, else-if ladder,switch.
o Conditional iterative(looping) statements – for , while, do-while.
Unconditional statements
break, continue
NCET Page 23
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
if
keyword is if
This is used to check only one condition at a time. So it is called as one way selection statement.
Syntax: if expression is true then it will execute set of statements
if( expression )
{ statements; }
Example:
int a=5 ,b=3;
if(a>b)
System.out.println(“a is Big:” +a); //output: a is Big:5
if - else
class First
{
public static void main( String s[ ] )
{
int n = 13;
if (n%2= = 0)
{
System.out.println(“even number”);
}
else
{
System.out.println (“odd number”);
}
}
}
NCET Page 24
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
else if ladder
Nested if statement
“An if or if –else statements present within another if or if-else statement is called nested if statement”.
if(condition1)
if(a>b)
{
{
if(condition 2) if(a>c)
{ {
Statements; System.out.println (“a is big”);
} }
} }
else if(b>c)
{
System.out.println (“b is big”);
}
else
{
System.out.println (“c is big”);
}
NCET Page 25
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
switch statement
switch statement is used to make selection between many alternatives.
Instead of else-if statement we are using switch to reduce program complexity.
Syntax:
switch( choice)
{
case 1: statements;
break;
case 2: statements;
break;
…………………..
………………….
default : System.out.println(“give error message”);
}
NCET Page 26
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Looping statements
We can also known as repetition or iteration statements.
A set of statements may have to be repeatedly executed for specified number of time or till the condition
satisfied called looping statements.
Types or three ways of Loops
while loop
for loop
do-while loop
while loop
A set of statements may have to be repeatedly executed till the condition is true once the condition becomes
false control comes out of the loop.
It is pre-test loop or top testing looping and hence condition testing occurs at the top.
Syntax:
initialization;
while(condition)
{
Statements;
increment / decrement ;
}
Example:
package jk;
import java.util.Scanner;
NCET Page 27
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
// Java program to find sum of natural numbers
package jk;
import java.util.Scanner;
sum=0;
i=1;
while(i<=n)
{
sum =sum+i;
i++;
}
System.out.println("sum="+sum);
}
for loop
A set of statements may have to be repeatedly executed for specified number of time or till the
condition satisfied.
Once specified number of times loop executed, control comes out of the loop.
This method is also top testing loop i.e condition is test at the top and body of the loop executed
only if the condition is true.
Syntax:
NCET Page 28
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Examples:
//Java Program to print squares of a natural numbers.
package jk;
import java.util.Scanner;
sum=0;
for(i=1;i<=n;i++)
{
sum=sum+i*i;
}
System.out.println("sum="+sum);
}
}
package jk;
import java.util.Scanner;
fact=1;
for(i=1;i<=n;i++)
{
fact= fact*i;
}
System.out.println(fact);
}
}
NCET Page 29
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
//Java Program to print the first n terms of Fibonacci series. (Lab Program)
package jk;
import java.util.Scanner;
public class Fib
{
public static void main(String[] args)
{
int n,i,first,second,next;
first=0;
second=1;
System.out.print(first+"\t"+second);
for(i=2;i<=n-1;i++)
{
next=first+second;
System.out.print("\t"+next);
first=second;
second=next;
}
}
}
// Java Program to find given number is prime or not
package jk;
import java.util.Scanner;
for(i=1; i<=n ; i ++ )
{
if( n % i == 0 )
counter ++ ;
}
if(counter == 2)
System.out.println("The Given Number " +n+ " is a prime" ) ;
else
System.out.println("The Given Number " +n+ " is not a prime");
}
}
NCET Page 30
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
do while loop
do while loop is similar to while loop but condition is test at bottom.
This loop is called post-testing or bottom- testing loop.
As bottom testing loop , all the statements within body are executed at least once .
Syntax:
do
{
Statements;
}while(condition);
semicolon ( ; ) is must at the end of do-while loop.
Example:
import java.util.Scanner;
sum=0;
i=1;
do
{
sum =sum+i;
i++;
} while(i<=n) ;
System.out.println("sum="+sum);
}
}
NCET Page 31
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
foreach loop
The Java for-each loop or enhanced for loop.
It provides an alternative approach to traverse the array in Java.
The advantage of the for-each loop is that it eliminates the possibility of bugs and makes the code
more readable.
It is known as the for-each loop because it traverses each element one by one.
The drawback of the enhanced for loop is that it cannot traverse the elements in reverse order.
But, it is recommended to use the Java for-each loop for traversing the elements of array because
it makes the code readable.
Syntax
The syntax of Java for-each loop consists of data_type with the variable followed by a colon (:), then array.
for (type var_name : Array_name)
{
//Body of the loop
}
Example:
package jk;
for(int i:a)
System.out.println(i);
}
}
NCET Page 32
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
break
break we can use in switch statement(branching) and also in looping statements.
Use break in switch statement to terminate it.
Use break in looping statement, to make control come out of that loop.
Examples : break used in loop break used in switch
for(i=1;i<=5;i++) switch(operator)
{ {
if (i= = 3) case ‘+’ : System.out.println(a+b);
break; break;
case ‘-’: System.out.println(a-b);
System.out.print(“\t”+i);
break;
} }
Output:
12
means control break when i is 3
continue
continue used only in looping statements.
This keyword used to skips execution of present statement and continue execution from next statement.
for(i=1;i<=5;i++)
{
if (i= = 3)
continue;
System.out.print (“\t”+i);
}
Output:
12 4 5
NCET Page 33
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
MODULE 2
CLASS
OBJECTS
REFERENCE VARIABLE
CLASSES METHODS
CONSTRUCTORS
GARBAGE COLLECTION
METHODS METHOD OVERLOADING
CONSTRUCTOR OVERLOADING
OBJECTS AND METHODS
NESTED CLASSES
ACCESS MODIFIER
SETTER AND GETTER
NCET Page 34
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Class
Keyword is class.
class is a collection of fields, methods, constructors, and certain properties.
class acts like a blueprint.
When defining class , it should starts with keyword class followed by name of the class;
and the class body, enclosed by a pair of curly braces.
In the above example class definition, class name is First ,r is a member(instance variable means
need to create object to access) which is used to find area of circle, and main is a method or
function to perform operation and Math.PI gives the mathematical constant that is 3.1412.
Object
Object is a instance of the class.
Object is used to access members and member functions.
Object should be created for instance variable, but for local variables and static variable
object creation is not required.
Object is created using new keyword , which allocates the memory for object when its
created.
NCET Page 35
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Example:
Reference variables
A reference variable is used to access the object of a class. Reference variables are created
at the program compilation time.
Reference variable is just a alias name for object.
Object reference variables act differently than you might expect when an assignment takes
place.
b1
For example, First object
First b1=new First( ) ; b2
First b2=b1 ;
We might think that b2 is being assigned a reference to a copy of the object referred to by
b1. That is, we might think that b1and b2 refer to separate and distinct objects. However,
this would be wrong. Instead, after this fragment executes, b1and b2 will both refer to the
same object. The assignment of b1 to b2 did not allocate any memory or copy any part of
the original object. It simply makes b2 refer to the same object as does b1. Thus, any
changes made to the object through b2 will affect the object to which b1is referring, since
they are the same object.
NCET Page 36
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Methods
We already know that class contains members (instance variables) and member functions
(methods).
A method is a module or function, which is used to declare the elements of its structure.
A method is used to reduce the whole problem into smaller problems to make it easy
programming.
Access modifier: this determines the visibility of a variable or a method from another class.
Return type: A method may return a value. If a method is not returning any value then method
return data type should be void, if method returning integer value then method return type should
be int, etc.,
Method name: It’s a unique identifier and it’s case sensitive. It cannot be same as any other
identifier.
Parameter List: enclosed between parenthesis. Parameter List is optional that is, a method may
contain no parameters.
Method Body: this contains the set of instructions need to complete the required activity.
Scope
Local Scope:
o The variables which are declared inside one method, we cannot use the same
variables in other method.
o The left and right curly braces that form the body of a method create scope.
Class Scope:
o The variable which are declared inside the class and outside all the methods,
which are used in any methods known as Class Scope.
Writing method –
o Without parameters and without return value.
o Without parameters and with a return value.
o With parameters and without return value.
o With parameters and with return value.
NCET Page 37
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Writing a Method without parameters and without return value
In this type A Method will not accept any parameters and not return any value to the
Main method.
Example: program to find the Sum of 2 numbers
public class First
{
public void add()
{
int a=20, b=30, sum;
sum=a+b;
System.out.println("Addition is: " +sum );
}
public static void main(String[] args)
{
First obj = new First( ) ;
obj.add( ) ;
}
}
NCET Page 38
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
public class First
{
public void add(int a,int b)
{
int sum;
sum=a+b;
System.out.println("Addition is: " +sum );
}
public static void main(String[] args)
{
First obj = new First( ) ;
obj.add(20,30 ) ;
}
}
In this type A Method will accept parameters and return value to the Main method.
Example: program to find the Sum of 2 numbers
public class First
{
public int add(int a,int b)
{
int sum;
sum=a+b;
return sum;
}
public static void main(String[] args)
{
First obj = new First( ) ;
int sum =obj.add(20,30 ) ;
System.out.println("Addition is: " +sum );
}
}
NCET Page 39
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Constructors
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created.
At the time of calling constructor, memory for the object is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new( ) keyword, at least one constructor is
called.
It calls a default constructor if there is no constructor available in the class. In such case,
Java compiler provides a default constructor by default.
Types of constructors:
1. Default or parameter less constructor.
2. Parameterized constructor.
3. Copy constructor.
NCET Page 40
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Parameterized constructor
If a Constructor method is defined with parameters, we call that as parameterized
constructor.
Parameterized constructor should be defined by the programmer but never defined by the
compiler implicitly.
Example:
public class First
{
int a, b ;
Copy Constructor
If we want to create multiple instances with the same value then we can use copy
constructor.
Copy constructor is used to copy data of one object into another object.
In copy constructor, the constructor takes the same class as a parameter to it.
public class First
{
int a, b ;
NCET Page 41
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
this keyword
In Java, this is a reference variable that refers to the current object.
Uses –
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.
Etc..,
The this keyword can be used to refer current class instance variable. If there is
ambiguity (confusion) between the instance variables and local parameters, this keyword
resolves the problem of ambiguity.
Example:
//without using this keyword
public class First
{
int a, b ; String name;
}
}
In the above program , instance variables and local variables are with same name so, compiler
will returns default values of their datatypes.
//Using this keyword
public class First
{
int a, b ; String name;
}
}
NCET Page 42
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Garbage Collection
Since objects are dynamically allocated by using the new operator, we might be wondering
how such objects are destroyed and their memory released for later reallocation.
In some languages, such as C++, dynamically allocated objects must be manually released
by use of a delete operator. Java takes a different approach; it handles deallocation for you
automatically.
The technique that accomplishes this is called garbage collection. 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 can be reclaimed. There is no explicit need to destroy
objects as in C++.
Garbage collection only occurs sporadically (if at all) during the execution of your
program.
It will not occur simply because one or more objects exist that are no longer used.
Furthermore, different Java run-time implementations will take varying approaches to
garbage collection, but for the most part, you should not have to think about it while
writing your programs.
Method overloading
Java allows us to create more than one method with same name, but with different
parameter list and different definitions. This is called method overloading.
Method overloading is used when methods are required to perform similar tasks but using
different input parameters. Overloaded methods must differ in number and/or type of
parameters they take.
This enables the compiler to decide which one of the definitions to execute depending on
the type and number of arguments in the method call.
Example:
public class First
{
public void Addition( int a, int b)
{
System.out.println(a+b);
}
public void Addition( int a, int b,int c)
{
System.out.println(a+b+c);
}
public static void main(String[] args)
{
First obj = new First( ) ;
obj.Addition(10, 20);
obj.Addition(10, 20, 30);
}
}
NCET Page 43
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Constructor Overloading
The process of creating more than one constructor with same name, which is similar to class
name, but with different parameters is called constructor overloading.
Example:
public class First
{
int a, b ,c ;
First(int x, int y)
{
a=x; b=y;
}
First(int x, int y,int z)
{
a = x; b = y; c = z;
}
obj.addition(obj);
}
}
NCET Page 44
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Objects and arrays
Array is a set of similar type of elements.
In Java, Arrays are implemented as objects.
Because of this, there is a special array attribute that you will want to take advantage of. Specifically, the
size of an array—that is, the number of elements that an array can hold—is found in its length instance
variable.
All arrays have this variable, and it will always hold the size of the array.
Here is a program that demonstrates this property:
class inner
{
void display( )
{ System.out.println("value of a is "+a); }
}
void test( )
{
inner obj=new inner();
obj.display();
}
NCET Page 45
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Access Modifiers (Access Specifiers)
The access modifier’s in Java specifies the accessibility or scope of a field, method, constructor, or class.
We can change the access level of fields, constructors, methods, and class by applying the access modifier on it.
Types:
Public
Private
Protected
Public Y Y Y Y
Private Y N N N
Protected Y Y Y N
Public
The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class,
within the package and outside the package.
It has the widest scope among all other modifiers.
Example:
public class A
{
public void msg() //public method
{
System.out.println("Hello Kiran");
}
}
public class B
{
public static void main(String[] args)
{
A obj=new A();
obj.msg();
}
}
NCET Page 46
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Private
The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
Example:
package jk; //save as A.java in jk package
public class A
{
private void msg() //private method
{
System.out.println("Hello Kiran");
}
}
public class B
{
public static void main(String[] args)
{
A obj=new A(); Compile error : cant access
obj.msg();
private method outside the
}
} class
Similarly we can’t access private variables(members) also from outside the class.
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.
Example:
package jk; //save as A.java in jk package
public class A
{
protected void msg() //protected method
{
System.out.println("Hello Kiran");
}
}
NCET Page 47
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Setters and getters
Getter and Setter are methods used to protect your data and make your code more secure.
Getter returns the value( that is, it returns the value of data type int, String, double, float, etc.) While Setter
sets or updates the value. It sets the value for any variable used in a class’s programs.
Private members (variables) of one class can access in another class using set and get methods.
Example:
public class C1
{
private String name; //name variable is private
public class C2 {
}
Output:
NCET Page 48
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Lab Programs:
2.a. Write a Java program to demonstrate method overloading to create a class called Calculator with three
methods named Demo with different type of parameters and print the computed results.
package jk;
import java.util.Scanner;
a=sc.nextInt(); b=sc.nextInt();
c=sc.nextInt(); d=sc.nextInt();
obj.Demo(a,b);
obj.Demo(a,b,c);
obj.Demo(a,b,c,d);
}
}
Output:
NCET Page 49
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
2.b. Write a Java program to demonstrate constructor overloading to calculate the area of a rectangle and
circle.
package jk;
System.out.println("Area of a Circle:");
System.out.println(3.142*obj1.r*obj1.r);
System.out.println("Area of a Rectangle:");
System.out.println(obj2.l*obj2.b);
}
}
Output:
NCET Page 50
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
MODULE 3
INHERITANCE BASICS
USING SUPER
INHERITANCE CREATING MULTI-LEVEL HIERARCHY
INTERFACES METHOD OVERRIDING
PACKAGES USING ABSTRACT CLASSES
USING FINAL
INTERFACES.
PACKAGES: ACCESS PROTECTION,
IMPORTING PACKAGES
Inheritance
One of the most important concepts in object-oriented programming is
inheritance.
To inherit a class, we simply incorporate the definition of one class into another by using the
extends keyword.
Definition:
“Creating a new class (child class) from existing class (parent class) is called as
inheritance”.
Or
“Acquiring (taking/Consuming) the properties of one class into another class is
called inheritance.”
Or
“When a new class needs same members as an existing class, then instead of
creating those members again in new class, the new class can be created from
existing class, which is called as inheritance.”
Main advantage of inheritance is reusability of the code and Method overriding (polymorphism) can be
achieved.
Base class: is the class from which features are to be inherited into another class.
Syntax:
class Base_Class
{
Members of class
}
Derived class: it is the class in which the base class features are inherited.
Syntax:
class Derived_class extends Base_class
{
Members of class
}
NCET Page 51
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Example:
As shown above child class can access properties (variables or methods) of the parent class.
Types of Inheritance:
Inheritance can be classified into 5 types
1. Single Inheritance
2. Multi-Level Inheritance
3. Hierarchical Inheritance
4. Hybrid Inheritance
5. Multiple Inheritance
Single Inheritance
Base class
When a single derived class is created from a single base
class then the inheritance is called as single inheritance.
Derived class
Syntax:
class A
{
----
----
}
class B extends A
{
----
----
}
NCET Page 52
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Example:
package jk;
class Test
{
public static void main(String[] args)
{
Two obj = new Two();
obj.display1();
obj.display2();
}
}
NCET Page 53
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Example:
package jk;
class One
{
void display1()
{
System.out.println("Ha ha ha");
}
}
class Two extends One
{
void display2()
{
System.out.println("Hi hi hi");
}
}
class Three extends Two
{
void display3()
{
System.out.println("La La La");
}
}
class Test
{
public static void main(String[] args)
{
Three obj=new Three();
obj.display1();
obj.display2();
obj.display3();
}
}
Hierarchical Inheritance
When more than one derived class is created from a single base class, then that inheritance is called as
hierarchical inheritance.
Base Class
Syntax:
class A
Derived Class 1 Derived Class 2 {- - - - - }
class B extends A
{- - - - -}
class C extends A
{---- - -}
NCET Page 54
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
package jk;
}
public class Two extends One
{
void display2()
{
System.out.println("Hi hi hi");
}
}
public class Three extends One
{
void display3()
{
System.out.println("La La La");
}
}
public class Test {
Hybrid Inheritance
Any combination of single, hierarchical, multi-level and Multiple inheritances is called as hybrid
inheritance.
Class A
class C extends B
NCET Page 55
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
package jk;
}
public class Two extends One
{
void display2()
{
System.out.println("Hi hi hi");
}
}
public class Three extends Two
{
void display3()
{
System.out.println("La La La");
}
}
public class Four extends One
{
void display4()
{
System.out.println("wow wow wow");
}
}
public class Test {
Note: Students should note that the concept explained above is multi level hierarchy (if students got question in
exam Explain how to create multilevel hierarchy)
NCET Page 56
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Multiple Inheritances
In multiple inheritance, one class can have more than one super class (Base class) and inherits
features from all parent classes.
Note: Java doesn’t supports Multiple Inheritance with class and it can achieved by using
Interfaces.
Note: Students need explain in the exam by using interface if marks are more.
Syntax:
Base interface 1 Base interface 2 interface A
{- - - - - }
class C implements A , B
{- - - - -}
NCET Page 57
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
super keyword
The super keyword in Java is a reference variable which is used to refer immediate parent class
object.
super keyword in java we can use in different ways
super can be used to refer immediate parent class instance variable.
super can be used to invoke immediate parent class method.
super( ) can be used to invoke immediate parent class constructor.
package superexample;
}
}
The super keyword can also be used to invoke parent class method.
It should be used if subclass contains the same method as parent class. In other words, it
is used if method is overridden.
NCET Page 58
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
package superexample;
package superexample;
NCET Page 59
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Method overriding
The process of re-implementing the parent class method under the child class with same name
and same number of parameters is called method overriding.
Method overriding means same method names with same signatures(parameters) in different
classes.
Method overriding is used to provide the specific implementation of a method which is already
provided by its super class.
Method overriding is used for runtime polymorphism.
package jk;
NCET Page 60
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
class A class A
{ {
public void Display(int x, int y) public void Display(int x, in y)
{ {
System.out.println(x+y); System.out.println (x+y);
} }
public void Display(int x,int y, int z) }
{ class B extends A
System.out.println (x+y+z); {
} public void Display(int x, int y)
} {
class Test System.out.println (x*y);
{ }
public static void main(String s[ ] ) }
{ class Test
A obj = new A( ); {
obj.Display(10,20); public static void main(String s[ ] )
obj.Display(10,20,30); {
} B obj= new B( );
} Obj.Display(10,20);
}
Output: }
30
60 Output:
200
Abstract classes
A class which is declared with the abstract keyword is known as an abstract class in Java.
It can have abstract methods (method without body) and non-abstract methods (method
with the body).
Abstract class cannot be instantiated.
Abstract method:
A method without method body is known as abstract method.
It contains only declaration of the method.
We can define abstract method using abstract keyword.
Abstract method must be implemented in child class.
Note: Abstraction is the process of hiding the implementation details and showing only
functionality to the user.
Using abstract class we can achieve partial abstraction because this class may contains
non-abstract methods also
Using interface we can achieve 100% abstraction because interface contains only abstract
classes.
NCET Page 61
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
package jk;
final keyword
final keyword is used to restrict the user to change value of the variable or method or class.
That is, if the variable is declared as final then we cannot change throughout the program.
final variable
package jk;
NCET Page 62
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
final method
If we make any method as final, we cannot override it.
package jk;
final class
If we make any class as final, we cannot Inherits it.
package superexample;
public class Two extends One //we can’t extends final class One
{
public static void main(String s[]) Output:
{
//Body Compile Time Error
}
}
NCET Page 63
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Interfaces
An Interface is a collection of abstract methods (methods without definition / only method declarations) and abstract
methods should be implemented by the derived/child class.
Syntax:
interface interfaceName
{
Method declarations ; //only method protocols- No Implementation
}
Example:
package hi;
Note:
NCET Page 64
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Packages
A java package is a group of similar types of classes, interfaces and sub-packages.
Keyword is package
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Advantages:
Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
Java package provides access protection.
Java package removes naming collision.
NCET Page 65
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Here, we will have the detailed learning of creating and using user-defined packages.
class One
{
public static void main(String s[ ])
{
System.out.println(“package is created”);
}
}
Let us discuss how to access package from another package (Access Protection)
There are 3 ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
import package.*
If we use package.* then all the classes and interfaces of this package will be accessible.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
package mypack1; //save One.java in the package mypack1
NCET Page 66
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
import package.classname
If you import package.classname then only declared class of this package will be accessible.
package mypack1; //save One.java in the package mypack1
NCET Page 67
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
MODULE 4
Exception Handling
“Exception is a class responsible for abnormal termination of the program whenever run
time errors occurred in a program”.
A Java exception is an object that describes an exceptional (that is, error) condition that
has occurred in a piece of code.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally.
Briefly, here is how they work. Program statements that you want to monitor for
exceptions are contained within a try block. If an exception occurs within the try
block, it is thrown. Our code can catch this exception (using catch) and handle it
in some rational manner.
System-generated exceptions are automatically thrown by the Java run-time
system. To manually throw an exception, use the keyword throw. Any exception
that is thrown out of a method must be specified as such by a throws clause. Any
code that absolutely must be executed after a try block completes is put in a
finally block.
NCET Page 68
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
General form of an exception-handling block:
try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler forExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler forExceptionType2
}
// ...
finally
{
// block of code to be executed after try block ends
}
Exception Types
1. Built-in Exceptions
Checked Exception
Unchecked Exception
2. User-Defined Exceptions
NCET Page 69
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Built-in Exception
Exceptions that are already available in Java libraries are referred to as built-in exception.
It can be categorized into two broad categories, i.e., checked exceptions and unchecked
exception.
Checked exceptions
Checked exceptions are called compile-time exceptions because these exceptions are checked at
compile-time by the compiler. The compiler ensures whether the programmer handles the
exception or not. The programmer should have to handle the exception; otherwise, the system
has shown a compilation error.
Example:
Sl.No
Exception Description
1 ClassNotFoundException Class not found.
2 CloneNotSupportedException Attempt to clone an object that does not implement
the Cloneable interface.
3 IllegalAccessException Access to a class is denied.
4 InstantiationException Attempt to create an object of an abstract class or
interface.
5 InterruptedException One thread has been interrupted by another thread.
6 NoSuchFieldException A requested field does not exist.
7 NoSuchMethodException A requested method does not exist.
8 FileNotFoundException A requested file does not exist.
Etc,,,.
Un-Checked exceptions
An unchecked exception is an exception that occurs at the time of execution. These are also
called as Runtime Exceptions. These include programming bugs, such as logic errors or
improper use of an API. Runtime exceptions are ignored at the time of compilation.
The unchecked exceptions defined in java.lang
Sl.No
Exception Description
1 ArithmeticException Arithmetic error, such as divide-by-zero.
2 ArrayIndexOutOfBoundsException Array index is out-of-bounds.
3 IndexOutOfBoundsException Some type of index is out-of-bounds.
4 NullPointerException Invalid use of a null reference.
5 NumberFormatException Invalid conversion of a string to a numeric
format.
6 StringIndexOutOfBounds Attempt to index outside the bounds of a string.
7 ArrayStoreException Assignment to an array element of an
NCET Page 70
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
incompatible type.
8 ClassCastException Invalid cast.
9 EnumConstantNotPresentException Anattempt is made to use an undefined
enumeration value.
10 IllegalArgumentException Illegal argument used to invoke a method.
11 IllegalStateException Environment or application is in incorrect state.
12 IllegalThreadStateException Requested operation not compatible with current
thread state.
13 NegativeArraySizeException Array created with a negative size
14 SecurityException Attempt to violate security.
15 TypeNotPresentException Type not found
Example:
// A Class that represents user-defined exception
package kiran;
class MyException extends Exception
{
public MyException( )
{
System.out.println(“My exception occurs”);
}
}
NCET Page 71
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Uncaught Exceptions
In java, assume that, if we do not handle the exceptions in a program. In this case, when an
exception occurs in a particular function, then Java prints an exception message with the
help of uncaught exception handler.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Java programming language has a very strong exception handling mechanism. It allows us
to handle the exception use the keywords like try, catch, finally, throw, and throws.
When an uncaught exception occurs, the JVM calls a special private method
known dispatchUncaughtException( ), on the Thread class in which the exception occurs
and terminates the thread.
The Division by zero exception is one of the example for uncaught exceptions.
Look at the following code.
import java.util.Scanner;
Output:
In the above example code, we are not used try and catch blocks, but when the value of b is zero
the division by zero exception occurs and it caught by the default exception handler.
NCET Page 72
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Using try, catch - Exception handling keywords
Although the default exception handler provided by the Java run-time system is useful for
debugging, you will usually want to handle an exception yourself. Doing so provides two
benefits. First, it allows you to fix the error. Second, it prevents the program from
automatically terminating.
To handle a run-time error, simply enclose the code that we want to monitor inside a try
block. Immediately following the try block, includes a catch clause that specifies the
exception type that you wish to catch.
Example:
package jk;
import java.util.Scanner;
NCET Page 73
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Multiple catch Clauses
In some cases, more than one exception could be raised by a single piece of code.
To handle this type of situation, you can specify two or more catch clauses, each catching a
different type of exception.
When an exception is thrown, each catch statement is inspected in order, and the first one
whose type matches that of the exception is executed. After one catch statement executes,
the others are bypassed, and execution continues after the try/catch block.
Example:
Let us consider an example contain array of 3 elements and we trying to print 5th index element
which is not present and this error match with the second catch clause that print exception error.
package jk;
}
Output:
NCET Page 74
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Example:
package jk;
import java.util.Scanner;
}
}
Output: (Error in index)
NCET Page 75
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Output: (consider b value as zero)
throw keyword
So far, we have only been catching exceptions that are thrown by the Java run-time system.
However, it is possible for our program to throw an exception explicitly, using the throw
statement.
The general form of throw is shown here:
throw new exception_class( ) ; //we can pass parameter also
Where the throw Instance must be of type Throwable or subclass of Throwable. For example,
Exception is the sub class of Throwable and the user-defined exceptions usually extend the
Exception class.
Example: Below program shows using throw keyword in User Defined Exception similarly we
can also use throw keyword in checked and unchecked Exceptions also.
If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception. we do
this by including a throws clause in the method’s declaration.
throws keyword should use with method signature.
If we use throws keyword then no need of try and catch blocks.
A throws clause lists the types of exceptions that a method might throw.
Syntax:
The general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw.
Example:
package jk ;
NCET Page 77
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
finally keyword
finally creates a block of code that will be executed after a try/catch block has completed
and before the code following the try/catch block.
The finally block will execute whether or not an exception is thrown.
If an exception is thrown, the finally block will execute even if no catch statement matches
the exception.
The finally clause is optional. However, each try statement requires at least one catch or a
finally clause.
Syntax:
Example:
package jk;
import java.util.Scanner;
NCET Page 78
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Applets
Still now we discussed console based applications but to create window based applications
we will use applets.
Applet is a window based application works with java and html programs (files).
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
Some Important points –
An applet is a Java class that extends the java.applet.Applet class.
Applets are not stand-alone programs. Instead, they run within either a web
browser or an applet viewer. JDK provides a standard applet viewer tool called
applet viewer.
In general, execution of an applet does not begin at main( ) method.
Output of an applet window is not performed by System.out.println( ). Rather it is
handled with various AWT methods, such as drawString( ).
1. Open new notepad write java source code and save as First.java
2. Open command prompt for the same path where our java and html files present.
3. Compile java program to create class file by using command, javac First.java
4. Open new notepad in same folder of First.java , write html code that contains applet tag
with code=”First.class” and save as test.html
5. To create applet window type the command in the cmd prompt , appletviewer test.html
6. Finally our applet window is created and opened.
Simple Example:
//First.java
import java.awt.*;
import java.applet.*;
<html> //test.html
<applet code=”First.class” width=300 height = 300>
</applet>
</html>
NCET Page 79
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Output:
This applet begins with two import statements. The first imports the Abstract Window
Toolkit (AWT) classes that provides GUI(Graphical user Interface) by using paint ( )
method. The second import statement imports the applet package, which contains the class
Applet. Every applet that you create must be a subclass of Applet.
The next line in the program declares the class First. This class must be declared as public,
because it will be accessed by code that is outside the program.
Inside First, paint( ) is declared. This method is defined by the AWT. paint( )is called each
time that the applet must redisplay its output.
paint ( ) method is used for several purposes like to draw string , to draw rectangle , to draw
Line, show status etc,,.
Inside paint( )is a call to drawString( ), which is a member of the Graphics class. This
method outputs a string beginning at the specified X,Y location on the screen.
Notice that the applet does not have a main( )method. Unlike Java programs, applets do not
begin execution at main( ).
NCET Page 80
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Html program always starts with the tag <html>
Next line we starts with the tag
<applet code=”First.class” width=300 height=300>
means, in the html file we connect to our java compiled file that is class file with applet
window width and height values.
Next line we will close applet tag by </applet>
Next line we will close html tag by </html>
The java.applet.Applet class has 4 life cycle methods – init( ), start( ), stop( ) and destroy( )
java.awt.Component class provides 1 life cycle method – paint( ).
It is important to understand the order in which the various methods shown in the above
image are called.
When an applet begins, the following methods are called, in this sequence:
init( )
start( )
paint( )
When an applet is terminated, the following sequence of method calls takes place:
stop( )
NCET Page 81
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
destroy( )
int area=length*breadth;
g.drawString("Area of Rectangle is "+area ,100,100);
}
public void stop( ) //suspend current task
{
System.out.println("Welcome to Stop method "); //observe in cmd prompt while minimize applet window
}
public void destroy( ) //close or destroy the applet window
{
System.out.println("Welcome to destroy method "); //observe in cmd prompt while close applet window
NCET Page 82
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
}
}
<html> //save as test.html
<applet code="First.class" width=300 height=300>
</applet>
</html>
Output:
Now Applet window is created and shown to you (same time observe cmd prompt init, start paint
methods are invoked)
Minimize the applet and observe cmd prompt , stop method is invoked.
Close the applet window then stop and destroy method will be invoked.
NCET Page 83
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Applet Heirarchy
The AWT allows us to use various graphical components. When we start writing any applet
program we essentially import two packages namely – java.awt and java.applet.
The java.applet package contains a class Applet which uses various interfaces such as
AppletContext, AppletStub and AudioCIip.
The applet class is a sub class of Panel class belonging to java.awt package.
To create a user friendly graphical interface we need to place various components on GUI
window. There is a Component class from java.awt package which derives several classes
for components. These classed include Check box, Choice, List, buttons and so on.
The Component class in java.awt is an abstract class.
Component class is an extension of object class that is java.lang.Object.
NCET Page 84
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Passing parameters and getting parameters in applet
Output:
NCET Page 85
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
MODULE 5
Event Handling and Multi-
ThreadedProgramming:
Two event handling mechanisms, the
delegation event model,
Event classes,
EVENT HANDLING Sources of events,
AND MULTI- Event listener interfaces,
Using the delegation event model,
THREADED
Adapter classes, Inner classes.
PROGRAMMING Multi-Threaded Programming:
What are threads?
How to make the classes threadable,
Extending threads,
Implementing runnable,
Synchronization
NCET Page 86
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Multi-Threaded Programming
Multithreading in Java is a process of executing multiple threads simultaneously for
maximum utilization of CPU.
Each part of such a program is called a thread.
Multithreading is used to achieve multitasking.
There are two distinct types of multitasking:
Process based multitasking.
Thread-based multitasking.
Process-based multitasking (Multiprocessing):
Process-based multitasking is to run two or more programs concurrently
Each process has an address in memory. In other words, each process
allocates a separate memory area.
Thread-based multitasking (Multithreading):
In thread-based multitasking, a single program can perform two or more tasks
simultaneously.
Threads share the same address space.
Thread Model
A thread in Java at any point of time exists in any one of the following states. A thread lies only in one of
the shown states at any instant:
New:
The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.
Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.
Blocked
This is the state when the thread is still alive, but is currently not eligible to run.
NCET Page 87
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
WAITING:
A thread enters this state if it waits to be notified by another thread, which is the result of calling
Object.wait( ) or Thread.join( ). The thread also enters waiting state if it waits for a Lock or
Condition in the java.util.concurrent package. When another thread calls Objects
notify()/notifyAll() or Condition‟s signal()/signalAll(), the thread comes back to the runnable
state.
Timed-Waiting
A thread enters this state if a method with timeout parameter is called: sleep(), wait(),
join(), Lock.tryLock() and Condition.await(). The thread exits this state if the timeout expires or
the appropriate notification has been received.
Terminated
A thread enters terminated state when it has completed execution. The thread terminates for one
of two reasons:
o The run( ) method exits normally.
o The run() method exits abruptly due to a uncaught exception occurs.
NCET Page 88
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
NCET Page 89
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
NCET Page 90
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Example program that demonstrates Multi-threading programming which is the
combination of extends Thread and Implements runnable (Lab Program)
import java.util.Scanner;
public class Multithreading
{ Write a Java program that implements a multi-thread
public static void main(String[ ] args) application that has three threads. First thread
{ generates a random integer forevery 1 second; second
first t1=new first( ); thread computes the square of the number and prints;
t1.start( ) ; third thread will print the value of cube of the number.
}
}
NCET Page 91
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
class third implements Runnable
{
public int x;
public third(int x)
{
this.x=x;
}
public void run( )
{
System.out.println("Third thread: Cube of num is"+(x*x*x));
}
}
Output:
Synchronization
Synchronization in java is the capability to control the access of multiple threads to any shared
resource.
Key to synchronization is the concept of the monitor (also called a semaphore).
A monitor is an object that is used as a mutually exclusive lock, or mutex.
Only one thread can own a monitor at a given time.
When a thread acquires a lock, it is said to have entered the monitor.
All other threads attempting to enter the locked monitor will be suspended until the first thread
exits the monitor. These other threads are said to be waiting for the monitor.
Example:
NCET Page 92
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
package jk;
package jk;
package jk;
package jk;
t1.start();
t2.start();
}
}
NCET Page 93
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Output:
Without Thread Synchronization (Random output with both threads – we will get
different outputs with different runs)
11 51 51
51 11 11
52 52 52
12 12 12
53 13 53
13 53 13
54 54 14
14 14 54
55 55 15
15 15 55
With Thread Synchronization (Always gets same output that is Thread1 followed by
Thread2)
11
12
13
14
15
51
52
53
54
55
NCET Page 94
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Thread Priorities
Thread priorities are used by the thread scheduler to decide when each thread should be allowed
to run. In theory, higher-priority threads get more CPU time than lower-priority threads. In
practice, the amount of CPU time that a thread gets often depends on several factors besides its
priority. A higher-priority thread can also preempt a lower-priority one.
To set a thread’s priority, use the setPriority( ) method, which is a member of Thread.
Here, level specifies the new priority setting for the calling thread. The value of level must be
within the range MIN_PRIORITY and MAX_PRIORITY.
The following example demonstrates two threads at different priorities, which do not run on a
preemptive platform in the same way as they run on a non preemptive platform. One thread is set
two levels above the normal priority, as defined by Thread.NORM_PRIORITY, and the other
is set to two levels below it. The threads are started and allowed to run for ten seconds. Each
thread executes a loop, counting the number of iterations. After ten seconds, the main thread
stops both threads. The number of times that each thread made it through the loop is then
displayed.
NCET Page 95
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
lo.stop();
hi.stop();
// Wait for child threads to terminate.
try {
hi.t.join();
lo.t.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread: " + lo.click);
System.out.println("High-priority thread: " + hi.click);
}
}
The output of this program, shown as follows when run under Windows, indicates that the
threads did context switch, even though neither voluntarily yielded the CPU nor blocked for I/O.
The higher-priority thread got the majority of the CPU time.
NCET Page 96
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Event Handling
What is an Event?
Change in the state of an object is known as event i.e. event describes the change in
state of source.
Events are generated as result of user interaction with the graphical user interface
components.
For example, clicking on a button, moving the mouse, entering a character through
keyboard, selecting an item from list, scrolling the page are the activities that causes
an event to happen.
What is Event Handling?
Event Handling is the mechanism that controls the event and decides what should
happen if an event occurs.
These mechanisms have the code which is known as event handler that is executed
when an event occurs.
Java Uses the Delegation Event Model to handle the events.
This model defines the standard mechanism to generate and handle the events
Two event handling mechanisms;
The way in which events are handled changed significantly between the original
version of Java (1.0) and modern versions of Java, beginning with version 1.1.
The 1.0 method of event handling is still supported, but it is not recommended for
new programs.
Also, many of the methods that support the old 1.0 event model have been
deprecated. The modern approach is the way that events should be handled by all new
programs and thus is the method employed by Programs.
The Delegation Event Model
The delegation event model is defining standard and consistent mechanisms to
generate and process events.
A source generates an event and sends it to one or more listeners.
The listener simply waits until it receives an event.
Once an event is received, the listener processes the event and then returns.
In the delegation event model, listeners must register with a source in order to receive
an event notification.
The notifications are sent only to listeners that want to receive them.
Events:
An event is an object that describes a state change in a source.
Some of the activities that cause events to be generated are pressing a button,
entering a character via the keyboard, selecting an item in a list, and clicking the
mouse.
Events may also occur that are not directly caused by interactions with a user
interface.
Example:
An event may be generated when
NCET Page 97
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
A timer expires
A counter exceeds a value
A software or hardware failure occurs, or an operation is completed
Event Sources
A source is an object that generates an event, occurs when the internal state of
that object changes in some way.
Sources may generate more than one type of event.
A source must register listeners in order for the listeners to receive notifications
about a specific type of event.
Each type of event has its own registration method.
Syntax:
public void addTypeListener(TypeListener el)
Type is the name of the event
el is a reference to the event listener.
Example
The method that registers a keyboard event listener is called addKeyListener( )
The method that registers a mouse motion listener is called addMouseMotionListener( )
When an event occurs, all registered listeners are notified and receive a copy of the eventobject
is known as multicasting the event.
Some sources may allow only one listener to register.
Syntax:
public void addTypeListener(TypeListener el)
throws java.util.TooManyListenersException
Type is the name of the event
el is a reference to the event listener.
When such an event occurs, the registered listener is notified. This is known as unicasting the event.
A source must also provide a method that allows a listener to unregister an interest in a specific type
of event.
Syntax:
public void removeTypeListener(TypeListener el)
Type is the name of the event
el is a reference to the event listener.
Example:
To remove a keyboard listener, you would call removeKeyListener( ).
NCET Page 98
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
Sources of Events
Some of the user interface components that can generate the events.
In addition to these graphical user interface elements, any class derived from Component,
such as Applet, cangenerate events.
Example
You can receive key and mouse events from an applet. (You may also build your
own componentsthat generate events.)
Button Generates action events when the button is pressed.
Check box Generates item events when the check box is selected or
deselected.
Choice Generates item events when the choice is changed.
List Generates action events when an item is double-clicked;
generates itemevents when an item is selected or deselected.
Menu Item Generates action events when a menu item is selected;
generates itemevents when a checkable menu item is selected or
deselected.
Scroll bar Generates adjustment events when the scroll bar is manipulated.
Text components Generates text events when the user enters a character.
Window Generates window events when a window is activated, closed,
deactivated, iconified, opened, or quit.
NCET Page 99
OBJECT ORIENTED PROGRAMMING USING JAVA 2023
MouseMotionListener Defines two methods to recognize when the mouse is dragged or
moved.
MouseWheelListener Defines one method to recognize when the mouse wheel is
moved.
TextListener Defines one method to recognize when a text value changes.
This interface defines four methods that are invoked when a component is resized, moved,
shown, or hidden. Their general forms are shown here:
This interface defines five methods. If the mouse is pressed and released at the same point,
mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered( ) method
void mouseClicked(MouseEventme)
void mouseEntered(MouseEventme)
void mouseExited(MouseEventme)
void mousePressed(MouseEventme)
void mouseReleased(MouseEventme)
KeyEvent :
A KeyEvent is generated when keyboard input occurs. There are three types of key events, which are identified
by these integer constants:KEY_PRESSED, KEY_RELEASED, and KEY_TYPED. The first two events are
generated when any key is pressed or released. The last event occurs only when a character is generated. Remember
not all keypresses result in characters. For example, pressing shift does not generate a character.
There are many other integer constants that are defined by KeyEvent.
For example, VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbers
MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggersPopup)
Using the delegation event model is actually quite easy. Just follow these two steps:
1. Implement the appropriate interface in the listener so that it will receive the type of event
desired.
2. Implement code to register and unregister (if necessary) the listener as a recipient for the event
notifications.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet
implements MouseListener, MouseMotionListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init ( ) {
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint( );
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint ( );
}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
To handle keyboard events, you use the same general architecture as that shown in the mouse
event example in the preceding section. The difference, of course, is that you will be
implementing the KeyListenerinterface.
Before looking at an example, it is useful to review how key events are generated. When a key is
pressed, a KEY_PRESSED event is generated. This results in a call to the keyPressed( ) event
handler. When the key is released, a KEY_RELEASED event is generated and the
keyReleased( ) handler is executed. If a character is generated by the keystroke, then a
KEY_TYPED event is sent and the keyTyped( ) handler is invoked. Thus, each time the user
presses a key, at least two and often three events are generated. If all you care about are actual
characters, then you can ignore the information passed by the keypress and release events.
However, if your program needs to handle special keys, such as the arrow or function keys, then
it must watch for them through the keyPressed( ) handler.
The following program demonstrates keyboard input. It echoes keystrokes to the applet window
and shows the pressed/released status of each key in the status window.
Adapter Classes
Java provides a special feature, called anadapter class,that can simplify the creation of event
handlers in certain situations. An adapter class provides an empty implementation of all methods
in an event listener interface. Adapter classes are useful when you want to receive and process
only some of the events that are handled by a particular event listener interface. You can define a
new class to act as an event listener by extending one of the adapter classes and implementing
only those events in which you are interested.
For example, the MouseMotionAdapterclass has two methods, mouseDragged( ) and
mouseMoved( ), which are the methods defined by the MouseMotionListener interface. If you
were interested in only mouse drag events, then you could simply extend MouseMotionAdapter
and overridemouseDragged( ). The empty implementation of mouseMoved( ) would handle the
mouse motion events for you.
The following example demonstrates an adapter. It displays a message in the status bar of an
applet viewer or browser when the mouse is clicked or dragged. However, all other mouse events
are silently ignored. The program has three classes. AdapterDemo extends Applet. Its init( )
method creates an instance of MyMouseAdapter and registers that object to receive
notifications of mouse events. It also creates an instance of MyMouseMotionAdapter and
registers that object to receive notifications of mouse motion events.
Both of the constructors take a reference to the applet as an argument. MyMouseAdapter
extends MouseAdapter and overrides the mouseClicked( ) method. The other mouse events are
silently ignored by code inherited from the MouseAdapter class. MyMouseMotionAdapter
extends MouseMotionAdapter and overrides the mouseDragged( ) method. The other mouse
motion event is silently ignored by code inherited from the MouseMotionAdapterclass.
As you can see by looking at the program, not having to implement all of the methods defined by
the MouseMotionListener and MouseListenerinterfaces saves you a considerable amount of
effort and prevents your code from becoming cluttered with empty methods.