0% found this document useful (0 votes)
6 views16 pages

Java Interfaces and Multithreading Guide

The document provides a comprehensive overview of Java interfaces, including their definition, syntax, and implementation, as well as the concept of packages in Java. It explains multithreading, including creating and managing threads, thread life cycle, and synchronization. Additionally, it covers error and exception handling in Java, detailing the try-catch-finally mechanism and the use of throw and throws keywords.

Uploaded by

yogeshpandiyan19
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views16 pages

Java Interfaces and Multithreading Guide

The document provides a comprehensive overview of Java interfaces, including their definition, syntax, and implementation, as well as the concept of packages in Java. It explains multithreading, including creating and managing threads, thread life cycle, and synchronization. Additionally, it covers error and exception handling in Java, detailing the try-catch-finally mechanism and the use of throw and throws keywords.

Uploaded by

yogeshpandiyan19
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INTERFACES

1. Introduction to Interfaces
An interface in Java is a reference type, similar to a class, that can contain:
• Only constants (public, static, final),
• Method declarations (implicitly public and abstract),
• Default methods (Java 8+),
• Static methods, and
• Private methods (Java 9+).
Purpose:
• To achieve abstraction.
• To implement multiple inheritance in Java.
Syntax:
interface InterfaceName {
// constant fields
// abstract methods
// default/static methods (Java 8+)
}
Example:
interface Animal {
void makeSound(); // abstract method
}
Defining Interfaces
To define an interface, use the interface keyword. All methods are implicitly public and
abstract (unless marked as default, static, or private).
Syntax:
interface MyInterface {
int VALUE = 10; // public static final by default
void method1(); // public abstract by default
}
Example:
[Link]
interface Animal {
void makeSound();
}
class Dog implements Animal {
public void makeSound() {
[Link]("Dog class!");
}
}
class Cat implements Animal {
public void makeSound() {
[Link]("Cat Class!");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Animal a1 = new Dog();
Animal a2 = new Cat();
[Link]();
[Link]();
}}
Output:
Dog Class!
Cat Class!

Extending Interfaces
An interface can extend one or more interfaces using the extends keyword.
Syntax:
interface A {
void methodA();
}
interface B extends A {
void methodB();
}
Example:
[Link]
interface Flyable {
void fly();
}
interface Bird extends Flyable {
void layEggs();
}
class Sparrow implements Bird {
public void fly() {
[Link]("Sparrow flies high.");
}
public void layEggs() {
[Link]("Sparrow lays eggs.");
}
}
public class InterfaceExtendsExample {
public static void main(String[] args) {
Sparrow sp = new Sparrow();
[Link]();
[Link]();
}
}
Output:
Sparrow flies high
Sparrow lays eggs

Implementing Interfaces
A class implements an interface using the implements keyword. It must provide concrete
implementations for all abstract methods of the interface.
Syntax:
class ClassName implements InterfaceName {
// Provide method definitions
}
Example:
interface Drawable {
void draw();
}

class Circle implements Drawable {


public void draw() {
[Link]("Drawing Circle");
}
}
Note: A class can implement multiple interfaces (comma-separated).
class MyClass implements Interface1, Interface2 {
// implement methods of both interfaces
}

Accessing Interface Variables


Variables in an interface are:
• Public
• Static
• Final
They can be accessed:
• Directly using the interface name
• Through implementing class (not recommended)
Example:
[Link]
interface Constants {
int VALUE = 100; // public static final
}
class Demo implements Constants {
void display() {
[Link]("Accessing VALUE using interface name: " + [Link]);
[Link]("Accessing VALUE directly: " + VALUE); // not recommended
}
}

public class InterfaceVariableExample {


public static void main(String[] args) {
Demo d = new Demo();
[Link]();
}
}
Output:
Accessing VALUE using interface name: 100
Accessing VALUE directly: 100

Packages in Java
Introduction
• A package is a collection of related classes and interfaces.
• Helps in organizing code, avoiding name conflicts, and reusability.
Java API Packages
• Java provides many predefined packages:
o [Link] → Basic classes (String, Math, Object).
o [Link] → Data structures (ArrayList, HashMap).
o [Link] → Input/output classes.
o [Link] → Database connectivity.

Using System Packages


• Importing a package:
Syntax:
import [Link];
import packageName.*; // imports all classes
Example:
import [Link];
class InputExample {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter name: ");
String name = [Link]();
[Link]("Hello " + name);
}
}
Naming Conventions
• Package names should be unique and usually written in lowercase.
• Common practice: use the reverse of domain names.
o Example: [Link]
Creating Packages
• Define package using package keyword.
Syntax:
package packageName;
public class MyClass {
// code
}
Note: Save the file inside a directory with the same name as the package.
Accessing a Package
• To use classes from another package, use:
import [Link];

• Run program with -cp option (classpath) if packages are in different folders.

Using a Package
• To use classes from a package, import them:
import [Link];
import packageName.*;
Adding a Class to a Package
• To add a class, declare package at the top of the file.
• Example:
package mypackage;
public class MyClass {
public void display() {
[Link]("Inside MyClass");
}
}

Hiding Classes
• Classes with default access (no modifier) are accessible only within the same
package.
• Provides encapsulation and hides implementation details from outside packages.
Why Hide Classes?
1. Encapsulation – Internal implementation details can be hidden from outside.
2. Security – Prevents external classes from using helper/utility classes that are not
meant for them.
3. Clean API – Only important classes are exposed (public), while unnecessary classes
remain hidden.

Example
File 2: in another package
File 1: inside package mypackage
package anotherpackage;
package mypackage;
import [Link];
// Public class - accessible everywhere

public class PublicClass {


public class Test {
public void show() {
public static void main(String[] args) {
[Link]("I am a Public Class");
PublicClass obj = new PublicClass();
}}
[Link](); // Works fine ✅
// Default (package-private) class - hidden outside
// HiddenClass obj2 = new HiddenClass(); ❌
class HiddenClass { ERROR
void display() { // Cannot access HiddenClass outside
[Link]("I am a Hidden Class"); 'mypackage'

} }

} }
Multithreaded Programming
Introduction

• Multitasking → executing multiple tasks at the same time.


o Process-based multitasking: running multiple programs simultaneously.
o Thread-based multitasking: running multiple threads of the same program
simultaneously.
• Thread → lightweight subprocess, independent unit of execution, shares memory
with other threads.
• Java provides built-in support for multithreading.

Creating Threads
We can create threads in java using two ways
• Extending Thread Class
• Implementing a Runnable interface

By Extending Thread Class


Create a class that extends Thread. Override the run() method, this is where you put the code
that the thread should execute. Then create an object of your class and call the start() method.
This will internally call run() in a new thread.

Example:
import [Link].*;
import [Link].*;
class MyThread extends Thread
{
// initiated run method for Thread
public void run()
{
String str = "Thread Started Running...";
[Link](str);
}
}
public class Geeks
{
public static void main(String args[])
{
MyThread t1 = new MyThread();
[Link]();
}
}
Using Runnable Interface
Create a class that implements Runnable. Override the run() method, this contains the code
for the thread. Then create a Thread object, pass your Runnable object to it and call start().

Example:
import [Link].*;
import [Link].*;
class MyThread implements Runnable
{
// Method to start Thread
public void run()
{
String str = "Thread is Running Successfully";
[Link](str);
}

}
public class Geeks
{
public static void main(String[] args)
{
MyThread g1 = new MyThread();

// initializing Thread Object


Thread t1 = new Thread(g1);

// Running Thread
[Link]();
}
}

Extending the Thread Class

• Simple but less flexible (no multiple inheritance).


• Each class extending Thread must override run().

Examples:
class HelloThread extends Thread {
public void run(){
[Link]("Hello from thread!");
}
}
public class Test {
public static void main(String[] args){
new HelloThread().start();
}
}
Stopping and Blocking a Thread
Blocking methods in java are the particular set of methods that block the thread until its
operation is complete.

• stop() is deprecated (unsafe).

• Use a flag:

Example:
class Worker extends Thread {
boolean running = true;
public void run(){
while(running){
[Link]("Working...");
}
}
public void stopThread(){
running = false;
}
}

Blocking: thread waits for something (I/O, sleep(), or resource).

Example:
[Link](2000); // blocks for 2 seconds

Life Cycle of a Thread

• NEW — Thread object created but start() not yet called.


• RUNNABLE — Thread started; ready to run or actually running (in Java the JVM
uses one state for both “ready” and “running” — there is no separate RUNNING
enum).
• BLOCKED — Thread waiting to acquire a monitor lock to enter a synchronized
block/method.
• WAITING — Thread waiting indefinitely for another thread to perform a particular
action (e.g., [Link]() with no timeout, [Link]() with no timeout, or
[Link]()).
• TIMED_WAITING — Thread waiting for a specified amount of time (e.g.,
[Link](ms), [Link](ms), join(ms), [Link]()).
• TERMINATED — run() method completed (normal return or uncaught exception)
— thread finished.
Using Thread Methods
Method Description

start() begins execution, calls run()

run() contains code executed by thread

sleep(ms) pauses thread temporarily

join() waits for another thread to finish

interrupt() interrupts sleeping/waiting thread

isAlive() checks if thread is still running

Thread Exceptions

• InterruptedException → thrown when interrupted while sleeping/waiting.


• IllegalThreadStateException → if start() is called more than once.

Example:
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]("Interrupted!");
}
Thread Priority

• Threads have priorities 1–10.


• MIN_PRIORITY = 1, NORM_PRIORITY = 5, MAX_PRIORITY = 10.
• Higher priority = more chance to be scheduled (not guaranteed).

Example:
Thread t1 = new Thread(() -> [Link]("T1 running"));
Thread t2 = new Thread(() -> [Link]("T2 running"));

[Link](Thread.MAX_PRIORITY);
[Link](Thread.MIN_PRIORITY);

[Link]();
[Link]();

Synchronization

• Used when multiple threads access shared data.


• Prevents race conditions.
• synchronized keyword ensures only one thread executes at a time.

Example:

class Counter {
private int count = 0;
public synchronized void increment(){
count++;
}
public int getCount(){
return count;
}
}
Managing Errors and Exceptions:

Introduction:

• Errors are problems or flaws in a program that cause incorrect results or abnormal
termination.
• In Java (or any programming language), errors prevent the normal execution of a
program.
• Errors generally occur due to mistakes in logic, incorrect syntax, or unexpected
situations at runtime.

Types of Exception Handling Code in Java


In Java, exceptions are handled using the try-catch-finally-throw-throws mechanism. The
main types of exception handling code are:

Try Block

• A block of code that contains statements which may generate exceptions.

Syntax:

try {
// Risky code (may throw exception)
}

Catch Block

• Used to catch and handle the exception thrown inside the try block.
• Multiple catch blocks can be used for different types of exceptions.
• Syntax:

catch(ExceptionType e) {
// Handling code
}

Finally Block

• A block that always executes, whether an exception occurs or not.


• Commonly used to release resources like files, database connections.
• Syntax:

finally {
// Cleanup code
}

Throw Statement

• Used to explicitly throw an exception (object of Throwable class or its subclass).


• Example:

throw new ArithmeticException("Division by zero not


allowed");

Throws Keyword

• Used in method declaration to specify which exceptions a method might throw.


• Example:

void myMethod() throws IOException {


// code
}
Example:
// Example to demonstrate Types of Exception Handling Code
import [Link].*;

class ExceptionDemo {

// Method declares an exception using 'throws'


static void readFile() throws IOException {
// Explicitly throwing an exception
throw new IOException("File not found!");
}

public static void main(String[] args) {


try {
// Risky code (division by zero)
int a = 10, b = 0;
int result = a / b; // Will cause ArithmeticException

// Calling method which may throw exception


readFile();
}
// Catch block to handle ArithmeticException
catch (ArithmeticException e) {
[Link]("Error: Division by zero is not allowed.");
}
// Catch block to handle IOException
catch (IOException e) {
[Link]("Error: " + [Link]());
}
// Finally block (always executed)
finally {
[Link]("Finally block executed – Cleaning up resources.");
}

[Link]("Program continues after exception handling...");


}
}

OUTPUT:

Error: Division by zero is not allowed.


Finally block executed – Cleaning up resources.
Program continues after exception handling...

You might also like