0% found this document useful (0 votes)
10 views121 pages

Inheritance in JAVA

Inheritance in Java allows one class to inherit properties and behaviors from another, promoting code reusability and method overriding. Java does not support multiple inheritance to avoid ambiguity, but it allows multiple inheritance through interfaces. Abstract classes and interfaces provide templates for subclasses, with specific rules governing method overriding and access modifiers.

Uploaded by

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

Inheritance in JAVA

Inheritance in Java allows one class to inherit properties and behaviors from another, promoting code reusability and method overriding. Java does not support multiple inheritance to avoid ambiguity, but it allows multiple inheritance through interfaces. Abstract classes and interfaces provide templates for subclasses, with specific rules governing method overriding and access modifiers.

Uploaded by

kevinnemish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 121

Inheritance in JAVA

• 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 we
can create new classes that are built upon
existing classes.
• When we inherit methods from an existing
class, we can reuse methods and fields of the
parent class. However, we can add new
methods and fields in your current class also.
Why Do We Need Java Inheritance?
• Code Reusability
• Method Overriding
• Abstraction
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println(p.salary);
System.out.printlnp.bonus);
}
}
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
class Animal{
void eat()
{
System.out.println("eating...");}
}
class Dog extends Animal{
void bark()
{
System.out.println("barking...");}
}
class Cat extends Animal{
void meow()
{
System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}
}
Why multiple inheritance is not supported in
Java?

• To reduce the complexity and simplify the


language, multiple inheritance is not
supported in java.
• Suppose there are three classes A, B, and C. The
C class inherits A and B classes.

• If A and B classes have the same method and


we call it from child class object, there will be
ambiguity to call the method of A or B class.

• Since compile-time errors are better than


runtime errors, Java renders compile-time error
if you inherit 2 classes.

• So whether you have same method or different,


there will be compile time error.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
• However, Java supports multiple inheritance
through interfaces, where a class can
implement multiple interfaces.
Abstract Class
• A class that is declared with the abstract
keyword is known as an abstract class in Java.
• It can have abstract and non-abstract
methods (method with the body).
• An abstract class in Java acts as a partially
implemented class that itself cannot be
instantiated.
• It exists only for subclassing purposes, and
provides a template for its subcategories to
follow.
• Abstract classes can have implementations
with abstract methods.
• Abstract methods are declared to have no
body, leaving their implementation to
subclasses.
Points to Remember

• An abstract class must be declared with an abstract


keyword.

• It can have abstract and non-abstract methods.

• It cannot be instantiated.

• It can have constructors and static methods also.

• It can have final methods which will force the subclass not
to change the body of the method.
public abstract class Shape {
public abstract double area();
public void display() {
System.out.println("This is a shape.");
}
}
abstract class Bike{
abstract void run();
}

class Honda4 extends Bike{


void run(){
System.out.println("running safely");
}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Interface
• Interface is a reference type that acts as a
blueprint for classes.

• It contains abstract methods (methods


without a body) and constants.

• An interface is used to achieve abstraction


and multiple inheritance in Java.
Key Characteristics of an Interface
• Abstract Methods Only: By default, all
methods in an interface are public and
abstract (before Java 8).

• Constant Fields: Variables in an interface are


implicitly public, static, and final.

• No Constructors: Interfaces cannot have


constructors since they cannot be
instantiated.
Key Characteristics of an Interface
• Multiple Inheritance Support: A class can
implement multiple interfaces, overcoming
Java’s limitation of single inheritance.

• Implementation by Classes: A class must


implement all methods of an interface unless
it is an abstract class.
Defining an Interface
// Defining an interface
interface Animal {
void makeSound();
}
// Implementing the interface
class Dog implements Animal {
public void makeSound() {
System.out.println("Woof! Woof!");
}
}

public class InterfaceExample {


public static void main(String[] args) {
Animal myDog = new Dog();
myDog.makeSound(); // Output: Woof! Woof!
}
}
Multiple Inheritance in Java
interface Printable{
void print();
}

interface Showable{
void show();
}
class A7 implements Printable,Showable{

public void print(){System.out.println("Hello");}


public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
Points Abstract Class Interface

Cannot be instantiated; contains both


Specifies a set of methods a class must
abstract (without implementation) and
implement; methods are abstract by
concrete methods (with
default.
implementation)
Definition

Can have both implemented and Methods are abstract by default; Java 8,
abstract methods. can have default and static methods.
Implementation Method

class can inherit from only one abstract A class can implement multiple
class. interfaces.
Inheritance

Methods and properties can have any


Methods and properties are implicitly
access modifier (public, protected,
public.
private).
Access Modifiers

Can have member variables (final, non- Variables are implicitly public, static, and
final, static, non-static). final (constants).
Variables
Method Overriding in Java
• If subclass (child class) has the same method
as declared in the parent class, it is known
as method overriding in Java.

• In other words, If a subclass provides the


specific implementation of the method that
has been declared by one of its parent class, it
is known as method overriding.
Rules for Java Method Overriding
• Same Method Name: The overriding method in the subclass
must have the same name as the method in the superclass
that it is overriding.

• Same Parameters: The overriding method must have the


same number and types of parameters as the method in the
superclass. This ensures compatibility and consistency with
the method signature defined in the superclass.

• IS-A Relationship (Inheritance): Method overriding requires


an IS-A relationship between the subclass and the superclass.
This means that the subclass must inherit from the superclass,
either directly or indirectly, to override its methods.
• Same Return Type : The return type of the overriding method
can be the same as the return type of the overridden method
in the superclass.

• Access Modifier Restrictions: The access modifier of the


overriding method must be the same as or less restrictive than
the access modifier of the overridden method in the
superclass.

• No Final Methods: Methods declared as final in the superclass


cannot be overridden in the subclass. This is because final
methods cannot be modified or extended.

• No Static Methods: Static methods in Java are resolved at


compile time and cannot be overridden. Instead, they are
hidden in the subclass if a method with the same signature is
defined in the subclass.
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}

class Bike2 extends Vehicle{


void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
class Bank{
int getRateOfInterest()
{ class ICICI extends Bank{
return 0; int getRateOfInterest()
} {
} return 7;
}
class SBI extends Bank{ }
int getRateOfInterest() class AXIS extends Bank{
{ int getRateOfInterest()
return 8; {
} return 9;
} }
}
class Test2
{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
s.o.p(s.getRateOfInterest());
s.o.p(i.getRateOfInterest());
s.o.p(a.getRateOfInterest());

}
}
Object Class and Overriding Its Methods in
Java
• In Java, the Object class is the root of the class
hierarchy. Every class in Java implicitly inherits
from the Object class.

• It is part of java.lang package and provides


default implementations of fundamental
methods that every Java object inherits.
Common Methods of the Object Class
Method Signature Purpose

public String toString() Returns a string representation of the object.

public boolean equals(Object obj) Checks if two objects are equal.

public int hashCode() Returns a hash code for the object.

protected Object clone() Creates a new object that is a copy of the original.

protected void finalize() Called by the garbage collector before an object is destroyed.
Overriding toString()
class Employee {
String name;
int id;

Employee(String name, int id) {


this.name = name;
this.id = id;
}

// Overriding toString() method


@Override
public String toString() {
return "Employee{name='" + name + "', id=" + id + "}";
}
}
public class ToStringExample {
public static void main(String[] args) {

Employee emp = new Employee("John", 101);

S.o.p (emp);
}
}
Overriding equals()
• The equals() method checks if two objects are
equal. By default, it compares object
references.

• We override it to compare objects based on


their fields.
class Person {
public class EqualsExample {
String name; public static void main(String[] args) {
Person p1 = new Person("Alice");
Person p2 = new Person("Alice");
Person(String name) { Person p3 = new Person("Bob");
this.name = name;
System.out.println(p1.equals(p2));
} System.out.println(p1.equals(p3));
}
}
@Override
public boolean equals(Object obj) {
Person p = (Person) obj;
return this.name.equals(p.name);

}
}
Overriding finalize()
• The finalize() method is called before an
object is destroyed by the garbage collector.

• It can be used to release resources.


class Employee {
int id;

Employee(int id) {
this.id = id;
}

@Override
protected void finalize() throws Throwable {
System.out.println("Employee object with id " + id + " is being garbage collected.");
}
}

public class FinalizeExample {


public static void main(String[] args) {
Employee emp = new Employee(106);
emp = null; // Make eligible for garbage collection
System.gc(); // Request JVM to run garbage collector
}
}
Overriding hashcode()
• The hashCode() method in Java returns an
integer that represents an object’s memory
address or a computed hash value.

• It is primarily used in hash-based collections


like HashMap, HashSet, and HashTable for
efficient storage and retrieval of objects.
Why Override hashCode()?
• When you override equals(), you must also
override hashCode() to maintain consistency.
According to Java's contract:
– If two objects are equal (equals() returns true),
their hash codes must be the same.
– If two objects are not equal, their hash codes can
be different (but not necessarily).
class Person {
int id; public class Main {
public static void main(String[] args) {
public Person(int id) { Person p1 = new Person(101);
this.id = id; Person p2 = new Person(102);

}
s.o.p ("HashCode of p1: " + p1.hashCode());
s.o.p ("HashCode of p2: " + p2.hashCode());
@Override }
public int hashCode() { }
return id;
// Simple hash function using ID
}
}
Java Package
• A java package is a group of similar types of
classes, interfaces and sub-packages.

• Package in java can be categorized in two form


– built-in package
– user-defined package.
Packages are used for:
• Prevent naming conflicts by allowing classes
with the same name to exist in different
packages,like college.staff.cse.Employee and c
ollege.staff.ee.Employee.

• They make it easier to organize, locate, and


use classes, interfaces, and other components.
• Packages also provide controlled access for
Protected members that are accessible within
the same package and by subclasses.

• Also for default members (no access specifier)


that are accessible only within the same
package.
Working of Java Packages
• Directory Structure: Package names and
directory structures are closely related.

• For example, if a package name


is college.staff.cse, then three directories
are, college, staff, and cse, where cse is inside
staff, and staff is inside the college.
Built-in Packages
• Some of the commonly used built-in packages are:

• java.lang: Contains language support classes(e.g classes which


defines primitive data types, math operations). This package is
automatically imported.

• java.io: Contains classes for supporting input / output


operations.

• java.util: Contains utility classes which implement data


structures like Linked List, Dictionary and support ; for Date /
Time operations.
• java.applet: Contains classes for creating
Applets.

• java.awt: Contain classes for implementing


the components for graphical user interfaces
(like button , ;menus etc). )

• java.net: Contain classes for supporting


networking operations.
How to access package from another
package?
• There are three ways to access the package
from outside the package.
1. Import a specific class:
– import java.util.Vector;

2. Import all classes from a package:


– import java.util.*;
– Note : This imports all classes and interfaces from
the java.util package but does not include sub-
packages.
3. Using fully qualified name
Ex. Java.util.Scanner sc = new java.util.Scanner(System.in)

o If you use fully qualified name then only declared


class of this package will be accessible.
o Now there is no need to import.
o But you need to use fully qualified name every
time when you are accessing the class or
interface.
User-defined Packages
1. Create the Package:
• First we create a directory myPackage (name
should be same as the name of the package).

• Then create the MyClass inside the directory


with the first statement being the package
names.
// Name of the package must be same as the directory
// under which this file is saved
package myPackage;

public class MyClass


{
public void getNames(String s)
{
System.out.println(s);
}
}
2. Use the Class in Program:

// import 'MyClass' class from 'names' myPackage


import myPackage.MyClass;

public class Geeks {


public static void main(String args[]) {

// Initializing the String variable


// with a value
String s = “Hello";

// Creating an instance of class MyClass in


// the package.
MyClass o = new MyClass();

o.getNames(s);
}
}
Types of Errors in Java
• Errors are severe issues that occur at compile
time or runtime and are beyond the control of
the programmer. These are mainly caused by
the environment or system failure.
Common Types of Errors:
• Compile-time Errors – Errors detected by the compiler (e.g.,
syntax errors, missing semicolons).

• Runtime Errors – Errors occurring during program execution.

• Logical Errors – Incorrect logic leading to unintended


behavior.

• OutOfMemoryError – When JVM runs out of memory.

• StackOverflowError – Infinite recursion leading to stack


overflow.
Compile-Time Errors
public class CompileTimeErrorExample {
public static void main(String[] args) {
System.out.println("Hello World")
}
}

These errors occur due to incorrect syntax or


missing components in the code and are detected
by the compiler.
Runtime Errors
public class RuntimeErrorExample {
public static void main(String[] args) {
int result = 10 / 0; // Division by zero ->
Runtime error
System.out.println(result);
}
}
Logical Errors
public class LogicalErrorExample {
public static void main(String[] args) {
int num1 = 5, num2 = 10;
int sum = num1 - num2; // Incorrect logic, should be num1 +
num2
System.out.println("Sum: " + sum);
}
}
These errors do not crash the program but produce incorrect
output due to wrong logic.
OutOfMemoryError
import java.util.ArrayList;
import java.util.List;

public class OutOfMemoryErrorExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
while (true) {
list.add("OutOfMemoryError"); // Keeps adding to the list, consuming
memory
}
}
}
StackOverflowError
public class StackOverflowErrorExample {
public static void recursiveMethod() {
recursiveMethod(); // Infinite recursion
}

public static void main(String[] args) {


recursiveMethod();
}
}

Occurs when a method calls itself indefinitely, leading to


excessive memory consumption.
Exception Handling
What is Exception Handling?

Exception handling in Java is a mechanism that


allows a program to handle runtime errors,
ensuring that the normal flow of execution is
not disrupted.
Need for Exception Handling in Java
• Exception handling is a crucial feature in Java
that ensures the smooth execution of
programs by handling unexpected errors.

• Without exception handling, an error can


cause a program to terminate abruptly,
leading to data loss, security risks, and poor
user experience.
To Prevent Program Crashes
If an exception occurs and is not handled, the Java Virtual Machine (JVM) will
terminate the program. Exception handling allows us to catch errors and continue
program execution.

public class NoExceptionHandling {


public static void main(String[] args) {
int result = 10 / 0; // Runtime exception (Divide by zero)
System.out.println("This will not be printed.");
}
}
To Provide Meaningful Error Messages
If an exception occurs, Java provides a default error message, which might not be
user-friendly. With exception handling, we can show a custom error message.

public class ExceptionHandlingExample {


public static void main(String[] args) {
try {
int result = 10 / 0; // Exception occurs
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
}
System.out.println("Program continues...");
}
}
To Handle Unexpected Scenarios
Certain errors may occur only in specific conditions, such as:
• Network failures (e.g., lost internet connection)
• File handling errors (e.g., file not found)
• Database connectivity issues (e.g., server down)
• import
Exception handling helps in gracefully managing such
java.io.File;
import java.io.FileNotFoundException;
situations.
import java.util.Scanner;

public class FileExceptionExample {


public static void main(String[] args) {
try {
File file = new File("non_existent_file.txt");
Scanner reader = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("Error: File not found.");
}
}
}
Types of Exceptions in Java
Checked Exceptions (Compile-time exceptions)
 Must be handled using try-catch or declared using
throws.
Example: IOException, SQLException.

Unchecked Exceptions (Runtime exceptions)


 Occur due to logical errors in code.
Example: NullPointerException, ArithmeticException.

Errors
 Serious problems that the program cannot recover
from.
Checked Exceptions (Compile-Time Exceptions)
Unchecked Exceptions (Compile-Time Exceptions)
• Exception Handling Keywords
Java provides five keywords for handling
exceptions:
– try
– catch
– finally
– throw
– throws
• try-catch Block
The try block contains the code that may throw an
exception. The catch block handles the exception.
public class TryCatchExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
}
System.out.println("Program continues...");
}
}
Multiple catch Blocks
• A try block can have multiple catch blocks to
handle different exceptions separately.
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // This will throw
ArrayIndexOutOfBoundsException
}
catch (ArithmeticException e) {
System.out.println("Arithmetic Exception caught.");
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds.");
}
catch (Exception e) {
System.out.println("Some other exception occurred.");
}
}
finally Block
• The finally block is always executed, whether an
exception occurs or not.
public class FinallyExample {
public static void main(String[] args) {
try {
int num = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e);
} finally {
System.out.println("Finally block executed.");
}
}
}
throw Keyword
• The throw keyword is used to explicitly throw an
exception.
public class ThrowExample {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible to
vote.");
} else {
System.out.println("Eligible to vote.");
}
}

public static void main(String[] args) {


checkAge(16); // This will throw an exception
}
}
throws Keyword
• The throws keyword is used in method declarations
to specify that a method may throw an exception.
import java.io.IOException;

public class ThrowsExample {


static void readFile() throws IOException {
throw new IOException("File not found.");
}

public static void main(String[] args) {


try {
readFile();
} catch (IOException e) {
System.out.println("Exception handled: " + e.getMessage());
}
}
}
User-Defined Exception
• In Java, we can create our own custom exceptions
(user-defined exceptions) by extending the Exception
class or RuntimeException class. This helps in
handling specific application-related errors in a
meaningful way.
Why Use User-Defined Exceptions?

• More Meaningful Error Messages – Default


exceptions like NullPointerException and
IOException may not always be clear for
specific use cases.
• Improves Readability – Helps distinguish
between different types of errors.
• Enforces Business Logic – Ensures specific
conditions are met in an application.
Steps to Create a User-Defined Exception

– Create a class that extends Exception (for checked


exceptions) or RuntimeException (for unchecked
exceptions).

– Define a constructor that calls the superclass


constructor (super(message)).

– Throw this exception in the program when needed


using the throw keyword.

– Catch and handle the exception using try-catch.


// Step 1: Create a custom exception class
class AgeException extends Exception {
public AgeException(String message) {
super(message); // Calling Exception class constructor
}
}

// Step 2: Use the custom exception in a method


public class UserDefinedExceptionExample {
static void validateAge(int age) throws AgeException {
if (age < 18) {
throw new AgeException("Age must be 18 or above."); // Throwing custom exception
} else {
System.out.println("You are eligible.");
}
}

public static void main(String[] args) {


try {
validateAge(16); // Passing an invalid age
} catch (AgeException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}
// Step 1: Create a custom unchecked exception class
class InsufficientBalanceException extends RuntimeException {
public InsufficientBalanceException(String message) {
super(message);
}
}

// Step 2: Use the custom exception in a method


public class CustomRuntimeException {
static void withdraw(double balance, double amount) {
if (amount > balance) {
throw new InsufficientBalanceException("Insufficient balance in account.");
} else {
System.out.println("Withdrawal successful! Remaining balance: " + (balance -
amount));
}
}

public static void main(String[] args) {


withdraw(5000, 7000); // Trying to withdraw more than balance
}
}
thread in java
• In Java, a thread is the smallest unit of
execution in a program. It allows a program to
perform multiple tasks simultaneously, making
it possible to achieve multithreading (running
multiple threads at the same time).
Benefits of Multithreading in Java
• Increased Performance & Responsiveness
– Multiple threads can execute tasks simultaneously, reducing
execution time.
– UI applications remain responsive, avoiding "freezing" when
performing heavy tasks (e.g., downloading a file).

• Better CPU Utilization


– A single-threaded program may leave the CPU idle while waiting for
I/O operations.
– Multithreading keeps the CPU busy by running other threads in
parallel.
• Faster Execution (Concurrency)
– Tasks like sorting large datasets, handling network requests, or
rendering graphics can be split into multiple threads, reducing
processing time.
– Example: A web server handles multiple requests simultaneously
using threads.

• Efficient Resource Sharing


– Threads of the same process share memory & resources, reducing
memory consumption compared to creating multiple processes.
– Example: A music player can play songs while also allowing browsing
of the playlist.
Real-Life Example: How Microsoft Word
Uses Multithreading
• Auto-Saving While Typing (Background Thread)
• Spell & Grammar Checking (Separate Thread)
• Formatting & UI Updates (Parallel Processing)
• Printing in the Background
• Auto-Correction & Word Suggestions
• Multitasking with Multiple Documents
Thread Life Cycle in Java (Thread States)
• In Java, a thread always exists in any one of
the following states. These states are:
– New
– Active
– Blocked / Waiting
– Timed Waiting
– Terminated
• New: Whenever a new thread is created, it is always in the
new state.

• For a thread in the new state, the code has not been run yet
and thus has not begun its execution.

• Active: When a thread invokes the start() method, it moves


from the new state to the active state.

• The active state contains two states within it: one is runnable,
and the other is running.
• Runnable: A thread, that is ready to run is then moved to the
runnable state.
• In the runnable state, the thread may be running or may be
ready to run at any given instant of time.
• It is the duty of the thread scheduler to provide the thread
time to run, i.e., moving the thread the running state.

• Running: When the thread gets the CPU, it moves from the
runnable to the running state.

• Generally, the most common change in the state of a thread is


from runnable to running and again back to runnable.

• Blocked or Waiting: Whenever a thread is inactive for a span


of time (not permanently) then, either the thread is in the
blocked state or is in the waiting state.
• Terminated: A thread reaches the termination state
because of the following reasons:
– When a thread has finished its job, then it exists or
terminates normally.
– Abnormal termination: It occurs when some unusual
events such as an unhandled exception or segmentation
fault.
ways to create a thread
• By Extending Thread Class
• By Implementing Runnable Interface
Thread Class
• The simplest way to create a thread in Java is
by extending the Thread class and overriding
its run() method.

• Thread class provide constructors and


methods to create and perform operations on
a thread.
Constructors of Thread Class
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r, String name)
Thread Class Methods
• public void run(): is used to perform action for a thread.

• public void start(): starts the execution of the thread.JVM


calls the run() method on the thread.

• public void sleep(long miliseconds): Causes the currently


executing thread to sleep (temporarily cease execution) for
the specified number of milliseconds.

• public void join(): waits for a thread to die.


• public int getPriority(): returns the priority of the thread.
• public int setPriority(int priority): changes the priority of the
thread.
• public String getName(): returns the name of the thread.
• public void setName(String name): changes the name of the thread.
• public Thread currentThread(): returns the reference of currently
executing thread.
• public int getId(): returns the id of the thread.
• public boolean isAlive(): tests if the thread is alive.
• public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
• public void suspend(): is used to suspend the thread(depricated).
• public void resume(): is used to resume the suspended
thread(depricated).
• public void stop(): is used to stop the thread(depricated).
Creating Thread by Extending Thread Class

class Multi extends Thread


{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
}
}
Write a program that executes two threads.
One thread displays “Thread1” every 1000
milliseconds, and the other displays “Thread2”
every 2000 milliseconds. Create the threads by
extending the Thread class
Write a program that executes two threads.
One thread will print the even numbers and
another thread will print odd numbers from 1
to 200.
implementing Runnable interface

• The Runnable interface is used for


multithreading in Java.

• Instead of extending the Thread class, we


implement Runnable and pass an instance to a
Thread object.
Steps to Implement Runnable Interface

• Create a class that implements Runnable.


• Override the run() method to define the task
for the thread.
• Create an instance of the class and pass it to a
Thread object.
• Call start() on the Thread object to begin
execution.
public class ExampleClass implements Runnable {

@Override
public void run() {
System.out.println("Thread has ended");
}

public static void main(String[] args) {


ExampleClass ex = new ExampleClass();
Thread t1= new Thread(ex);
t1.start();
System.out.println("Hi");
}
}
Thread priority

• Each thread has a priority. Priorities are represented by a


number between 1 and 10.

• In most cases, the thread scheduler schedules the threads


according to their priority (known as preemptive scheduling).

• But it is not guaranteed because it depends on JVM


specification that which scheduling it chooses.

• Note that not only JVM a Java programmer can also assign the
priorities of a thread explicitly in a Java program.
• Setter & Getter Method of Thread Priority
Let's discuss the setter and getter method of the thread priority.
– public final int getPriority(): The
java.lang.Thread.getPriority() method returns the priority
of the given thread.

– public final void setPriority(int newPriority): The


java.lang.Thread.setPriority() method updates or assign
the priority of the thread to newPriority.

– The method throws IllegalArgumentException if the value


newPriority goes out of the range, which is 1 (minimum) to
10 (maximum).
• constants defined in Thread class:
– public static int MIN_PRIORITY
– public static int NORM_PRIORITY
– public static int MAX_PRIORITY

• Default priority of a thread is 5 (NORM_PRIORITY).


The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
class MyThread extends Thread {
public void run() {
System.out.println(getName() + " Priority: " + getPriority());
}
}

public class ThreadPriorityExample {


public static void main(String[] args) {
MyThread t1 = new MyThread(), t2 = new MyThread(), t3 = new MyThread();
t1.setPriority(1); t2.setPriority(5); t3.setPriority(10);
t1.start(); t2.start(); t3.start();
}
}
File Handling in Java
• In Java, a File is an abstract data type. A
named location used to store related
information is known as a File.

• There are several File Operations like creating


a new File, getting information about File,
writing into a File, reading from a
File and deleting a File.
• Stream
– A series of data is referred to as a stream. In Java, Stream is classified
into two types, i.e., Byte Stream and Character Stream.
Byte Stream
• Byte Stream is mainly involved with byte data. A file handling
process with a byte stream is a process in which an input is
provided and executed with the byte data.
Character Stream
• Character Stream is mainly involved with character data. A
file handling process with a character stream is a process in
which an input is provided and executed with the character
data.
File Operations
• We can perform the following operation on a file:
– Create a File
– Get File Information
– Write to a File
– Read from a File
– Delete a File
import java.io.File;
import java.io.IOException;
class CreateFile {
public static void main(String args[]) {
try {

File f0 = new File("D:FileOperationExample.txt");


if (f0.createNewFile()) {
System.out.println("File " + f0.getName() + " is created success
fully.");
} else {
System.out.println("File is already exist in the directory.");
}
} catch (IOException exception) {
System.out.println("An unexpected error is occurred.");
exception.printStackTrace();
}
}
}
import java.io.File;
class FileInfo {
public static void main(String[] args) {

File f0 = new File("D:FileOperationExample.txt");


if (f0.exists()) {

System.out.println("The name of the file is: " + f0.getName());

System.out.println("The absolute path of the file is: " + f0.getAbsolutePath());

System.out.println("Is file writeable?: " + f0.canWrite());

System.out.println("Is file readable " + f0.canRead());

System.out.println("The size of the file in bytes is: " + f0.length());


} else {
System.out.println("The file does not exist.");
}
}
}
import java.io.FileWriter;
import java.io.IOException;

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

try {
FileWriter fwrite = new FileWriter("D:FileOperationExample.txt");
fwrite.write("A named location used to store related information is referred to as a File.");
fwrite.close();
System.out.println("Content is successfully wrote to the file.");
} catch (IOException e) {
System.out.println("Unexpected error occurred");
e.printStackTrace();
}
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

class ReadFromFile {
public static void main(String[] args) {
try {

File f1 = new File("D:FileOperationExample.txt");


Scanner dataReader = new Scanner(f1);
while (dataReader.hasNextLine()) {
String fileData = dataReader.nextLine();
System.out.println(fileData);
}
dataReader.close();
} catch (FileNotFoundException exception) {
System.out.println("Unexcpected error occurred!");
exception.printStackTrace();
}
}
}
import java.io.File;
class DeleteFile
{
public static void main(String[] args)
{
File f0 = new File("D:FileOperationExample.txt");
if (f0.delete()) {
System.out.println(f0.getName()+ " file is deleted successfully.");
}
else {
System.out.println("Unexpected error found in deletion of the file."
);
}
}
}

You might also like