SlideShare a Scribd company logo
JAVA
Sai Vidya Institute of technology
Rajangunte, Bengaluru
Module 1
•An Overview of Java
•Data Types, Variables, and Arrays
•Operators
•Control Statements
An Overview of Java:
Object Oriented Programming Paradigms:
OOPs is an approach to program organising and development.
Object: Data + Function (Method)
Class: Group Of Objects
Obj1 Obj2
Data
Method
Data
Message
Features of OOPs:
•Emphasis on data rather than procedure
•Follows bottom up approach
•Programs are divided into Object (data + Method)
•Data is hidden and can’t be accessed by external functions
•Object may communicate with each other through message
Abstraction:
Def: It Refers to the act of representing essential features without including
the background details or explanation.
• Hiding internal Implementation, Just highlight setup services.
Ex: ATM machine
Advantages:
• Security
• Enhancement
• Maintainability
• Modularity
Three principles on OOPs
•Encapsulation- Security
•Inheritance - Reusability
•Polymorphism- Flexibility
Encapsulation:
Def: The wrapping up of data and methods into a single unit.
•It refers to the bundling of data (attributes or properties) and methods
(functions or procedures) that operate on the data into a single unit,
often known as a class.
•The primary goal of encapsulation is to hide the internal details of an
object and to restrict direct access to some of its components.
Inheritance
Inheritance is a fundamental concept in object-oriented programming
(OOP) that allows a new class, known as a subclass or derived class, to
inherit properties and behaviors from an existing class, called a
superclass or base class.
Key concepts related to inheritance include:
1. Base Class (Superclass) 2. Derived Class (Subclass)
3. "is-a" Relationship 4. Code Reusability 5. Method Overriding
Polymorphism
Polymorphism is one of the four fundamental principles of
object-oriented programming (OOP) and is a key concept in Java. It
allows objects of different classes to be treated as objects of a common
interface or superclass.
There are two types of polymorphism in Java:
1. Compile-time (static) polymorphism
2. Runtime (dynamic) polymorphism.
Lexical Issues
• Reserved Keywords int class = 20;
• Illegal Characters int variable-name= 12;
• Mismatched Braces
• String Literal Issues String message = “hello, world!;
• Missing Semicolons String message = “hello, world!”
• Comments Issues // incorrect : Unterminated comment
/* this is a comment
• Identifier Case Sensitivity int count=4;
int Count=3;
• Indentation and Formatting
Arrays
•An array is an Object in java, which stores similar type of data, in its
contagious memory location.
•Declaration of Array: (SubScript -Operator)
1. int arr[] = new int[5]
2. int[] arr = {10,20,30,40}
3. int[] arr = new int[n]
Types : 1. Single Dimensional Array
2. Multi-Dimensional Array
Constructors
•Constructor is Block of code similar to method
•It is called when instance of class is created.
•At the time of calling the constructor, memory for the object is
allocated in the memory.
• It is used to initialize the object.
•Every time an object is created using the new() keyword, at least one
constructor is called.
•Class Name and Constructor name should be same.
•Constructor doesn't have a return type
Types of Constructors
•Default Constructor - default constructor is a special constructor that
is automatically generated by the compiler if no other constructor is
defined in a class.
Syntax:
Class_Name() {
}
•Parameterized Constructor - A parameterized constructor is a type of
constructor in object-oriented programming that accepts parameters or
arguments when an object is being created.
Syntax:
Class_Name(int id, String name) {
}
•Copy Constructor - this creates a new object as a copy of an existing
object. The purpose of a copy constructor is to initialize a new object
by duplicating the state of an existing object.
Syntax: Class_Name(Class_ Name Object reference) {
}
this Keyword
•this keyword - is a reserved keyword in java i.e, we can’t use it as an
identifier. It is used to refer current class’s instance as well as static
members. It can be used in various contexts as given below:
•to refer instance variable of current class
•to invoke or initiate current class constructor
•can be passed as an argument in the method call
•can be passed as argument in the constructor call
•can be used to return the current class instance
Super Keyword
super keyword
1.super is a reserved keyword in java i.e, we can’t use it as an identifier.
2.super is used to refer super-class’s instance as well as static
members.
3.`
4.super keyword in java programming language refers to the superclass
of the class where the super keyword is currently being used.
5.The most common use of super keyword is that it eliminates the
confusion between the superclasses and subclasses that have methods
with same name.
Difference between Procedural programming
and OOPs
Procedural:
• Paradigm
• Data and Behaviour
• Encapsulation
• Inheritance
• Polymorphism
• Flexibility and modularity
• Real World modelling
OOPs:
• Paradigm
• Data and Behaviour
• Encapsulation
• Inheritance
• Polymorphism
• Flexibility and modularity
• Real World modelling
Class
Class is collection of Object and it doesn't take any space in memory.
Class is also called blueprint / logical entity
Class
Predefined
Scanner
Console
System
String
User-define
d
Car
Shape
Calculator
etc
Object
•Object is a instance of the class that execute the class, Once the obj of
that class is created, it takes up space like variable in the memory
•Syntax:
ClassName vef_var = new ClassName();
class-name obj-reference DMA Constructor
Method
Method is a group / block of code which takes input from user,
process it and gives output.
Method run only when they called
Method
Pre-Defined
Print();
Sort();
Sqrt();
nectInt();
User-Define
d
Add()
Sun()
Show()
Syntax:
return_type method_name (……)
{
// statement
}
Variables
Variable is container
which holds the value
while java program is
executed.
Variable
Local Variable Instance variable Static Variable
Local, Instance and Static Variable
•Local – Declared inside the method or method parameter.
We can access it directly.
•Instance – Declared inside the class and outside the method.
To access instance variable, we need to create object of c
class.
•Static – Declared in side the class and outside the method with static
keyword.
We can access it with the help of class name.
•Final – once we declare the variable as a final we can’t perform re-
assignment.
Data type
Data Type Specify the size and values that can be stored in variable.
Types:
•Primitive
•Non- Primitive
Data Types
Data Type
Primitive
Numeric
Integic
Byte(1)
Short(2)
Int (4)
Long(8)
Decimal
Float(4)
Double (8)
Non-Numer
ic
Char(2)
Boolean(1)
Non-Primiti
ve
Class
Interface
Arrays
String
Operators
•Operator is a symbol that is used to perform the operations as per user
requirement (Variable and values).
Types:
• Arithematic Operator
• Relational Operator
• Logical Operator
• Increment/ Decrement
• Assignment Operator
• Ternary Operator
• Bitwise Operator
Types:
Ari thematic
Operator (+, -, *, /,
%)
Relational Operator
(<, >, <=, >=, ==, !=)
Logical Operator
(&&, ||, !)
Increment/
Decrement
Pre Inc/Post Inc
(++exp, exp++)
Pre Decr/Post Decr
(--exp, exp--)
Assignment
Operator
Simple (=)
Complex (+=, -=, *=
etc)
Ternary Operator
(?:)
Bitwise
Operator(AND, OR,
XOR, Complement)
Control Statements
A control statement in java is a statement that determines whether the
other statements will be executed or not
Control Statements
Conditional
Statement
If condition (if
(condition){ })
If-else condition (if
(condition){ } else { })
else-if condition (if
(condition 1){ }else if
(condition 2) { })
Loop Statement
for loop
(for(Initialization;
condition; updating))
While (while
(condition))
do-while (do {
statement } while
(condition) )
Call By Value
•In call by value, a copy of the actual value is passed to the method.
•Changes made to the parameter inside the method have no effect on
the actual value outside the method.
•Java uses call by value for primitive data types (int, float, double, char,
etc.).
Call By Reference
•In true call by reference, a reference to the actual object is passed to
the method.
•Changes made to the parameter inside the method affect the actual
object outside the method.
•Java uses call by value for object references. When you pass an object
reference, you are passing the value of the reference, not the actual
object.
Recursion
•Recursion is a programming concept where a method calls itself in
order to solve a problem. In Java, recursion can be implemented in a
method by having the method call itself with a modified input until a
base case is reached.
For Loop
•for(Initialization; Condition; Inc/Dec) {
//Statements
}
Infinite for loop:
for( ; ; ) or for( ; true ; )
{
S.O.P(“Hello!”);
}
For-each Loop
•Iterating over Arrays and ArrayList more easily.
Syntax: for( type Var_name : Array/ArrayList ) {
//Statements
}
•In each iteration, the variable Var_name holds the value of an element
inside the Array/ArrayList, starting from the first element.
•There is no index
•Safe(Boundaries)
•ArrayList<String> itemsArrayList = new ArrayList<>();
itemsArrayList.add(“item1”);
itemsArrayList.add(“item2”);
itemsArrayList.add(“irem3”);
String[] itemArray = {“item1”, “item2”, “item3”};
for(String item : itemsArrayList )
Type-Casting or Type-Conversion
•It is the process of converting one data type into another. In
programming, variables and values have specific data types that define
the kind of data they can hold. Typecasting allows you to change the
data type of a variable or value.
There are two main types of typecasting:
1. Primitive type casting
2. Reference type casting
1.Primitive type casting
(Two types in it)
1.Widening (Implicit) Casting:
• This occurs when you are converting a smaller data type to a larger data type.
• It happens automatically, and there is no loss of information.
int intValue = 5;double
doubleValue = intValue; // Implicit casting from int to double
2. Narrowing (Explicit) Casting:
• This occurs when you are converting a larger data type to a smaller data type.
• It requires explicit casting and may result in loss of information.
double doubleValue = 5.67;
int intValue = (int) doubleValue; // Explicit casting from double to int
2.Reference Type Casting:
•Reference type casting involves converting from one class type to
another, and it can be either upcasting or downcasting.
1. Upcasting (Implicit):
•Upcasting occurs when you assign an object of a subclass to a variable
of its superclass.
•It happens automatically and is safe.
class Animal {}
class Dog extends Animal {}
Animal animal = new Dog(); // Upcasting
2.Downcasting (Explicit):
•Down-casting occurs when you assign an object of a superclass to a
variable of its subclass.
•It requires explicit casting and may result in a `ClassCastException` if
the object is not actually an instance of the subclass.
Animal animal = new Dog();
Dog dog = (Dog) animal; // Downcasting
Jump Statements
• Jump statements are used to alter the flow of control in a program. There are three
main types of jump statements in Java:
break, continue and return.
1. break Statement:
• The `break` statement is used to terminate the innermost loop or switch statement.
• When the `break` statement is encountered inside a loop or switch statement, the
control is transferred to the statement immediately following the loop or switch.
for (int i = 0; i < 10; i++) {
System.out.println(i);
if (i == 5) {
break; // exit the loop when i is 5
}
}
2.continue Statement:
•The `continue` statement is used to skip the rest of the code inside a loop
for the current iteration and move to the next iteration
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue; // skip the rest of the loop body when i is 5 }
System.out.println(i);
}
3. return Statement:
•The `return` statement is used to exit a method and return a value to the
caller.
•It can also be used to simply exit a method without returning any value (in
the case of a method with a void return type)
public int addNumbers(int a, int b) {
int sum = a + b;
return sum; // return the sum to the caller
}
Access Control in Java
•Access control in Java involves restricting access to the members
(fields, methods, and inner classes) of a class. It is implemented
through access modifiers like `public`, `private`, `protected`, and
default (package-private).
Access Modifiers
1.Public: Accessible from anywhere.
2.Private: Accessible only within the class.
3.Protected: Accessible within the package and by subclasses.
4.Default (Package-Private): Accessible within the package.
Garbage Collection in Java
•Garbage Collection is a process in Java that automatically reclaims
memory occupied by objects that are no longer in use by the program.
In Java, memory management is primarily handled by the Java Virtual
Machine (JVM), and the garbage collector is responsible for
identifying and freeing up memory occupied by unreachable objects.
How Garbage Collection Works
1. Allocation: When objects are created in Java, memory is allocated for them
in the heap.
2. Reference Tracking: The JVM keeps track of references to objects. If an
object is no longer referenced, it becomes a candidate for garbage collection.
3. Reclamation: The garbage collector identifies and releases the memory
occupied by unreachable objects.
Object as a Parameter
You can pass an object as a parameter to a method just like you
would with any other data type. When you pass an object as a
parameter, you are actually passing a reference to the object, not the
object itself. This means that changes made to the object inside the
method will affect the original object outside the method.
Returning Objects
•In java we can return an object from a method just like we would with
any other data type. When you return an object, you are returning a
reference to that object.
•if there's no meaningful object to return or if there's an error condition
you can return `null`. However, it's important to handle `null`
appropriately to avoid potential `NullPointerException`
Inner and Nested classes
•Inner and Nested classes are classes defined within another class. They
are used for various purposes, such as encapsulation, logical grouping,
and improving code organization.
Nested Class
•The term "nested class" is often used as a general term for any class
that is defined within another class, including inner classes.
•It's worth noting that a static nested class is always a nested class, but
not all nested classes are static.
Inner Class
• An inner class is a class that is defined inside another class. It can access the
members (fields and methods) of the outer class, including private members.
• Four types of inner class
• Member Inner Class: Defined at the member level of a class.
• Local Inner Class: Defined within a block of code, typically a method.
• Anonymous Inner Class: A class without a name, often used for instantiating an interface
or extending a class.
• Static Nested Class: A static class that is a member of another class.
Significance of Inner and nested class
•Encapsulation
•Code Organization
•Access to Outer Class Members
•Improved Readability
•Event Handling
•Private Implementation
Final Class
When a class is declared as `final`, it means that the class cannot be
subclassed or extended. No other class can inherit from a final class.
Syntax: final class Class_name {
//statements
}
Final Method
When a method is declared as `final`, it means that the method
cannot be overridden by subclasses. Subclasses cannot provide their
own implementation of a final method.
Syntax: final return_type method_name() {
// Statements
}
Final Variable
•When a variable is declared as `final`, it means that the variable cannot
be reassigned after its initial assignment. It essentially becomes a
constant, and its value cannot be changed
Syntax: final int a =20;
Benefits and Use Cases:
•Final Class: Used when you want to prevent the class from being
extended, often for security or design reasons.
•Final Method: Used when you want to enforce a specific behavior in
a method and ensure that subclasses cannot change it. It provides a
level of design control and can contribute to the security and reliability
of the code.
•Final Variable: Used when you want to create constants or immutable
objects. It improves code readability, reduces bugs, and ensures that
the value of the variable remains constant.
Module 3
•Inheritance: Inheritance Basics, Using super, Creating a Multilevel
Hierarchy, When Constructors Are Executed, Method Overriding,
Dynamic Method Dispatch, Using Abstract Classes, Using final with
Inheritance, Local Variable Type Inference and Inheritance, The
Object Class.
•Interfaces: Interfaces, Default Interface Methods, Use static Methods
in an Interface, Private Interface Methods.
Inheritance
Inheritance is one of the fundamental concepts in object-oriented
programming (OOP) and is supported in Java. It allows a class (subclass
or derived class) to inherit the properties and behaviors (fields and
methods) of another class (superclass or base class). This promotes code
reusability and establishes a relationship between classes.
Basic concepts of inheritance in java
•Superclass and Subclass
•Syntax for Creating a Subclass
•“Is-a relationship”
•Access Modifiers
•Keyword "extends“
•Constructors in Inheritance
•Method Overriding
•Keyword "super"
Super Keyword in inheritance
• The `super` keyword is used to refer to the immediate parent class object
1. Accessing Superclass Members: When a subclass has overridden a method or
hidden a field, you can use `super` to refer to the members of the superclass.
2. Invoking Superclass Constructors: The `super` keyword is used to invoke the
constructor of the immediate parent class. It is often used in the constructor of
the subclass to initialize the fields of the superclass.
3. Calling Superclass Methods: You can also use `super` to call methods of the
immediate parent class, even if they are not overridden in the subclass.
Types of Inheritance
•Single inheritance
•Multilevel Inheritance
•Multiple Inheritance
•Hierarchical Inheritance
Creating a Multilevel Hierarchy
In multilevel inheritance, a class inherits from another class, and then
another class inherits from the second class, creating a chain of
inheritance
Example: Class A
Class B
Class C
Class D
So on
Create object of last class which hold properties of all super class
extends
extends
extends
extends
When Constructors Are Executed
Constructors are executed in a specific order when dealing with
inheritance. When an object of a derived class (subclass) is created, the
constructors are called in the following order:
•Superclass Constructor: The constructor of the immediate superclass
(parent class) is called first. This ensures that the fields and behaviors
defined in the superclass are properly initialized before the subclass-specific
initialization takes place.
•Subclass Constructor: After the superclass constructor is executed, the
constructor of the subclass is called. This allows for the initialization of the
fields and behaviors specific to the subclass.
Local Variable Type Inference and Inheritance
• Local Variable Type Inference, introduced in Java 10 with the var keyword, allows you
to declare local variables without explicitly specifying their types. The type is inferred
by the compiler based on the initializer expression on the right-hand side. It's important
to note that this feature is specifically for local variables and cannot be used for fields,
method parameters, or return types.
• When it comes to inheritance, the use of var doesn't affect the inheritance mechanism
itself. Inheritance still works as it does with explicitly typed variables. The type of the
variable is determined at compile-time based on the actual type of the assigned object.
The Object Class
•the Object class is at the top of the class hierarchy. Every class in Java
is a direct or indirect subclass of the Object class. This makes Object a
fundamental part of Java's inheritance mechanism.
•The Object class is defined in the java.lang package, and it includes
methods that are common to all Java objects
Some of the key methods in the Object class include:
• toString(): This method returns a string representation of the object. It is often overridden in subcla
provide a meaningful string representation.
• equals(Object obj): This method is used to compare the equality of two objects. Subclasses often o
method to provide their own definition of equality.
• hashCode(): This method returns a hash code for the object. It is used in conjunction with the equa
when objects are stored in hash-based collections.
• getClass(): This method returns the runtime class of an object. It is commonly used to determine th
object at runtime.
• clone(): This method creates and returns a copy of the object. For the clone method to work correct
must implement the Cloneable interface.
• notify(), notifyAll(), and wait(): These methods are used for inter-thread communication and sync
Dynamic Method Dispatch
Dynamic Method Dispatch that allows a program to determine at
runtime which method implementation to invoke, based on the actual
type of the object rather than the declared type. This is also known as
late binding or runtime polymorphism.
Significance of Inheritance in java
•Code Reusability
•Method Overriding
•Polymorphism
•Code Organization
•Base for Interfaces
•Encapsulation
•Interfaces: Interfaces, Default Interface Methods, Use static Methods
in an Interface, Private Interface Methods
Interface
Defination
An interface is a syntactical contract that outlines a set of methods
that a class must implement. It defines a blueprint for a class, specifying
a set of methods without providing any implementation details.
An interface declares a collection of abstract methods that any class
implementing the interface must define
Syntax
interface Interface_name
{
variable declaration;
method declaration;
}
static final datatype variable_name;
abstract return-type method_name(parameter);
class A inetrface A
extends implements
class B class B
inetrface C
extends
interface D class A inetrface B
class C extends A implemnts B
Significance of Interface
• Abstraction
• Multiple Inheritance
• Polymorphism
• Encapsulation
• API Design
• Code Reusability
• Dependency Injection
• Frameworks and Libraries
• Java Standard Libraries
• Runnable
• Iterable
Default Interface Methods
•Default Interface Methods are a feature introduced in Java 8 to allow
the addition of new methods to interfaces in a backward-compatible
manner.
•With Default Interface Methods, you can provide a default
implementation for a method directly in the interface itself.
Use static Methods in an Interface
•Starting from version 8, interfaces can have static methods. These
static methods are associated with the interface itself, not with any
instance of the interface.
Private Interface Methods
Private interface methods are a feature introduced in Java 9 that
allows interfaces to have private methods. Prior to Java 9, interfaces
could only have abstract methods (methods without a body) and
constants. The introduction of private interface methods was aimed at
providing a way to share common code among default or static methods
within an interface without exposing these methods to the outside world
module 4
•Packages: Packages, Packages and Member Access, Importing
Packages.
•Exceptions: Exception-Handling Fundamentals, Exception Types,
Uncaught Exceptions, Using try and catch, Multiple catch Clauses,
Nested try Statements, throw, throws, finally, Java’s Built-in
Exceptions, Creating Your Own Exception Subclasses, Chained
Exceptions.
Packages
• Def: Packages are used to organize and group related classes and interfaces.
This helps in avoiding naming conflicts and makes the code more maintainable.
• Def: Package in Java is a mechanism to encapsulate a group of classes, sub
packages and interfaces.
Ex: package package_name;
• Subpackages: Packages that are inside another package are the subpackages.
These are not imported by default, they have to imported explicitly. Also,
members of a subpackage have no access privileges, i.e., they are considered as
different package for protected and default access specifiers.
Ex: import java.util.*;
•Preventing naming conflicts. For example there can be two classes with
name Employee in two packages, college.staff.cse.Employee and
college.staff.ee.Employee
•Making searching/locating and usage of classes, interfaces, enumerations
and annotations easier.
• Providing controlled access: protected and default have package level
access control. A protected member is accessible by classes in the same
package and its subclasses. A default member (without any access
specifier) is accessible by classes in the same package only.
•Packages can be considered as data encapsulation (or data-hiding).
Member Access(Access Modifiers)
• Private: Accessible only within the same class.
• Default (no modifier): Accessible within the same package.
• Protected: Accessible within the same package and by subclasses.
• Public: Accessible from anywhere.
JAVA Class Presentation.pdf Vsjsjsnheheh
Advantages of Packages
•Organizational Structure
•Encapsulation
•Access Control
•Namespace Management
•Versioning and Maintenance
•Code Reusability
•Readability and Understanding
•Security
•Import Statements
•Distribution and Deployment
Exception
Def: Exception is an unwanted or unexpected or abnormal event,
which occurs during the execution of a program, i.e. at run time, that
disrupts the normal flow of the program’s instructions.
Exception handling: In exception handling, we should have alternate
source through which we can handle the exception.
Advantage of Exception Handling:
The core advantage of exception handling is to maintain the normal
flow of the application. Exception normally disrupts the normal flow of
the application that is why we use exception handling
Exception-Handling Fundamentals
1.Try-Catch Blocks:
• The try block contains the code that might throw an exception.
• The catch block contains the code to handle the exception if it occurs.
2. Multiple Catch Blocks:
• You can have multiple catch blocks to handle different types of exceptions.
• The catch blocks are checked in order, and the first one that matches the exception type is
executed.
3. Finally Block:
• The finally block contains code that will be executed whether an exception occurs or not.
• It is often used for cleanup tasks, such as closing resources like files or database connections.
4. Throw Statement:
• The throw statement is used to explicitly throw an exception from a method or block of
code.
Exception types
1. Built-in Exceptions
1. Checked Exception
2. Unchecked Exception
2. User-Defined Exceptions
Difference between checked and
unchecked exceptions :
1) Checked Exception: The classes that extend Throwable class except
RuntimeException and Error are known as checked exceptions e.g.IOException,
SQLException etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception: The classes that extend RuntimeException are known
as unchecked exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked
at compile-time rather they are checked at runtime.
3) Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.
Uncaught Exceptions in Java
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.
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.
Using try and catch
•The try statement allows you to define a block of code to be tested for
errors while it is being executed.
•The catch statement allows you to define a block of code to be
executed, if an error occurs in the try block.
•The try and catch keywords come in pairs
Multiple catch Clauses
•A try block can be followed by one or more catch blocks. Each catch block must
contain a different exception handler. So, if you have to perform different tasks
at the occurrence of different exceptions, use java multi-catch block.
Points to remember
• At a time only one exception occurs and at a time only one catch block is
executed.
• All catch blocks must be ordered from most specific to most general, i.e. catch
for
•ArithmeticException must come before catch for Exception
JAVA Class Presentation.pdf Vsjsjsnheheh
Nested try Statements
•In Java, using a try block inside another try block is permitted. It is
called as nested try block.Every statement that we enter a statement in
try block, context of that exception is pushed onto the stack.
•For example, the inner try block can be used to handle
ArrayIndexOutOfBoundsException while the outer try block can
handle the ArithemeticException (division by zero).
Why use nested try block
•Sometimes a situation may arise where a part of a block may cause
one error and the entire block itself may cause another error. In such
cases, exception handlers have to be nested
Syntax:
....
//main try block
try
{
statement 1;
statement 2;
//try catch block within another try
block
try
{
statement 3;
statement 4;
//try catch block within nested
try block
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}
catch(Exception e1)
{
//exception message
}
//catch block of parent
(outer) try block
catch(Exception e3)
{
//exception message
}
....
throw, throws, finally
•The throw keyword is used to throw an exception explicitly. Only object of
Throwable class or its sub classes can be thrown. Program execution stops on
encountering throw statement, and the closest catch statement is checked for
matching type of exception.
•The throws keyword is used to declare the list of exception that a method may
throw during execution of program. Any method that is capable of causing
exceptions must list all the exceptions possible during its execution, so that
anyone calling that method gets a prior knowledge about which exceptions are
to be handled.
•A finally keyword is used to create a block of code that follows a try block. A
finally block of code is always executed whether an exception has occurred or
not. Using a finally block, it lets you run any cleanup type statements that you
want to execute, no matter what happens in the protected code. A finally block
appears at the end of catch block.
throw throws
throw keyword is used to throw an
exception explicitly.
throws keyword is used to declare an
exception possible during its execution.
throw keyword is followed by an
instance of Throwable class or one of its
sub-classes.
throws keyword is followed by one or
more Exception class names separated by
commas.
throw keyword is declared inside a
method body.
throws keyword is used with method
signature (method declaration).
We cannot throw multiple exceptions
using throw keyword.
We can declare multiple exceptions
(separated by commas) using throws
keyword.
Java’s Built-in Exceptions
•Built-in exceptions are the exceptions which are available in Java
libraries. These exceptions are suitable to explain certain error
situations. Below is the list of important built-in exceptions in Java.
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
IllegalArgumentException Illegal argument used to invoke a method.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NullPointerException Invalid use of a null reference.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
UnsupportedOperationException An unsupported operation was encountered.
ClassCastException Invalid cast.
Creating Your Own Exception Subclasses
•Java’s exception handling mechanism is not limited to these errors. In fact,
part of the power of Java’s approach to exceptions is its ability to handle
exceptions that you create which correspond to errors in your own code.
Creating an exception is easy. Just define a subclass of Exception (which is,
of course, a subclass of Throwable). Your subclasses don’t need to actually
implement anything—it is their existence in the type system that allows you
to use them as exceptions.
•The Exception class does not define any methods of its own. It does, of
course, inherit those methods provided by Throwable
Chained Exceptions
Chained Exceptions allows to relate one exception with another exception, i.e one
exception describes cause of another exception.
Constructors Of Throwable class Which support chained exceptions in java :
Throwable(Throwable cause) :- Where cause is the exception that causes the current
exception.
Throwable(String msg, Throwable cause) :- Where msg is the exception message and
cause is the exception that causes the current exception.
Methods Of Throwable class Which support chained exceptions in java :
getCause() method :- This method returns actual cause of an exception.
initCause(Throwable cause) method :- This method sets the cause for the calling
exception.
Module 5-Syllubus
• Multithreaded Programming: The Java Thread Model, The Main Thread, Creating a Thread,
Creating Multiple Threads, Using isAlive() and join(), Thread Priorities, Synchronization,
Interthread Communication, Suspending, Resuming, and Stopping Threads, Obtaining a Thread’s
State.
• Enumerations, Type Wrappers and Autoboxing: Enumerations (Enumeration Fundamentals,
The values() and valueOf() Methods), Type Wrappers (Character, Boolean, The Numeric Type
Wrappers), Autoboxing (Autoboxing and Methods, Autoboxing/Unboxing Occurs in Expressions,
Autoboxing/Unboxing Boolean and Character Values).
Multitasking operating system
A multitasking operating system is an operating system that gives
you the perception of 2 or more tasks/jobs/processes running
simultaneously. It does this by dividing system resources amongst these
tasks/jobs/processes and switching between the tasks/jobs/processes
while they are executing over and over again.
Multitasking Programming is of Two Types:
1. Process-based Multitasking
2. Thread-based Multitasking
The Java Thread Model
Java programming language allows us to create a program that
contains one or more parts that can run simultaneously at the same time.
This type of program is known as a multithreading program. Each part
of this program is called a thread. Every thread defines a separate path
of execution in java
Def: A thread is a light wieght process
or
Def:A thread is a subpart of a process that can run individually.
Thread Life Cycle - a thread goes through different states throughout
its execution. These stages are called thread life cycle states or phases.
New
When a thread object is created using new, then the thread is said to be in
the New state. This state is also known as Born state.
Thread t1 = new Thread();
Runnable / Ready
When a thread calls start( ) method, then the thread is said to be in the
Runnable state. This state is also known as a Ready state.
t1.start();
Running
When a thread calls run( ) method, then the thread is said to be Running.
The run( ) method of a thread called automatically by the start( ) method.
Dead / Terminated
A thread in the Running state may move into the dead state due to either its
execution completed or the stop( ) method called. The dead state is also known
as the terminated state.
Blocked / Waiting
A thread in the Running state may move into the blocked state due to various reasons like
sleep( ) method called, wait( ) method called, suspend( ) method called, and join( ) method
called, etc. When a thread is in the blocked or waiting state, it may move to Runnable state due
to reasons like sleep time completed, waiting time completed, notify( ) or notifyAll( ) method
called, resume( ) method called, etc.
Example
• Thread.sleep(1000);
• wait(1000);
• wait();
• suspened();
• notify();
• notifyAll();
• resume();
How to create / define a Thread
1. By extending Thread Class
Syntax:
public class Class_Name extends Thread{
// Statements
}
2. By Implementing Runnable Interface
Syntax:
public class Class_Name implements Runnable {
//Statements
}
The Main Thread
It is the thread from which other “child” threads will be spawned. It must be
the last thread to finish execution because it performs various shutdown actions
It's important to note that the main thread is just like any other thread in
Java, but it's special because it's the one that starts the program's execution. You
can manipulate the main thread like any other thread in Java, for example, you
can set its name, priority, or manage its lifecycle using methods provided by the
Thread class or by using higher-level concurrency utilities provided by the
java.util.concurrent package.
Using isAlive() and join()
•Sometimes one thread needs to know when other thread is terminating.
In java, isAlive() and join() are two different methods that are used to
check whether a thread has finished its execution or not.
•The isAlive() method returns true if the thread upon which it is called
is still running otherwise it returns false.
•Using join() method, we tell our thread to wait until the specified
thread completes its execution.
Thread Priorities
In multithreading environment in which thread scheduler assigns the
processor to a thread based on the priority of thread. Whenever we create a
thread in Java, it always has some priority assigned to it. Priority can either be
given by JVM while creating the thread or it can be given by the programmer
explicitly.
Priorities in threads is a concept where each thread is having a priority which
in layman’s language one can say every object is having priority here which is
represented by numbers ranging from 1 to 10.
• The default priority is set to 5 as excepted.
• Minimum priority is set to 1.
• Maximum priority is set to 10.
Here 3 constants are defined in it namely as follows:
1. public static int NORM_PRIORITY
2. public static int MIN_PRIORITY
3. public static int MAX_PRIORITY
Synchronization
Java Synchronization is used to make sure by some synchronization method that only
one thread can access the resource at a given point in time.
1.Synchronized Methods: You can declare methods as synchronized to ensure that
only one thread can execute them at a time. When a thread enters a synchronized method,
it acquires the intrinsic lock (also known as monitor lock) associated with the object on
which the method is declared. Other threads attempting to execute synchronized methods
on the same object will be blocked until the owning thread releases the lock.
public synchronized void synchronizedMethod() {
// Synchronized method body
}
2. Synchronized Blocks: In addition to synchronizing entire methods, you can
also synchronize specific blocks of code. This is useful when only a portion of a
method needs to be synchronized. To do this, you specify the object that will be
used as the lock.
public void someMethod() {
synchronized (lockObject) {
// Synchronized block of code
}
}
Interthread Communication
Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which
a thread is paused running in its critical section and another thread is
allowed to enter (or lock) in the same critical section to be executed
• wait()
• notify()
• notifyAll()
•wait- Object wait methods has three variance, one which waits
indefinitely for any other thread to call notify or notifyAll method on
the object to wake up the current thread. Other two variances puts
the current thread in wait for specific amount of time before they
wake up.
•notify -notify method wakes up only one thread waiting on the object
and that thread starts execution. So if there are multiple threads
waiting for an object, this method will wake up only one of them
•notifyall- notifyAll method wakes up all the threads waiting on the
object, although which one will process first depends on the OS
implementation.
Suspending, Resuming, and Stopping
Threads,
•sleep()- thread will be blocked for a specified time
•suspend() - blocked untill further orders
•wait()- blocked untill certain condition occurs
•resume()- resumes the suspended thread
•notify()- notify to thread which is in waiting state
•stop()- kills/terminate the thread
Obtaining a Thread’s State.
The getState() method of the Thread class is an instance method that
returns the state of the thread object on which this method is invoked.
Enumerations Fundamentals
enumeration is a special kind of class that includes a list of constant values.
The values in the enumeration list define the values an object can have
Creating Enumerations:
When creating an enumeration list, we don't use the keyword class and when
you create a enumeration object, we don't use the keyword new
To create an enumeration list we need to import java.util.Enumeration
An enumeration is created using the enum keyword followed by the variable
Name we want associated with the list
Syntax Example
public enum variable_name{
ITEM1,ITEM2,ITEM3
}
Creating an enumeration object
Syntax: variableName object;
example: Gender gen
Assigning default values:
public enum Gender {
MALE(1), FEMALE(2), UNKNOWN(0)
}
public enum GENDER{
MAKE,FEMALE,UNKNOWN
}
Assigning values to the enumeration
object
Syntax:object = variableName.ITEM;
example: Gender gen=Gender.MALE;
The values() and valueOf() Methods
1.Values():
• Method returns an array that contains a
list of the enumeration constants
• values() returns the values in the
enumeration and stores them in an array.
We can process the array with a foreach
loop.
Syntex: public static enum-type[ ] values( )
Example: Values value[] =
Values.values();
for (Values a : value)
statement;
2.ValueOf():
• method returns the enumeration constant
whose value corresponds to the string passed in
str.
• method takes a single parameter of the
constant name to retrieve and returns the
constant from the enumeration, if it exists.
Syntax: enumerationVariable =
enumerationName.valueOf("EnumerationValueInL
ist");
Example
WeekDays wd =
WeekDays.valueOf("MONDAY");
Type Wrappers(Character, Boolean, The Numeric
Type Wrappers)
• Java uses primitive types (also called simple
types), such as int or double, to
• hold the basic data types supported by the
language.
• Instead of primitive types if objects are used
everywhere for even simple
• calculations then performance overhead is the
problem.
• So to avoid this java had used primitive types.
• So primitive types do not inherit Object class
• But there are times when you will need an
object representation for
• primitives like int and char.
• Example, you can’t pass a primitive type
by reference to a method.
• Many of the standard data structures
implemented by Java operate on objects,
• which mean that you can’t use these data
structures to store primitive types.
• To handle these (and other) situations,
Java provides type wrappers, which
• are classes that encapsulate a primitive
type within an object.
• Character is a wrapper around a
char.
•The constructor for Character is
Character(char ch) here ch is a
character
•variable whose values will be
wrapped to character object by the
wrapper class
• To obtain the char value contained
in a Character object, call charValue(
), shown
•here:
•char charValue( )
•It returns the encapsulated character.
• Boolean is a wrapper around boolean values. It
defines these constructors:
• Boolean(boolean boolValue)
• Boolean(String boolString)
• In the first version, boolValue must be
either true or false. In the second version, if
• boolString contains the string "true" (in
uppercase or lowercase), then the new Boolean
• object will be true. Otherwise, it will be false.
• To obtain a boolean value from a Boolean
object, use booleanValue( ), shown here:
• boolean booleanValue( )
• It returns the boolean equivalent of the
invoking object.
The Numeric Type Wrappers
The most commonly used type wrappers are those that represent
numeric values. These
are Byte, Short, Integer, Long, Float, and Double. All of the numeric
type wrappers
inherit the abstract class Number.
Number declares methods that return the value of an object in each
of the different
number formats. These methods are shown here:
1. byte byteValue( )
2. double doubleValue( )
3. float floatValue( )
4. int intValue( )
5. long longValue( )
6. short shortValue( )
Autoboxing
• Autoboxing is the process by which a
primitive type is automatically encapsulated
• (boxed) into its equivalent type wrapper
whenever an object of that type is needed.
• There is no need to explicitly construct an
object.
• For example, converting int to Integer class.
The Java compiler applies autoboxing
• when a primitive value is:
• Passed as a parameter to a method that
expects an object of the corresponding
• wrapper class.
• Assigned to a variable of the corresponding
wrapper class
• Auto-unboxing is the process by which the
value of a boxed object is automatically
• extracted(unboxed) from a type wrapper
when its value is needed. There is no need
• to call a method such as intValue( ) or
doubleValue( ).
• For example conversion of Integer to int. The
Java compiler applies unboxing when an
• object of a wrapper class is:
• Passed as a parameter to a method that
expects a value of the corresponding
• primitive type.
• Assigned to a variable of the corresponding
primitive type.
Autoboxing and Methods:
•autoboxing/unboxing might occur when an argument is passed to a
method, or when a value is returned by a method.
•autoboxing automatically occurs whenever a primitive type must be
converted into an object.autounboxing takes place whenever an object
must be converted into a primitive typ
Autoboxing/Unboxing Occurs in Expressions
•autoboxing and unboxing take place whenever a conversion into an
object or from an object is required.
•This applies to expressions. Within an expression, a numeric object is
automatically unboxed.
•The outcome of the expression is reboxed, if necessary
Autoboxing/Unboxing Boolean and Character
Values
•Java also supplies wrappers for boolean and char. These are Boolean
and Character.
•Autoboxing/unboxing applies to these wrappers, too
•Character ch = 'x'; // box a char
• char ch2 = ch; // unbox a char
• Boolean b = true; here the value true is boxed in b
•if(b) System.out.println("b is true"); // here b is unboxed

More Related Content

Similar to JAVA Class Presentation.pdf Vsjsjsnheheh (20)

PPTX
Android Training (Java Review)
Khaled Anaqwa
 
PDF
7. VARIABLEs presentation in java programming. Pdf
simukondasankananji8
 
PPT
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
mcjaya2024
 
PPTX
Introduction to oop and java fundamentals
AnsgarMary
 
PPTX
Module 1.pptx
YakaviBalakrishnan
 
PPTX
Presentation2.ppt java basic core ppt .
KeshavMotivation
 
PPTX
Java Unit-1.1 chunri kyu shuru kar rh koi si je di of du th n high ch ka dh h...
gkgupta1115
 
PPT
core_java.ppt
YashikaDave
 
PPTX
Introduction to OOP with java
Sujit Kumar
 
PPTX
class as the basis.pptx
Epsiba1
 
PPTX
JAVA-PPT'S-complete-chrome.pptx
KunalYadav65140
 
PPTX
JAVA-PPT'S.pptx
RaazIndia
 
PPT
Java core - Detailed Overview
Buddha Tree
 
PPT
Java Tutorials
Woxa Technologies
 
PPTX
ppt_on_java.pptx
MAYANKKUMAR492040
 
PPTX
Object Oriented Programming Tutorial.pptx
ethiouniverse
 
PPTX
Java interview questions 1
Sherihan Anver
 
PPTX
Object oriented programming
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Introduction to OOP concepts
Ahmed Farag
 
PPTX
Scala, Play 2.0 & Cloud Foundry
Pray Desai
 
Android Training (Java Review)
Khaled Anaqwa
 
7. VARIABLEs presentation in java programming. Pdf
simukondasankananji8
 
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
mcjaya2024
 
Introduction to oop and java fundamentals
AnsgarMary
 
Module 1.pptx
YakaviBalakrishnan
 
Presentation2.ppt java basic core ppt .
KeshavMotivation
 
Java Unit-1.1 chunri kyu shuru kar rh koi si je di of du th n high ch ka dh h...
gkgupta1115
 
core_java.ppt
YashikaDave
 
Introduction to OOP with java
Sujit Kumar
 
class as the basis.pptx
Epsiba1
 
JAVA-PPT'S-complete-chrome.pptx
KunalYadav65140
 
JAVA-PPT'S.pptx
RaazIndia
 
Java core - Detailed Overview
Buddha Tree
 
Java Tutorials
Woxa Technologies
 
ppt_on_java.pptx
MAYANKKUMAR492040
 
Object Oriented Programming Tutorial.pptx
ethiouniverse
 
Java interview questions 1
Sherihan Anver
 
Introduction to OOP concepts
Ahmed Farag
 
Scala, Play 2.0 & Cloud Foundry
Pray Desai
 

Recently uploaded (20)

PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Ad

JAVA Class Presentation.pdf Vsjsjsnheheh

  • 1. JAVA Sai Vidya Institute of technology Rajangunte, Bengaluru
  • 2. Module 1 •An Overview of Java •Data Types, Variables, and Arrays •Operators •Control Statements
  • 3. An Overview of Java: Object Oriented Programming Paradigms: OOPs is an approach to program organising and development. Object: Data + Function (Method) Class: Group Of Objects Obj1 Obj2 Data Method Data Message
  • 4. Features of OOPs: •Emphasis on data rather than procedure •Follows bottom up approach •Programs are divided into Object (data + Method) •Data is hidden and can’t be accessed by external functions •Object may communicate with each other through message
  • 5. Abstraction: Def: It Refers to the act of representing essential features without including the background details or explanation. • Hiding internal Implementation, Just highlight setup services. Ex: ATM machine Advantages: • Security • Enhancement • Maintainability • Modularity
  • 6. Three principles on OOPs •Encapsulation- Security •Inheritance - Reusability •Polymorphism- Flexibility
  • 7. Encapsulation: Def: The wrapping up of data and methods into a single unit. •It refers to the bundling of data (attributes or properties) and methods (functions or procedures) that operate on the data into a single unit, often known as a class. •The primary goal of encapsulation is to hide the internal details of an object and to restrict direct access to some of its components.
  • 8. Inheritance Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new class, known as a subclass or derived class, to inherit properties and behaviors from an existing class, called a superclass or base class. Key concepts related to inheritance include: 1. Base Class (Superclass) 2. Derived Class (Subclass) 3. "is-a" Relationship 4. Code Reusability 5. Method Overriding
  • 9. Polymorphism Polymorphism is one of the four fundamental principles of object-oriented programming (OOP) and is a key concept in Java. It allows objects of different classes to be treated as objects of a common interface or superclass. There are two types of polymorphism in Java: 1. Compile-time (static) polymorphism 2. Runtime (dynamic) polymorphism.
  • 10. Lexical Issues • Reserved Keywords int class = 20; • Illegal Characters int variable-name= 12; • Mismatched Braces • String Literal Issues String message = “hello, world!; • Missing Semicolons String message = “hello, world!” • Comments Issues // incorrect : Unterminated comment /* this is a comment • Identifier Case Sensitivity int count=4; int Count=3; • Indentation and Formatting
  • 11. Arrays •An array is an Object in java, which stores similar type of data, in its contagious memory location. •Declaration of Array: (SubScript -Operator) 1. int arr[] = new int[5] 2. int[] arr = {10,20,30,40} 3. int[] arr = new int[n] Types : 1. Single Dimensional Array 2. Multi-Dimensional Array
  • 12. Constructors •Constructor is Block of code similar to method •It is called when instance of class is created. •At the time of calling the constructor, memory for the object is allocated in the memory. • It is used to initialize the object. •Every time an object is created using the new() keyword, at least one constructor is called. •Class Name and Constructor name should be same. •Constructor doesn't have a return type
  • 13. Types of Constructors •Default Constructor - default constructor is a special constructor that is automatically generated by the compiler if no other constructor is defined in a class. Syntax: Class_Name() { }
  • 14. •Parameterized Constructor - A parameterized constructor is a type of constructor in object-oriented programming that accepts parameters or arguments when an object is being created. Syntax: Class_Name(int id, String name) { }
  • 15. •Copy Constructor - this creates a new object as a copy of an existing object. The purpose of a copy constructor is to initialize a new object by duplicating the state of an existing object. Syntax: Class_Name(Class_ Name Object reference) { }
  • 16. this Keyword •this keyword - is a reserved keyword in java i.e, we can’t use it as an identifier. It is used to refer current class’s instance as well as static members. It can be used in various contexts as given below: •to refer instance variable of current class •to invoke or initiate current class constructor •can be passed as an argument in the method call •can be passed as argument in the constructor call •can be used to return the current class instance
  • 17. Super Keyword super keyword 1.super is a reserved keyword in java i.e, we can’t use it as an identifier. 2.super is used to refer super-class’s instance as well as static members. 3.` 4.super keyword in java programming language refers to the superclass of the class where the super keyword is currently being used. 5.The most common use of super keyword is that it eliminates the confusion between the superclasses and subclasses that have methods with same name.
  • 18. Difference between Procedural programming and OOPs Procedural: • Paradigm • Data and Behaviour • Encapsulation • Inheritance • Polymorphism • Flexibility and modularity • Real World modelling OOPs: • Paradigm • Data and Behaviour • Encapsulation • Inheritance • Polymorphism • Flexibility and modularity • Real World modelling
  • 19. Class Class is collection of Object and it doesn't take any space in memory. Class is also called blueprint / logical entity Class Predefined Scanner Console System String User-define d Car Shape Calculator etc
  • 20. Object •Object is a instance of the class that execute the class, Once the obj of that class is created, it takes up space like variable in the memory •Syntax: ClassName vef_var = new ClassName(); class-name obj-reference DMA Constructor
  • 21. Method Method is a group / block of code which takes input from user, process it and gives output. Method run only when they called Method Pre-Defined Print(); Sort(); Sqrt(); nectInt(); User-Define d Add() Sun() Show() Syntax: return_type method_name (……) { // statement }
  • 22. Variables Variable is container which holds the value while java program is executed. Variable Local Variable Instance variable Static Variable
  • 23. Local, Instance and Static Variable •Local – Declared inside the method or method parameter. We can access it directly. •Instance – Declared inside the class and outside the method. To access instance variable, we need to create object of c class. •Static – Declared in side the class and outside the method with static keyword. We can access it with the help of class name. •Final – once we declare the variable as a final we can’t perform re- assignment.
  • 24. Data type Data Type Specify the size and values that can be stored in variable. Types: •Primitive •Non- Primitive
  • 25. Data Types Data Type Primitive Numeric Integic Byte(1) Short(2) Int (4) Long(8) Decimal Float(4) Double (8) Non-Numer ic Char(2) Boolean(1) Non-Primiti ve Class Interface Arrays String
  • 26. Operators •Operator is a symbol that is used to perform the operations as per user requirement (Variable and values). Types: • Arithematic Operator • Relational Operator • Logical Operator • Increment/ Decrement • Assignment Operator • Ternary Operator • Bitwise Operator
  • 27. Types: Ari thematic Operator (+, -, *, /, %) Relational Operator (<, >, <=, >=, ==, !=) Logical Operator (&&, ||, !) Increment/ Decrement Pre Inc/Post Inc (++exp, exp++) Pre Decr/Post Decr (--exp, exp--) Assignment Operator Simple (=) Complex (+=, -=, *= etc) Ternary Operator (?:) Bitwise Operator(AND, OR, XOR, Complement)
  • 28. Control Statements A control statement in java is a statement that determines whether the other statements will be executed or not Control Statements Conditional Statement If condition (if (condition){ }) If-else condition (if (condition){ } else { }) else-if condition (if (condition 1){ }else if (condition 2) { }) Loop Statement for loop (for(Initialization; condition; updating)) While (while (condition)) do-while (do { statement } while (condition) )
  • 29. Call By Value •In call by value, a copy of the actual value is passed to the method. •Changes made to the parameter inside the method have no effect on the actual value outside the method. •Java uses call by value for primitive data types (int, float, double, char, etc.).
  • 30. Call By Reference •In true call by reference, a reference to the actual object is passed to the method. •Changes made to the parameter inside the method affect the actual object outside the method. •Java uses call by value for object references. When you pass an object reference, you are passing the value of the reference, not the actual object.
  • 31. Recursion •Recursion is a programming concept where a method calls itself in order to solve a problem. In Java, recursion can be implemented in a method by having the method call itself with a modified input until a base case is reached.
  • 32. For Loop •for(Initialization; Condition; Inc/Dec) { //Statements } Infinite for loop: for( ; ; ) or for( ; true ; ) { S.O.P(“Hello!”); }
  • 33. For-each Loop •Iterating over Arrays and ArrayList more easily. Syntax: for( type Var_name : Array/ArrayList ) { //Statements } •In each iteration, the variable Var_name holds the value of an element inside the Array/ArrayList, starting from the first element. •There is no index •Safe(Boundaries)
  • 34. •ArrayList<String> itemsArrayList = new ArrayList<>(); itemsArrayList.add(“item1”); itemsArrayList.add(“item2”); itemsArrayList.add(“irem3”); String[] itemArray = {“item1”, “item2”, “item3”}; for(String item : itemsArrayList )
  • 35. Type-Casting or Type-Conversion •It is the process of converting one data type into another. In programming, variables and values have specific data types that define the kind of data they can hold. Typecasting allows you to change the data type of a variable or value. There are two main types of typecasting: 1. Primitive type casting 2. Reference type casting
  • 36. 1.Primitive type casting (Two types in it) 1.Widening (Implicit) Casting: • This occurs when you are converting a smaller data type to a larger data type. • It happens automatically, and there is no loss of information. int intValue = 5;double doubleValue = intValue; // Implicit casting from int to double 2. Narrowing (Explicit) Casting: • This occurs when you are converting a larger data type to a smaller data type. • It requires explicit casting and may result in loss of information. double doubleValue = 5.67; int intValue = (int) doubleValue; // Explicit casting from double to int
  • 37. 2.Reference Type Casting: •Reference type casting involves converting from one class type to another, and it can be either upcasting or downcasting. 1. Upcasting (Implicit): •Upcasting occurs when you assign an object of a subclass to a variable of its superclass. •It happens automatically and is safe. class Animal {} class Dog extends Animal {} Animal animal = new Dog(); // Upcasting
  • 38. 2.Downcasting (Explicit): •Down-casting occurs when you assign an object of a superclass to a variable of its subclass. •It requires explicit casting and may result in a `ClassCastException` if the object is not actually an instance of the subclass. Animal animal = new Dog(); Dog dog = (Dog) animal; // Downcasting
  • 39. Jump Statements • Jump statements are used to alter the flow of control in a program. There are three main types of jump statements in Java: break, continue and return. 1. break Statement: • The `break` statement is used to terminate the innermost loop or switch statement. • When the `break` statement is encountered inside a loop or switch statement, the control is transferred to the statement immediately following the loop or switch. for (int i = 0; i < 10; i++) { System.out.println(i); if (i == 5) { break; // exit the loop when i is 5 } }
  • 40. 2.continue Statement: •The `continue` statement is used to skip the rest of the code inside a loop for the current iteration and move to the next iteration for (int i = 0; i < 10; i++) { if (i == 5) { continue; // skip the rest of the loop body when i is 5 } System.out.println(i); }
  • 41. 3. return Statement: •The `return` statement is used to exit a method and return a value to the caller. •It can also be used to simply exit a method without returning any value (in the case of a method with a void return type) public int addNumbers(int a, int b) { int sum = a + b; return sum; // return the sum to the caller }
  • 42. Access Control in Java •Access control in Java involves restricting access to the members (fields, methods, and inner classes) of a class. It is implemented through access modifiers like `public`, `private`, `protected`, and default (package-private).
  • 43. Access Modifiers 1.Public: Accessible from anywhere. 2.Private: Accessible only within the class. 3.Protected: Accessible within the package and by subclasses. 4.Default (Package-Private): Accessible within the package.
  • 44. Garbage Collection in Java •Garbage Collection is a process in Java that automatically reclaims memory occupied by objects that are no longer in use by the program. In Java, memory management is primarily handled by the Java Virtual Machine (JVM), and the garbage collector is responsible for identifying and freeing up memory occupied by unreachable objects.
  • 45. How Garbage Collection Works 1. Allocation: When objects are created in Java, memory is allocated for them in the heap. 2. Reference Tracking: The JVM keeps track of references to objects. If an object is no longer referenced, it becomes a candidate for garbage collection. 3. Reclamation: The garbage collector identifies and releases the memory occupied by unreachable objects.
  • 46. Object as a Parameter You can pass an object as a parameter to a method just like you would with any other data type. When you pass an object as a parameter, you are actually passing a reference to the object, not the object itself. This means that changes made to the object inside the method will affect the original object outside the method.
  • 47. Returning Objects •In java we can return an object from a method just like we would with any other data type. When you return an object, you are returning a reference to that object. •if there's no meaningful object to return or if there's an error condition you can return `null`. However, it's important to handle `null` appropriately to avoid potential `NullPointerException`
  • 48. Inner and Nested classes •Inner and Nested classes are classes defined within another class. They are used for various purposes, such as encapsulation, logical grouping, and improving code organization.
  • 49. Nested Class •The term "nested class" is often used as a general term for any class that is defined within another class, including inner classes. •It's worth noting that a static nested class is always a nested class, but not all nested classes are static.
  • 50. Inner Class • An inner class is a class that is defined inside another class. It can access the members (fields and methods) of the outer class, including private members. • Four types of inner class • Member Inner Class: Defined at the member level of a class. • Local Inner Class: Defined within a block of code, typically a method. • Anonymous Inner Class: A class without a name, often used for instantiating an interface or extending a class. • Static Nested Class: A static class that is a member of another class.
  • 51. Significance of Inner and nested class •Encapsulation •Code Organization •Access to Outer Class Members •Improved Readability •Event Handling •Private Implementation
  • 52. Final Class When a class is declared as `final`, it means that the class cannot be subclassed or extended. No other class can inherit from a final class. Syntax: final class Class_name { //statements }
  • 53. Final Method When a method is declared as `final`, it means that the method cannot be overridden by subclasses. Subclasses cannot provide their own implementation of a final method. Syntax: final return_type method_name() { // Statements }
  • 54. Final Variable •When a variable is declared as `final`, it means that the variable cannot be reassigned after its initial assignment. It essentially becomes a constant, and its value cannot be changed Syntax: final int a =20;
  • 55. Benefits and Use Cases: •Final Class: Used when you want to prevent the class from being extended, often for security or design reasons. •Final Method: Used when you want to enforce a specific behavior in a method and ensure that subclasses cannot change it. It provides a level of design control and can contribute to the security and reliability of the code. •Final Variable: Used when you want to create constants or immutable objects. It improves code readability, reduces bugs, and ensures that the value of the variable remains constant.
  • 56. Module 3 •Inheritance: Inheritance Basics, Using super, Creating a Multilevel Hierarchy, When Constructors Are Executed, Method Overriding, Dynamic Method Dispatch, Using Abstract Classes, Using final with Inheritance, Local Variable Type Inference and Inheritance, The Object Class. •Interfaces: Interfaces, Default Interface Methods, Use static Methods in an Interface, Private Interface Methods.
  • 57. Inheritance Inheritance is one of the fundamental concepts in object-oriented programming (OOP) and is supported in Java. It allows a class (subclass or derived class) to inherit the properties and behaviors (fields and methods) of another class (superclass or base class). This promotes code reusability and establishes a relationship between classes.
  • 58. Basic concepts of inheritance in java •Superclass and Subclass •Syntax for Creating a Subclass •“Is-a relationship” •Access Modifiers •Keyword "extends“ •Constructors in Inheritance •Method Overriding •Keyword "super"
  • 59. Super Keyword in inheritance • The `super` keyword is used to refer to the immediate parent class object 1. Accessing Superclass Members: When a subclass has overridden a method or hidden a field, you can use `super` to refer to the members of the superclass. 2. Invoking Superclass Constructors: The `super` keyword is used to invoke the constructor of the immediate parent class. It is often used in the constructor of the subclass to initialize the fields of the superclass. 3. Calling Superclass Methods: You can also use `super` to call methods of the immediate parent class, even if they are not overridden in the subclass.
  • 60. Types of Inheritance •Single inheritance •Multilevel Inheritance •Multiple Inheritance •Hierarchical Inheritance
  • 61. Creating a Multilevel Hierarchy In multilevel inheritance, a class inherits from another class, and then another class inherits from the second class, creating a chain of inheritance Example: Class A Class B Class C Class D So on Create object of last class which hold properties of all super class extends extends extends extends
  • 62. When Constructors Are Executed Constructors are executed in a specific order when dealing with inheritance. When an object of a derived class (subclass) is created, the constructors are called in the following order: •Superclass Constructor: The constructor of the immediate superclass (parent class) is called first. This ensures that the fields and behaviors defined in the superclass are properly initialized before the subclass-specific initialization takes place. •Subclass Constructor: After the superclass constructor is executed, the constructor of the subclass is called. This allows for the initialization of the fields and behaviors specific to the subclass.
  • 63. Local Variable Type Inference and Inheritance • Local Variable Type Inference, introduced in Java 10 with the var keyword, allows you to declare local variables without explicitly specifying their types. The type is inferred by the compiler based on the initializer expression on the right-hand side. It's important to note that this feature is specifically for local variables and cannot be used for fields, method parameters, or return types. • When it comes to inheritance, the use of var doesn't affect the inheritance mechanism itself. Inheritance still works as it does with explicitly typed variables. The type of the variable is determined at compile-time based on the actual type of the assigned object.
  • 64. The Object Class •the Object class is at the top of the class hierarchy. Every class in Java is a direct or indirect subclass of the Object class. This makes Object a fundamental part of Java's inheritance mechanism. •The Object class is defined in the java.lang package, and it includes methods that are common to all Java objects
  • 65. Some of the key methods in the Object class include: • toString(): This method returns a string representation of the object. It is often overridden in subcla provide a meaningful string representation. • equals(Object obj): This method is used to compare the equality of two objects. Subclasses often o method to provide their own definition of equality. • hashCode(): This method returns a hash code for the object. It is used in conjunction with the equa when objects are stored in hash-based collections. • getClass(): This method returns the runtime class of an object. It is commonly used to determine th object at runtime. • clone(): This method creates and returns a copy of the object. For the clone method to work correct must implement the Cloneable interface. • notify(), notifyAll(), and wait(): These methods are used for inter-thread communication and sync
  • 66. Dynamic Method Dispatch Dynamic Method Dispatch that allows a program to determine at runtime which method implementation to invoke, based on the actual type of the object rather than the declared type. This is also known as late binding or runtime polymorphism.
  • 67. Significance of Inheritance in java •Code Reusability •Method Overriding •Polymorphism •Code Organization •Base for Interfaces •Encapsulation
  • 68. •Interfaces: Interfaces, Default Interface Methods, Use static Methods in an Interface, Private Interface Methods
  • 70. Defination An interface is a syntactical contract that outlines a set of methods that a class must implement. It defines a blueprint for a class, specifying a set of methods without providing any implementation details. An interface declares a collection of abstract methods that any class implementing the interface must define
  • 71. Syntax interface Interface_name { variable declaration; method declaration; } static final datatype variable_name; abstract return-type method_name(parameter);
  • 72. class A inetrface A extends implements class B class B inetrface C extends interface D class A inetrface B class C extends A implemnts B
  • 73. Significance of Interface • Abstraction • Multiple Inheritance • Polymorphism • Encapsulation • API Design • Code Reusability • Dependency Injection • Frameworks and Libraries • Java Standard Libraries • Runnable • Iterable
  • 74. Default Interface Methods •Default Interface Methods are a feature introduced in Java 8 to allow the addition of new methods to interfaces in a backward-compatible manner. •With Default Interface Methods, you can provide a default implementation for a method directly in the interface itself.
  • 75. Use static Methods in an Interface •Starting from version 8, interfaces can have static methods. These static methods are associated with the interface itself, not with any instance of the interface.
  • 76. Private Interface Methods Private interface methods are a feature introduced in Java 9 that allows interfaces to have private methods. Prior to Java 9, interfaces could only have abstract methods (methods without a body) and constants. The introduction of private interface methods was aimed at providing a way to share common code among default or static methods within an interface without exposing these methods to the outside world
  • 77. module 4 •Packages: Packages, Packages and Member Access, Importing Packages. •Exceptions: Exception-Handling Fundamentals, Exception Types, Uncaught Exceptions, Using try and catch, Multiple catch Clauses, Nested try Statements, throw, throws, finally, Java’s Built-in Exceptions, Creating Your Own Exception Subclasses, Chained Exceptions.
  • 78. Packages • Def: Packages are used to organize and group related classes and interfaces. This helps in avoiding naming conflicts and makes the code more maintainable. • Def: Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. Ex: package package_name; • Subpackages: Packages that are inside another package are the subpackages. These are not imported by default, they have to imported explicitly. Also, members of a subpackage have no access privileges, i.e., they are considered as different package for protected and default access specifiers. Ex: import java.util.*;
  • 79. •Preventing naming conflicts. For example there can be two classes with name Employee in two packages, college.staff.cse.Employee and college.staff.ee.Employee •Making searching/locating and usage of classes, interfaces, enumerations and annotations easier. • Providing controlled access: protected and default have package level access control. A protected member is accessible by classes in the same package and its subclasses. A default member (without any access specifier) is accessible by classes in the same package only. •Packages can be considered as data encapsulation (or data-hiding).
  • 80. Member Access(Access Modifiers) • Private: Accessible only within the same class. • Default (no modifier): Accessible within the same package. • Protected: Accessible within the same package and by subclasses. • Public: Accessible from anywhere.
  • 82. Advantages of Packages •Organizational Structure •Encapsulation •Access Control •Namespace Management •Versioning and Maintenance •Code Reusability •Readability and Understanding •Security •Import Statements •Distribution and Deployment
  • 83. Exception Def: Exception is an unwanted or unexpected or abnormal event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions. Exception handling: In exception handling, we should have alternate source through which we can handle the exception.
  • 84. Advantage of Exception Handling: The core advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the normal flow of the application that is why we use exception handling
  • 85. Exception-Handling Fundamentals 1.Try-Catch Blocks: • The try block contains the code that might throw an exception. • The catch block contains the code to handle the exception if it occurs. 2. Multiple Catch Blocks: • You can have multiple catch blocks to handle different types of exceptions. • The catch blocks are checked in order, and the first one that matches the exception type is executed. 3. Finally Block: • The finally block contains code that will be executed whether an exception occurs or not. • It is often used for cleanup tasks, such as closing resources like files or database connections. 4. Throw Statement: • The throw statement is used to explicitly throw an exception from a method or block of code.
  • 86. Exception types 1. Built-in Exceptions 1. Checked Exception 2. Unchecked Exception 2. User-Defined Exceptions
  • 87. Difference between checked and unchecked exceptions : 1) Checked Exception: The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time. 2) Unchecked Exception: The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime. 3) Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
  • 88. Uncaught Exceptions in Java 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. 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.
  • 89. Using try and catch •The try statement allows you to define a block of code to be tested for errors while it is being executed. •The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. •The try and catch keywords come in pairs
  • 90. Multiple catch Clauses •A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block. Points to remember • At a time only one exception occurs and at a time only one catch block is executed. • All catch blocks must be ordered from most specific to most general, i.e. catch for •ArithmeticException must come before catch for Exception
  • 92. Nested try Statements •In Java, using a try block inside another try block is permitted. It is called as nested try block.Every statement that we enter a statement in try block, context of that exception is pushed onto the stack. •For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while the outer try block can handle the ArithemeticException (division by zero).
  • 93. Why use nested try block •Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested Syntax: .... //main try block try { statement 1; statement 2; //try catch block within another try block try { statement 3; statement 4; //try catch block within nested try block try { statement 5; statement 6; } catch(Exception e2) { //exception message } catch(Exception e1) { //exception message } //catch block of parent (outer) try block catch(Exception e3) { //exception message } ....
  • 94. throw, throws, finally •The throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub classes can be thrown. Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception. •The throws keyword is used to declare the list of exception that a method may throw during execution of program. Any method that is capable of causing exceptions must list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about which exceptions are to be handled. •A finally keyword is used to create a block of code that follows a try block. A finally block of code is always executed whether an exception has occurred or not. Using a finally block, it lets you run any cleanup type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of catch block.
  • 95. throw throws throw keyword is used to throw an exception explicitly. throws keyword is used to declare an exception possible during its execution. throw keyword is followed by an instance of Throwable class or one of its sub-classes. throws keyword is followed by one or more Exception class names separated by commas. throw keyword is declared inside a method body. throws keyword is used with method signature (method declaration). We cannot throw multiple exceptions using throw keyword. We can declare multiple exceptions (separated by commas) using throws keyword.
  • 96. Java’s Built-in Exceptions •Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in exceptions in Java.
  • 97. Exception Meaning ArithmeticException Arithmetic error, such as divide-by-zero. ArrayIndexOutOfBoundsException Array index is out-of-bounds. IllegalArgumentException Illegal argument used to invoke a method. IndexOutOfBoundsException Some type of index is out-of-bounds. NullPointerException Invalid use of a null reference. SecurityException Attempt to violate security. StringIndexOutOfBounds Attempt to index outside the bounds of a string. NoSuchFieldException A requested field does not exist. NoSuchMethodException A requested method does not exist. UnsupportedOperationException An unsupported operation was encountered. ClassCastException Invalid cast.
  • 98. Creating Your Own Exception Subclasses •Java’s exception handling mechanism is not limited to these errors. In fact, part of the power of Java’s approach to exceptions is its ability to handle exceptions that you create which correspond to errors in your own code. Creating an exception is easy. Just define a subclass of Exception (which is, of course, a subclass of Throwable). Your subclasses don’t need to actually implement anything—it is their existence in the type system that allows you to use them as exceptions. •The Exception class does not define any methods of its own. It does, of course, inherit those methods provided by Throwable
  • 99. Chained Exceptions Chained Exceptions allows to relate one exception with another exception, i.e one exception describes cause of another exception. Constructors Of Throwable class Which support chained exceptions in java : Throwable(Throwable cause) :- Where cause is the exception that causes the current exception. Throwable(String msg, Throwable cause) :- Where msg is the exception message and cause is the exception that causes the current exception. Methods Of Throwable class Which support chained exceptions in java : getCause() method :- This method returns actual cause of an exception. initCause(Throwable cause) method :- This method sets the cause for the calling exception.
  • 100. Module 5-Syllubus • Multithreaded Programming: The Java Thread Model, The Main Thread, Creating a Thread, Creating Multiple Threads, Using isAlive() and join(), Thread Priorities, Synchronization, Interthread Communication, Suspending, Resuming, and Stopping Threads, Obtaining a Thread’s State. • Enumerations, Type Wrappers and Autoboxing: Enumerations (Enumeration Fundamentals, The values() and valueOf() Methods), Type Wrappers (Character, Boolean, The Numeric Type Wrappers), Autoboxing (Autoboxing and Methods, Autoboxing/Unboxing Occurs in Expressions, Autoboxing/Unboxing Boolean and Character Values).
  • 101. Multitasking operating system A multitasking operating system is an operating system that gives you the perception of 2 or more tasks/jobs/processes running simultaneously. It does this by dividing system resources amongst these tasks/jobs/processes and switching between the tasks/jobs/processes while they are executing over and over again. Multitasking Programming is of Two Types: 1. Process-based Multitasking 2. Thread-based Multitasking
  • 102. The Java Thread Model Java programming language allows us to create a program that contains one or more parts that can run simultaneously at the same time. This type of program is known as a multithreading program. Each part of this program is called a thread. Every thread defines a separate path of execution in java Def: A thread is a light wieght process or Def:A thread is a subpart of a process that can run individually.
  • 103. Thread Life Cycle - a thread goes through different states throughout its execution. These stages are called thread life cycle states or phases.
  • 104. New When a thread object is created using new, then the thread is said to be in the New state. This state is also known as Born state. Thread t1 = new Thread(); Runnable / Ready When a thread calls start( ) method, then the thread is said to be in the Runnable state. This state is also known as a Ready state. t1.start(); Running When a thread calls run( ) method, then the thread is said to be Running. The run( ) method of a thread called automatically by the start( ) method. Dead / Terminated A thread in the Running state may move into the dead state due to either its execution completed or the stop( ) method called. The dead state is also known as the terminated state.
  • 105. Blocked / Waiting A thread in the Running state may move into the blocked state due to various reasons like sleep( ) method called, wait( ) method called, suspend( ) method called, and join( ) method called, etc. When a thread is in the blocked or waiting state, it may move to Runnable state due to reasons like sleep time completed, waiting time completed, notify( ) or notifyAll( ) method called, resume( ) method called, etc. Example • Thread.sleep(1000); • wait(1000); • wait(); • suspened(); • notify(); • notifyAll(); • resume();
  • 106. How to create / define a Thread 1. By extending Thread Class Syntax: public class Class_Name extends Thread{ // Statements } 2. By Implementing Runnable Interface Syntax: public class Class_Name implements Runnable { //Statements }
  • 107. The Main Thread It is the thread from which other “child” threads will be spawned. It must be the last thread to finish execution because it performs various shutdown actions It's important to note that the main thread is just like any other thread in Java, but it's special because it's the one that starts the program's execution. You can manipulate the main thread like any other thread in Java, for example, you can set its name, priority, or manage its lifecycle using methods provided by the Thread class or by using higher-level concurrency utilities provided by the java.util.concurrent package.
  • 108. Using isAlive() and join() •Sometimes one thread needs to know when other thread is terminating. In java, isAlive() and join() are two different methods that are used to check whether a thread has finished its execution or not. •The isAlive() method returns true if the thread upon which it is called is still running otherwise it returns false. •Using join() method, we tell our thread to wait until the specified thread completes its execution.
  • 109. Thread Priorities In multithreading environment in which thread scheduler assigns the processor to a thread based on the priority of thread. Whenever we create a thread in Java, it always has some priority assigned to it. Priority can either be given by JVM while creating the thread or it can be given by the programmer explicitly. Priorities in threads is a concept where each thread is having a priority which in layman’s language one can say every object is having priority here which is represented by numbers ranging from 1 to 10.
  • 110. • The default priority is set to 5 as excepted. • Minimum priority is set to 1. • Maximum priority is set to 10. Here 3 constants are defined in it namely as follows: 1. public static int NORM_PRIORITY 2. public static int MIN_PRIORITY 3. public static int MAX_PRIORITY
  • 111. Synchronization Java Synchronization is used to make sure by some synchronization method that only one thread can access the resource at a given point in time. 1.Synchronized Methods: You can declare methods as synchronized to ensure that only one thread can execute them at a time. When a thread enters a synchronized method, it acquires the intrinsic lock (also known as monitor lock) associated with the object on which the method is declared. Other threads attempting to execute synchronized methods on the same object will be blocked until the owning thread releases the lock. public synchronized void synchronizedMethod() { // Synchronized method body }
  • 112. 2. Synchronized Blocks: In addition to synchronizing entire methods, you can also synchronize specific blocks of code. This is useful when only a portion of a method needs to be synchronized. To do this, you specify the object that will be used as the lock. public void someMethod() { synchronized (lockObject) { // Synchronized block of code } }
  • 113. Interthread Communication Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other. Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed • wait() • notify() • notifyAll()
  • 114. •wait- Object wait methods has three variance, one which waits indefinitely for any other thread to call notify or notifyAll method on the object to wake up the current thread. Other two variances puts the current thread in wait for specific amount of time before they wake up. •notify -notify method wakes up only one thread waiting on the object and that thread starts execution. So if there are multiple threads waiting for an object, this method will wake up only one of them •notifyall- notifyAll method wakes up all the threads waiting on the object, although which one will process first depends on the OS implementation.
  • 115. Suspending, Resuming, and Stopping Threads, •sleep()- thread will be blocked for a specified time •suspend() - blocked untill further orders •wait()- blocked untill certain condition occurs •resume()- resumes the suspended thread •notify()- notify to thread which is in waiting state •stop()- kills/terminate the thread
  • 116. Obtaining a Thread’s State. The getState() method of the Thread class is an instance method that returns the state of the thread object on which this method is invoked.
  • 117. Enumerations Fundamentals enumeration is a special kind of class that includes a list of constant values. The values in the enumeration list define the values an object can have Creating Enumerations: When creating an enumeration list, we don't use the keyword class and when you create a enumeration object, we don't use the keyword new To create an enumeration list we need to import java.util.Enumeration An enumeration is created using the enum keyword followed by the variable Name we want associated with the list
  • 118. Syntax Example public enum variable_name{ ITEM1,ITEM2,ITEM3 } Creating an enumeration object Syntax: variableName object; example: Gender gen Assigning default values: public enum Gender { MALE(1), FEMALE(2), UNKNOWN(0) } public enum GENDER{ MAKE,FEMALE,UNKNOWN } Assigning values to the enumeration object Syntax:object = variableName.ITEM; example: Gender gen=Gender.MALE;
  • 119. The values() and valueOf() Methods 1.Values(): • Method returns an array that contains a list of the enumeration constants • values() returns the values in the enumeration and stores them in an array. We can process the array with a foreach loop. Syntex: public static enum-type[ ] values( ) Example: Values value[] = Values.values(); for (Values a : value) statement; 2.ValueOf(): • method returns the enumeration constant whose value corresponds to the string passed in str. • method takes a single parameter of the constant name to retrieve and returns the constant from the enumeration, if it exists. Syntax: enumerationVariable = enumerationName.valueOf("EnumerationValueInL ist"); Example WeekDays wd = WeekDays.valueOf("MONDAY");
  • 120. Type Wrappers(Character, Boolean, The Numeric Type Wrappers) • Java uses primitive types (also called simple types), such as int or double, to • hold the basic data types supported by the language. • Instead of primitive types if objects are used everywhere for even simple • calculations then performance overhead is the problem. • So to avoid this java had used primitive types. • So primitive types do not inherit Object class • But there are times when you will need an object representation for • primitives like int and char. • Example, you can’t pass a primitive type by reference to a method. • Many of the standard data structures implemented by Java operate on objects, • which mean that you can’t use these data structures to store primitive types. • To handle these (and other) situations, Java provides type wrappers, which • are classes that encapsulate a primitive type within an object.
  • 121. • Character is a wrapper around a char. •The constructor for Character is Character(char ch) here ch is a character •variable whose values will be wrapped to character object by the wrapper class • To obtain the char value contained in a Character object, call charValue( ), shown •here: •char charValue( ) •It returns the encapsulated character. • Boolean is a wrapper around boolean values. It defines these constructors: • Boolean(boolean boolValue) • Boolean(String boolString) • In the first version, boolValue must be either true or false. In the second version, if • boolString contains the string "true" (in uppercase or lowercase), then the new Boolean • object will be true. Otherwise, it will be false. • To obtain a boolean value from a Boolean object, use booleanValue( ), shown here: • boolean booleanValue( ) • It returns the boolean equivalent of the invoking object.
  • 122. The Numeric Type Wrappers The most commonly used type wrappers are those that represent numeric values. These are Byte, Short, Integer, Long, Float, and Double. All of the numeric type wrappers inherit the abstract class Number. Number declares methods that return the value of an object in each of the different number formats. These methods are shown here: 1. byte byteValue( ) 2. double doubleValue( ) 3. float floatValue( ) 4. int intValue( ) 5. long longValue( ) 6. short shortValue( )
  • 123. Autoboxing • Autoboxing is the process by which a primitive type is automatically encapsulated • (boxed) into its equivalent type wrapper whenever an object of that type is needed. • There is no need to explicitly construct an object. • For example, converting int to Integer class. The Java compiler applies autoboxing • when a primitive value is: • Passed as a parameter to a method that expects an object of the corresponding • wrapper class. • Assigned to a variable of the corresponding wrapper class • Auto-unboxing is the process by which the value of a boxed object is automatically • extracted(unboxed) from a type wrapper when its value is needed. There is no need • to call a method such as intValue( ) or doubleValue( ). • For example conversion of Integer to int. The Java compiler applies unboxing when an • object of a wrapper class is: • Passed as a parameter to a method that expects a value of the corresponding • primitive type. • Assigned to a variable of the corresponding primitive type.
  • 124. Autoboxing and Methods: •autoboxing/unboxing might occur when an argument is passed to a method, or when a value is returned by a method. •autoboxing automatically occurs whenever a primitive type must be converted into an object.autounboxing takes place whenever an object must be converted into a primitive typ
  • 125. Autoboxing/Unboxing Occurs in Expressions •autoboxing and unboxing take place whenever a conversion into an object or from an object is required. •This applies to expressions. Within an expression, a numeric object is automatically unboxed. •The outcome of the expression is reboxed, if necessary
  • 126. Autoboxing/Unboxing Boolean and Character Values •Java also supplies wrappers for boolean and char. These are Boolean and Character. •Autoboxing/unboxing applies to these wrappers, too •Character ch = 'x'; // box a char • char ch2 = ch; // unbox a char • Boolean b = true; here the value true is boxed in b •if(b) System.out.println("b is true"); // here b is unboxed