Meet Sharma Ad024 ITS Report
Meet Sharma Ad024 ITS Report
ii
Acknowledgement
I take this opportunity to express my deep sense of gratitude to my ITS coordinator Mr. Hemant
Mittal Assistant Professor and Mr.Manish Kumar Jha Assistant Professor Department of
Computer Science and Engineering, Global Institute of Technology, Jaipur, for his valuable
guidance and cooperation throughout the Practical Training work. She provided constant
encouragement and unceasing enthusiasm at every stage of the Practical Training work.
I am grateful to our respected Dr. I. C. Sharma, Principal GIT for guiding me during Industrial
Training period.
I express my indebtedness to Dr. Pradeep Jha, Head of Department of Computer Science and
Engineering, Global Institute of Technology, Jaipur for providing me ample support during my
Industrial Training period. Without their support and timely guidance, the completion of our
Industrial Training would have seemed a farfetched dream. In this respect we find ourselves lucky
to have mentors of such a great potential.
Meet Sharma
RTU Roll No. - 23EGJAD024
B.Tech. III Semester, II Year, AI-DS
iii
Abstract
As of March 2024, Java 22 is the latest version. Java 8, 11, 17, and 21 are previous LTS versions
still officially supported.
iv
Table of Contents
Certificate..................................................................................................................ii
Acknowledgement.....................................................................................................iii
Abstract......................................................................................................................iv
Table of Content........................................................................................................v
List of Figures............................................................................................................vii
List of Tables.............................................................................................................viii
1. Introduction to Java
2. Java Fundamentals
v
4. Control Flow Statements
5.0 Arrays...............................................................................................................35
5.1 Strings...............................................................................................................35
6.0 Concept.............................................................................................................37
6.1 Prerequisites of OOP.........................................................................................37
6.2 Object and Class................................................................................................39
6.3 The 4 pillars of OOPs........................................................................................40
6.4 Advantages of OOPs..........................................................................................41
7. Exception Handling
7.0 Exceptions in Java..............................................................................................43
7.1 Exception hierarchy and types of exceptions.....................................................43
7.2 How does JVM handle exceptions.....................................................................45
7.3 How does programmer handle exceptions..........................................................46
Conclusion......................................................................................................47
References.......................................................................................................48
vi
List of Figures
15.) Fig 7.3 Call stack and searching the call stack for exception handler...................46
vii
List of Tables
1.) Table 3.1 Integer Datatypes....................................................................20
viii
Programming in Java/ AI-DS
CHAPTER 1
Introduction to Java
1.0 What is Java?
Java was developed by James Gosling at Sun Microsystems Inc in May 1995 and later acquired
by Oracle Corporation. It is a simple programming language. Java makes writing, compiling, and
debugging programming easy. It helps to create reusable code and modular programs. Java is a
class-based, object-oriented programming language and is designed to have as few implementation
dependencies as possible. A general-purpose programming language made for developers to write
once run anywhere that is compiled Java code can run on all platforms that support Java. Java
applications are compiled to byte code that can run on any Java Virtual Machine. The syntax of
Java is similar to C/C++.
1). Java evolved over time, with Java 2 introducing multiple configurations tailored for different
platforms, showcasing its versatility.
2). In 1997, Sun Microsystems aimed to formalize Java through the ISO standards body but
eventually withdrew from the process.
3). Despite not formalizing through ISO, Sun Microsystems offered most Java implementations at
no cost, earning revenue by licensing specialized products such as the Java Enterprise System.
Session 2024-25 9
Programming in Java/ AI-DS
4). A significant milestone in Java’s history occurred on November 13, 2006, when Sun
Microsystems released a large portion of the Java Virtual Machine (JVM) as free, open-source
software.
5). By May 8, 2007, the core JVM code was fully available under open-source distribution terms.
6). Java was designed with core principles: simplicity, robustness, security, high performance,
portability, multi-threading, and dynamic interpretation.
7). Today, Java continues to be a cornerstone of modern software development, widely used across
industries and platforms.
1.2 Overview of Java Editions (Java SE, Java EE, Java ME)
java.util − This package provides classes and interfaces (API’s) related to collection framework,
events, data structure and other utility classes such as date.
Session 2024-25 10
Programming in Java/ AI-DS
java.io − This package provides classes and interfaces for file operations, and other input and
output operations.
java.math − This package provides classes and interfaces for Mult precision arithmetic.
java.nio − This package provides classes and interfaces the non-blocking I/O framework for Java
java.sql − This package provides classes and interfaces for accessing/manipulating the data stored
in databases and data sources.
java.awt − This package provides classes and interfaces to create GUI components in Java.
java.text − This package provides classes and interfaces to handle text, dates, numbers, and
messages.
JEE − Java Enterprise Edition using this, you can develop Enterprise applications. This includes
1. Platform Independent
Compiler converts source code to byte code and then the JVM executes the byte code generated
by the compiler. This byte code can run on any platform be it Windows, Linux, or macOS which
Session 2024-25 11
Programming in Java/ AI-DS
means if we compile a program on Windows, then we can run it on Linux and vice versa. Each
operating system has a different JVM, but the output produced by all the OS is the same after the
execution of the byte code. That is why we call java a platform-independent language.
2. Object-Oriented Programming
Java is an object-oriented language, promoting the use of objects and classes. Organizing the
program in terms of a collection of objects is a way of object-oriented programming, each of which
represents an instance of the class.
Encapsulation
Inheritance
Polymorphism
3. Simplicity
Java’s syntax is simple and easy to learn, especially for those familiar with C or C++. It eliminates
complex features like pointers and multiple inheritances, making it easier to write, debug, and
maintain code.
4. Robustness
Java language is robust which means reliable. It is developed in such a way that it puts a lot of
effort into checking errors as early as possible, that is why the java compiler can detect even those
errors that are not easy to detect by another programming language. The main features of java that
make it robust are garbage collection, exception handling, and memory allocation.
5. Security
In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it shows
ArrayIndexOutOfBound Exception if we try to do so. That’s why several security flaws like stack
corruption or buffer overflow are impossible to exploit in Java. Also, java programs run in an
environment that is independent of the os(operating system) environment which makes java
programs more secure.
6. Distributed
We can create distributed applications using the java programming language. Remote Method
Invocation and Enterprise Java Beans are used for creating distributed applications in java. The
java programs can be easily distributed on one or more systems that are connected to each other
through an internet connection.
Session 2024-25 12
Programming in Java/ AI-DS
7. Multithreading
Java supports multithreading, enabling the concurrent execution of multiple parts of a program.
This feature is particularly useful for applications that require high performance, such as games
and real-time simulations.
8. Portability
As we know, java code written on one machine can be run on another machine. The platform-
independent feature of java in which its platform-independent bytecode can be taken to any
platform for execution makes java portable. WORA(Write Once Run Anywhere) makes java
application to generates a ‘.class’ file that corresponds to our applications(program) but contains
code in binary format. It provides ease t architecture-neutral ease as bytecode is not dependent on
any machine architecture. It is the primary reason java is used in the enterprising IT industry
globally worldwide.
9. High Performance
Java architecture is defined in such a way that it reduces overhead during the runtime and at
sometimes java uses Just In Time (JIT) compiler where the compiler compiles code on-demand
basis where it only compiles those methods that are called making applications to execute faster.
Session 2024-25 13
Programming in Java/ AI-DS
Chapter – 2
Java Fundamentals
2.0 Java Development Kit (JDK)
The Java Development Kit (JDK) is a cross-platformed software development environment that
offers a collection of tools and libraries necessary for developing Java-based software applications
and applets. It is a core package used in Java, along with the JVM (Java Virtual Machine) and the
JRE (Java Runtime Environment).
Beginners often get confused with JRE and JDK, if you are only interested in running Java
programs on your machine then you can easily do it using Java Runtime Environment. However,
if you would like to develop a Java-based software application then along with JRE you may need
some additional necessary tools, which is called JDK.
The Java Runtime Environment in JDK is usually called Private Runtime because it is separated
from the regular JRE and has extra content. The Private Runtime in JDK contains a JVM and all
the class libraries present in the production environment, as well as additional libraries useful to
developers, e.g, internationalization libraries and the IDL libraries.
Most Popular JDKs:
Session 2024-25 14
Programming in Java/ AI-DS
Oracle JDK: the most popular JDK and the main distributor of Java11,
OpenJDK: Ready for use: JDK 15, JDK 14, and JMC,
Azul Systems Zing: efficient and low latency JDK for Linux os,
Azul Systems: based Zulu brand for Linux, Windows, Mac OS X,
IBM J9 JDK: for AIX, Linux, Windows, and many other OS,
Amazon Corretto: the newest option with the no-cost build of OpenJDK and long-term support.
The Java Runtime Environment, or JRE, is a software layer that runs on top of a computer’s
operating system software and provides the class libraries and other resources that a specific Java
program requires to run.
The JRE combines Java code created by using the JDK with the necessary libraries required to run
it on a JVM and then creates an instance of the JVM that runs the resulting program. JVMs are
available for multiple operating systems, and programs created with the JRE run on all of them. In
this way, the Java Runtime Environment enables a Java program to run in any operating system
without modification.
First, the source ‘.java’ file is passed through the compiler, which then encodes the source code
into a machine-independent encoding, known as Bytecode. The content of each class contained in
the source file is stored in a separate ‘.class’ file. While converting the source code into the
bytecode, the compiler follows the following steps:
Step 1: Parse: Reads a set of *.java source files and maps the resulting token sequence into AST
(Abstract Syntax Tree)-Nodes.
Step 2: Enter: Enters symbols for the definitions into the symbol table.
Step 3: Process annotations: If Requested, processes annotations found in the specified compilation
units.
Step 4: Attribute: Attributes the Syntax trees. This step includes name resolution, type checking
and constant folding.
Session 2024-25 15
Programming in Java/ AI-DS
Step 5: Flow: Performs dataflow analysis on the trees from the previous step. This includes checks
for assignments and reachability.
Step 6: Desugar: Rewrites the AST and translates away some syntactic sugar.
Step 7: Generate: Generates ‘. Class’ files.[2]
The class files generated by the compiler are independent of the machine or the OS, which allows
them to be run on any system. To run, the main class file (the class that contains the method main)
is passed to the JVM and then goes through three main stages before the final machine code is
executed. These stages are:
These states do include:
ClassLoader
Bytecode Verifier
Just-In-Time Compiler
Session 2024-25 16
Programming in Java/ AI-DS
Rules
1. package statement
Session 2024-25 17
Programming in Java/ AI-DS
- but when we write a package statement we have to write as a first line in the program
2. import statement
-import statement is used to import and use the existing packages both use defined and predefined
packages -writing import statement is optional
-but when we write we must write after package statement and before the class declaration
-If we want to import multiple packages, we must write multiple packages and we can write any
number of import statements
3. class Declaration
-class contains a set of variables and methods which are together called as members of the class
- we can write any number of variables and methods inside the class
4. main() method
- java program execution done by JVM and java program execution begin from main() method
statements;
Chapter 3
Session 2024-25 18
Programming in Java/ AI-DS
3.0 Datatypes
Data types are used to create the variables by deciding what type values we are storing, what is the
size required and what is the range allowed.
- primitive data types are the basic data types or fundamental data types which are used to store
single value.
-derived data types are the predefined data types which are used to store multiple values of same
type. Eg: Arrays
-user defined data types are defined by user or programmer which are used to store multiple values
of different type. Eg: classes
Primitive data types are the basic data types or fundamental data types which are used to store
single value. -We have totally 8 primitive data types which are classified into following 4
categories
1. Integer category
If we write any number either +ve or -ve without any decimal part, then it is called as integer.
-To store this kind of integer we must use the integer category.
Session 2024-25 19
Programming in Java/ AI-DS
2. Floating-point category
-If we write any number either +ve or -ve with decimal part then it is called as floating-point values
-To store this kind of floating-point value we must use the floating-point category.
3. Character category
- whenever we write single character between single cotes then it is called as character value
-To store this kind of character we must use this character category.
4. Boolean Category
-This category is used to store logical values like true or false (in lower case)
Variable is container that store a value. This value can be changed during the execution of the
program.
Declaration of variables means the process of choosing memory locations by choosing the type of
data,size and required range.
Session 2024-25 20
Programming in Java/ AI-DS
syntax:
Variable initialization
When we declare variables and not initialized with any value then they automatically initialized
with default values. But if we want to initialize variables with our own values then we have to go
for variable initialization.
Syntax:
Example:
Variable assignment
Keywords
-Keywords are the predefined words or reserved words which are given by java people, which are
used to implement different java concepts
-In Java totally 50 keywords which are all defined in lower case
-Each keyword has its own meaning & purpose that we never change.
Session 2024-25 21
Programming in Java/ AI-DS
Identifiers
An identifier is a name given to a class or method or variable,... To identify and access in the
application
1. Identifier must contain chars only from character set a-z, A-Z, 0-9, $,
2.Identifier must not begin with any digit, but it can begin with either alphabet or $ or _ and it must
not be any value
6. We can also use predefined class names or methods names as identifier but it is not
recommended.
Session 2024-25 22
Programming in Java/ AI-DS
3.3 Operators
Operators in Java are the symbols used for performing specific operations in Java. Operators make
tasks like addition, multiplication, etc which look easy although the implementation of these tasks
is quite complex.[2]
There are multiple types of operators in Java all are mentioned below:
1. Arithmetic Operators
They are used to perform simple arithmetic operations on primitive and non-primitive data types.
*: Multiplication
/: Division
%: Modulos
+: Addition
–: Subtraction
2. Unary Operators
Unary operators need only one operand. They are used to increment, decrement, or negate a value.
– : Unary minus, used for negating the values.
+ : Unary plus indicates the positive value (numbers are positive without this, however). It
performs an automatic conversion to int when the type of its operand is the byte, char, or short.
This is called unary numeric promotion.
++ : Increment operator, used for incrementing the value by 1. There are two varieties of increment
operators.
Post-Increment: Value is first used for computing the result and then incremented.
Pre-Increment: Value is incremented first, and then the result is computed.
– – : Decrement operator, used for decrementing the value by 1. There are two varieties of
decrement operators.
Session 2024-25 23
Programming in Java/ AI-DS
Post-decrement: Value is first used for computing the result and then decremented.
Pre-Decrement: The value is decremented first, and then the result is computed.
3. Assignment Operator
‘=’ 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.
variable = value;
In many cases, the assignment operator can be combined with other operators to build a shorter
version of the statement called a Compound Statement. For example, instead of a = a+5, we can
write a += 5.
+=, for adding the left operand with the right operand and then assigning it to the variable on the
left.
-=, for subtracting the right operand from the left operand and then assigning it to the variable on
the left.
*=, for multiplying the left operand with the right operand and then assigning it to the variable on
the left.
/=, for dividing the left operand by the right operand and then assigning it to the variable on the
left.
%=, for assigning the modulo of the left operand by the right operand and then assigning it to the
variable on the left.
4. Relational Operators
These 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
Session 2024-25 24
Programming in Java/ AI-DS
!=, Not Equal to returns true if the left-hand side is not equal to the right-hand side.
<, less than: returns true if the left-hand side is less than the right-hand side.
<=, less than or equal to returns true if the left-hand side is less than or equal to the right-hand side.
>, Greater than: returns true if the left-hand side is greater than the right-hand side.
>=, Greater than or equal to returns true if the left-hand side is greater than or equal to the right-
hand side.
5. Logical Operators
These operators are used to perform “logical AND” and “logical OR” operations, i.e., a function
similar to AND gate and OR gate in digital electronics. One thing to keep in mind is the second
condition is not evaluated if the first one is false, i.e., it has a short-circuiting effect. Used
extensively to test for several conditions for making a decision. Java also has “Logical NOT”,
which returns true when the condition is false and vice-versa
&&, Logical AND: returns true when both conditions are true.
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 above statement means that if the condition evaluates to true, then execute the statements after
the ‘?’ else execute the statements after the ‘:’.
7. Bitwise Operators
Session 2024-25 25
Programming in Java/ AI-DS
These operators are used to perform the manipulation of individual bits of a number. They can be
used with any of the integer types. They are used when performing update and query operations
of the Binary indexed trees.
&, Bitwise AND operator: returns bit by bit AND of input values.
|, Bitwise OR operator: returns bit by bit OR of input values.
^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
~, Bitwise Complement Operator: This is a unary operator which returns the one’s complement
representation of the input value, i.e., with all bits inverted.
8. Shift Operators
These operators are used to shift the bits of a number left or right, thereby multiplying or dividing
the number by two, respectively. They can be used when we have to multiply or divide a number
by two. General format-
Numbershift_opnumber_of_places_to_shift;
<<, Left shift operator shifts the bits of the number to the left and fills 0 on voids left as a result.
Similar effect as multiplying the number with some power of two.
>>, Signed Right shift operator shifts the bits of the number to the right and fills 0 on voids left as
a result. The leftmost bit depends on the sign of the initial number. Similar effect to dividing the
number with some power of two.
>>>, Unsigned Right shift operator shifts the bits of the number to the right and fills 0 on voids
left as a result. The leftmost bit is set to 0.
9. instanceof operator
The instance of the operator is used for type checking. It can be used to test if an object is an
instance of a class, a subclass, or an interface. General format-
Session 2024-25 26
Programming in Java/ AI-DS
Session 2024-25 27
Programming in Java/ AI-DS
Chapter 4
Control Flow Statements
A programming language uses control statements to control the flow of execution of a program
based on certain conditions. These are used to cause the flow of execution to advance and branch
based on changes to the state of a program.
1. if: 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. [4]
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. if statement accepts boolean values
– if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement
will consider the immediate one statement to be inside its block. For example,
if(condition) //Assume condition is true
statement1; //part of if block
statement2; // separate from if block
Session 2024-25 28
Programming in Java/ AI-DS
nested-if: A nested if is an if statement that is the target of another if or else. Nested if statements
mean an if statement inside an if statement. Yes, java allows us to nest if statements within if
statements. i.e, we can place an if statement inside another if statement. [4]
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
Session 2024-25 29
Programming in Java/ AI-DS
if-else-if ladder: Here, a user can decide among multiple options.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. If none of the conditions
is true, then the final else statement will be executed. There can be as many as ‘else if’ blocks
associated with one ‘if’ block but only one ‘else’ block is allowed with one ‘if’ block.[4]
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
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.
Session 2024-25 30
Programming in Java/ AI-DS
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
java provides Three types of Conditional statements this second type is loop statement .
while loop: A while loop is a control flow statement that allows code to be executed repeatedly
based on a given Boolean condition. The while loop can be thought of as a repeating if statement.
Syntax :
while (boolean condition)
{
loop statements...
}
Session 2024-25 31
Programming in Java/ AI-DS
While loop starts with the checking of Boolean condition. If it evaluated to true, then the loop body
statements are executed otherwise first statement following the loop is executed. For this reason it
is also called Entry control loop
Once the condition is evaluated to true, the statements in the loop body are executed. Normally the
statements contain an update value for the variable being processed for the next iteration.
When the condition becomes false, the loop terminates which marks the end of its life cycle.
for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for
statement consumes the initialization, condition and increment/decrement in one line thereby
providing a shorter, easy to debug structure of looping.
Syntax:
for (initialization condition; testing condition;increment/decrement)
{
statement(s)
}
Session 2024-25 32
Programming in Java/ AI-DS
Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value.
It is also an Entry Control Loop as the condition is checked prior to the execution of the loop
statements.
Statement execution: Once the condition is evaluated to true, the statements in the loop body are
executed.
Increment/ Decrement: It is used for updating the variable for next iteration.
Loop termination:When the condition becomes false, the loop terminates marking the end of its
life cycle.
do while: do while loop is similar to while loop with only difference that it checks for condition
after executing the statements, and therefore is an example of Exit Control Loop.
Syntax:
do
{
statements..
}
while (condition);
do while loop starts with the execution of the statement(s). There is no checking of any condition
for the first time.
After the execution of the statements, and update of the variable value, the condition is checked
for true or false value. If it is evaluated to true, next iteration of loop starts.
Session 2024-25 33
Programming in Java/ AI-DS
When the condition becomes false, the loop terminates which marks the end of its life cycle.
It is important to note that the do-while loop will execute its statements atleast once before any
condition is checked, and therefore is an example of exit control loop.
Session 2024-25 34
Programming in Java/ AI-DS
Chapter 5
Arrays and Strings
5.1 Arrays
Arrays are fundamental structures in Java that allow us to store multiple values of the same type
in a single variable. They are useful for managing collections of data efficiently. Arrays in Java
work differently than they do in C/C++.
To declare an array in Java, use the following syntax:
type[] arrayName;
type: The data type of the array elements (e.g., int, String).
arrayName: The name of the array.
Since arrays are objects in Java, we can find their length using the object property length. This is
different from C/C++, where we find length using size of.
A Java array variable can also be declared like other variables with [] after the data type.
The variables in the array are ordered, and each has an index beginning with 0.
Java array can also be used as a static field, a local variable, or a method parameter.
An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a class,
depending on the definition of the array. In the case of primitive data types, the actual values might
be stored in contiguous memory locations (JVM does not guarantee this behavior). In the case of
class objects, the actual objects are stored in a heap segment.
5.2 Strings
In Java, a String is an object that represents a sequence of characters. Java provides a robust and
flexible API for handling strings, allowing for various operations such as concatenation,
comparison, and manipulation. Strings are the type of objects that can store the character of values
and in Java, every character is stored in 16 bits i,e using UTF 16-bit encoding. A string acts the
same as an array of characters in Java.
Example:
Session 2024-25 35
Programming in Java/ AI-DS
// Main Function
System.out.println(str);
Session 2024-25 36
Programming in Java/ AI-DS
Chapter 6
Object Oriented Programming in Java
6.0 Concept
Object-Oriented Programming or Java OOPs concept refers to 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.
Object-oriented programming aims to implement real-world entities like inheritance, hiding,
polymorphism, etc. in programming. The main aim of OOPs is to bind together the data and the
functions that operate on them so that no other part of the code can access this data except that
function.[5]
Session 2024-25 37
Programming in Java/ AI-DS
Let us discuss prerequisites by polishing concepts of method declaration and message passing.
Starting with the method declaration consists of six components:
Access Modifier: Defines the access type of the method i.e. from where it can be accessed in your
application. In Java, there are 4 types of access specifiers:
protected: Accessible within the package in which it is defined and in its subclass(es) (including
subclasses declared outside the package).
default (declared/defined without using any modifier): Accessible within the same class and
package within which its class is defined.
The return type: The data type of the value returned by the method or void if it does not return a
value.
Method Name: The rules for field names apply to method names as well, but the convention is a
little different.
Parameter list: Comma-separated list of the input parameters that are defined, preceded by their
data type, within the enclosed parentheses. If there are no parameters, you must use empty
parentheses ().
Exception list: The exceptions you expect the method to throw. You can specify these exception(s).
Method body: It is the block of code, enclosed between braces, that you need to execute to perform
your intended operations.
Message Passing: Objects communicate with one another by sending and receiving information to
each other. A message for an object is a request for execution of a procedure and therefore will
invoke a function in the receiving object that generates the desired results. Message passing
involves specifying the name of the object, the name of the function and the information to be
sent.[5]
Session 2024-25 38
Programming in Java/ AI-DS
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, you can
create multiple objects with the same behavior instead of writing their code multiple times. This
includes classes for objects occurring more than once in your code. In general, class declarations
can include these components in order:
Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any, preceded
by the keyword implements. A class can implement more than one interface.
What is Object?
An object is a basic unit of Object-Oriented Programming that represents real-life entities. A
typical Java program creates many objects, which as you know, interact by invoking methods. The
objects are what perform your code, they are the part of your code visible to the viewer/user. An
object mainly consists of:
State: It is represented by the attributes of an object. It also reflects the properties of an object.
Behavior: It is represented by the methods of an object. It also reflects the response of an object to
other objects.
Session 2024-25 39
Programming in Java/ AI-DS
Identity: It is a unique name given to an object that enables it to interact with other objects.
Method: A method is a collection of statements that perform some specific task and return the
result to the caller. A method can perform some specific task without returning anything. Methods
allow us to reuse the code without retyping it, which is why they are considered time savers. In
Java, every method must be part of some class, which is different from languages like C, C++, and
Python.[5]
Pillar 1: 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.
Data Abstraction may also be defined as the process of identifying only the required characteristics
of an object, ignoring the irrelevant details. The properties and behaviors of an object differentiate
it from other objects of similar type and also help in classifying/grouping the object.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the car speed or applying brakes will stop the car, but he does not know
how on pressing the accelerator, the speed is actually increasing. He does not know about the inner
mechanism of the car or the implementation of the accelerators, brakes etc. in the car. This is what
abstraction is.
In Java, abstraction is achieved by interfaces and abstract classes. We can achieve 100%
abstraction using interfaces.
The abstract method contains only method declaration but not implementation.
Pillar 2: Encapsulation
It is defined as the wrapping up of data under a single unit. It is the mechanism that binds together
the code and the data it manipulates. 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.
Technically, in encapsulation, the variables or the data in a class is hidden from any other class
and can be accessed only through any member function of the class in which they are declared.
Session 2024-25 40
Programming in Java/ AI-DS
In encapsulation, the data in a class is hidden from other classes, which is like what data-hiding
does. So, the terms “encapsulation” and “data-hiding” are used interchangeably.
Encapsulation can be achieved by declaring all the variables in a class as private and writing public
methods in the class to set and get the values of the variables.
Pillar 3: Inheritance
Pillar 4: 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.
Session 2024-25 41
Programming in Java/ AI-DS
Object-oriented programming (OOP) offers several key advantages over procedural programming:
OOP promotes code reusability: By using objects and classes, you can create reusable components,
leading to less duplication and more efficient development.
OOP enhances code organization: It provides a clear and logical structure, making the code easier
to understand, maintain, and debug.
OOP supports the DRY (Don’t Repeat Yourself) principle: This principle encourages minimizing
code repetition, leading to cleaner, more maintainable code. Common functionalities are placed in
a single location and reused, reducing redundancy.
OOP enables faster development: By reusing existing code and creating modular components,
OOP allows for quicker and more efficient application development
Session 2024-25 42
Programming in Java/ AI-DS
Chapter 7
Exception Handling in Java
7.0 Exceptions in Java
Exception Handling in Java is one of the effective means to handle runtime errors so that the
regular flow of the application can be preserved. Java Exception Handling is a mechanism to
handle runtime errors such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
In Java, Exception is an unwanted or unexpected event, which occurs during the execution of a
program, i.e. at run time, that disrupts the normal flow of the program’s instructions. Exceptions
can be caught and handled by the program. When an exception occurs within a method, it creates
an object. This object is called the exception object. It contains information about the exception,
such as the name and description of the exception and the state of the program when the exception
occurred.
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.
Session 2024-25 43
Programming in Java/ AI-DS
Types of Exceptions
Java defines several types of exceptions that relate to its various class libraries. Java also allows
users to define their own exceptions.
Exceptions can be categorized in two ways:
Built-in Exceptions
User-Defined Exceptions
1. Built-in Exceptions
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are
suitable to explain certain error situations.
Checked Exceptions: Checked exceptions are called compile-time exceptions because these
exceptions are checked at compile-time by the compiler.
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 didn’t handle or declare it, the program would not give a
compilation error.
Session 2024-25 44
Programming in Java/ AI-DS
2. User-Defined Exceptions:
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’.
If it finds an appropriate handler, then it passes the occurred exception to it. An appropriate handler
means the type of exception object thrown matches the type of exception object it can handle.
If the run-time system searches all the methods on the call stack and couldn’t have found the
appropriate handler, then the run-time system handover the Exception Object to the default
exception handler, which is part of the run-time system. This handler prints the exception
information in the following format and terminates the program abnormally.
Session 2024-25 45
Programming in Java/ AI-DS
Fig 7.3 Call stack and searching the call stack for exception handler
Session 2024-25 46
Programming in Java/ AI-DS
Conclusion
In conclusion, Java stands as one of the most versatile and widely used programming languages in
modern software development. Its platform independence, achieved using the Java Virtual
Machine (JVM), allows developers to write code that can run on any system, making it a powerful
tool for cross-platform development. Throughout this report, we have explored key features such
as object-oriented programming (OOP), exception handling, multithreading, and the rich set of
APIs that contribute to Java's robustness and scalability.
Overall, Java’s balance between simplicity and functionality makes it an excellent language for
both beginners and experienced developers, providing a solid foundation for building complex,
secure, and efficient applications.
Session 2024-25 47
Programming in Java/ AI-DS
References
Session 2024-25 48