0% found this document useful (0 votes)
40 views48 pages

Meet Sharma Ad024 ITS Report

This Industrial Training Report focuses on programming in Java, detailing its history, features, and applications. Java is a high-level, object-oriented language known for its portability, robustness, and security, allowing developers to write code that runs on any platform. The document includes various sections on Java fundamentals, control flow, object-oriented programming, exception handling, and more.
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)
40 views48 pages

Meet Sharma Ad024 ITS Report

This Industrial Training Report focuses on programming in Java, detailing its history, features, and applications. Java is a high-level, object-oriented language known for its portability, robustness, and security, allowing developers to write code that runs on any platform. The document includes various sections on Java fundamentals, control flow, object-oriented programming, exception handling, and more.
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
You are on page 1/ 48

An

Industrial Training Report


on
Programming in JAVA
Submitted in partial fulfillment for the award of degree of
Bachelor of Technology
In
Computer Science and Engineering

Submitted to: Submitted By:


Dr. Pradeep Jha Meet Sharma

HOD-CSE/IT/AI&DS/IOT/CYBER SECURITY Dept. Roll no - 23EGJAD024

Department of Computer Science & Engineering


Global Institute of Technology
Jaipur (Rajasthan)-302022
Session: 2024-25
Certificate

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.

Place: GIT, Jaipur

Meet Sharma
RTU Roll No. - 23EGJAD024
B.Tech. III Semester, II Year, AI-DS

iii
Abstract

Java is a high-level, class-based, object-oriented programming language that is designed to have


as few implementations dependencies as possible. It is a general-purpose programming language
intended to let programmers write once, run anywhere (WORA),[16] meaning that compiled Java
code can run on all platforms that support Java without the need to recompile.[17] Java applications
are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of
the underlying computer architecture. The syntax of Java is like C and C++, but has fewer low-
level facilities than either of them. The Java runtime provides dynamic capabilities (such as
reflection and runtime code modification) that are typically not available in traditional compiled
languages.
Java was originally developed by James Gosling at Sun Microsystems. It was released in May
1995 as a core component of Sun's Java platform. The original and reference implementation Java
compilers, virtual machines, and class libraries were originally released by Sun under proprietary
licenses. As of May 2007, in compliance with the specifications of the Java Community Process,
Sun had relicensed most of its Java technologies under the GPL-2.0-only license. Oracle offers its
own HotSpot Java Virtual Machine; however, the official reference implementation is the
OpenJDK JVM which is free open-source software and used by most developers and is the default
JVM for almost all Linux distributions.[1]

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

1.0 What is Java? ............................................................................................. 9


1.1 History and evolution of Java..................................................................... 9
1.2 Overview of Java Editions (Java SE, Java EE, JavaME)............................10
1.3 Features of Java...........................................................................................11

2. Java Fundamentals

2.0 Java Development Kit (JDK).......................................................................14


2.1 Java Runtime Environment (JRE)................................................................15
2.2 Compilation and execution process in Java..................................................15
2.3 Java syntax and semantics............................................................................17

3. Data Types and Operators


3.0 Datatypes.......................................................................................................19
3.1 Variables and constant...................................................................................20
3.2 Keywords and Identifiers...............................................................................21
3.3 Operators........................................................................................................23

v
4. Control Flow Statements

4.0 Conditional statements: if, if-else, switch.......................................................28


4.1 Loops: for, while, do-while.............................................................................31
4.2 Breakcontinue, and return statements..............................................................34

5. Arrays and Strings

5.0 Arrays...............................................................................................................35
5.1 Strings...............................................................................................................35

6. Object Oriented Programming in Java

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

1.) fig 1.1 History of Java..............................................................................................10

2.) fig 2.1 Java Development Kit...................................................................................14

3.) Fig 2.2 Compilation and Execution process in Java................................................16


4.) Fig 2.3 Syntax of Java..............................................................................................17

5.) Fig 3.1 Keywords in Java........................................................................................22


6.) Fig 3.2 Operators in Java and their associativity.....................................................27
7.) Fig 4.1 If else condition...........................................................................................29

8.) Fig 4.2 Nested if-else..............................................................................................30


9.) fig 4.3.Flowchart of while loop...............................................................................32

10.) Fig 4.4 Flowchart of for loop................................................................................33

11.) Fig 6.1 OOPs in Java.............................................................................................37

12.) Fig 6.2 Access modifiers in Java .................................................................39

13.) Fig 7.1 Exception hierarchy..................................................................................43

14.) Fig 7.2 Types of Exceptions..................................................................................44

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 is a class-based, object-oriented programming language that is designed to have as few


implementation dependencies as possible. It is intended to let application developers write once,
and run anywhere (WORA), meaning that compiled Java code can run on all platforms that support
Java without the need for recompilation. Java was first released in 1995 and is widely used for
developing applications for desktop, web, and mobile devices. Java is known for its simplicity,
robustness, and security features, making it a popular choice for enterprise-level applications.

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.1 History of Java


Java’s history is as interesting as it is impactful. The journey of this powerful programming
language began in 1991 when James Gosling, Mike Sheridan, and Patrick Naughton, a team
of engineers at Sun Microsystems known as the “Green Team,” set out to create a new language
initially called “Oak.” Oak was later renamed Java, inspired by Java coffee, and was first publicly
released in 1996 as Java 1.0. This initial version provided a no-cost runtime environment across
popular platforms, making it accessible to a broad audience. Arthur Van Hoff rewrote the Java
1.0 compiler to strictly comply with its specifications, ensuring its reliability and cross-platform
capabilities.

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.

Fig 1.1 History of Java

1.2 Overview of Java Editions (Java SE, Java EE, Java ME)

Java provides three editions JSE, JEE, JME.


JSE − Java Standard Edition using this, you can develop stand-alone applications. This provides
the following packages −
java.lang − This package provides the language basics.

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.net − This package provides classes and interfaces related to networking.


java.security − This package provides classes and interfaces such as key generation, encryption,
and decryption which belongs to the security framework.

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.

java.rmi − Provides the RMI package.


java.time − The main API for dates, times, instants, and durations.
java.beans − The java.beans package contains classes and interfaces related to JavaBeans
components.

JEE − Java Enterprise Edition using this, you can develop Enterprise applications. This includes

API’s like Servlets, WebSocket, JavaServerFaces, Unified Expression Language.


Web service specifications like API for Restful web services, API for JSON processing, API for
JSON Bonding, Architecture for XML binding, API for XML web services.
Enterprise specifications like Dependency Injection, Enterprise JavaBean, Java Persistence API,
Java Transaction API.
JME − Java Micro Edition using this, you can develop applications that run on small scale devices
like mobile phones.

1.3 Features of Java

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.

The four main concepts of Object-Oriented programming are:


Abstraction

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.

Fig 2.1 Java Development kit

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.

2.1 Java Runtime Environment (JRE)

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.

2.2 Compilation and execution process in Java

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

Fig 2.2 Compilation and Execution process in Java

Session 2024-25 16
Programming in Java/ AI-DS

2.3 Java syntax and semantics


In any programming language the program has to be written in a format that is understandable by
its compiler, Following is the structure of java language.

Fig 2.3 Syntax of Java

Rules

1. package statement

- Package statement is used to create user defined packages

Session 2024-25 17
Programming in Java/ AI-DS

-writing package statement is optional

- but when we write a package statement we have to write as a first line in the program

- At most one package statement We can write

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

- using import statement, we can import only one package at a time

-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 declaration is also optional

- we can write 0 or more number of classes

-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

- JVM always expect main() method like follows

public static void main(String args[]){

statements;

- in main() method we can write any number of statements.

Chapter 3

Session 2024-25 18
Programming in Java/ AI-DS

Data Types and Operators

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.

We have following 3 types of data types,

1. Primitive data types

- primitive data types are the basic data types or fundamental data types which are used to store
single value.

Eg: int, float,.

2. Derived data types

-derived data types are the predefined data types which are used to store multiple values of same
type. Eg: Arrays

3. User defined data types

-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

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.

Eg: 10, -78,23, ...

-To store this kind of integer we must use the integer category.

Session 2024-25 19
Programming in Java/ AI-DS

-In this category we have following 4 data types

Table 3.1 Integer Datatypes

2. Floating-point category

-If we write any number either +ve or -ve with decimal part then it is called as floating-point values

Eg: 10.7, -78.1,23.9,...

-To store this kind of floating-point value we must use the floating-point category.

- In this category we have following 2 data types

3. Character category

- whenever we write single character between single cotes then it is called as character value

Eg: 'a', 'A','8', '#',...

-To store this kind of character we must use this character category.

- In this category we have following 1 data type

4. Boolean Category

-This category is used to store logical values like true or false (in lower case)

- In this category we have following one data type.

3.1 Variables and Constants

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:

datatype var1, var2, var3,

Eg: double salary; char gender; boolean check;

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:

datatype var1-value1,var2=value2, var3-value3,....;

Example:

double salary=100000.0; char gender='m'; Boolean check=true;

Variable assignment

-variable assignment means changing the value of the variable

-we always do variable assignment only after declaration of variable

- we can do variable assignment any number of times

Eg: int age=20;

3.2 Keywords and Identifiers

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

Fig 3.1 Keywords in Java

Identifiers

An identifier is a name given to a class or method or variable,... To identify and access in the
application

Rules for identifiers

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

3. It must not be any java keyword

4. Length can be anything, but it is recommended it should not exceed 16 chars

5. It should be short and meaningful/

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]

Types of Operators in Java

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.

! : Logical not operator, used for inverting a boolean value.

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.

The general format of the assignment operator is:

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

Some of the relational operators are-


==, Equal to returns true if the left-hand side is equal to the right-hand side.

!=, 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

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.

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?iftrue:iffalse

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-

object instance of class/subclass/interface

Session 2024-25 26
Programming in Java/ AI-DS

Fig 3.2 Operators in Java and their associativity

Session 2024-25 27
Programming in Java/ AI-DS

Chapter 4
Control Flow Statements

4.0 Conditional statements: if, if-else, switch

Decision Making in programming is similar to decision-making in real life. In programming also


face some situations where we want a certain block of code to be executed when some condition
is fulfilled.

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

// Here if the condition is true


// if block will consider statement1 as its part and executes in only true condition
// statement2 will be separate from the if block so it will always executes whether the condition
is true or false.

Session 2024-25 28
Programming in Java/ AI-DS

Fig 4.1 If else condition

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

Fig 4.2 Nested if-else

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;
}

4.1 Loops: for, while, do-while

Looping in programming languages is a feature which facilitates the execution of a set of


instructions/functions repeatedly while some condition evaluates to true. Java provides three ways
for executing the loops. While all the ways provide similar basic functionality, they differ in their
syntax and condition checking time.

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

fig 4.3 Flowchart of while loop

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

Fig 4.4 Flowchart of for loop


Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An
already declared variable can be used or a variable can be declared, local to loop only.

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.

4.2 Break, continue, and return 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:

1) Terminate a sequence in a switch statement (discussed above).


2) To exit a loop.

3) 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.
Return: 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.

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.

In Java, all arrays are dynamically allocated.


Arrays may be stored in contiguous memory [consecutive memory locations].

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

String name = "Geeks";

Below is an example of a String in Java:

public class StringExample {

// Main Function

public static void main(String args[])

String str = new String("example");

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]

Fig 6.1 OOPs in Java

6.1 Prerequisites of OOPs

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:

public: Accessible in all classes in your application.

protected: Accessible within the package in which it is defined and in its subclass(es) (including
subclasses declared outside the package).

private: Accessible only within the class in which it is defined.

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

Fig 6.2 Access modifiers in Java


6.2 Class and Object
What is Class?

A class is a user-defined blueprint or prototype from which objects are created. It represents the
set of properties or methods that are common to all objects of one type. Using classes, 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:

Modifiers: A class can be public or have default access.


Class name: The class name should begin with the initial letter capitalized by convention.
Superclass (if any): The name of the class’s parent (superclass), if any, preceded by the keyword
extends. A class can only extend (subclass) one parent.

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.

Body: The class body is surrounded by braces, { }.

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]

6.3 The four pillars of OOPs

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

Inheritance is an important pillar of 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.
We are achieving inheritance by using extends keyword. Inheritance is also known as “is-a”
relationship.
Let us discuss some frequently used important terminologies:
Superclass: The class whose features are inherited is known as superclass (also known as base or
parent class).
Subclass: The class that inherits the other class is known as subclass (also known as derived or
extended or child class). The subclass can add its own fields and methods in addition to the
superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new
class and there is already a class that includes some of the code that we want, we can derive our
new class from the existing class. By doing this, we are reusing the fields and methods of the
existing class.

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.

6.4 Advantage of OOPs over Procedure-oriented programming language

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.

7.1 Exception hierarchy and types of exceptions


Exception Hierarchy

All exception and error types are subclasses of the class Throwable, which is the base class of the
hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that
user programs should catch. NullPointerException is an example of such an exception. Another
branch, Error is used by the Java run-time system(JVM) to indicate errors having to do with the
run-time environment itself(JRE). StackOverflowError is an example of such an error.

Fig 7.1 Exception hierarchy

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

Fig 7.2 Types of 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’.

7.2 How Does JVM Handle an Exception?


Default Exception Handling: Whenever inside a method, if an exception has occurred, the method
creates an Object known as an Exception Object and hands it off to the run-time system(JVM).
The exception object contains the name and description of the exception and the current state of
the program where the exception has occurred. Creating the Exception Object and handling it in
the run-time system is called throwing an Exception. There might be a list of the methods that had
been called to get to the method where an exception occurred. This ordered list of methods is called
Call Stack. Now the following procedure will happen.
The run-time system searches the call stack to find the method that contains a block of code that
can handle the occurred exception. The block of the code is called an Exception handler.
The run-time system starts searching from the method in which the exception occurred and
proceeds through the call stack in the reverse order in which methods were called.

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

7.3 How Programmer Handle an Exception?


Customized Exception Handling: Java exception handling is managed via five keywords: try, catch,
throw, throws, and finally. Briefly, here is how they work. Program statements that you think can
raise exceptions are contained within a try block. If an exception occurs within the try block, it is
thrown. Your code can catch this exception (using catch block) and handle it in some rational
manner. System-generated exceptions are automatically thrown by the Java run-time system. To
manually throw an exception, use the keyword throw. Any exception that is thrown out of a method
must be specified as such by a throws clause. Any code that absolutely must be executed after a
try block completes is put in a final block.

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.

Furthermore, Java’s strong emphasis on security, memory management, and backward


compatibility continues to make it a preferred choice for developing enterprise-level applications,
mobile apps (via Android), and web services. The language's constant evolution, supported by a
vast community and Oracle's regular updates, ensures that it remains relevant in an ever-changing
technological landscape.

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

1.) Java programming language: https://en.wikipedia.org/wiki/Java_(programming_language)

2.) Operators in Java Availabe: https://www.geeksforgeeks.org/operators-in-java/

3.) Execution and compilation of a Java Program: https://www.geeksforgeeks.org/compilation-


execution-java-program/

4.) Conditional Statements in Java: https://www.geeksforgeeks.org/decision-making-javaif-else-


switch-break-continue-jump/

5.) Object Oriented Programming in Java: https://www.geeksforgeeks.org/object-oriented-


programming-oops-concept-in-java/

Session 2024-25 48

You might also like