CORE JAVA MODULE 2 NOTES
INTERFACES:- Defining and Implementing Interfaces, Abstract Classes land Methods, Multiple Interface
Implementation
1. INTERFACE IN JAVA:-
- An interface in Java is a collection of abstract methods (methods without body).
- It is used to achieve abstraction and multiple inheritance in Java.
Syntax:
interface InterfaceName {
// constant variables
int x = 10;
// abstract method
void display();
2. DEFINING AND IMPLEMENTING INTERFACES:-
• DEFINING AN INTERFACE:-
- Use the keyword interface instead of class.
- All methods are public and abstract by default.
- Variables are public, static, and final by default.
• IMPLEMENTING AN INTERFACE:-
- A class implements an interface using the implements keyword.
- The class must provide the body for all abstract methods in the interface.
Example:
interface Animal {
void sound(); // abstract method
Prepared by: Nandini Shetty | [Link]. IT
class Dog implements Animal {
public void sound() {
[Link]("Dog barks");
public class Test {
public static void main(String[] args) {
Animal a = new Dog();
[Link]();
Output:
Dog barks
Explanation:
- Animal is an interface with an abstract method sound().
- Dog implements it and provides the body.
- Interface ensures a common behavior across classes.
3. ABSTRACT CLASSES AND METHODS
ABSTRACT CLASS:-
- An abstract class is a class declared using the keyword abstract.
- It can have abstract methods (without body) and non-abstract methods (with body).
FEATURES:
- Cannot be instantiated directly.
- Can include constructors, fields, and concrete methods.
Prepared by: Nandini Shetty | [Link]. IT
- Used when some implementation is common but others must be implemented by subclasses.
Syntax:
abstract class Shape {
abstract void draw(); // abstract method
void display() {
[Link]("Displaying shape");
class Circle extends Shape {
void draw() {
[Link]("Drawing circle");
public class TestShape {
public static void main(String[] args) {
Shape s = new Circle();
[Link]();
[Link]();
Output:
Drawing circle
Displaying shape
Prepared by: Nandini Shetty | [Link]. IT
4. MULTIPLE INTERFACE IMPLEMENTATION:-
- Java does not support multiple inheritance through classes,
- but it allows a class to implement multiple interfaces.
Syntax:
interface A {
void show();
interface B {
void display();
class Demo implements A, B {
public void show() {
[Link]("Show method");
public void display() {
[Link]("Display method");
public class TestInterface {
public static void main(String[] args) {
Demo d = new Demo();
[Link]();
[Link]();
Prepared by: Nandini Shetty | [Link]. IT
}
Output:
Show method
Display method
Explanation:
- Class Demo implements both interfaces A and B.
- This achieves multiple inheritance using interfaces.
5. DIFFERENCE BETWEEN ABSTRACT CLASS AND INTERFACE:-
Abstract Class Interface
Declared using the abstract keyword. Declared using the interface keyword.
Can contain abstract and concrete Contains only abstract methods (till Java 7); default &
methods. static methods allowed from Java 8.
Can have instance variables. Can have only public, static, final (constant)
variables.
Constructors are allowed. Constructors are not allowed.
Supports single inheritance. Supports multiple inheritance (a class can implement
multiple interfaces).
Methods can have any access modifier Methods are public by default.
(public, protected, default).
Can provide partial abstraction. Provides full abstraction (100% abstraction).
Child class uses extends keyword. Implementing class uses implements keyword.
Slightly faster because no dynamic Slightly slower due to additional abstraction level.
dispatch of all methods.
Suitable when classes share common Suitable when different classes need to follow
code + abstract methods. common behavior without sharing code.
Example: abstract class Shape {} Example: interface Shape {}
Prepared by: Nandini Shetty | [Link]. IT
PACKAGES:- Introduction to predefined packages, User Defined Packages, Access specifier, Java Built-in
packages
❖ PACKAGES IN JAVA:-
1. INTRODUCTION:-
- A package in Java is a collection of classes, interfaces, and sub-packages.
- It helps to group related classes together, making the code more organized, reusable, and easy
to maintain.
- Packages also help avoid name conflicts and control access between classes.
Syntax:
package packagename;
2. TYPES OF PACKAGES:-
- There are two main types of packages in Java:
1. PREDEFINED (BUILT-IN) PACKAGES
2. USER-DEFINED PACKAGES
1. PREDEFINED (BUILT-IN) PACKAGES:-
- These are the packages that come with the Java API.
- They provide many ready-made classes and methods for various purposes.
-
✓ COMMON BUILT-IN PACKAGES:
Package Description
Name
[Link] Contains fundamental classes like String, Math, Object, System, Thread.
Automatically imported in every program.
[Link] Contains utility classes like ArrayList, HashMap, Date, Collections.
[Link] Contains classes for input and output operations (e.g., FileReader,
BufferedReader, FileWriter).
[Link] Contains classes for networking (e.g., Socket, URL, InetAddress).
[Link] Used for creating Graphical User Interface (GUI) using Abstract Window Toolkit.
[Link] Advanced GUI toolkit for creating window-based applications.
[Link] Contains classes for database programming using JDBC.
2. USER-DEFINED PACKAGES:-
- These are packages created by the programmer to organize their own classes.
- Steps to create and use a user-defined package:
Prepared by: Nandini Shetty | [Link]. IT
(a) Create a Package:-
// File: MyPackage/[Link]
package MyPackage;
public class Example {
public void show() {
[Link]("Hello from User-defined Package!");
(B) COMPILE THE PACKAGE:-
javac -d . [Link]
(The -d . option creates the package directory structure.)
(c) USE THE PACKAGE:-
import [Link];
class Demo {
public static void main(String[] args) {
Example obj = new Example();
[Link]();
Output:
Hello from User-defined Package!
Prepared by: Nandini Shetty | [Link]. IT
3. ACCESS SPECIFIERS IN PACKAGES:-
- Access specifiers determine the visibility of classes, methods, and variables.
Specifier Access Within Access from Subclass Access from Non-Subclass
Same Package (Other Package) (Other Package)
public Yes Yes Yes
protected Yes Yes No
default (no Yes No No
modifier)
private No No No
4. ADVANTAGES OF PACKAGES:-
- Code Reusability: Classes can be reused in other programs.
- Name Conflict Avoidance: Similar class names can exist in different packages.
- Access Control: Controlled visibility using access specifiers.
- Easy Maintenance: Logical grouping of related classes.
- Encapsulation: Helps hide implementation details.
5. EXAMPLE DEMONSTRATION:-
// File: mypack/[Link]
package mypack;
public class Hello {
public void greet() {
[Link]("Hello Nandini! Welcome to Java Packages.");
// File: [Link]
import [Link];
public class Demo {
public static void main(String[] args) {
Hello obj = new Hello();
[Link]();
Output: Hello Nandini! Welcome to Java Packages.
Prepared by: Nandini Shetty | [Link]. IT
EXCEPTION HANDLING:- Try, Catch, and Finally Blocks, Throw and Throws Keywords
❖ EXCEPTION HANDLING IN JAVA:-
Definition:-
Exception handling in Java is a mechanism that allows developers to handle runtime errors,
ensuring the normal flow of the program is maintained.
1. NEED FOR EXCEPTION HANDLING:-
- To prevent abnormal termination of a program.
- To handle runtime errors gracefully.
- To separate error-handling code from normal code.
- To maintain the program’s normal flow even after an error occurs.
2. KEYWORDS USED IN EXCEPTION HANDLING:-
Java provides five main keywords:-
try, catch, finally, throw, and throws
a) try Block:-
The try block contains code that may throw an exception.
It must be followed by either a catch or finally block.
Syntax:
try {
// Code that might cause an exception
Example:
try {
int a = 10 / 0; // This will cause ArithmeticException
Prepared by: Nandini Shetty | [Link]. IT
b) catch Block:-
The catch block handles the exception thrown by the try block.
Multiple catch blocks can be used to handle different exception types.
Syntax:
catch (ExceptionType e) {
// Code to handle exception
Example:
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Division by zero not allowed.");
c) finally Block:-
The finally block always executes whether an exception is handled or not.
Used to close resources like files, connections, etc.
Syntax:
finally {
// Cleanup code
Example:
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Exception caught.");
Prepared by: Nandini Shetty | [Link]. IT
} finally {
[Link]("Finally block executed.");
Output:
Exception caught.
Finally block executed.
d) throw Keyword:-
Used to explicitly throw an exception (either built-in or user-defined).
Can be used inside a method or block.
Syntax:-
throw new ExceptionType("Error Message");
Example:-
public class Example {
static void checkAge(int age) {
if (age < 18)
throw new
ArithmeticException("Not eligible to vote");
else
[Link]("Eligible to vote");
public static void main(String[] args) {
checkAge(15);
}
Prepared by: Nandini Shetty | [Link]. IT
Output:
Exception in thread "main" [Link]: Not eligible to vote
e) throws Keyword:-
Used in method declaration to indicate that a method may throw an exception.
Helps the calling method to handle the exception.
Syntax:
returnType methodName() throws ExceptionType1, ExceptionType2 {
// code
Example:
void readFile() throws IOException {
FileReader file = new FileReader("[Link]");
3. EXAMPLE OF ALL TOGETHER:-
public class ExceptionDemo {
static void divide(int a, int b)
throws ArithmeticException {
int result = a / b;
[Link]("Result: " + result);
public static void main(String[] args) {
try {
divide(10, 0);
Prepared by: Nandini Shetty | [Link]. IT
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero.");
} finally {
[Link]("Program completed.");
Output:
Cannot divide by zero.
Program completed.
4. DIFFERENCE BETWEEN THROW AND THROWS
Point throw throws
1. Definition Used to explicitly throw an exception Used to declare exceptions that a
from a method/block. method may throw.
2. Purpose To manually generate an exception. To warn the caller about possible
exceptions.
3. Usage Used inside the method body. Used in method
Location declaration/signature.
4. Number of Can throw only one exception at a Can declare multiple exceptions
Exceptions time. separated by commas.
5. Type Must throw an exception object (e.g., No object required; only names
Requirement new IOException()). expected exception types.
6. Exception Exception must be handled by catch Calling method must handle using
Handling block or JVM. try-catch or rethrow using throws.
7. Execution Immediately halts the method Does not halt execution; only
Flow execution when thrown. declares the exception.
8. Used For For custom/explicit errors, validation For checked exceptions propagation
failures. (File I/O, SQL, etc.).
9. Compile-time Works at runtime when exception Checked at compile time for checked
Role occurs. exceptions.
10. Syntax Form It is a statement. It is part of the method signature.
11. Effect on Does not modify method signature. Adds exception specification to
Method method signature.
12. Example throw new void m() throws IOException { }
ArithmeticException("Error");
Prepared by: Nandini Shetty | [Link]. IT
INTRODUCTION TO THREADS:- Creating and Running Threads, Thread Lifecycle
❖ THREADS IN JAVA:-
1. INTRODUCTION TO THREADS:-
1. A thread is a lightweight sub-process that allows a program to perform multiple tasks
simultaneously.
2. Java supports multithreading, meaning multiple threads can run concurrently.
3. Each thread has its own path of execution.
4. The main program always runs inside the main thread.
5. Multithreading helps in:
- Better CPU utilization
- Faster execution
- Smooth user interface
6. Threads share the same memory area, so communication between threads is easy.
2. Creating and Running Threads:-
- Java provides two ways to create a thread:
A. By Extending the Thread Class:-
Steps:-
1. Create a class and extend Thread.
2. Override the run() method.
3. Create an object of your class.
4. Call start() to begin execution.
Example:-
class MyThread extends Thread {
public void run() {
[Link]("Thread is running...");
Prepared by: Nandini Shetty | [Link]. IT
public class Demo {
public static void main(String[] args) {
MyThread t = new MyThread();
[Link](); // run() is called internally
B. By Implementing the Runnable Interface:-
Steps:-
1. Create a class that implements Runnable.
2. Override the run() method.
3. Create a Thread object by passing your class object.
4. Call start().
Example
class MyTask implements Runnable {
public void run() {
[Link]("Runnable thread running...");
public class Demo {
public static void main(String[] args) {
MyTask task = new MyTask();
Thread t = new Thread(task);
[Link]();
}
Prepared by: Nandini Shetty | [Link]. IT
3. THREAD LIFECYCLE:-
Diagram (Simple Explanation)
New → Runnable → Running → (Blocked / Waiting / Timed Waiting) → Runnable → Terminated
- A thread in Java goes through the following states:
1. New - A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
2. Runnable - After a newly born thread is started, the thread becomes runnable. A thread in
this state is considered to be executing its task.
3. Waiting - Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task. A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
4. Timed Waiting - A runnable thread can enter the timed waiting state for a specified interval of
time. A thread in this state transitions back to the runnable state when that time interval
expires or when the event it is waiting for occurs.
5. Terminated (Dead) - A runnable thread enters the terminated state when it completes its task
or otherwise terminates.
4. IMPORTANT THREAD METHODS:-
1. start() – starts the thread and calls run().
2. run() – contains the code executed by a thread.
3. sleep(ms) – stops execution temporarily.
4. join() – waits for a thread to finish.
5. yield() – gives CPU to other threads.
6. isAlive() – checks if thread is still running.
Prepared by: Nandini Shetty | [Link]. IT
Prepared by: Nandini Shetty | [Link]. IT