0% found this document useful (0 votes)
61 views79 pages

Java Programming Basics and Features

Java is a high-level, object-oriented programming language known for its platform independence, simplicity, and security features. It supports multithreading and utilizes a Just-In-Time compiler for performance. The document also covers basic concepts such as data types, variables, keywords, and operators in Java.

Uploaded by

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

Java Programming Basics and Features

Java is a high-level, object-oriented programming language known for its platform independence, simplicity, and security features. It supports multithreading and utilizes a Just-In-Time compiler for performance. The document also covers basic concepts such as data types, variables, keywords, and operators in Java.

Uploaded by

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

Introduction to Java :

Java is a high-level, object-oriented programming language


developed by Sun Microsystems in 1995. It is mostly used for building desktop
applications, web applications, Android apps, and enterprise systems.

Key Features of Java:

 Platform Independent:
 Java is famous for its Write Once, Run Anywhere (WORA)
feature. This means we can write our Java code once, and it
will run on any device or operating system if Java Virtual
Machine is installed.
 Simple:
 No complex features like pointers and multiple inheritance,
which makes it a good choice for beginners.
 Object-Oriented:
 This makes code clean and reusable.
 Secured:
 Since there are no pointers, it has built-in protections to keep
our programs secure from common problems like memory
leakage and segment fault.
 Multithreading:
 Programs can do many things at the same time using multiple
threads. This is useful for handling complex tasks like
processing transactions.
 Just-In-Time (JIT) Compiler:
 Java uses a JIT compiler. It improves performance by converting
the bytecode into machine readable code at the time of
execution.
Example Of Hello World Program in Java:

When we learn any programming language, the first step is writing a simple
program to display "Hello World". So, here is a simple Java program that
displays "Hello World" on the screen.

Example:

// This is a simple Java program to print Hello World!


public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello World!");
}
}

Output:
Hello World

Java Virtual Machine(JVM) :

JVM (Java Virtual Machine) runs Java applications as a run-time


engine. JVM is the one that calls the main method present in a Java code. JVM is a
part of JRE (Java Runtime Environment). Java applications are called WORA
(Write Once Run Anywhere). This means a programmer can develop Java code on
one system and expect it to run on any other Java-enabled system without any
adjustments. This is all possible because of the JVM. When we compile a .java
file, .class files (containing byte-code) with the same class names present in the
.java file are generated by the Java compiler. This .class file goes through various
steps when we run it.

Data Types in Java:


In Java, data types specify the type of values a variable can hold. They
define the size, range and nature of data stored in memory.
Java has two main categories of data types:
1. Primitive :
 Byte
 Short
 integer
 long
 float
 double,
 char
 Boolean

2. Non-Primitive:
 String
 Arrays
 Classes
 Interfaces
 Objects

Example of Data types:

public class DataTypesDemo {


public static void main(String[] args) {

// -------- Primitive Data Types --------

byte b = 100; // 1 byte


short s = 30000; // 2 bytes
int i = 100000; // 4 bytes
long l = 10000000000L; // 8 bytes

float f = 3.14f; // 4 bytes


double d = 3.14159265359; // 8 bytes

char c = 'A'; // 2 bytes (Unicode character)


boolean flag = true; // 1 bit
// -------- Non-Primitive Data Types --------

String str = "Hello, Java"; // String (class in Java)


int[] arr = {1, 2, 3, 4, 5}; // Array
Integer wrapperInt = [Link](50); // Wrapper class example
StringBuilder sb = new StringBuilder("Java"); // Class object

// -------- Output --------

[Link]("byte: " + b);


[Link]("short: " + s);
[Link]("int: " + i);
[Link]("long: " + l);
[Link]("float: " + f);
[Link]("double: " + d);
[Link]("char: " + c);
[Link]("boolean: " + flag);

[Link]("String: " + str);


[Link]("Array: ");
for (int num : arr) {
[Link](num + " ");
}
[Link]();

[Link]("Wrapper Integer: " + wrapperInt);


[Link]("StringBuilder: " + sb);
}
}

Output:

byte: 100
short: 30000
int: 100000
long: 10000000000
float: 3.14
double: 3.14159265359
char: A
boolean: true
String: Hello, Java
Array: 1 2 3 4 5
Wrapper Integer: 50
StringBuilder: Java

Variables In Java:

variables are containers that store data in memory. Understanding


variables plays a very important role as it defines how data is stored,
accessed, and manipulated.

Syntax:
Data type Variable Name= “Value”;

Naming Rules for Variable:


 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three different
variables)

Types of Java Variables:

Now let us discuss different types of variables which are listed as follows:

 Local Variables
 Instance Variables
 Static Variables
1. Local Variables :

A variable defined within a block or method or constructor is called a local


variable.
 The Local variable is created at the time of declaration and destroyed when
the function completed its execution.
 The scope of local variables exists only within the block in which they are
declared.
 We first need to initialize a local variable before using it within its scope.

[Link] Variables:

Instance variables are known as non-static variables and are declared in a


class outside of any method, constructor, or block.
 Instance variables are created when an object of the class is created and
destroyed when the object is destroyed.
 Unlike local variables, we may use access specifiers for instance variables. If
we do not specify any access specifier, then the default access specifier will
be used.
 Initialization of an instance variable is not mandatory. Its default value is
dependent on the data type of variable. For String it
is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it
is null, etc.

[Link] Variables:
Static variables are also known as class variables.
 These variables are declared similarly to instance variables. The difference is
that static variables are declared using the static keyword within a class
outside of any method, constructor, or block.
 Unlike instance variables, we can only have one copy of a static variable per
class, irrespective of how many objects we create.
 Static variables are created at the start of program execution and destroyed
automatically when execution ends.
 Initialization of a static variable is not mandatory. Its default value is
dependent on the data type of variable. For String it is null, for float it
is 0.0f, for int it is 0, for Wrapper classes like Integer it is null, etc.

Keywords:

keywords are the reserved words that have some predefined meanings and
are used by the Java compiler for some internal process or represent some
predefined actions. These words cannot be used as identifiers such as Variable
names, method names, class names, or object names.

List out:

Abstract

Boolean

Char

Break

Byte

OPERATORS:
Java operators are special symbols that perform operations on
variables or values. These operators are essential in programming as
they allow you to manipulate data efficiently.

Types of Operators in Java:


1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
Let's see all these operators one by one with their proper examples.

1. Arithmetic Operators:
Arithmetic Operators are used to perform simple arithmetic
operations on primitive and non-primitive data types.
 * : Multiplication
 / : Division
 % : Modulo
 + : Addition
 - : Subtraction

Example:

// Java Program to show the use of


// Arithmetic Operators
import [Link].*;

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

// Arithmetic operators on integers


int a = 10;
int b = 3;

// Arithmetic operators on Strings


String n1 = "15";
String n2 = "25";

// Convert Strings to integers


int a1 = [Link](n1);
int b1 = [Link](n2);

[Link]("a + b = " + (a + b));


[Link]("a - b = " + (a - b));
[Link]("a * b = " + (a * b));
[Link]("a / b = " + (a / b));
[Link]("a % b = " + (a % b));
[Link]("a1 + b1 = " + (a1 + b1));

}
}

Output:
a + b = 13
a-b=7
a * b = 30
a/b=3
a%b=1
a1 + b1 = 40

2. Unary Operators:
Unary Operators need only one operand. They are used to increment,
decrement, or negate a value.
 - , Negates the value.
 + , Indicates a positive value (automatically converts byte, char,
or short to int).
 ++ , Increments by 1.
o Post-Increment: Uses value first, then increments.
o Pre-Increment: Increments first, then uses value.
 -- , Decrements by 1.
o Post-Decrement: Uses value first, then decrements.
o Pre-Decrement: Decrements first, then uses value.
 ! , Inverts a boolean value.

Example:

// Java Program to show the use of


// Unary Operators
import [Link].*;

// Driver Class
class Geeks {
// main function
public static void main(String[] args)
{
// Interger declared
int a = 10;
int b = 10;

// Using unary operators


[Link]("Postincrement : " + (a++));
[Link]("Preincrement : " + (++a));

[Link]("Postdecrement : " + (b--));


[Link]("Predecrement : " + (--b));
}
}

Output:
Postincrement : 10
Preincrement : 12
Postdecrement : 10
Predecrement : 8
3. Assignment Operator
'=' The assignment operator is used to assign a value to any
variable. It has right-to-left associativity, i.e. value given on the right-
hand side of the operator is assigned to the variable on the left, and
therefore right-hand side value must be declared before using it or
should be a constant.

The general format of the assignment operator is:


variable = value;

In many cases, the assignment operator can be combined with


others to create shorthand compound statements. For example, a +=

5 replaces a = a + 5. Common compound operators include:


 += , Add and assign.
 -= , Subtract and assign.
 *= , Multiply and assign.
 /= , Divide and assign.
 %= , Modulo and assign.

Example:

// Java Program to show the use of


// Assignment Operators
import [Link].*;

// Driver Class
class Geeks {
// Main Function
public static void main(String[] args)
{

// Assignment operators
int f = 7;
[Link]("f += 3: " + (f += 3));
[Link]("f -= 2: " + (f -= 2));
[Link]("f *= 4: " + (f *= 4));
[Link]("f /= 3: " + (f /= 3));
[Link]("f %= 2: " + (f %= 2));
[Link]("f &= 0b1010: " + (f &= 0b1010));
[Link]("f |= 0b1100: " + (f |= 0b1100));
[Link]("f ^= 0b1010: " + (f ^= 0b1010));
[Link]("f <<= 2: " + (f <<= 2));
[Link]("f >>= 1: " + (f >>= 1));
[Link]("f >>>= 1: " + (f >>>= 1));
}
}

Output:

f += 3: 10
f -= 2: 8
f *= 4: 32
f /= 3: 10
f %= 2: 0
f &= 0b1010: 0
f |= 0b1100: 12
f ^= 0b1010: 6
f <<= 2: 24
f >>= 1: 12
f >>>= 1: 6
4. Relational Operators
Relational Operators are used to check for relations like equality,
greater than, and less than. They return boolean results after the
comparison and are extensively used in looping statements as well as
conditional if-else statements.
The general format is ,
variable relation_operator value

Relational operators compare values and return Boolean results:


 == , Equal to.
 != , Not equal to.
 < , Less than.
 <= , Less than or equal to.
 > , Greater than.
 >= , Greater than or equal to.

Example:

// Java Program to show the use of


// Relational Operators
import [Link].*;

// Driver Class
class Geeks {

// main function
public static void main(String[] args)
{
// Comparison operators
int a = 10;
int b = 3;
int c = 5;

[Link]("a > b: " + (a > b));


[Link]("a < b: " + (a < b));
[Link]("a >= b: " + (a >= b));
[Link]("a <= b: " + (a <= b));
[Link]("a == c: " + (a == c));
[Link]("a != c: " + (a != c));
}
}

Output:

a > b: true
a < b: false
a >= b: true
a <= b: false
a == c: false
a != c: true

5. Logical Operators:
Logical Operators are used to perform "logical AND" and "logical
OR" operations, similar to AND gate and OR gate in digital electronics.
They have a short-circuiting effect, meaning the second condition is not
evaluated if the first is false.
Conditional operators are:
 &&, Logical AND: returns true when both conditions are true.
 ||, Logical OR: returns true if at least one condition is true.
 !, Logical NOT: returns true when a condition is false and vice-
versa
Example:
// Java Program to show the use of
// Logical operators
import [Link].*;

class Geeks {

// Main Function
public static void main (String[] args) {

// Logical operators
boolean x = true;
boolean y = false;

[Link]("x && y: " + (x && y));


[Link]("x || y: " + (x || y));
[Link]("!x: " + (!x));
}
}

Output:
x && y: false
x || y: true
!x: false

6. Ternary operator:
The Ternary Operator is a shorthand version of the if-else
statement. It has three operands and hence the name Ternary.
The general format is,
condition ? if true : if false
The above statement means that if the condition evaluates to true, then
execute the statements after the '?' else execute the statements after
the ':'.
Example:

// Java program to illustrate


// max of three numbers using
// ternary operator.
public class Geeks {

public static void main(String[] args)


{
int a = 20, b = 10, c = 30, result;

// result holds max of three


// numbers
result = ((a > b) ? (a > c) ? a : c : (b > c) ? b : c);
[Link]("Max of three numbers = "+ result);
}
}

Output:
Max of three numbers = 30

7. Bitwise Operators
Bitwise Operators are used to perform the manipulation of individual
bits of a number and with any of the integer types. They are used when
performing update and query operations of the Binary indexed trees.
 & (Bitwise AND): returns bit-by-bit AND of input values.
 | (Bitwise OR): returns bit-by-bit OR of input values.
 ^ (Bitwise XOR): returns bit-by-bit XOR of input values.
 ~ (Bitwise Complement): inverts all bits (one's complement).
Example:

// Java Program to show the use of


// bitwise operators
import [Link].*;

class Geeks
{
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;

[Link]("d & e : " + (d & e));


[Link]("d | e : " + (d | e));
[Link]("d ^ e : " + (d ^ e));
[Link]("~d : " + (~d));
[Link]("d << 2 : " + (d << 2));
[Link]("e >> 1 : " + (e >> 1));
[Link]("e >>> 1 : " + (e >>> 1));
}
}

Output:
d&e:8
d | e : 14
d^e:6
~d : -11
d << 2 : 40
e >> 1 : 6
e >>> 1 : 6

Expressions:
An expression is a combination of operators, constants and
variables. An expression may consist of one or more operands, and zero
or more operators to produce a value.
Example:
Result = a + b * c ..

Types of Expressions:

Expressions may be of the following types:


Constant expressions

Integral expressions

Floating expressions

Relational expressions

Logical expressions

Pointer expressions

Bitwise expressions


Constant expressions:
Constant Expressions consists of only constant values. A
constant value is one that doesn't change.
Examples:
5, 10 + 5 / 6.0, 'x’

 Integral expressions:
Integral Expressions are those which produce integer results after
implementing all the automatic and explicit type conversions.
Examples:
x, x * y, x + int( 5.0)

where x and y are integer variables.


 Floating expressions:
Float Expressions are which produce floating point results after
implementing all the automatic and explicit type conversions.

Examples:
x + y, 10.75
where x and y are floating point variables.


Relational expressions:
Relational Expressions yield results of type bool which takes
a value true or false. When arithmetic expressions are used on
either side of a relational operator, they will be evaluated first and
then the results compared.
Relational expressions are also known as Boolean expressions.

Examples:
x <= y, x + y > 2

Logical expressions:
Logical Expressions combine two or more relational
expressions and produces bool type results.

Examples:
x > y && x == 10, x == 10 || y == 5

Pointer expressions:
Pointer Expressions produce address values. Examples:
&x, ptr, ptr++
where x is a variable and ptr is a pointer.
 Bitwise expressions: Bitwise Expressions are used to manipulate
data at bit level. They are basically used for testing or shifting bits.
Examples:
x << 3
shifts three bit position to left
y >> 1
shifts one bit position to right. Shift operators are often used for
multiplication and division by powers of two.

Control statements:

A programming language uses control statements to control the


flow of execution of a program based on certain conditions.. Java
provides several control statements to manage program flow, including:

 Conditional Statements: if, if-else, nested-if, if-else-if


 Switch-Case: For multiple fixed-value checks
 Jump Statements: break, continue, return

Types of Control Statements:

 If
 If-else
 Nested if
 if-else-if
 switch case
 jump- break, continue, return.


If Statement
The if statement is the most simple decision-making statement. It is used to
decide whether a certain statement or block of statements will be executed or not
i.e. if a certain condition is true then a block of statements is executed otherwise
not.

Syntax:
if(condition) {
// Statements to execute if
// condition is true
}

Example:

import [Link].*;
class Geeks {
public static void main(String args[])
{
int i = 10;

if (i < 15)

// part of if block(immediate one statement after if condition)


[Link]("Inside If block");

// always executes as it is outside of if block


[Link]("10 is less than 15");

// This statement will be executed as if considers one statement by


default again below statement is outside of if block
[Link]("I am Not in if");
}
}

Output:
Inside If block
10 is less than 15
I am Not in if

If-else Statement:
The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false it won't. But what if we want to do
something else if the condition is false? Here, comes the "else" statement.

Syntax:
if(condition){
// Executes this block if
// condition is true
}else{
// Executes this block if
// condition is false
}

Example:
import [Link].*;

class Geeks {
public static void main(String args[])
{
int i = 10;

if (i < 15)
[Link]("i is smaller than 15");
else
[Link]("i is greater than 15");
}
}
Output:
i is smaller than 15

Nested if :
Nested if in Java refers to having one if statement inside another if
statement. If the outer condition is true the inner conditions are checked and
executed accordingly. Nested if condition comes under decision-making statement
in Java, enabling multiple branches of execution.
Syntax of Nested if:

if (condition1) {
if (condition2) {
if (condition3) {
// statements;
}
}
}

Example:

class Geeks {
public static void main(String args[]) {
int i = 10;

// Outer if statement
if (i < 15) {
[Link]("i is smaller than 15");

// Nested if statement
if (i == 10) {
[Link]("i is exactly 10");

}
}
}
}

Output:
i is smaller than 15
i is smaller than 12 too

If-else-if:
The if statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with that 'if' is
executed, and the rest of the ladder is bypassed.

Syntax:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}

Example:
import java. util.*;

class Geeks {
public static void main(String args [])
{
int i = 20;

if (i == 10)
System. out. println("i is 10");
else if (i == 15)
System. out. println("i is 15");
else if (i == 20)
System. out. println("i is 20");
else
System. out. println("i is not present");
}
}

Output:
i is 20

Switch Case:
The switch statement is a multiway branch statement. It provides an easy
way to dispatch execution to different parts of code based on the value of the
expression.
Syntax:
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
// more cases...
default:
// code to be executed if no cases match
}

Example:
import [Link].*;
class Geeks {
public static void main(String[] args)
{
int num = 20;
switch (num) {
case 5:
[Link]("It is 5");
break;
case 10:
[Link]("It is 10");
break;
case 15:
[Link]("It is 15");
break;
case 20:
[Link]("It is 20");
break;
default:
[Link]("Not present");
}
}
}

Output:
It is 20

6. jump Statements:
Java supports three jump statements: break, continue and return.
These three statements transfer control to another part of the program.

 Break: In Java, a break is majorly used for:


o Terminate a sequence in a switch statement (discussed above).
o To exit a loop.
o Used as a "civilized" form of goto.
 Continue: Sometimes it is useful to force an early iteration of a loop. That is,
you might want to continue running the loop but stop processing the
remainder of the code in its body for this particular iteration. This is, in
effect, a goto just past the body of the loop, to the loop's end. The continue
statement performs such an action.
Example:

import [Link].*;

class Geeks {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {

// If the number is even, skip and continue


if (i % 2 == 0)
continue;

// If number is odd, print it


[Link](i + " ");
}
}
}

Output:
13579

Return Statement:
The return statement is used to explicitly return from a method. That is, it
causes program control to transfer back to the caller of the method.

Example:
import [Link].*;
public class Geeks {
public static void main(String args[])
{
boolean t = true;
[Link]("Before the return.");

if (t)
return;

// Compiler will bypass every statement return


[Link]("This won't execute.");
}
}

Output:
Before the return.

Classes and Objects in Java:


Classes and objects are basic concepts of Object Oriented Programming
(OOPs) that are used to represent real-world concepts and entities.
 A class is a template to create objects having similar properties and
behavior, or in other words, we can say that a class is a blueprint for
objects.
 An object is an instance of a class. For example, the animal type Dog is a
class, while a particular dog named Tommy is an object of the Dog class.
Example:

// File: [Link]
class Student {
int id;
String n;

// Added constructor to initialize both fields


public Student(int id, String n) {
[Link] = id;
this.n = n;
}
}

// File: [Link]
public class Main {
public static void main(String[] args) {

// Creating Student object using the new constructor


Student s1 = new Student(10, "Alice");

[Link]([Link]);
[Link](s1.n);
}
}

Output:
10
Alice

Class Declaration in Java:

access_modifier class<class_name> {
data member;
method;
constructor;
nested class;
interface
;
}

Constructors:
 constructors play an important role in object creation. A constructor is a
special block of code that is called when an object is created.
 Its main job is to initialize the object, to set up its internal state, or to
assign default values to its attributes.
 This process happens automatically when we use the "new" keyword to
create an object.
Syntax:
class Geek
{
......
// A Constructor
Geek() {
}
.......
}
// We can create an object of the above class
// using the below statement. This statement
// calls above constructor.
Geek obj = new Geek();

Types of Constructors in Java:


Now is the correct time to discuss the types of the constructor, so primarily
there are three types of constructors in Java are mentioned below:

 Default Constructor
 Parameterized Constructor
 Copy Constructor

[Link] Constructor in Java:


 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.
 Once you define a constructor (with or without parameters), the compiler
no longer provides the default constructor. Defining a parameterized
constructor does not automatically create a no-argument constructor, we
must explicitly define if needed.
 The default constructor can be implicit or explicit.

 Implicit Default Constructor:


 If no constructor is defined in a class, the Java compiler
automatically provides a default constructor.
 This constructor doesn’t take any parameters and initializes the
object with default values, such as 0 for numbers, null for
objects.
 Explicit Default Constructor:
 If we define a constructor that takes no parameters, it's called
an explicit default constructor.
 This constructor replaces the one the compiler would normally
create automatically. Once you define any constructor (with or
without parameters), the compiler no longer provides the
default constructor for you.

Example:

// Java Program to demonstrate


// Default Constructor
import [Link].*;

// Driver class
class Geeks{

// Default Constructor
Geeks() {
[Link]("Default constructor");
}
// Driver function
public static void main(String[] args)
{
Geeks hello = new Geeks();
}
}

Output:
Default constructor

2. Parameterized Constructor in Java:


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.

Example:
// Java Program for Parameterized Constructor

import [Link].*;

class Geeks {

// data members of the class

String name;

int id;

Geeks(String name, int id) {

[Link] = name;

[Link] = id;

}
class GFG

public static void main(String[] args)

// This would invoke the parameterized constructor

Geeks geek1 = new Geeks("Sweta", 68);

[Link]("GeekName: " + [Link]

+ " and GeekId: " + [Link]);

Output:
GeekName: Sweta and GeekId: 68

3. Copy Constructor in Java:


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:
// Java Program for Copy Constructor

import [Link].*;

class Geeks {

// data members of the class


String name;

int id;

// Parameterized Constructor

Geeks(String name, int id)

[Link] = name;

[Link] = id;

// Copy Constructor

Geeks(Geeks obj2)

[Link] = [Link];

[Link] = [Link];

class GFG {

public static void main(String[] args)

// This would invoke the parameterized constructor

[Link]("First Object");

Geeks geek1 = new Geeks("Sweta", 68);


[Link]("GeekName: " + [Link]

+ " and GeekId: " + [Link]);

[Link]();

// This would invoke the copy constructor

Geeks geek2 = new Geeks(geek1);

[Link](

"Copy Constructor used Second Object");

[Link]("GeekName: " + [Link]

+ " and GeekId: " + [Link]);

Output:
First Object

GeekName: Sweta and GeekId: 68

Copy Constructor used Second Object

GeekName: Sweta and GeekId: 68

Method Overloading in Java:


 Method Overloading allows us to define multiple methods with the same
name but different parameters within a class.

 This difference may include:


 The number of parameters

 The types of parameters

 The order of parameters

 Method overloading in Java is also known as Compile-time Polymorphism,


Static Polymorphism, or Early binding, because the decision about which
method to call is made at compile time.

 When there are overloaded methods that accept both a parent type and a
child type, and the provided argument could match either one, Java prefers
the method that takes the more specific (child) type.

 Key features of Method Overloading:


 Multiple methods can share the same name in a class when their
parameter lists are different.

 Overloading is a way to increase flexibility and improve the readability of


code.

 Overloading does not depend on the return type of the method, two
methods cannot be overloaded by just changing the return type.

Example:
// Java program to demonstrate working of method

// overloading in Java

public class Sum {


// Overloaded sum()

// This sum takes two int parameters

public int sum(int x, int y) { return (x + y); }

// Overloaded sum()

// This sum takes three int parameters

public int sum(int x, int y, int z)

return (x + y + z);

// Overloaded sum()

// This sum takes two double parameters

public double sum(double x, double y)

return (x + y);

// Driver code

public static void main(String args[])

Sum s = new Sum();

[Link]([Link](10, 20));

[Link]([Link](10, 20, 30));

[Link]([Link](10.5, 20.5));
}

Output:
30

60

31.0

Number of Parameters:
Method overloading can be achieved by changing the number of
parameters while passing to different methods.

Type of Parameters:
methods can be considered overloaded if they have the same name but
have different parameter types, methods are considered to be overloaded.

Order of the Parameters:


Method overloading can also be implemented by rearranging the
parameters of two or more overloaded methods.

For example, if the parameters of method 1 are (String name, int roll_no)
and the other method is (int roll_no, String name) but both have the same name,
then these 2 methods are considered to be overloaded with different sequences
of parameters.

Arrays in Java:
an array is an important linear data structure that allows us to store
multiple values of the same type.

 Arrays in Java are objects, like all other objects in Java, arrays implicitly
inherit from the [Link] class. This allows you to invoke
methods defined in Object (such as toString(), equals() and
hashCode()).

 Arrays have a built-in length property, which provides the number of


elements in the array

Example:
public class Geeks {

public static void main(String[] args) {

// initializing array

int[] arr = { 40,55,63,17,22,68,89,97,89};

// size of array

int n = [Link];

// traversing array

for (int i = 0; i < n; i++)

[Link](arr[i] + " ");

Output:
40 55 63 17 22 68 89 97 89

Basics Operation on Arrays in Java:


1. Declaring an Array

The general form of array declaration is

// Method 1:
int arr[];

// Method 2:
int[] arr;

The element type determines the data type of each element that comprises the
array. Like an array of integers, we can also create an array of other primitive data
types like char, float, double, etc. or user-defined data types (objects of a class).

2. Initialization an Array in Java

When an array is declared, only a reference of an array is created. We use new to


allocate an array of given size.

int arr[] = new int[size];

 Array Declaration is generally static, but if the size in not defined, the Array
is Dynamically sized.

 Memory for arrays is always dynamically allocated (on heap segment) in


Java. This is different from C/C++ where memory can either be statically
allocated or dynamically allocated.

 The elements in the array allocated by new will automatically be initialized


to zero (for numeric types), false (for boolean) or null (for reference types).

3. Change an Array Element


 To change an element, assign a new value to a specific index. The index
begins with 0 and ends at (total array size)-1.
 // Changing the first element to 90
arr[0] = 90;
 4. Array Length
 We can get the length of an array using the length property:
 // Getting the length of the array
int n = [Link];
5. Accessing and Updating All Array Elements
 All the elements of array can be accessed using Java for Loop.
 Each element in the array is accessed via its index.
Example:
Java program to illustrate creating an array of integers, puts some values in
the array and prints each value to standard output.

class Geeks {

public static void main(String[] args)

// declares an Array of integers.

int[] arr;

// allocating memory for 5 integers.

arr = new int[5];

// initialize the elements of the array, first to last(fifth) element

arr[0] = 2;

arr[1] = 4;

arr[2] = 8;

arr[3] = 12;

arr[4] = 16;

// accessing the elements of the specified array

for (int i = 0; i < [Link]; i++)

[Link]("Element at index " + i + " : " + arr[i]);

}
}

Output
Element at index 0 : 2

Element at index 1 : 4

Element at index 2 : 8

Element at index 3 : 12

Element at index 4 : 16

Strings In Java:
 String is the type of object that can store a sequence of characters
enclosed by double quotes and every character is stored in 16 bits.

 A string acts the same as an array of characters. Java provides a robust


and flexible API for handling strings, allowing for various operations such
as concatenation, comparison and manipulation.

Example:
String name = "Geeks";
String num = "1234";

Program:
public class Geeks {

// Main Function

public static void main(String args[])


{

// creating Java string using a new keyword

String str = new String("Geeks");

[Link](str);

Output:
Geeks

Ways of Creating a Java String


There are two ways to create a string in Java:

 String Literal

 Using new Keyword

1. String literal (Static Memory)


To make Java more memory efficient (because no new objects are created
if it exists already in the string constant pool).

Example:
String str = “GeeksforGeeks”;

2. Using new keyword (Heap Memory)


 String s = new String("Welcome");

 In such a case, JVM will create a new string object in normal (non-pool)
heap memory and the literal "Welcome" will be placed in the string
constant pool. The variable s will refer to the object in the heap (non-pool)

Example:
String str = new String (“GeeksforGeeks”);

Interfaces and Classes in Strings in Java


CharSequence Interface

 CharSequence Interface is used for representing the sequence of


Characters in Java.

 Classes that are implemented using the CharSequence interface are


mentioned below and It provides basic methods such as length(),
charAt(), subSequence() and toString().

Classes that implement CharSequence include:

1. String:
String is an immutable class in Java, which means that once a String object
is created, its value cannot be changed. If you want to modify a string a new
String object is created and the original remains unchanged.

Syntax:
// Method 1
String str= "geeks";
// Method 2
String str= new String("geeks");

2. StringBuffer:
 StringBuffer is a peer class of String, it is mutable in nature and it is
thread safe class , we can use it when we have multi threaded
environment and shared object of string buffer i.e, used by mutiple
thread.

 As it is thread safe so there is extra overhead, so it is mainly used for


multithreaded program.

Syntax:
StringBuffer demoString = new StringBuffer("GeeksforGeeks");

3. StringBuilder
 StringBuilder in Java represents an alternative to String and StringBuffer
Class, as it creates a mutable sequence of characters and it is not thread
safe.

 It is used only within the thread , so there is no extra overhead , so it is


mainly used for single threaded program.

Syntax:
StringBuilder demoString = new StringBuilder();
[Link]("GFG");

4. StringTokenizer:
 StringTokenizer class in Java is used to break a string into tokens.

 A StringTokenizer object internally maintains a current position within


the string to be tokenized. Some operations advance this current
position past the characters processed.

 A token is returned by taking a substring of the string that was used to


create the StringTokenizer object.

Syntax:
public StringJoiner(CharSequence delimiter)

Inheritance in Java:
 Java Inheritance is a fundamental concept in OOP(Object-Oriented
Programming). It is the mechanism in Java by which one class is allowed
to inherit the features(fields and methods) of another class.

 Inheritance means creating new classes based on existing ones. A class


that inherits from another class can reuse the methods and fields of that
class.

Example:

In the following example, Animal is the base class and Dog, Cat and
Cow are derived classes that extend the Animal class.

Implementation:
// Parent class

class Animal {

void sound() {

[Link]("Animal makes a sound");

// Child class

class Dog extends Animal {

void sound() {
[Link]("Dog barks");

// Child class

class Cat extends Animal {

void sound() {

[Link]("Cat meows");

// Child class

class Cow extends Animal {

void sound() {

[Link]("Cow moos");

// Main class

public class Geeks {

public static void main(String[] args) {


Animal a;

a = new Dog();

[Link]();

a = new Cat();

[Link]();

a = new Cow();

[Link]();

Output:
Dog barks

Cat meows

Cow moos

Constructors in Inheritance:
In Java, when a class inherits another class, the constructor of the parent
class is executed first, followed by the constructor of the child class. This ensures
that the base class is properly initialized before the derived class adds its own
functionality.

How Constructors Work in Inheritance

When an object of a derived class is created, the constructor of the base


class is automatically called first. If there is no explicit call to the superclass
constructor, Java automatically invokes the default constructor of the superclass.

Example:
class Parent {

Parent() {

[Link]("Parent class constructor called");

class Child extends Parent {

Child() {

[Link]("Child class constructor called");

public class Main {

public static void main(String[] args) {

Child obj = new Child();

Output:
Parent class constructor called
Child class constructor called

Explanation:

 When we create an object of Child, the constructor of Parent is called first.

 After that, the constructor of Child is executed.

Constructor Chaining in Inheritance

Constructor chaining refers to the process where one constructor calls another
constructor in the same or parent class using this() or super() .

Example:
class A {

A() {

[Link]("Constructor of A");

class B extends A {

B() {

super(); // Calls the constructor of A

[Link]("Constructor of B");

}
class C extends B {

C() {

super(); // Calls the constructor of B

[Link]("Constructor of C");

public class Main {

public static void main(String[] args) {

C obj = new C();

Output:
Constructor of A

Constructor of B

Constructor of C

Explanation:
 The super() calls ensure that constructors are called from the base class to
the derived class in the correct order.

Method Overriding in Java:


 Method Overriding is a feature that allows a subclass to provide a specific
implementation of a method that is already defined in its parent class.
 The overridden method in the child class must have the same method
signature as the one in the parent class.

Key Rules of Method Overriding:

 The method in the child class must have the same name as in the
parent class.

 The method must have the same parameters as in the parent


class.

 There must be an inheritance relationship (i.e., one class must be


a subclass of another).

 The return type should be the same or covariant (subtype of the


return type in the parent class).

 The access modifier cannot be more restrictive than the method


in the parent class.

 Methods marked as final, static, or private cannot be overridden.

Example:
// Parent class

class Animal {

void makeSound() {

[Link]("Animal makes a sound");

// Child class
class Dog extends Animal {

// Overriding the makeSound method

@Override

void makeSound() {

[Link]("Dog barks");

// Main class

public class Main {

public static void main(String[] args) {

Animal myAnimal = new Animal();

[Link](); // Calls method from Animal class

Animal myDog = new Dog();

[Link](); // Calls overridden method from Dog class

Output:
Animal makes a sound

Dog barks
Super Class in Java:
The super keyword in Java is a reference variable that is used to refer to the
parent class when we are working with objects. You need to know the basics
of Inheritance and Polymorphism to understand the Java super keyword.

Characteristics of Super Class:

The characteristics of the super keyword are listed below:


 Calling the Parent Class Constructor: When we create an object of the
subclass, its constructor needs to call the constructor of the parent class.
This can be done with the help of the super keyword and it calls the
constructor of the parent class.

 Accessing Parent Class Methods: If the subclass wants to access the


methods of the parent class, it can also be done with the help of the super
keyword.

 Accessing Parent Class Fields: Fields from the parent class can also be
accessed using the super keyword in the subclass.

 First Statement in a Constructor: When calling a superclass constructor,


the super() statement must be the first statement in the constructor of the
subclass. This ensures that the parent class is properly initialized before the
subclass does anything else.

 Cannot be used in Static Context: We cannot use super in a static variable,


static method and static block.

 Not Always Required: We know that the super keyword is used to call the
methods from the parent class. If a method is not overridden in the
subclass, then calling it without the super keyword will invoke the parent
class's implementation.
Use of super Class in Java
Super Keyword are mainly used in the following contexts which are listed
below:
1. Use of super with Variables:
This scenario occurs when a derived class and base class have the same data
members. In that case, there is a possibility of ambiguity for the JVM.
Real-world example: Suppose there is a child, whose name is "Max" and the child
has also a parent named "Max". Normally, to refer to the parent, we would say
"parent Max", this is similar to using [Link].
Program:
// Super keyword with variable

// Base class vehicle

class Vehicle {

int maxSpeed = 120;

// sub class Car extending vehicle

class Car extends Vehicle {

int maxSpeed = 180;

void display()

// print maxSpeed from the vehicle class

// using super

[Link]("Maximum Speed: "


+ [Link]);

// Driver Program

class Test {

public static void main(String[] args)

Car small = new Car();

[Link]();

Output
Maximum Speed: 120

2. Use of super with Methods:


This is used when we want to call the parent class method. So, whenever a parent
and child class have the same-named methods then to resolve ambiguity we use
the super keyword.

Real-world Example: It is simply just like when we want to listen to our


parents' advice instead of our own decision, [Link]() helps us follow
the parents' behavior in code.

Program:
// superclass Person
class Person {

void message()

[Link]("This is person class\n");

// Subclass Student

class Student extends Person {

void message()

[Link]("This is student class");

// Note that display() is

// only in Student class

void display()

// will invoke or call current

// class message() method

message();
// will invoke or call parent

// class message() method

[Link]();

// Driver Program

class Test {

public static void main(String args[])

Student s = new Student();

// calling display() of Student

[Link]();

Output
This is student class

This is person class

3. Use of super with Constructors:


The super keyword can also be used to access the parent class constructor.
One more important thing is that ‘super’ can call both parametric as well as non-
parametric constructors depending on the situation.

Real-world Example: Before a child born, first the parent exists. Similarly, the
parent class constructor must be called before the child's constructor finishes it's
work.

Program:
// superclass Person

class Person {

Person()

[Link]("Person class Constructor");

// subclass Student extending the Person class

class Student extends Person {

Student()

// invoke or call parent class constructor

super();

[Link]("Student class Constructor");

}
// Driver Program

class Test {

public static void main(String[] args)

Student s = new Student();

Output
Person class Constructor

Student class Constructor

Advantages of Using Java Super Class:


 With the help of super keyword, subclasses can inherit the functionality
from their parent classes.

 Subclasses can override methods and can access fields and methods from
their parent class with the help of super keyword, because of this the code
becomes more flexible.

 With the help of super keyword we can easily access the methods and
fields from the parent class without recreating it in the subclass.

Abstract Class in Java:


 Definition: An abstract class is a class that cannot be instantiated directly
(which means we can not create an object directly from an abstract class).
An abstract class is like a blueprint for other classes.

 Method Implementation: An abstract class can contain both abstract


methods (methods without an implementation) and concrete methods
(methods with an implementation).

 Variables: Abstract classes can have member variables, including final,


non-final, static, and non-static variables.

 Constructors: Abstract classes can have constructors, which can be used


to initialize variables in the abstract class when it is instantiated by a
subclass.

Example:

// Abstract class Shape, serving as a blueprint for specific shape classes

abstract class Shape {

// Name of the shape

String objectName = " ";

// Constructor to initialize the name of the shape

Shape(String name) {

[Link] = name;

// Concrete method to move the shape to a new position

public void moveTo(int x, int y) {

[Link]([Link] + " has been moved to x = " + x + "


and y = " + y);

// Abstract method to calculate the area of the shape

abstract public double area();

// Abstract method to draw the shape

abstract public void draw();

// Rectangle class extending Shape and providing its own implementation

class Rectangle extends Shape {

// Dimensions of the rectangle

int length, width;

// Constructor to initialize the rectangle's dimensions and name

Rectangle(int length, int width, String name) {

super(name);

[Link] = length;

[Link] = width;

}
// Implementation of draw method for rectangle

@Override

public void draw() {

[Link]("Rectangle has been drawn ");

// Implementation of area method for rectangle

@Override

public double area() {

return (double)(length * width);

// Circle class extending Shape and providing its own implementation

class Circle extends Shape {

// Value of pi for circle area calculation

double pi = 3.14;

// Radius of the circle

int radius;

// Constructor to initialize the circle's radius and name

Circle(int radius, String name) {


super(name);

[Link] = radius;

// Implementation of draw method for circle

@Override

public void draw() {

[Link]("Circle has been drawn ");

// Implementation of area method for circle

@Override

public double area() {

return (double)(pi * radius * radius);

// Main class to test the functionality of the shape classes

public class Geeks {

public static void main(String[] args) {

// Creating a Rectangle object and demonstrating its behavior

Shape rect = new Rectangle(2, 3, "Rectangle");


[Link]("Area of rectangle: " + [Link]());

[Link](1, 2);

[Link]();

// Creating a Circle object and demonstrating its behavior

Shape circle = new Circle(2, "Circle");

[Link]("Area of circle: " + [Link]());

[Link](2, 4);

Output
Area of rectangle: 6.0

Rectangle has been moved to x = 1 and y = 2

Area of circle: 12.56

Circle has been moved to x = 2 and y = 4

Interface in Java
 Definition: An interface is a reference type in Java, it is similar to a class,
and it is a collection of abstract methods and static constants.

 Method Implementation: All methods in an interface are by default


abstract and must be implemented by any class that implements the
[Link] Java 8, interfaces can have default and static methods
with concrete [Link] Java 9, interfaces can also have
private methods.

 Variables: Variables declared in an interface are by default public, static,


and final (constants).

Example:

// Interface defining the method to draw an object

interface Drawable {

void draw();

// Interface defining the method to move an object to a new position

interface Movable {

void moveTo(int x, int y);

// Circle class implementing both Drawable and Movable interfaces

class Circle implements Drawable, Movable {

double pi = 3.14; // Value of Pi for circle calculations

int radius; // Radius of the circle


// Constructor to initialize the radius of the circle

Circle(int radius) {

[Link] = radius;

// Implementation of the draw method from Drawable interface

@Override

public void draw() {

[Link]("Circle has been drawn ");

// Implementation of the moveTo method from Movable interface

@Override

public void moveTo(int x, int y) {

[Link]("Circle has been moved to x = " + x + " and y = " + y);

// Main class to test the implementation of Circle class

public class Geeks {

public static void main(String[] args) {


// Create a Circle object

Circle circle = new Circle(2);

// Call the draw method

[Link]();

// Call the moveTo method

[Link](2, 4);

Output:

Circle has been drawn

Circle has been moved to x = 2 and y = 4

Dynamic Method Dispatch In Java:


Method overriding is one of the ways in which Java supports Runtime
Polymorphism. Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile time.

 When an overridden method is called through a superclass reference,


Java determines which version(superclass/subclasses) of that method is
to be executed based upon the type of the object being referred to at
the time the call occurs. Thus, this determination is made at run time.

 At run-time, it depends on the type of the object being referred to (not


the type of the reference variable) that determines which version of an
overridden method will be executed

 A superclass reference variable can refer to a subclass object. This is also


known as upcasting. Java uses this fact to resolve calls to overridden
methods at run time.

Example:
if a superclass contains a method that is overridden by a subclass, then when
different types of objects are referred to through a superclass reference variable,
different versions of the method are executed. Here is an example that illustrates
dynamic method dispatch:

Program:

class A

void m1()

[Link]("Inside A's m1 method");

class B extends A

// overriding m1()

void m1()

{
[Link]("Inside B's m1 method");

class C extends A

// overriding m1()

void m1()

[Link]("Inside C's m1 method");

// Driver class

class Dispatch

public static void main(String args[])

// object of type A

A a = new A();

// object of type B
B b = new B();

// object of type C

C c = new C();

// obtain a reference of type A

A ref;

// ref refers to an A object

ref = a;

// calling A's version of m1()

ref.m1();

// now ref refers to a B object

ref = b;

// calling B's version of m1()

ref.m1();

// now ref refers to a C object

ref = c;
// calling C's version of m1()

ref.m1();

Output:
Inside A's m1 method

Inside B's m1 method

Inside C's m1 method

Packages in Java:
 Packages are used for organizing and sharing code in Java.

 The 'package' keyword is used to define a package in Java.

 The 'import' keyword is used to import a package into an existing Java file.

 Packages promote code reusability and maintainability.

 Packages can store classes, interfaces, and subpackages.

 Packages are used for grouping classes.

 Packages in Java can be classified as:

 Internal packages (predefined packages): Also known as predefined


packages, these are built-in packages in Java.

 External packages (user-defined packages): These packages are created by


the user to organize their code.
 Some commonly user predefined packages in Java include:

 [Link].*: The java package is the main package and serves as the default
package. The lang package is a subpackage.

 [Link].*: Contains useful utilities, such as the Scanner class.

 [Link].*: Used for handling input and output streams.

 [Link].* (Abstract Window Toolkit): Used for creating graphical user


interfaces.

 [Link].*: This is a sub-subpackage under [Link] that contains


classes for handling events in GUI applications.

 [Link].*: Provides classes for database connectivity.

 [Link].*: Used for network connectivity.

 [Link].*: Provides classes for building GUIs using Swing components.

 Inside java package

Creating our own Package in Java

 Creating a package in Java is a straightforward process, but effectively using


it may require some understanding. Let's take a simple class and transform
it into a package.

class Shape {

void color() {

[Link]("Coloring the shape");

void cal_area() {

[Link]("Calculating area.");
}

void cal_square() {

[Link]("Calculating square");

Exception Handling In Java:


 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
ClassNotFoundException, IOException, SQLException, RemoteException,
etc.

 By handling these exceptions, Java enables developers to create robust


and fault-tolerant applications.

Types of Java Exceptions:


Java defines several types of exceptions that relate to its various class
libraries. Java also allows users to define their it's exceptions.

Exceptions can be categorized in two ways:

1. Built-in Exceptions

 Checked Exception

 Unchecked Exception

2. user-defined Exceptions

1. Built-in Exception
Build-in Exception are pre-defined exception classes provided by Java to
handle common errors during program execution. There are two type of built-in
exception in java.

 Checked Exceptions

Checked exceptions are called compile-time exceptions because these


exceptions are checked at compile-time by the compiler. Examples of Checked
Exception are listed below:

 ClassNotFoundException: Throws when the program tries to load a class at


runtime but the class is not found because it's belong not present in the
correct location or it is missing from the project.

 InterruptedException: Thrown when a thread is paused and another thread


interrupts it.

 IOException: Throws when input/output operation fails.

 InstantiationException: Thrown when the program tries to create an object


of a class but fails because the class is abstract, an interface or has no
default constructor.

 SQLException: Throws when there is an error with the database.

 FileNotFoundException: Thrown when the program tries to open a file that


does not exist.

 Unchecked Exceptions

The unchecked exceptions are just opposite to the checked exceptions. The
compiler will not check these exceptions at compile time.

In simple words, if a program throws an unchecked exception and even if


we did not handle or declare it, the program would not give a compilation error.

Examples of Unchecked Exception are listed below:


 ArithmeticException: It is thrown when there is an illegal math operation.

 ClassCastException: It is thrown when we try to cast an object to a class it


does not belong to.

 NullPointerException: It is thrown when we try to use a null object (e.g.


accessing its methods or fields).

 ArrayIndexOutOfBoundsException: This occurs when we try to access an


array element with an invalid index.

 ArrayStoreException: This happens when we store an object of the wrong


type in an array.

 IllegalThreadStateException: It is thrown when a thread operation is not


allowed in its current state.

2. User-Defined Exception
Sometimes, the built-in exceptions in Java are not able to describe a certain
situation. In such cases, users can also create exceptions, which are called "user-
defined Exceptions".
Methods to Print the Exception Information

1. printStackTrace(): Prints the full stack trace of the exception, including the
name, message and location of the error.

2. toString(): Prints exception information in the format of the Name of the


exception.

3. getMessage() : Prints the description of the exception

Try-Catch Block

A try-catch block in Java is a mechanism to handle exception. The try block


contains code that might thrown an exception and the catch block is used to
handle the exceptions if it occurs.

Internal working of try-catch Block

 Java Virtual Machine starts executing the code inside the try block.

 If an exception occurs, the remaining code in the try block is skipped and
the JVM starts looking for the matching catch block.

 If a matching catch block is found, the code in that block is executed.

 After the catch block, control moves to the finally block (if present).

 If no matching catch block is found the exception is passed to the JVM


default exception handler.

 The final block is executed after the try catch block. regardless of whether
an exception occurs or not.

Syntax:

try {

// Code that may throw an exception

} catch (ExceptionType e) {

// Code to handle the exception

Nested try-catch:
In Java, you can place one try-catch block inside another to handle exceptions at
multiple levels.

public class NestedTryExample {


public static void main(String[] args) {

try {

[Link]("Outer try block");

try {

int a = 10 / 0; // This causes ArithmeticException

} catch (ArithmeticException e) {

[Link]("Inner catch: " + e);

String str = null;

[Link]([Link]()); // This causes


NullPointerException

} catch (NullPointerException e) {

[Link]("Outer catch: " + e);

finally Block:
The finally block is used to execute important code regardless of whether an
exception occurs or not.

Syntax:
try {

// Code that may throw an exception

catch (ExceptionType e) {

// Code to handle the exception

finally{

// cleanup code

Advantages of Exception Handling:


 Provision to complete program execution.

 Easy identification of program code and error-handling code.

 Propagation of errors.

 Meaningful error reporting.

 Identifying error types.

You might also like