0% found this document useful (0 votes)
6 views

Javaenture Workshop Finaldraft.pptx

The document provides an introduction to Java, highlighting its key features such as platform independence, object-oriented design, and dynamic capabilities. It discusses the Java Development Kit (JDK) and Java Runtime Environment (JRE), along with the latest updates in JDK 21, including virtual threads and string templates. Additionally, it covers Java's memory management, string handling, control flow constructs, and basic string operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Javaenture Workshop Finaldraft.pptx

The document provides an introduction to Java, highlighting its key features such as platform independence, object-oriented design, and dynamic capabilities. It discusses the Java Development Kit (JDK) and Java Runtime Environment (JRE), along with the latest updates in JDK 21, including virtual threads and string templates. Additionally, it covers Java's memory management, string handling, control flow constructs, and basic string operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 181

Introduction to Java

JAVA in a general purpose, object oriented, platform independent and


portable multithreaded and interactive, dynamic and extensible
programming language develop by sun micro system of USA
JAVA vs C
WHY JAVA ???
1. Platform independent
Java code is written once and can run anywhere.
2. Object-Oriented
Java is treated as an object, making it easy to manage and extend.
3. Dynamic
Java loads classes dynamically at runtime, making it highly flexible.
4. Portable
Java applications are portable because they do not rely on platform-
specific
Java Development
JDK includes a large no. of development tools. The development tools are
part of system known as JDK. It comes with a collection of tools that are
used for developing and running JAVA programs. It includes :-
a. javac (java compiler)
b. java (java interpreter)
c. java p(java disassembles)
d. java h(for c headerfile)
e. jdb (java debugger)
f. applet viewer
g. javadoc (for creating HTML sequence)
Java Development Kit
The JDK is regularly updated by Oracle and other organisations like OpenJDK. Each
version introduces new features, performance improvements, and security updates.
For example:

J⁠ DK 8 : It Introduced lambda expressions and the Stream API.


JDK 11 : A long-term support (LTS) release with new features like the ⁠var ,
keyword for local variables.
JDK 17 : The latest LTS release as of 2023, with features like sealed classes and
pattern matching.
Latest Version
Oracle published JDK 21 on September 19, 2023, making it the latest version of the
JDK as of October 2023.It will receive updates and support for a long time (usually
several years) because this is the most recent
Long-Term Support (LTS).
Essential Elements of JDK 21: A number of improvements
and new features are included in JDK 21, including:
1. ⁠Virtual Threads (Final): As a component of Project Loom,
virtual threads make it simpler to create, manage, and
scale high-throughput applications, thus simplifying
concurrent programming.
2.⁠⁠String Templates (Preview): Makes formatting and variable interpolation easier.
Java Runtime
The Java Runtime Environment, or JRE, is a software layer that runs on
top of a computer’s operating system software.it includes the Java
Virtual Machine (JVM), runtime class libraries, and a Java application
launcher.
JDK vs JRE:
• JDK : Used for developing Java applications. It includes the JRE and
development tools.
• JRE : Used for running Java applications. It includes the JVM and
libraries but lacks
development tools.
JRE vs JDK
JDK vs JRE:
• JDK : It is used for developing Java applications. It includes the
JRE and development tools.
• JRE : It is used for running Java applications. It includes the JVM and libraries
but lacks development tools.
Java Virtual
The JAVA compiler produces an
intermediate code known as byte code for
a machine that does not exist. This machine
is called the JVM and it exists only inside
computer memory. It is simulated
computer within the computer and does all
major function of a real computer.
Why JVM?
1. Platform Independent : JVM makes java “Write Once ,Run Anywhere”.
Ex : The same Java program can run on windows, MAC,
Linux, etc. no matter Where it is written.
2. Memory Management : JVM handles memory and Garbage collection automatically
i.e. it removes unwanted data on it’s on.
3. Security : JVM provides a secure environment to run Java code.
JVM
1. When a class file is executed, JVM loads all required classes automatically from the local
disk or network. This is the function of class loader utility of JVM.
2. After loading the required classes, JVM verifies to make sure that the classes do not
violate any of the basic rule of the JAVA language, this is the function of Byte code
Verifier.
3. JVM keeps track of memory usage, it performs memory allocation and release. This
process which manages de-reference object is called garbage collection.
What is Java Tokens?
The smallest unit of code that can access java compiler for translation that is
smallest individual units in program is called java token. Following types of token
are used
a. Reserve word (int, char, float etc)
b. Identifiers (name, roll etc)
c. Literals (integer literal, floating, character, string, boolean)
d. operators
e. separetors
Operators in Java
In Java, operators are special symbols or keywords used to
perform operations on variables and values.
Types of Operators in Java :-
1. Arithmetic Operators : Use for basic math operations.
Ex : + ; - ; * ; / ; %
2. Relational (Comparison) Operators : Use to compare.
Ex : == ; != ; > ; < ; <= ;>=
3. Logical Operators : Use to combine multiple condition.
Ex : && ; ! ;
4. Bitwise Operators : Use to operate on Bits and perform bit-by-bit operation
Ex : & ; ^ ; ~ ; `(Bitwise or)
Operators in Java
4. Assignment Operators : Use to assign values.

Ex : = ; += ; -= ; *= ; /= ; %=

5. Unary Operators : Use to work on single operand.

Ex : + ; - ; ++ ; - -
Operators in Java
JAVA C
Malloc, calloc, realloc, and free are
⁠Java Memory Management: Automatic
examples of functions used in manual
garbage collection memory management. No
memory management. Memory allocation
manual deallocation or allocation of memory
and deallocation must be done directly by
(e.g., no free or malloc).
developers.

Enables pointer arithmetic, which includes


⁠ rithmetic Functions: Java string type
A
incrementing and decrementing pointers.
verification. For instance, dividing two
Inadequate type checking can result in
numbers always yields a shortened result,
unexpected behavior (e.g., splitting integers
which is also an integer. Pointer arithmetic is
can result in unexpected values if handled
not supported.
carelessly).
KEYWORD
Java reserves words with specific meanings that are predefined by the language
as keywords. Since these terms are a part of the Java grammar and are used to
specify the structure and behavior of programs, they cannot be used as identifiers
(e.g., variable names, class names, or method names).
Characteristics of Java Keywords:

Reserved: Keywords cannot be used for any other purpose


(e.g., as variable names).

Case-Sensitive: All keywords are in lowercase (e.g., int, class, public).


List of Java Keywords:

1.Data Types : byte, short, int, long, float, double, char, boolean.

2. Flow Control : if, else, switch, case, default, while, do, for, break, continue, return.

3. Class and Object Management : class, new, this, super, instanceof.


What Is this keyword ?
“this” is a special object reference, which is also a keyword.

“this” is automatically created by Java in a method’s argument, as


soon we call that method.

“this” stores the memory address of the CURRENT OBJECT (the object
on which the method has been called)
Benefits Of Using “this”. . . .

By using “this” we can resolve the overlapping of instance variable


of a class done by the local variables of a method with the same
name.

By using “this” we can perform CONSTRUCTOR CHAINING


Variables
Variables are the containers for storing the data values or you can also
call it a memory location name for the data. Every variable has a:

1. Data Type – The kind of data that it can hold. For example, int,
string, float, char, etc.
2. Variable Name – To identify the variable uniquely within the scope.
3. Value – The data assigned to the variable.
Literals
Any constant value which can be assigned to the variable is called literal/constant.

In simple words, Literals in Java is a synthetic representation of boolean, numeric,


character, or string data. It is a medium of expressing particular values in the
program, such as an integer variable named ‘’/count is assigned an integer value in
the following statement.
FLOW
CONTROL
If-Else
The if-else statement in Java is a fundamental control flow construct that
allows you to execute certain blocks of code based on specified conditions.
It is used to make decisions in your program, enabling different actions
based on different inputs or states.
Loops
Loops can execute a block of code as long as a specified condition is reached.
There are four types of loop
a. while loop
b. for loop
c. do while loop
d. For each loop
While loop
The while loop loops through a block of code as long as a
specified condition is true:
Syntax:
while (condition) {
// code block to be executed}
While loop
Do-While Loop
The do/while loop is a variant of the while loop. This loop will
execute the code block once, before checking if the condition
is true, then it will repeat the loop as long as the condition is
true.
Syntax:
do { // code block to be executed}
while (condition);
Do-While Loop
For Loop
Java for loop is a control flow statement that allows code to be
executed repeatedly based on a given condition. The for loop
in Java provides an efficient way to iterate over a range of
values, execute code multiple times, or traverse arrays and
collections
Syntax:
for (statement 1; statement 2; statement 3)
{// code block to be executed}
For Loop
For-Each Loop
loop which is used exclusively to loop through elements in an array (or other
data sets).it is a way to iterate over elements in an array or a collection ,It
simplifies the process of traversing elements without needing to use an
index or an iterator explicitly

Syntax:
for (type variableName : arrayName)
{ // code block to be executed}
For each Loop
Strings
1. Strings in Java represent a sequence of characters.
2. They are objects of the String class.
3. Java provides various methods to manipulate strings.
4. Strings are immutable (cannot be changed after creation).
5. Why Are Strings Immutable?
Once created, a String object cannot be modified.
Any modification creates a new String object.
Ensures security and thread-safety.
Efficient memory usage through the String Pool.
Memory Allocation of Strings
1. . In Java, strings are stored in the memory as objects of the class String.
2. When memory is allocated for any Java program, JVM (Java virtual machine)
divides allocated memory into two parts. One part is Stack and the other part is
Heap. In Heap memory, java allocates some memory, especially for literals that
memory is called the String constant pool(SCP). SCP is the predefined area inside
the Heap. String pool helps in saving a lot of space for Java Runtime. String class
uses SCP to store unique string literals.
Memory Allocation of Strings
1. In Stack memory, variables or variable references or references to the objects are
stored.
2. In Heap memory, all the objects that are dynamically allocated are stored. To
allocate memory to an object we use a new keyword.
There are two ways of creating string objects.
1. String literal
String s5 = “java”;
Whenever we create a string literal, JVM first checks if the string literal already
exists in the string constant pool. If not available, it will create a new string literal in
SCP. In the given picture, str1 points to “java” in SCP.
Memory Allocation of Strings
2. By using a new keyword
String s4= new String(“java”);
//Instantiating the string class using a new keyword

When a string object is created using a new keyword, it will create two objects. One
in SCP another in Heap and the reference variable is stored in the stack.
Memory Allocation of Strings
We have already created the literal “java” by using
String s5 = “java”;

As we cannot have duplicates in SCP, So JVM will not create one more object in SCP
but will return the existing reference to the variable str3 in the stack and it will create
one object in Heap. Str3 will point to the object “java” in the Heap but not in SCP.
Memory Allocation of Strings
Following are the different cases of how memory is allocated for string objects.
Case 1: How the string objects defined above are stored in memory.
public class stringsStorageConcept{
public static void main(String[] args){
String str1 = “MyString”;
String str2 = new String(“MyString”);
System.out.println(str1 == str2); //Output:False
System.out.println(str1.equals(str2)); //Output:True
}
}
Memory Allocation of Strings
When we compare str1 and str2 using the “==” operator it returns false. As we know
“==” operator compares their physical addresses. Here in our example str1 is pointing to
the object in SCP and str2 is pointing to the object in the Heap. So it returns false.
But in the case of str1.equals(str2), as we know “equals” function checks the individual
characters both str1 and str3 have the same value stored it returns true.
Memory Allocation of Strings
Case 2: Another string literal
String str3 = “MyString”;
Both str1 and str3 will point to the same string literal in SCP.
public class stringsStorageConcept{
public static void main(String[] args){
String str1 = “MyString”;
String str3 = “MyString”;
System.out.println(str1 == str2); //Output:True
System.out.println(str1.equals(str2)); //Output:True
}
}
Memory Allocation of Strings

s1 == s3 returns true, as “==” operator compares their physical addresses but not the
content.
s1.equals(s3) returns true, and the “equals“ function checks the individual characters in
both reference variables.
Memory Allocation of Strings
Case 3: Another string object is created using a new keyword

String str4 = new String(“NewString”);

In this case, JVM will check for this string in SCP it cannot find the string object with
the value “NewString”, so it will create two objects one in SCP and another in Heap,
the reference variable str4 will be stored in the stack. Str4 will have the reference to
the object in the Heap.
Memory Allocation of Strings
Case 4: Another string literal is created.

String str5 = “NewString”;

In this case, JVM will check in SCP if this literal is already available or not, here
“NewString” is already present in SCP so JVM will not create a duplicate in SCP
instead it returns the reference to the variable str5.
Memory Allocation of Strings
Case 5: Assigning one string to another string

String str4 = new String(“NewString”);


String str6 = str4; //Assigning

Here str6 and str4 will point to the same object in Heap and will not erase the value in str4.
Memory Allocation of Strings
public class stringsStorageConcept{
public static void main(String[] args){
String str4 = new String(“NewString”);
String str6 = str4;
System.out.println(str4 == str6); //Output:true
}
}
JVM will give the reference of the “NewString” in the heap to the variable str6. That’s the
reason str4 == str6 returns true.
Memory Allocation of Strings
In conclusion, creating string objects using string literal and by ‘new’ operator has
its pros and cons.
By using string literals, we can make memory more efficient by not creating
duplicates. JVM creates one unique object and the string stays in the SCP
forever. The downside of this is that the string pool has a fixed size and it will get
full at some time.
But by using a new keyword it creates two objects, one in SCP and the other in
Heap. In a Heap, if we don’t need the object it will be erased by a garbage
collector to make space. But the downside of this is that with a ‘new’ operator
JVM will always have to create a new object and it is an overload for JVM
Java Program to demonstrate String:-
Result
Addressing of Strings in Java
Basic String Operations
1. Concatenation:

2. Length of a String: int length =


result.length();
3.Accessing Characters: char ch =
Basic String Operations
4. Extracting a substring:

5. Converting to uppercase and lowercase:


Basic String Operations
6. replace(old, new) - The replace() method searches a string for a
specified character, and returns a new string where the specified character(s)
are replaced.
7.trim() - Removes leading and trailing spaces
Comparing Strings
String str1 = "Hello";
String str2 = "hello";

1. Using equals():
System.out.println(str1.equals(str2)); // false

2. Case-insensitive comparison:
System.out.println(str1.equalsIgnoreCase(str2)); // true
Comparing Strings
String str1 = "Hello";
String str2 = "hello";

3. Using compareTo():
System.out.println(str1.compareTo("Apple")); // Positive value
System.out.println(str1.compareTo("Hello")); // 0 (Equal)
System.out.println(str1.compareTo("Zebra")); // Negative value
4. Using '==' (Not Recommended): String str3 = new
String("Hello"); System.out.println(str1 == str3); // false
(different references)
Searching in Strings
Using String phrase = "Java programming is awesome";

1. Checking if it starts or ends with a specific string:


System.out.println(phrase.startsWith("Java")); // true
System.out.println(phrase.endsWith("some")); // true

2. Finding index of a substring:


System.out.println(phrase.indexOf("pro")); // 5
System.out.println(phrase.lastIndexOf("a")); // 22
3. contains(substring) - Checks if a string contains a substring
System.out.println(phrase.contains("pro")); // true
Mutable Strings: StringBuffer &
StringBuilder
1. StringBuffer is a class in Java that represents a mutable sequence of
characters. It provides an alternative to the immutable String class, allowing
you to modify the contents of a string without creating a new object every
time.
//Using StringBuffer:-
Performance Considerations
// Inefficient way (creates multiple objects)

// Efficient way using StringBuilder


Java Collection Framework
1. The Java Collection Framework (JCF) provides a set of classes and
interfaces for storing and manipulating groups of data.
2. It includes lists, sets, maps, and queues.
3. Provides reusable data structures and algorithms.
4. Advantages of Collection Framework:-
Consistent API: Unified interface for different collections.
Reduces programming effort: Predefined implementations save
time.
Increases performance: Optimized data structures.
Encourages code reusability.
List Interface
1. Ordered collection that allows duplicate elements.
2. Implemented by ArrayList, LinkedList, and Vector.
3. Elements can be accessed using an index.
4. Example:
Set Interface
1. Unordered collection that does not allow duplicates.
2. Implemented by HashSet, LinkedHashSet, TreeSet.
3. Used when unique elements are required.
// Example of HashMap
Queue Interface
1. Used for processing elements in FIFO (First In, First Out)
order.
2. Implemented by LinkedList, PriorityQueue, ArrayDeque.
3. PriorityQueue orders elements based on priority.
// Example of PriorityQueue
Map Interface
1. Stores key-value pairs, where keys must be unique.
2. Implemented by HashMap, LinkedHashMap, TreeMap.
3. HashMap is unordered, TreeMap is sorted.
// Example of HashMap
Comparison of Collections
1. ArrayList vs. LinkedList: ArrayList is faster for indexing,
LinkedList is better for frequent insertions/deletions.
2. HashSet vs. TreeSet: HashSet is faster, TreeSet maintains
order.
3. PriorityQueue vs. LinkedList Queue: PriorityQueue sorts
elements based on priority.
4. HashMap vs. TreeMap: HashMap is faster, TreeMap sorts
keys.
Choosing the Right Collection
1. Use ArrayList when frequent retrieval is needed.
2. Use LinkedList when frequent insertions/removals occur.
3. Use HashSet when uniqueness is required.
4. Use TreeMap when sorted key storage is needed.
5. Use PriorityQueue for priority-based processing.
Object Oriented Programming
Popular programming approaches

Procedure Oriented Programming

Object Oriented Programming

Functional Programming

Aspect Oriented Programming


Object Oriented Programming
Object-Oriented Programming or Java OOPs concept refers to
programming languages that use objects in programming. They use
objects as a primary source to implement what is to happen in the code.
Objects are seen by the viewer or user, performing tasks you assign.
Concepts Of OOP
Overview of OOP concepts
Classes and Objects
Java Class
A Class is a user-defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are
common to all objects of one type.

Using classes, we can create multiple objects with the same behaviours
instead of writing their code multiple times.
Example

Each person collectively comes


under a class called Human.

So we belong to the class


Human
Java Object

An Object is a basic unit of Object-Oriented Programming that represents real-life entities.

The objects are what perform your code, they are the part of your code visible to the
viewer/user.

Every Object has two main components :- Property and Behaviours


Example
Class vs Object
Each Type of car
collectively comes
under a class called
Car .

Class
Classes Vs. Objects
This keyword
What the hell is “this” ?
In Java, ‘this’ is a reference variable that refers to the current object, or can
be said “this” in Java is a keyword that refers to the current object instance.
It can be used to call current class methods and fields, to pass an instance
of the current class as a parameter, and to differentiate between the local
and instance variables. Using “this” reference can improve code readability
and reduce naming conflicts.
Uses of this keyword
1. Accessing Instance Variables: When you have a method parameter or a
local variable with the same name as an instance variable, you can use
this. to distinguish between them.
2. Calling Constructors: you can use this() within a constructor to call
another constructor in the same class.
3. Returning the Current Object: this can be used to return the current object
from a method, enabling method chaining.
Constructors
What is a Constructor ?
It is a block of codes similar to the method. It is called when an instance of the class is
created. At the time of calling the constructor, memory for the object is allocated in the
memory. It is a special type of method that is used to initialize the object. Every time an
object is created using the new() keyword, at least one constructor is called.

Purpose: Constructors are crucial for setting initial values for object attributes and
ensuring the object is in a valid state from the beginning.

Name: A constructor's name must be the same as the class name.

Return Type: Constructors cannot have a return type, not even void.
Constructors
Types of Constructor
1. Default Constructor
2. Parameterised Constructor
3. Copy Constructor
Default Constructor
A constructor that has no parameters is known as default constructor. A default
constructor is invisible. And if we write a constructor with no arguments, the compiler
does not create a default constructor. It is taken out. It is being overloaded and called a
parameterized constructor. The default constructor changed into the parameterized
constructor. But Parameterized constructor can’t change the default constructor. The
default constructor can be implicit or explicit.
Parameterised Constructor

A constructor that has parameters


is known as parameterized
constructor. If we want to initialize
fields of the class with our own
values, then use a parameterized
constructor.
Copy Constructor
Unlike other constructors copy constructor is passed with another object which copies
the data available from the passed object to the newly created object.
Example: 1
Write a program that to initialise a pen object and display it’s details

Output:

Pen Details:
Color: Blue
Type: Gel
Price: $2.5
Example: 1
Write a program that to initialise a Car object and display it’s details

Output:

Car Details:
Make: Toyota
Model: Camry
Year: 2022
Important Concepts of OOP
Overview
Encapsulation
What is Encapsulation ?
Encapsulation is the process of binding or wrapping the data and the
codes that operates on the data into a single entity

Another way to think about encapsulation is, that it is a protective shield


that prevents the data from being accessed by the code outside this
shield.
Rules of Encapsulation

1. Data :- Data members must be kept private.


2. Methods :- Methods only can access these
data members and these methods can be made
public.
Real world example of Encapsulation
Suppose you have an account in the bank. Is it possible for anyone obtain
your account details like your account balance, transactions done etc.?
Obviously No.

This means that your bank details are private, so that anyone cannot see
your account details.

Only you will have access to your account details and that too using
method defined inside that class and this method will ask your account id
and password for authentication.
How to achieve or implement Encapsulation in Java ?

There are two steps required to achieve or implement encapsulation in Java


program.

Declaring the instance variable of the class as private so that it cannot be


accessed directly by anyone from outside the class.

Provide the public setter and getter methods in the class to set/modify the
values of the variable/fields.
Example:1 Code without Encapsulation
Example:2 Code with Encapsulation
Inheritance
What is Inheritance?
Inheritance is a technique using which we can acquire the features of an existing
class/object in a newly created class/object.

We are achieving inheritance by using extends keyword. Inheritance is also


known as “is-a” relationship.

In JAVA we call the inherited class as sub-class and the class from where it
inherited is called the super-class
Example
Benefits of Inheritance

Reusability: The child class programmer is not


required to rewrite those methods or data again
which have already been designed by the parent
class programmer

Maintainability: Easy to incorporate changes in


the code
Types Of Inheritance
Single
Multilevel
Multiple
Hierarchical
Hybrid
Note: Java does not support multiple
inheritance and thus it also does not support
hybrid inheritance
Single Inheritance:
Multiple Inheritance:
Multiple Inheritance is one of the inheritance in
OOP where one class extends more than one class.
Multilevel Inheritance:
I M ltil l I h it l
Hierarchical Inheritance:
Hybrid Inheritance:
Example
Output
Super keyword
The super keyword in Java is a reference variable that is used to refer to
parent class when we’re working with objects.
Uses of super keyword:
1.super is used to call a superclass constructor.
2. super is used to call a superclass method.
3.super is used to access a superclass field
Example

Output
Specifiers in Java
Specifiers in Java
Access Specifiers:
○ Public: The member is accessible from anywhere in the program.
○ Private: The member is accessible only within the declared class and
cannot be accessed
from outside the class.
○ Protected: The member is accessible within the same package and by
subclasses in
different packages.
○ Default (no modifier): The member is accessible only within the same
package and not from outside the package.
Example:
Final, Static, and Abstract Specifiers:
Final:
■ Used to declare constants.
■ Prevents method overriding in derived classes.
■ Prevents class inheritance if applied to a class
Example:
Static Specifier:
Defines class-level members shared by all objects.
Static methods cannot access non-static members directly.

Example:
Abstract Specifier:
Used to declare abstract classes and methods.
Abstract methods must be implemented by subclasses.

Example:
Usage of Specifiers in Classes and
Methods:
Specifiers play a crucial role in:
Encapsulation: Restricting access to data members.
Code structure and behaviour: Defining constants, shared
members, and enforceable methods.
Security: Preventing unauthorized access and modifications.
Abstraction
What is abstraction ?
Data Abstraction is the property by virtue of which only the essential
details are displayed to the user. The trivial or non-essential units are
not displayed to the user.
Ex: A car is viewed as a car rather than its individual components.

The main purpose of abstraction is to make the interaction with the


application/product simple.
Example

Without Abstraction With Abstraction


Example

Without Abstraction With Abstraction


Example:1 Code without Abstraction
Example:2 Code with Abstraction
Polymorphism
Polymorphism
It refers to the ability of object-oriented programming languages to
differentiate between entities with the same name efficiently. This is
done by Java with the help of the signature and declaration of these
entities. The ability to appear in many forms is called polymorphism.
Types of Polymorphism
Method overriding in java
Types of Polymorphism
Polymorphism in Java is mainly of 2 types as mentioned below:

1. Method Overloading: Also, known as compile-time polymorphism,


is the concept of Polymorphism where more than one method share
the same name with different signature(Parameters) in a class. The
return type of these methods can or cannot be same.

2. Method Overriding: Also, known as run-time polymorphism, is the


concept of Polymorphism where method in the child class has the
same name, return-type and parameters as in parent class. The child
class provides the implementation in the method already written.
Method overloading
Method overriding
Method overloading Vs Overriding
Interface

An interface in Java is like a blueprint that defines


methods but does not provide their
implementation.

Classes that implement an interface must provide


their own implementation of the methods.
What is an Interface ?

An interface is a collection of abstract methods


(methods without a body).

It cannot have concrete (implemented)


methods (except in Java 8+, where default
methods are allowed).

It is used to achieve abstraction and multiple


inheritance in Java.
Example:
Abstract Class
An abstract class in Java is a class that cannot be
instantiated (you cannot create objects of it).

It is used as a base class for other classes,


allowing partial abstraction (some methods can
have implementation, while others are just defined
as rules)
In simple terms

1.An abstract class is a class that is declared with


the abstract keyword.

2. It can have both abstract (unimplemented)


and concrete (implemented) methods.

3. It is used for code reuse while still enforcing


some structure on subclasses.
Example
Why use abstract class ?
1. The Animal class has a common method (sleep()) and
an abstract method (sound()).

2. The subclasses (Dog, Cat) must override sound(),


enforcing consistency.

3. The sleep() method is already implemented, so no


need to repeat it in every subclass.
Abstract Class Interface
A class that can have abstract and
collection of abstract methods
concrete methods.
Can have both abstract and concrete Can have abstract methods (by default),
methods. default and static methods

Can have instance variables Only constants: public static final variables.

Can have constructors. Cannot have constructors.

All methods are public by default (no other


Can use public, protected, or private.
modifiers allowed).
Supports multiple inheritance (a class
Doesn't support multiple inheritance
can implement multiple interfaces).
Used for "can-do" or "has ability"
Used for "is-a" relationship.
relationship.

Can provide common method Cannot provide common implementations


implementations to subclasses. (except default methods in Java 8+).
abstract class Animal {
abstract void makeSound(); interface Flyable { void fly(); }
void eat() { ... } }
Advantage of OOPs over Procedure-Oriented Programming
Language
1. Reusability – Uses classes & objects to avoid
duplication.

2. Organization – Clear structure for easy


maintenance.

3. DRY Principle – Reduces repeated code,


improves efficiency.

4. Faster Development – Modular components


speed up coding.
Java Exception

Exception handling in Java allows developers to manage runtime


errors effectively by using mechanisms like try-catch block, finally
block, throwing Exceptions, Custom Exception handling, etc.
An Exception is an unwanted or unexpected event that occurs during
the execution of a program (i.e., at runtime) and disrupts the normal
flow of the program’s instructions. It occurs when something
unexpected things happen, like accessing an invalid index, dividing by
zero, or trying to open a file that does not exist.

Exception in Java is an error condition that occurs when something


wrong happens during the program execution.
Example
Example:
The below Java program modifies the previous example to handle an ArithmeticException using
try-catch , and finally blocks and keep the program running.
Output
Error: Division by zero is not allowed! Program
continues after handling the exception.
The summary is depicted via visual aid below as follows:
How to Handle Exceptions ?

Exception handling in Java is an effective mechanism for managing


runtime errors to ensure the application’s regular flow is maintained.
Some Common examples of exceptions include ClassNotFoundExcption ,
IOException, SQLException, RemoteException, etc. By handling these
exceptions, Java enables developers to create robust and fault-tolerant
applications.
Java Exception Hierarchy

All exception and error types are subclasses of the class Throwable, which is
the base class of the hierarchy. One branch is headed by Exception. This class
is used for exceptional conditions that user programs should catch.
NullPointerException is an example of such an exception. Another
branch, Error is used by the Java run-time system(JVM) to indicate errors
having to do with the run-time environment itself(JRE). StackoverflowError is
an example of such an error.
The below figure demonstrates the exception hierarchy in
Java:
Types of Java Exceptions
Input and Output in Java
1️⃣ User Input Methods
🔹 Scanner Class (java.util.Scanner)
Used for reading different types of user input (int, double,
string, etc.).
Simple and widely used for console-based programs.
Example:
🔹 BufferedReader & InputStreamReader (java.io)
More efficient than Scanner for large input.
Reads input as a string and requires conversion for numeric
values.
Example:
2️⃣ File Handling in Java
🔹 FileReader & FileWriter (java.io)
FileReader is used for reading files.
FileWriter is used for writing data to files.
Example:
3️⃣ Output Display
🔹 System.out.println()
Used for printing output to the console.
System.out.print() (without ln) prints on the same line
Example:
Arrays in Java
Definition and Importance:
An array in Java is a collection of elements of the same data type,
stored in contiguous memory locations. Arrays allow efficient
data storage and manipulation, making them essential for
handling large datasets, implementing algorithms, and optimizing
performance.
Importance of Arrays:

Provides a structured way to store multiple values.


Allows fast retrieval and manipulation of data.
Reduces code redundancy by eliminating multiple variable
declarations.
Enables implementation of complex algorithms like sorting and
searching.
Types of Arrays
1. Single-Dimensional Arrays
A single-dimensional array is a list of elements of the same type,
accessed using a single index.
Example:
2. Multi-Dimensional Arrays
A multi-dimensional array is an array of arrays. The most
common type is a 2D array, which is useful for representing
matrices.
2D Arrays
Jagged Arrays
A jagged array is an array where sub-arrays have different
Declaring, Initialising, and Accessing Arrays
Declaration of Arrays
Initialisation of Arrays
Using new Keyword

Using Curly Braces ({})

Using a Loop to Assign Values


Accessing Elements in an Array
A single-dimensional array is a list of elements stored in a
continuous memory location. Elements in the array can be
accessed using their index.
Arrays use zero-based indexing, meaning the first element is at
index 0:
Modifying Array & determining array length
You can update the value of any element by referencing its index:

To find out how many elements an array contains, use the .length property:
Looping through an array
Using a For Loop
A for loop is commonly used to iterate over an array by accessing elements with their index:

Using a For-Each Loop


A for-each loop provides a simpler way to iterate through an array without dealing with indexes:
Finding average number using array
Methods in JAVA
In Java, a method is a block of code that performs a specific task and is
executed when called. It can take input parameters, process them, and
optionally return a value.

Purpose and Functionality:


Code Reusability:
Methods allow you to write code once and reuse it multiple times
throughout your program.
Organisation:
They help break down complex tasks into smaller, manageable units,
making code easier to read, understand, and maintain.
Types of method
1. Instance Methods:
Belong to an object of a class and are accessed using the object's name

2.Static Methods:
Belong to the class itself and are accessed using the class name

3. Constructor Methods:
Special methods used to initialize objects of a class

4.Interface Methods:
Methods declared in an interface, which must be implemented by classes that
implement the interface.
Method Overloading
Java allows you to define multiple methods with the same name but
different parameter lists (number, order, or type of parameters) within
the same class. This is called method overloading.
The compiler distinguishes between these methods based on their
signatures (parameter lists).
Create a Method
A method must be declared within a class. It is defined with the name of the
method, followed by parentheses (). Java provides some pre-defined
methods, such as System.out.println(), but you can also create your own
methods to perform certain actions:
Parameters and Arguments
Information can be passed to methods as a parameter. Parameters act as
variables inside the method.
Arguments are the actual values that are passed in when the method is
invoked. When you invoke a method, the arguments used must match the
declaration's parameters in type and order.

You might also like