0% found this document useful (0 votes)
17 views350 pages

Java Software Programmer Handbook

The document is a Participant Handbook for the Software Programmer - Java course, aligned with National Occupational Standards for application development in the IT-ITeS sector. It outlines training content, objectives, and key learning outcomes, aiming to equip participants with the necessary skills and knowledge for software development. The handbook includes modules on programming, algorithms, and employability skills, and is published by the IT-ITeS Sector Skills Council NASSCOM.

Uploaded by

elakkiya2111nov
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)
17 views350 pages

Java Software Programmer Handbook

The document is a Participant Handbook for the Software Programmer - Java course, aligned with National Occupational Standards for application development in the IT-ITeS sector. It outlines training content, objectives, and key learning outcomes, aiming to equip participants with the necessary skills and knowledge for software development. The handbook includes modules on programming, algorithms, and employability skills, and is published by the IT-ITeS Sector Skills Council NASSCOM.

Uploaded by

elakkiya2111nov
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

Courseware

Software Programmer - Java

English (en-US)
Par�cipant Handbook

Sector
IT-ITeS

Sub-Sector
IT Services
Occupa�on
Applica�on Development

Reference ID: SSC/Q0510, Version 1.0


NSQF level: 4

So�ware Programmer
- Java

Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Published by
IT- ITeS Sector Skills Council NASSCOM
Plot No – 7, 8, 9 & 10, Sector 126, Noida, Uttar Pradesh - 201303
Email: ssc@[Link]
Website: [Link]
Phone: 0120 4990111 - 0120 4990172

First Edition, March 2023


This book is sponsored by IT- ITeS Sector Skills Council NASSCOM
Printed in India by NASSCOM

Under Creative Commons License:


Attribution-ShareAlike: CC BY-SA

This license lets others remix, tweak, and build upon your work even for commercial purposes, as long as they credit you and
license their new creations under the identical terms. This license is often compared to “copyleft” free and open-source software
licenses. All new works based on yours will carry the same license, so any derivatives will also allow commercial use. This is the
license used by Wikipedia and is recommended for materials that would benefit from incorporating content from Wikipedia and
similarly licensed projects.

Disclaimer
The information contained herein has been obtained from various reliable sources. IT- ITeS Sector Skills Council
NASSCOM disclaims all warranties to the accuracy, completeness or adequacy of such information. NASSCOM shall
have no liability for errors, omissions, or inadequacies, in the information contained herein, or for interpretations
thereof. Every effort has been made to trace the owners of the copyright material included in the book. The
publishers would be grateful for any omissions brought to their notice for acknowledgements in future editions of
the book. No entity in NASSCOM shall be responsible for any loss whatsoever, sustained by any person who relies
on this material. All pictures shown are for illustration purpose only. The coded boxes in the book called Quick
Response Code (QR code) will help to access the e-resources linked to the content. These QR codes are generated
from links and YouTube video resources available on Internet for knowledge enhancement on the topic and are not
created by NASSCOM. Embedding of the link or QR code in the content should not be assumed endorsement of
any kind. NASSCOM is not responsible for the views expressed or content or reliability of linked videos. NASSCOM
cannot guarantee that these links/QR codes will work all the time as we do not have control over availability of the
linked pages.

Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Skilling is building a be�er India.
If we have to move India towards
development then Skill Development
should be our mission.

Shri Narendra Modi


Prime Minister of India

iii
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
COMPLIANCE TO
QUALIFICATION PACK – NATIONAL OCCUPATIONAL
STANDARDS
is hereby issued by the
IT – ITeS Sector Skill Council NASSCOM
for

SKILLING CONTENT: PARTICIPANT HANDBOOK


Complying to National Occupational Standards of
Job Role/ Qualification Pack: ‘Software Programmer - Java’ QP No. ‘SSC/Q0510, NSQF Level 4’

Date of Issuance: November 17th, 2022

Valid up to: November 17th, 2025 Authorised Signatory


(IT – ITeS Sector Skill Council NASSCOM)
* Valid up to the next review date of the Qualification Pack

iv
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Acknowledgements
NASSCOM would like to express its gratitude towards company representatives, who belieive in our
vision of improving employability for the available pool of engineering students. SSC NASSCOM makes
the process easier by developing and implementing courses that are relevant to the projected industry
requirements.
The aim is to close the industry-academia skill gap and create a talent pool that can withstand upcoming
externalities within the IT-BPM industry.
This initiative is the belief of NASSCOM and concerns every stakeholder – students, academia, and
industries. The ceaseless support and tremendous amount of work offered by IT-ITeS members to
strategize meaningful program training materials, both from the context of content and design are
truly admirable.
We would also like to show our appreciation to Orion ContentGrill Pvt. Ltd. for their persistent effort,
and for the production of this course publication.

v
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

About this book


This Participant Handbook has been prepared as a guide for participants who aim to acquire the
knowledge and skills required to perform various activities in the role of software developer. Its con-
tent is aligned with the latest Qualification Pack (QP) designed for the job role. With the guidance of a
qualified instructor, participants will be equipped to perform the following efficiently in a job role:
• Knowledge and Understanding: Operational knowledge and understanding relevant to performing
the required functions.
• Performance Criteria: The skills required through practical training to perform the operations re-
quired by the applicable quality standards.
• Business acumen: Ability to make appropriate operational decisions regarding the work area.

The Participant Handbook details the relevant activities to be performed by the software -Programmer.
After studying this handbook, the job holders will be proficient enough to perform their duties as
per the applicable quality standards. The latest and approved edition of The Software Programmer’s
Handbook aligns with the following National Occupational Standards (NOS) detailed in.
1. SSC/N0509: Verify the specifications and contribute to the design of software program
2. SSC/N0510: Develop, test and execute software programs as per specifications using Java
3. DGT/VSQ/N0102: Employability Skill NOS (60 Hrs)

The handbook has been divided into an appropriate number of units and sub-units based on the con-
tents of the relevant QPs. We hope that it will facilitate easy and structured learning for the participants,
enabling them to acquire advanced knowledge and skills.

vi
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Table of Contents
[Link] and Units Page No

1. Programming and Algorithms (SSC/N0509) 1

Unit 1.1 - Software Programming & Algorithm Development 3

Unit 1.2 - Software Development Life Cycle 18

Unit 1.3 - Elements for Measuring Software Development Process 32

2. Develop, Test and Execute Software Programs as per Specifications using Java (SSC/N0510) 37

Unit 2.1 - Introduction to Java 39

Unit 2.2 - Introduction to Data Structures and Databases 124

Unit 2.3 - Core JAVA Concepts 176

Unit 2.4 - Testing and Execution 277

 Employability Skills (DGT/VSQ/N0102) 333

Employability Skills is available at the following location :

[Link]

Scan the QR code below to access the ebook

Annexure 335

vii
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

viii
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
1. Programming and
Algorithms
Unit 1.1 - Software Programming & Algorithm
Development
Unit 1.2 - Software Development Life Cycle
Unit 1.3 - Elements for Measuring Software
Development Process

SSC/N0509
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Key Learning Outcomes


By the end of this module, the participants will be able to:
1. Implement appropriate standards to assist in performing software construction as per
specifications
2. Identify software development needs and changes
3. Design algorithms to solve problems and execute test cases to convert them into code

2
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

UNIT 1.1: Software Programming & Algorithm Development

Unit Objectives
By the end of this unit, the participants will be able to:
1. List the steps involved in solving computational problems
2. List the disadvantages of data flow diagrams
3. Identify the process of algorithm development for software programming

1.1.1 Appropriate Standards for Software Construction as


Per Specifications
Software construction is the detailed creation of working, meaningful software through a combination
of coding, verification, unit testing, integration testing, and debugging. Software construction is strongly
intertwined with all other aspects of software engineering, especially software design and testing. It is
due to the fact that the software development process entails significant software design and testing
activity. It also uses the output of design as one of the inputs to testing, with both design and testing
being activities. The precise boundaries between design, construction, and testing (if any) will vary
depending on the software life cycle processes used in a project.
Since some of the detailed design work gets done before construction, the majority of design work is
carried out during the construction process. As a result, software construction and software design are
inextricably linked. Throughout the development process, software engineer’s unit-test and integrate
their work. Thus, software development is inextricably linked to software testing too. Software
development typically generates the most configuration items that must be managed in a software
project (source files, content, test cases, and so on). As a result, software development is inextricably
linked to software configuration management.
The following are the basic fundamentals/standards of software development:

Fig. 1.1.1: Software Construction Fundamentals

3
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

1. Minimizing complexity: Most people have a limited ability to retain complex structures and
information in their working memories, particularly over long periods of time. This has a significant
impact on how people communicate their intent to computers, resulting in one of the most
powerful forces in software development: minimizing complexity. The need to reduce complexity
applies to nearly every aspect of software development, but it is especially critical in software
testing. Software development complexity is reduced by emphasizing simple and readable code
creation over clever code creation.
2. Anticipating Change: Most software will evolve over time, and the anticipation of change drives
many aspects of software development; changes in the environments in which software operates
also have a variety of effects on software. Anticipating change assists software engineers in
developing extensible software, which allows them to improve a software product without
disrupting its underlying structure. Many specific techniques aid in anticipating change.
3. Constructing for Verification: Constructing for verification entails developing software in such a way
that flaws can be easily identified by software engineers writing the software as well as testers and
users during independent testing and operational activities. Following coding standards to support
code reviews and unit testing, organizing code to support automated testing, and limiting the use
of complex or difficult-to-understand language structures are some of the specific techniques that
support constructing for verification.
4. Reuse: The term "reuse" refers to the use of existing assets to solve various problems. Commonly
reused assets in software development include libraries, modules, components, source code, and
commercial off-the-shelf (COTS) assets. Reuse works best when done methodically, according
to a well-defined, repeatable process. Systematic reuse can lead to significant gains in software
productivity, quality, and cost. Construction for reuse and construction with reuse are two closely
related aspects of reuse. The former refers to the creation of reusable software assets, whereas the
latter refers to the reuse of software assets in the development of a new solution. Reuse frequently
crosses project boundaries, which means that reused assets can be built in other projects or
organizations.
5. Standards in Construction: Using external or internal development standards during construction
aids in meeting project goals for efficiency, quality, and cost. Allowable programming language
subsets and usage standards, in particular, are important aids in achieving higher security. Standards
that have a direct impact on construction issues include
a. Methods of communication (for example, standards for document formats and contents)
b. Programming languages (for example, java and C++ language standards) *coding standards (for
example, standards for naming conventions, layout, and indentation)
c. The platforms (for example, interface standards for operating system calls)
d. Tools (for example, diagrammatic notation standards such as UML (unified modeling language).

1.1.2 Steps involved in Computational Problems:


A computational problem is one that a computer can solve or one that a computer can answer. Consider
the factoring problem: "Find a nontrivial prime factor of n given a positive integer n."
A computational problem can be solved step by step by a computer. These problems usually have a
well-defined input, constraints, and conditions that the output must meet. A computational problem
can be thought of as a collection of instances or cases, each with its own set of solutions, which may or
may not be empty. For example, in the factoring problem, instances are integers n, and solutions are
prime numbers p that describes nontrivial prime factors of n.

4
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Fig. 1.1.2: Computational Problems

Types of computational problems:

Fig. 1.1.3: Types of Computational Problems

5
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Data collection or identification of a data set (numerical, text, audio, video, images, or symbols) and
analysis to discover similarities, differences, or trends. Abstraction Filtering out irrelevant information
to reduce complexity. This can help to simplify problem-solving and create a general understanding of
the computational problem.

Fig. 1.1.4: Problem Development Steps

1.1.3 Software Needs and Changes


It is critical for businesses because it allows them to stand out from competitors and become more
competitive. Enhancing customer experiences, bringing more feature-rich and innovative products
to market, and making setups safer, more productive, and more efficient are all benefits of software
development. Digitization and online information storage not only save space but also integrate and
centralize information, making it easily accessible to those who need it. It is also simple to safeguard
your data against intruders. As the company expands, so will the pool of data, and efficiently storing
this data will become a priority. In order to continue providing consistent performance to those who
use this data, businesses must develop and upgrade their digital organizations. Data analysis also
necessitates software development. When combined with the right software, businesses can use the
data collected from day-to-day tasks to keep track of trends among their clients.

Purpose of software development in business:

6
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Fig. 1.1.5: Purpose of software development in business

Important steps in developing software:

Fig. 1.1.6: Important steps in developing software

7
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

1.1.4 Data flow Diagrams


A data flow diagram (DFD) is a graphical depiction of data flow in an information system. It displays
incoming data flow, outgoing data flow, and stored data. The DFD makes no mention of how data flows
through the system. This technique is used for visually representing complex and difficult-to-describe
systems and processes. Data flow diagrams depict the flow of data through a process or system. It also
includes data inputs and outputs, data stores, and the different sub processes that data moves through.
DFD uses standardized notations and symbols to describe various entities and their relationships. It
is easier to identify flaws in a system when all of its components are visualized. These flaws are then
addressed to create a strong solution.

Fig. 1.1.7: Data Flow Diagrams

There is a significant distinction between DFD and Flowchart. The flowchart depicts the control flow
within programme modules. DFDs depict the data flow in a system at various levels. DFD contains no
control or branch elements.

Types of Data Flow Diagram


Data Flow Diagrams are classified as either logical or physical.
Logical DFD - This type of DFD focuses on the system process and data flow in the system. In a banking
software system, for example, how is data moved between different entities.
Physical DFD - This DFD type demonstrates how the data flow is implemented in the system. It is more
specific and closer to completion.

Components of Data Flow Diagram


Using the following components, DFD can represent the source, destination, storage, and flow of data.

8
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Fig. 1.1.8: Data Components

Important Concepts Associated with Designing Data Flow Diagrams:


Before going into the details of constructing a DFD model of a system, let us discuss some important
concepts associated with DFDs.

1. Synchronous and Asynchronous operations


If two bubbles are directly connected by a data flow arrow, they are synchronous. It means they
run at the same rate. If two bubbles are connected via a data store, the speed of operation of the
bubbles is independent. Data generated by the producer bubble is saved in the data store. Before
the consumer bubble consumes any data items, the producer bubble may store them in the data
store.

2. Data process
Composite data items can be defined in terms of primitive data items using the following data
definition operators:
a. + denotes the composition of two data items, e.g. a+b represents data a and b.
b. [,] represents selection, i.e. any one of the data items listed in the brackets can occur. For
example, [a, b] represents either a occurs or b occurs.
c. ( ) the contents inside the bracket represent optional data that may or may not appear. For
example, a+(b) represents either a occurs or a+b occurs.
d. { } represents iterative data definition, for example, {name}5 represents five name data. {name}*
represents zero or more instances of name data.
e. = represents equivalence, for example, a=b+c means that a represents b and c.
f. /* */ anything appearing within /* and */ is considered as a comment.

9
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

A DFD is developed by the following steps:

Fig. 1.1.9: Steps in Developing a Data Flow Diagram

Levels of Data Flow Diagram


a. Level 0 - It is the highest abstraction level of DFD, and it depicts the entire information system as
a single diagram that conceals all the underlying details. Context level DFDs are another name for
level 0 DFDs.

Fig. 1.1.10: Level 0 DFD

b. Level 1 - The Level 0 DFD is further subdivided into Level 1 DFD. Level 1 DFD depicts the system's
basic modules as well as the data flow between them. Level 1 DFD also mentions fundamental
processes and information sources.

10
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Fig. 1.1.11: Level 1 DFD

c. Level 2 - At this level, DFD demonstrates how data flows within the modules mentioned in Level 1 at
this level. Unless the desired level of specification is achieved, higher-level DFDs can be transformed
into more specific lower-level DFDs with a deeper level of understanding.

As previously stated, the DFD method is a component of object-oriented analysis and is widely used.
The use of DFDs encourages quick and simple project code development. FDs are simple to learn due
to their few simple symbols (once you decide on a particular DFD model). The syntax for designing DFDs
is straightforward, relying on English nouns or noun-adjective-verb constructs.

11
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Fig. 1.1.12: Advantages of DFD

Limitations of Data Flow Diagram


DFDs for large systems can become clumsy, difficult to translate and read, and time-consuming to
create. Data flow diagrams (DFDs) can be perplexing to programmers, but they are useless without the
necessary detail. Different DFD models use various symbols (circles and rectangles, for example, for
entities).
1. It makes the programmers a little confusing concerning the system.
2. The biggest drawback of the DFD is that it simply takes a long time to create, so long that the analyst
may not receive support from management to complete it.
3. Physical considerations are left out.

1.1.5 Algorithm Development for Software Programming


Algorithm development, debugging, and testing are typically carried out using a high-level programming
tool like MATLAB or C/C++. The algorithm is ready for hardware implementation after successful
algorithm development and simulations on test signals. The primary goal of detailed design is to specify
the logic for the various modules described during system design.
Specifying the logic will necessitate the creation of an algorithm that will carry out the given
specifications. Let's look at a few design principles for creating algorithms or logic that implement the
given specifications. The term "algorithm" is quite broad and covers a wide range of topics.
In the context of software, an algorithm is a clear procedure for solving a problem. A procedure is a
finite sequence of well-defined steps or operations, each requiring a finite amount of memory and
time to complete. In this definition, we assume that procedure termination is a necessary property.
We will now use the terms "procedures," "algorithms, and "logic" interchangeably. When creating an
algorithm, several steps must be taken.
A problem statement is the first step in the design of algorithms. The problem for which an algorithm is
being designed must be stated precisely, clearly, and thoroughly by the person responsible for designing

12
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

the algorithm. The problem statement for detailed design is derived from the system design. That is,
when the detailed design of a module begins, the problem statement is already available. The next step
is to create a mathematical model of the problem.
In modelling, the mathematical structures that are best suited to the problem must be chosen. Looking
at other similar problems that have been solved can be beneficial. Most models are built by taking
models from similar problems and modifying them to fit the current problem. The algorithm's design
is the next step.
The data structure and programme structure are decided during this step. After the algorithm has been
designed, its correctness must be verified. There is no clear procedure for designing algorithms. Having
such a procedure would be equivalent to automating the problem of algorithm development, which is
not possible with current methods. However, some heuristics or methods can be provided to assist the
designer in designing modules' algorithms.
The stepwise refinement technique is the most commonly used method for designing algorithms or
module logic. The stepwise refinement technique divides the logic design problem into a series of steps,
allowing for gradual development. The procedure begins by converting the module specifications into
an abstract description of an algorithm containing a few abstract statements. In each step, one or more
statements from the previously developed algorithm are decomposed into more detailed instructions.

Fig. 1.1.13: Design and Analysis of Algorithms

Algorithm:
An algorithm is a set of instructions, also known as a "process," that must be followed when solving
a specific problem. While the term is technically not defined, it is almost always associated with
computers because computer-processed algorithms can solve much larger problems much faster than
humans. Because algorithms are used much more frequently in modern computing than at any other
time in human history, a field has developed around their design, analysis, and refinement. A strong
mathematical background is required in the field of algorithm design, with computer science degrees
being particularly sought-after qualifications. It provides an increasing number of well-paying job
opportunities as the demand for more (and more sophisticated) algorithms grows.

Conceptual Design of Algorithm:


Algorithms, at their most basic, are simply a set of instructions needed to complete a task. For all of
recorded history, the development of algorithms, though they were not generally referred to as such,
has been a popular hobby and a professional pursuit. People established set routines for how they

13
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

would go about their daily tasks long before the dawn of the modern computer age, often writing
down lists of steps to take to accomplish important goals, reducing the risk of forgetting something
important. This is, in essence, what an algorithm is. Designers approach the development of algorithms
for computational purposes in the same way: they start with a problem. They then outline the steps
that would be required to resolve the issue. Finally, they develop a series of mathematical operations
to accomplish those steps.

Algorithm Design
Creating an efficient algorithm to solve a problem in the shortest amount of time and space is an
important aspect of algorithm design. Different approaches can be taken to solve a problem.
Some of them may be efficient in terms of time consumption, whereas others may be memory efficient.
However, keep in mind that both time consumption and memory usage cannot be optimized at the
same time. If we need an algorithm to run in less time, we must invest in more memory, and if we need
an algorithm to run in less memory, we must invest in more time.

Problem Development Steps:

Fig. 1.1.14: Problem Development Steps

Characteristics of Algorithms:
The main characteristics of algorithms are as follows –

14
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Fig. 1.1.15: Characteristics of Algorithms

Translation Problems of Algorithm


Translators usually have to deal with six different problematic areas in their work, whether they are
translating technical documents or a sworn statement. These include lexical-semantic problems;
grammar; syntax; rhetoric; and pragmatic and cultural problems. Not to mention administrative issues,
computer-related problems, and stress.

15
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Fig. 1.1.16: Translation Problems of Algorithm

The successive refinement process ends when all instructions are precise enough to be easily
converted into programming language statements. Both data and instructions must be refined during
the refinement process. A rule of thumb for refinement is that the amount of decomposition in each
step should be manageable and represent one or two design decisions. In general, detailed design
is specified using languages that have formal programming language features like outer structures
(like loops, conditionals, etc.) but a freer format for internal description. It enables the designer to
concentrate on the logic rather than its representation in the programming language.

Summary
• A development environment, also known as an integrated development environment (IDE),
provides comprehensive software development facilities to programmers by integrating a set of
development tools. A computational problem is one that a computer can solve step by step. These
problems typically have a well-defined input, constraints, and conditions that must be met by the
output. A computational problem can be thought of as a collection of instances or cases, each with
its own, possibly empty, set of solutions.
• There are several steps that one has to perform while developing an algorithm. The starting step in
the design of algorithms is a statement of the problem. The problem for which an algorithm is being
devised has to be precisely and clearly stated and properly understood by the person responsible
for designing the algorithm.
• Algorithm development, debugging, and testing are typically accomplished with a high-level
programming tool such as MATLAB or C/C++. After successful algorithm development and
simulations on test signals, the algorithm is ready for hardware implementation.
• Appropriate Data Store: A data flow diagram shows a store as two parallel lines. A store is any
type of storage for data or information and can refer to any automated database, file, or manual
file system. A data flow diagram can aid a systems analyst to determine if the data store has the
required input data to be processed to generate the needed output data or information. A data
flow diagram can assist in determining if the data store is appropriate for the generated output
information.
• Specific Processes: A data flow diagram shows a process, or bubble, as a circle, oval, or rectangle.
A process or bubble describes a program function and data flow diagrams provide simple names
and numbers to describe the specific program function. By numbering the process and keeping the
process names simple, the systems analyst can easily and accurately reference the specific process.
Examples of a process are: Calculate a Monthly Salary, Calculate Interest Rate, and Print a Report.

16
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Exercise
Answer the Following Questions:
1. What is the DFD?
2. What are the Advantages and Disadvantages of DFD?
3. Explain Algorithm Development.
4. Explain Data Definition.

MCQ Questions:
1. In a data flow diagram which among the following process is at the most detailed level?
a. Data flows b. Interface
c. Functional primitive d. Transform description

2. Which of the following model is used to show how data flows through a sequence of processing
steps?
a. Objects models b. System model
c. Semantic data models d. Data flow model
3. Which of the following identifies data flow in motion?
a. Circle b. Arrow
c. Open-embedded box d. Square

Fill in the blanks:


1. An ______________is a series of instructions, often referred to as a “process”, which is to be
followed when solving a particular problem.
2. A __________________shows a process, or bubble, as a circle, oval, or rectangle.
3. Translators usually have to deal with six different problematic areas in their work, whether they are
____________________or a_________________.

17
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

UNIT 1.2: Software Development Life Cycle

Unit Objectives
By the end of this unit, the participants will be able to:
1. Define the Software Development Life Cycle encompassing Business Requirements Specification
(BRS), Software Requirements Specification (SRS), High-Level Design (HLD), and Low-Level Design
(LLD)
2. List the different techniques used for Requirements Analysis

1.2.1 Software Development Life Cycle (SDLC)


The Software Development Lifecycle (SDLC) is a framework for defining the steps involved in software
development. It describes the detailed plan for developing, deploying, and maintaining software. The
SDLC defines the entire development cycle, which includes all tasks involved in gathering requirements
for product maintenance. The goal of SDLC is to deliver a high-quality product that meets the needs
of the customer. The SDLC's phases are as follows: requirement gathering, design, coding, testing, and
maintenance. It is critical to follow the phases to provide the product systematically. For example,
software must be developed, and a team is formed to work on a specific feature of the product while
being free to do so.

1.2.2 SDLC Cycle


The SDLC Cycle represents the software development process and is depicted diagrammatically below:

Fig. 1.2.1: SDLC cycle

18
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

1.2.3 Business Requirements Specification (BRS)


These are documents that list the business objectives that the client is attempting to achieve, as well
as the key targets and performance expectations of the products or system. It also demonstrates how
the client's business requirements are met on a broader level. It is known as a high-level document
and is one of the most widely used and universally accepted specification documents. Typically, the
Business Requirement Specification (BRS) is created at the beginning of the project life cycle. A business
analyst's BRS document is typically based on the specifications of other important stakeholders who
will interact with the final product following a thorough analysis of the client company. The client then
goes over the final draught of the document to ensure that it meets all of the expectations of the
business stakeholders.
Product investors, middle and upper management, and business analysts are the primary users of BRS
documents. A Business Requirement Specification (BRS) document typically includes the entire scope
of the project, the performance requirements and usability, the purpose of the product, the functions
of the product, the features of the product, and any other relevant information.

Fig. 1.2.2: Features of Business Requirements Specification

19
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Business Requirements:

Fig. 1.2.3: Business Requirements

1.2.4 Business Requirements Process


This is the process of identifying, analysing, defining, and documenting the requirements for a particular
business goal. And it is the process of defining the project's scope clearly and precisely to assess the
timeframes and resources needed to complete it. Similar to a CONOPS, business requirements, also
known as stakeholder requirements specifications (StRS), describe the characteristics of a proposed
system from the perspective of the system's end user. Methods for delivering, satisfying, or meeting
business requirements include products, systems, software, and processes.

Fig. 1.2.4: Business Requirements Process

1.2.5 Software Requirement Specification


The Software Requirements Specification (SRS) is a document that describes the main functionality
and business purpose of a product, the software that is to be developed, and how the core functions
of the software are to be performed. It is a summary of a project that includes the features of the
technology as well as the desired business goal. The SRS document is important because it bridges
the gap between what the business will get by documenting the characteristics, broad layout, and

20
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

workflows of the software being developed and what the business wants. Software Requirements
Specification (SRS) serves as the basis of any project because it consists of a framework that each team
member will follow.
System analysts are in charge of gathering all necessary information from the relevant stakeholders.
They then share the information with the other departments. The primary audience for the Software
Requirement Specification is project managers (SRS). SRS contains functional and non-functional
requirements. SRS provides a significant advantage in software development by reducing frustration and
non-productive time. It also assists team members in working together to ensure that all requirements
are met. Product Requirements Document (PRD) is another name for the Software Requirement
Specification (SRS) (PRD). A proposed software that is designed to track an employee's office time is an
example of a Software Requirement Specification (SRS) document. In this case, the document should
include the login module, the employee module, the administrator module, and the reporting module.

Fig. 1.2.5: Features of Software Requirement Specification

Steps involved in SRS:

21
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Fig. 1.2.6: Steps in SRS

1.2.6 High-Level Design


HLD is an abbreviation for "general system design," which refers to the overall description and
architecture of the application. It describes the system architecture, database design, and a summary
of systems, services, platforms, and module relationships. HLD, or high-level design, is a general
design system. It is also known as system or macro-level design. A high-level design includes an overall
description of the system architecture, the design of its database, and a brief description of its services,
systems, platforms used, and module relationships. A solution architect creates the HLD. It essentially
translates the overall client/business requirements into a high-level solution. It enters the picture
before the low-level design.

Fig. 1.2.7: Features of High-Level Design

22
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Fig. 1.2.8: Example of a High-level Design (Disruptive Architecture)


(Image Source: [Link])

1.2.7 Low-level Design


LLD, or low-level design, is essentially a detailed description of each module. In other words, the LLD
thoroughly describes each module, including the actual logic of each system component. It goes into
great detail with each system specification, earning it the moniker detailed/micro-level design. Low-
level design is created and implemented by designers and developers. It can transform a high-level
solution into a very detailed solution. As a result, the LLD comes into play only after the HLD has been
designed and implemented.

Fig. 1.2.9: Key Features of Low Level Design

23
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Fig. 1.2.10: Low level Design Document Sample


(Image Source: [Link])

1.2.8 Different Techniques Used for Requirements Analysis


There are different techniques used for Requirements Analysis. Below is a list of different Requirements
Analysis Techniques:

Fig. 1.2.11: Techniques used for Requirements Analysis

1. Business process modelling notation (BPMN)


This method is similar to creating process flowcharts, though BPMN has its own symbols and
elements. Graphs for business processes are created using business process modelling and notation.
These graphs make it easier to understand the business process. BPMN is a well-known process
improvement methodology.

24
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Fig. 1.2.12: Business Process Modelling Notation (BPMN)


(Image Source: [Link])

2. UML (Unified Modelling Language)


UML is an integrated set of diagrams used to specify, visualize, build, and document the artifacts
of a software system. When developing object-oriented software and working with the software
development process, UML is a useful technique. UML employs graphical notations to represent
the design of a software project. UML also aids in the validation of the software's architectural
design.

Fig. 1.2.13: UML (Unified Modelling Language)


(image Source: Microsoft Support)

3. Flowchart technique
A flowchart depicts the sequential flow and control logic of a group of related activities and comes
in a variety of formats, including linear, cross-functional, and top-down. The flowchart can depict
system interactions, data flows, and so on. Flow charts are simple to understand and can be used
by members of both technical and non-technical teams. The flowchart technique is useful for
highlighting the critical characteristics of a process.

25
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Fig. 1.2.14: Example of Flowchart Technique


(Image Source: conceptDraw)

4. Data flow diagram


This technique is used for visually representing complex and difficult-to-describe systems and
processes. Data flow diagrams depict the flow of data through a process or system. It also includes
the data inputs and outputs, data stores, and the various sub processes that data passes through.
DFD uses standardized notations and symbols to describe different entities and their relationships.
It is easier to identify flaws in a system when all of its components get visualized. These flaws are
then addressed to create a strong solution.

26
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Fig. 1.2.15: Data Flow Diagram Template


(Image Source: [Link])

5. Role Activity Diagrams (RAD)


A role-activity diagram (RAD) is a rule-oriented process model that represents role-activity diagrams.
Role activity diagrams are a high-level view of an organization's dynamics and role structure. Roles
are used for organizing activities into discrete units of responsibility. Activities are the fundamental
components of a role. An activity may be performed in isolation or in conjunction with other
activities within the role.

Fig. 1.2.16: Role Activity Diagrams (RAD)

6. Gantt Charts
Gant charts are used in project planning because they provide a visual representation of scheduled
tasks as well as timelines. The Gant charts assist in determining what is scheduled to be completed
by which date. All of the project's tasks' start and end dates are visible in a single view.

27
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Fig. 1.2.17: Gantt Charts

7. IDEF (Integrated Definition for Function Modelling)


The integrated definition for function modelling (IDEFM) technique represents the functions of
a process and their relationships to child and parent systems with the help of a box. It provides a
blueprint to gain an understanding of an organization’s system.

Fig. 1.2.18: IDEF


(Image Link: [Link])

28
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

8. Gap Analysis
Gap analysis is a technique that helps to analyse the gaps in the performance of a software
application to determine whether the business requirements are met or not. It also involves the
steps that are to be taken to ensure that all the business requirements are met successfully. Gap
denotes the difference between the present state and the target state. Gap analysis is also known
as need analysis, need assessment or need-gap analysis.

Gap Analysis Process:

Fig. 1.2.19: Gap Analysis Process

Fig. 1.2.20: Gap Analysis


(Image Source: Template Lab)

29
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Summary
• Software Development Lifecycle (SDLC) is a framework that defines the steps involved in the
development of software. It covers the detailed plan for building, deploying, and maintaining the
software.
• SDLC defines the complete cycle of development i.e. all the tasks involved in gathering a requirement
for the maintenance of a Product.
• The business analyst and Project Manager set up a meeting with the customer to gather all the
information like what the customer wants to build, who will be the end-user, and what is the purpose
of the product. Before building a product a core understanding or knowledge of the product is very
important.
• the requirement gathered in the SRS document is used as an input, and the software architecture
that is used for implementing system development is derived.
• In the case of UAT, a replica of the production environment is created and the customer along with
the developers does the testing. If the customer finds the application as expected, then sign-off is
provided by the customer to go live.
• Testing starts once the coding is complete and the modules are released for testing. In this phase,
the developed software is tested thoroughly and any defects found are assigned to developers to
get fixed.
• The low-level design, abbreviated as LLD, is essentially a detailed description of each module. In
other words, the LLD describes each module in detail by including the actual logic of each system
component.
• High-Level Design (HLD) is an abbreviation for general system design, which refers to the overall
system design. It describes the application's overall description/architecture. It describes the
system architecture, database design, and brief description of systems, services, platforms.

Exercise
Answer the Following Questions:
1. Differentiate between low-level Design and High-level Design.
2. Describe Software Requirements Specifications.
3. What are the business requirements in BRS?

Fill in the blanks:


1. ____________________is a technique that helps to analyse the gaps in the performance of a
software application to determine whether the business requirements are met or not.
2. The _________________________technique represents the functions of a process and their
relationships to child and parent systems with the help of a box.
3. Flowcharts are in different formats such as_________, _____________, and___________________.

MCQ Questions:
1. What is the first step in the software development lifecycle?
a. System Design
b. Coding

30
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

c. System Testing
d. Preliminary Investigation and Analysis

2. Which of the following is involved in the system planning and designing phase of the Software
Development Life Cycle (SDLC)?
a. Sizing b. Parallel run
c. Specification freeze d. All of the above

3. Which of the following prototypes does not associated with Prototyping Model?
a. Domain Prototype b. Vertical Prototype
c. Horizontal Prototype d. Diagonal Prototype

31
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

UNIT 1.3: Elements for Measuring Software Development


Process

Unit Objectives
By the end of this unit, the participants will be able to:
1. Classify elements for measuring various aspects of the software development process

1.3.1 Software Development Process


The set of instructions in the form of programs that govern the computer system and process the
hardware components is referred to as software. A set of activities is used to create a software product.
This collection is known as a software process. Designing, programming, documenting, testing, and bug
fixing are all part of the software development process. Software Components: There are three software
components: There are three of them: programme, documentation, and operating procedures.

Fig. 1.3.1: Software Components

The following figure explains four basic key process activities in software development process.

Fig. 1.3.2: Fig 4.22 Key Process Activities

32
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

The following figure explains the software crisis:

Fig. 1.3.3: Software Crisis

1.3.2 Software Development Process


A software metric is a measurable or countable measure of software characteristics. Software metrics
are useful for a variety of purposes, including measuring software performance, planning work items,
calculating productivity, and many others. Many metrics are associated with the software development
process. Software metrics are analogous to the four management functions: planning, organization,
control, and improvement.
Software metrics are divided into two categories:
1. Product Metrics: These are measurements of various aspects of the software product. The following
are the two most important software characteristics:
a. Size and complexity
b. Quality and reliability
These metrics can be computed at various stages of the SDLC.
2. Process Metrics: These are measurements of various aspects of the software development process.
Consider the effectiveness of fault detection. They are used to assess the characteristics of software
development methods, techniques, and tools.

33
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Fig. 1.3.4: Software Metrix


(Image source: [Link]

Summary
• The set of instructions in the form of programs that govern the computer system and process the
hardware components is referred to as software. A set of activities is used to create a software
product. This collection is known as a software process. Designing, programming, documenting,
testing, and bug fixing are all part of the software development process.
• Software Components: There are three software components: There are three of them: program,
documentation, and operating procedures.
• A computer program is a list of instructions that tell a computer what to do.
• Source information about the product is contained in design documents, detailed code comments,
etc.
• Software Specifications – A detailed description of a software system to be developed, including
functional and non-functional requirements, is provided in this process.
• Software Development – In this process, designing, programming, documenting, testing, and bug
fixing are done.
• Software Validation – This process involves evaluating software products to ensure that they meet
both business and end-user requirements.
• Software Evolution – Software evolution is the process of creating software and then updating it on
a regular basis for various reasons.
• A software metric is a measurable or countable measure of software characteristics. Software
metrics are useful for a variety of purposes, including measuring software performance, planning
work items, calculating productivity, and many others.

34
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Exercise
Answer the Following Questions:
1. Describe the Waterfall Model.
2. What is Software Process Model?
3. What is Software Development Process?

Fill in the blanks:


1. _______________, _______________, _________________, _____________, and
____________________are all part of the software development process.
2. _________________is a continuous process of software development, and it occurs concurrently
with development.
3. The first step to any process is always ________.
4. The _______________________process divides software development into tiny, sequential steps
in order to improve the product, project, and design as a whole.
5. _________________refers to the iterative logical process of developing software programs or
applications to meet the needs of any business or personal objectives.

35
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Notes
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________

36
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

2. Develop, Test and


Execute Software
Programs as per
Specifications using
Java
Unit 2.1 - Introduction to Java
Unit 2.2 - Introduction to Data Structures and
Databases
Unit 2.3 - Core JAVA Concepts
Unit 2.4 - Testing and Execution

SSC/N0510
37
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Key Learning Outcomes


By the end of this module, the participants will be able to:
1. Outline the evolution of programming languages
2. Distinguish between imperative and declarative programming paradigms
3. List the features of object-oriented programming: Class, Object, Encapsulation, Abstraction, etc.
4. Describe the features of Java as programming language such as platform independent,
multithreading, distributed, etc.
5. Outline the terminology used in java programming such as bytecode, JVM, JDK, JRC, etc.
6. Explain how Java can act as both compiled and interpreted language
7. List the tools used for programming in Java such as Eclipse IDE, Maven, etc.
8. Demonstrate the elements of imperative programming such as variables, flow control and
functions
9. Familiarize with the IDE to be used for java programming (e.g., Eclipse, Maven, etc.)

38
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

UNIT 2.1: Introduction to Java

Unit Objectives
By the end of this unit, the participants will be able to:
1. Outline the evolution of programming languages
2. Distinguish between imperative and declarative programming paradigms
3. List the features of object-oriented programming: Class, Object, Encapsulation, Abstraction, etc.
4. Describe the features of Java as programming language such as platform independent,
multithreading, distributed, etc.
5. Outline the terminology used in java programming such as bytecode, JVM, JDK, JRC, etc.
6. Explain how Java can act as both compiled and interpreted language
7. List the tools used for programming in Java such as Eclipse IDE, Maven, etc.
8. Demonstrate the elements of imperative programming such as variables, flow control and functions
9. Familiarize with the IDE to be used for java programming (e.g., Eclipse, Maven, etc.)

2.1.1 The Evolution of Computer Programming Languages


It's simple to overlook how far we have come in a path of great technological improvement in our
digital age, where practically everything is instantaneously possible with a few clicks. Let's examine
some significant advancements in computer programming languages over time:

Ada Lovelace writes the analytical engine programs in 1843


Charles Babbage, who is sometimes referred to as the "father of the computer," proposed the
analytical engine, a mechanical general-purpose computer, in 1837. Ada Lovelace, the first computer
programmer in history, recognized in 1843 that the analytical engine could perform much more than
simple calculations. As a result, she produced the first algorithm that was designed to be used with the
engine.

1949: The first type of programming language that is extensively used is Assembly
This kind of low-level programming language is important since it was the first to allow programmers
to write code using symbols rather than binary code, as was previously described. The same kind of
computer programming is still used today to create computer viruses or real-time software such as
simulated aircraft navigation systems and medical monitoring equipment.

Autocode debuts as the first compiled computer programming language in 1952


Autocode is a word for a family of "simplified coding systems" (later renamed to programming languages)
that eventually expanded to encompass examples like Cobol and Fortran. It was first created by Alick
Glennie for the Mark 1 computer. Even though Fortran isn't commonly used in business today, it is still
frequently utilized in research and engineering applications and by NASA.

39
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Fortran was created in 1957 and is used for scientific and numerical processing
Fortran, which was created by John Backus and IBM, is regarded as the first high level language. It
was intended to be broadly applicable and relatively simple to learn. Most notably, Fortran made it
possible for programmers to create software 500% quicker than they could using Assembly or machine
language. Fortran 5 was used to program the Voyager 1 and 2 spacecraft of NASA.

Cobol was created in 1959 as a Common Business-Oriented Language


By 1997, 80 percent of the world's business was using Cobol, making it the most popular choice for
business applications and greatly attributable to IBM. For the coronavirus pandemic aid and relief
program, the US Internal Revenue Service disrupted its path to a Cobol-based IMF (individual master
file) as recently as 2020. This was done to benefit residents and businesses.

Beginners' All-Purpose Symbolic Instruction Code, introduced in 1964


The BASIC programming language was created by John G. Kennedy and Thomas E. Kurtz with the goal
of being as user-friendly as possible, so it is not unexpected that it eventually took over the home
computer market that first appeared in the 1970s. By merging an improved version of BASIC with a
visual form builder, Microsoft created Visual Basic in 1991.

C starts influencing the development of the Rajual computer in 1972


The mother of practically all high-level languages, C is still one of the most widely used languages in
the world today. By utilizing the Common Gateway Interface, it can be utilized to construct a computer
operating system, an embedded system, as well as in online settings (CGI). Programming languages that
are descended from Care C#, D, Go, Java, JavaScript, Limbo, Python, and others.

[Link] Current Programming Language Trends


What function does a programming language serve?
What are some of the most significant and frequently used computer programming languages in use
today, given that the digital transformation of our world is advancing more quickly than ever and that
programming skills are still in great demand across a wide range of industries?

Java
Popular computer language Java was developed in [Link] is used by more than 3 billion devices
worldwide and is owned by Oracle. James Gosling oversaw a group of researchers at Sun Microsystems,
Inc. that worked to develop Java in an effort to develop a new language for interfacing consumer
electronics. The team started working on the language in 1991, but soon their attention shifted to the
World Wide Web, a brand-new market. When Java was initially published in 1995, it was clear that
because of its capacity for interactivity and multimedia, the Web was a particularly good fit for it.
It's employed for:
• Mobile programs (especially Android apps)
• Using desktop programs
• Web-based programs

40
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

• Application servers and web servers


• Database connection for games

Companies like Spotify and Amazon have embraced Java as one of the most popular and traditional
programming languages used today, for its ability to speed up and reduce the cost of software
development

Python
Python is a programming language that is used by nearly half of software developers today. Number of
websites, including Google, Pinterest, Wikipedia, Instagram, and others, support this high-level, legible
language.
JavaScript
Nearly 65 percent of modern programmers choose JavaScript, a multi-paradigm and dynamic language.
Microsoft, PayPal, Netflix, Uber, Facebook, and other companies support it.

PHP
The PHP programming language is used by around 22% of global experts in web development and
scripting. This open-source language is distinguished for its accessibility, affordability, and simplicity.

Typescript
As of 2022, TypeScript has consistently ranked in the top 10 most popular professional programming
languages, simplifying JavaScript by making it simpler to read and debug.

Exercise
MCQ Questions:
1. What is the only language that a computer understands directly?
a. English, as spoken in Boston, Mass.
b. BASIC, the Beginners' All-purpose Symbolic Instruction Code
c. machine language, different for every type of CPU

2. What are the three main types of computer programming languages?


a. machine language, assembly language, high level language
b. imperative language, functional language, declarative language
c. COBOL, Fortran-77, C++

3. From the point of view of the programmer what are the major advantages of using a high-level
language rather than internal machine code or assembler language?
a. Program portability b. Easy development
c. Efficiency d. All of the above

41
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

4. Programming language which is used for scientific purposes and work is to be done in batches is
a. PASCAL b. FORTRAN
c. LOGO d. COMAL

5. Which laboratory was Java invented or developed in?


a. Bell Laboratory b. Sun Microsystems
c. Dennis Ritchie Office d. Johnson and Johnson

[Link] Imperative and Declarative programming paradigms


Two popular programming paradigms are declarative and imperative. Declarative programming
concentrates on what the program should achieve, whereas imperative programming concentrates on
how the program should achieve the outcome. This is the main distinction between declarative and
imperative programming.
Depending on a feature, a programming paradigm is used to categorize a language. Additionally, it
enables the use of a specific pattern or method to address a specific issue.
a. Describe the term declarative programming
b. Describe the term imperative programming
c. Difference between Declarative and Imperative Programming

a. Describe the term declarative programming


Systems with intelligence frequently employ declarative languages. Declarative languages are
fundamentally distinct from other languages due to the way they are organized. A knowledge base
will be developed by programmers. A knowledge base includes a collection of connected facts and
regulations. An example from the real world can be used to demonstrate declarative programming.
Assume the user wants to see if any fresh emails have arrived. Enabling the inbox notifications is
one approach. The user simply needs to enable the notifications once, and after that, he receives
one each time a new email arrives. Declarative programming resembles it in several ways. It makes
everything simple. Declarative programming articulates the nature of the desired outcome. Without
explaining the control flow, it explains the reasoning behind a computation.

Fig. 2.1.1: Programming Methodologies

42
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

The example below shows how declarative programming works. It involves multiplying the values
of an array by a constant and putting the result in a new array.

Example:

var rollnum=[1,2,3];
var newrollnum= [Link](function(number)
{
return rollnum*5;
});
C [Link](newrollnum);

Correct code:
var rollnum=[1,2,3];
var newrollnum=[Link](function(rollnum)
{
return rollnum*5;
});
[Link](newrollnum);

Result:
5, 10, 15

To create a new array containing the results of each callback function, the computer follows the
instructions given by the word "map" in the preceding example. 5 + 10 + 15 = final result.
5,10,15 is final result. The major purpose of the program is accomplished by using the map function
to multiply the integers by 5. The callback function will be used to compute and append each
element's value to the new array. Detailed instructions are unnecessary. The main focus is on what
should be done.

b. Imperative programming
In imperative programming, assignment statements are used to find data in memory so that it
can be used later. Many programs use looping statements, which allow statements to be run one
after the other. Use a conditional branching statement to check if a condition is met before doing
something. When explaining imperative programming, the same real-world example can be used
as before. The user can sign into Gmail and keep refreshing the screen to see if he has any new
emails. This is like how programming in the imperative style works. It shows every step that needs
to be taken to get the desired result. Statements show how the state of a program has changed.

43
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

The following is an example of imperative programming: multiplying the members of an array by a


constant and saving the results in a new array.

Example:
var weights = [1,2,3];
var newweights= [];
for (int i=0; i<[Link] ; i++) {
[Link](weights[i]*5);
}
[Link](newweights);

Correct code:
var weights = [1,2,3];
var newweights= [];
for (var i=0; i<[Link] ; i++) {
[Link](weights[i]*5);
}
[Link](newweights);

Result:
[5, 10, 15]

In the previous illustration, numbers are an array. Each number is multiplied by 5 and added to the
newweights array as the loop iterates over the numbers. The 5, 10, and15 [5,10,15]newweights will
print at the conclusion of the loop.
Clearly, the imperative style outlines each step required to accomplish the project. It covers how
to put calculated values into new arrays, the number of times to iterate through the array before
leaving the loop, and how to utilize the i counter variable to iterate through the array, among other
things.
Both declarative and imperative programming were used to tackle the same issue.

c. Declarative programming is different from imperative programming.


The majority of developers have typically written web services using the imperative technique.
This required creating the service through service and operation contracts and implementing
the service. The majority of custom development, however, is neither either declarative nor
imperative. Although it often favours one over the other, it does include a combination of both.
Certainly, the development of services follows this trend. For instance, if a programmer adopts an
imperative methodology to create a service, the reasoning may contain if statements or other types
of conditional logic, yet the program may still have a declarative SQL query.

44
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Declarative vs Imperative Programming


Declarative programming is a paradigm Statements that change the state of the program
for computer programming that conveys a are used in the imperative programming
computation's logic without outlining its control paradigm.
flow.
Main Focus
Declarative programming is concerned with the The focus of imperative programming is on
goals that the program should achieve. how the program should produce the desired
outcome.
Flexibility
Declarative programming provides less flexibility. Imperative programming provides more flexibility.
Complexity
Declarative programming makes the software The program's complexity may rise as a result of
easier to use. imperative programming.
Categorization
Declarative programming includes functional, Imperative programming includes procedural
logic, and query programming. and object-oriented programming.

Exercise
MCQ Questions:
1. Java is procedural programming.
a) True b) False

2. Who developed Java Programming?


a) Guido van Rossum b) James Gosling
c) Dennis Ritchie d) Bjarne Stroustrup

3. Which statement is true about Java?


a) Java is a sequence-dependent programming language
b) Java is a code dependent programming language
c) Java is a platform-dependent programming language
d) Java is a platform-independent programming language

4. Java 8 Interfaces, methods can be:


a) default b) abstract
c) all d) none

45
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

5. The Java 8 API with a sequence of elements which of these supports sequential and parallel
aggregate operations -
a) Hadoop b) Streams
c) Sequence Programming d) Big data

6. Stream operations in java 8 can be divided into


a) Terminal types b) Intermediate types
c) All d) None

7. Lambda expressions in java 8 are based on


a) Procedural programming b) Functional programming
c) Data programming d) All

8. How many methods are there in functional interface in Java 8?


a) 0 b) 1
c) 2 d) 3
9. Lambdas introduced in Java 8 allow us to treat -
a) Data as code b) Code as data
c) none d) all

10. The newly introduced Streams API is available in which package of java 8:
a) [Link] b) [Link]
c) [Link] d) [Link]

[Link] List the features of object-oriented programming:


Class, Object, Encapsulation, Abstraction, etc.
What is OOPs Concept?
Object-oriented programming is the basis of Java programming, which is used to develop programs
using classes and objects. Another method to define OOPs is data control for code access. With this
approach, programmers describe both the data type and the operations to be carried out on a data
structure.

What are OOPs in java?


Java's OOPs are designed to properly describe Java programs, improving Java program readability
and reuse. The four main core ideas of object-oriented programming are abstraction, encapsulation,
inheritance, and polymorphism. These concepts aim to include real entities in programming.

46
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

List of OOPs Concepts in Java


• Object
• Class
• Abstraction
• Inheritance
• Polymorphism
• Encapsulation

Fig. 2.1.2: Object oriented principles

What are Objects?


When objects are created from classes, whether in Java or another language, they are always referred
to as instances of that class. They display states and behaviours. These things are almost usually actual
people or objects that may be found in the real world. They go by the name global run-time entities as
well. These are all-inclusive and include the methods and characteristics that enable the use of data.
Data that is both logical and physical can be categorized as objects. It comprises addresses and takes up
some memory. Among the many examples of items are a dog, a chair, a tree, etc.
Animals have attributes like colour, breed, and name when they are seen as objects, as well as behaviours
like eating and waving their tails. Consider the following scenario: We have a class called Mypen, and
we use the phrase new to denote the class name, followed by the object name.

Example 1:

public class Mypen


{
int x=10;
public static void main (String args [])

47
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

{
MypenMyobj = new Mypen ();
[Link](Myobj.x);
}
}

In the above example, a new object is created, and it returns the value of x which may be the number
of pens
Syntax for creating object:

MypenMyobj= new Mypen ();


This is the statement used for creating objects

Syntax for accessing value of x:


[Link];
The value of an object's x can be returned with this statement.
[Link](Myobj.x);

Multiple objects can be created in the same class, and we can create an object in one class and access it
in another. Remember that the class name and the java file name always remain the same when using
this strategy for better class organization.

Example 2:
In the example that follows, we'll see how to create many objects in the same class and access them
from another class.
[Link]
public class Mypen
{
int x=10;
int y=8;
}
[Link]

class compute
{
public static void main (String [] args)
{
Mypen myobj1 = new myobj1();

48
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Mypen myobj2 = new myobj2();


[Link] (myobj1.x);
[Link] (myobj2.y);
}
}

What are Classes?


For constructing objects, classes resemble object constructors. The group of objects is referred to as a
class. It is claimed that classes are logical quantities. Classes don't take up any memory space. A class
is also referred to as an object's template. Members of classes can be fields, methods, or constructors.
Both static and instance initializers are present in a class.

A class declaration consists of:


Modifiers: These can be public or default access.
Class name: Initial letter.
Superclass: A class can only extend (subclass) one parent.
Interfaces: A class can implement more than one interface.
Body: Body surrounded by braces, {}.

A class keyword is used to create a class. Below is a generalized, condensed definition of the class.:
class classname {
type instance variable-1;
type instance variable-2;
.
.
.
type instance variable-n;
type methodname-1 (parameter list)
{
// body ofthe method
}
type methodname-2 (parameter list) {
// body ofthe method
}
type methodname-n (parameter list) {
// body of the method
}

49
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Instance variables are the variables or data declared inside a class.


The methods are always composed of code. As a result, a class's declared variables and methods are
referred to as its members.
All of the methods have the same format as the main (); neither static nor public are given for these
methods.

What is Abstraction?
Abstraction is a method that reveals just the important information and hides the extraneous data. One
may argue that data concealment is the fundamental objective of abstraction. Abstraction minimizes
programming effort and complexity by selecting data from a large data pool to present the relevant
information.
In addition, there are abstract methods and classes. Abstract classes are classes that declare one
or more abstract methods. Abstract describes a method that contains a method definition but no
implementation. Once we have modelled our object using data abstraction, the same data may be
employed in numerous applications—abstract classes, generic types of actions, and object-oriented
programming hierarchy. Abstract methods are used when two or more subclasses perform the same
task differently and with distinct implementations. In an abstract class, both concrete methods and
abstract methods may be found.

Now, let's look at an abstraction example.


Let us assume we want to develop a student application and ask for the student's Rajual data. We
collect the following information from all the students.
Name
Class
Address
DoB
Fathers name
Mothers’ names etc.
It's possible that not all of the information we've collected will be required in order to finish the
application. Therefore, we must determine which pieces of information are required to finish the
application. Because of this, we have acquired, filtered, and selected the data, namely the information
on the students, from a massive amount of data. The term "abstraction" is used to describe this kind of
behaviour in the OOP’S concept.

Abstract class example:


//abstract parent class
abstract class car
{
//abstract method

50
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

public abstract void braking ();


}
public class santroextends car
{
public void braking ()
{
[Link] (“ Hydraulic brakes “ );
}
public static void main ( Stringargs [ ] )
{
carobj = new santro( );
obj. braking ();
}
}

Output will be : Hydraulic brakes

What is Inheritance?
Inheritance is one technique for an object to gain or inherit the attributes of another object, and it also
provides hierarchical categorization. This is based on the idea that we may construct new classes on
top of previous ones; that is, when you inherit from an earlier class, you can use its fields and methods
again. The parent-child relationship is symbolized via inheritance.
A whale, for example, comes within the category of marine animals, which falls under the category
of mammals. Top-down classification, also known as hierarchical classification, is used. Mammals are
more specialized organisms, and as such, they have more specific traits, such as teeth, whether they
are cold-blooded or warm-blooded, and so on. This is an animal subclass, while animals are an animal
superclass. A subclass is a class that inherits superclass attributes. This is known as a derived class. A
superclass is a base class or parental class from which a subclass inherits its characteristics. We mostly
utilize inheritance for method overriding. To inherit a class, use the extend keyword.
There are five different types of inheritance:
Hierarchical
Single
Multilevel
Hybrid
Multiple

1. Single level Inheritance


The parent class's features are passed down to the derived class in this one class. This offers the
code new functionality and allows it to be reused. For example, class B has characteristics that class
A does not. Class A is the base or parental class, while Class B is a derived class.

51
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Syntax:
class A {

}
class Bextends A {

}

2. Multilevel Inheritance
This particular class is derived from another class that is descended from yet another class, i.e., this
class has several parental classes, which is why multilevel inheritance is referred to as such.

Syntax:
class A {
….
}
class Bextends A{
….
}
class C extends B {

}

3. Hierarchical level Inheritance


In this case, we may say that one parent class has two or more derived classes, or that one parent
class has two or more child classes.
Syntax:
class A {

}
class B extends A {
..
}
class C extends class A {
..
}

52
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

4. Hybrid Inheritance
In Java, multiple inheritances are not supported because they create ambiguity; instead, this form
of inheritance may only be accomplished using interfaces. This is the mix of multiple and multilayer
inheritances. Think about how class a serve as the parent or base class for classes b and c, which in
turn serve as the parent or base classes for class d. Classes b and c are descended from class a, and
classes d are descended from classes b and c.
The extend keyword is used in the following program to construct a subclass add and a superclass
add, both of which are named sub.

// a simple example of inheritance


//create a superclass
class Add
{
int my;
int by;
void setmyby (int xy, int hy)
{
my=xy;
by=hy;
}
}
//create a sub class
class b extends add
{
int total;
void sum ()
{
public static void main (String args[])
{
b subOb= new b ();
subOb. Setmyby (10, 12);
subOb. Sum () ;
[Link](“total =” + subOb. Total);
}
}
Output: Total = 22

53
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Correct code:

class A
{
int my;
int by;
void setmyby (int xy, int hy)
{
[Link]=xy;
[Link]=hy;
}
}
//create a sub class
class b extends A
{
void sum()
{ [Link]("Sum = "+(my+by));
}
}
class g
{

public static void main (String args[])


{
b subOb= new b();
[Link] (10, 12);
[Link]();
}
}
Output: Total = 22

What is Polymorphism?
The ability to take on several forms or execute the same task in different ways is referred to as
polymorphism. This occurs when there are a large number of inherited classes. Polymorphism may
occur at either the compilation or execution stage. An instance of compile-time polymorphism is
when a static method is overloaded in Java. Run time polymorphism, also known as dynamic method
dispatch, is a technique in which a call to an overridden method is handled at run time rather than

54
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

compile time. The overridden method is always called using the reference variable. Method overloading
and overriding might be used to provide polymorphism. The term "polymorphism" is often used to
characterize a concept with several implementations and a single public face. Complexity is reduced
since a larger set of operations may now be performed using the same interface.

Example:
public class Bird
{

public void sound ()
{
[Link] (“birds sounds”);
}
}
public class pigeon extends Bird
{

@override
public void sound ()
{
[Link](“cooking”);
}
}
public class sparrow extends Bird ()
{
….
@override
public void sound ()
{
[Link](“chips”);
}
}

In the previous illustration, we saw an example of a standard action sound (), but there are various ways
to carry out the same action as well. This is an example of polymorphism, which occurs rather often.

55
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Polymorphism in java can be classified into two types:


1. Static /Compile-Time Polymorphism
2. Dynamic / Runtime Polymorphism

Short exercise:

What is Compile-Time Polymorphism in Java?


Ans:

What is Runtime Polymorphism in Java?


Ans:

What is Encapsulation?
Encapsulation is one of the OOPs concepts, and it refers to the practice of enclosing data and code
inside a single, impenetrable container. During this process, the data is protected from public view and
is only available via the current class's methods. This practice has been given the term "data hiding" as
a result. Encapsulation is a security mechanism that prevents unauthorized access to the underlying
data and code. All of this is controlled by means of a straightforward user interface.
To implement encapsulation, make the variables private while making the corresponding setter and
getter functions accessible to everyone. When a class is encapsulated, its fields may be either read-only
or write-protected. This method also improves the technique's reusability. Unit tests are made much
easier for encapsulated programs.

Example:
class animal
{
// private field
private int age;
//getter method
Public int getage() {
return age;
}
//setter method
public void setAge (int age)
{
this. Age = age;
}

56
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

}
class Main
{
public static void main (String args []);
//create an object of Raju
Animal a1= new Animal ();
//change age using setter
A1. setAge (12);
// access age using getter
[Link](“animal age is ”+ a1. getage ());
}
}

Correct Code:

class Raju
{
// private field
private int age;

//setter method
public void setAge (int age)
{
[Link]=age;
}
public int getage() {
return age;
}
}
class m
{
public static void main (String args [])
{
//create an object of Raju
Raju a1= new Raju();
//change age using setter

57
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

[Link](12);
// access age using getter
[Link]("Raju's age is "+ [Link]());
}
}

Output: Raju’s age is 12

In this particular example, we decided to make the age field a private one so that it would only be visible
to other members of the class. We avoided restrictions by utilizing open methods. These approaches
are known by the names getter and setter methods respectively. By keeping students' ages a secret,
we may be able to restrict unauthorized access from outside the class. This practice is characterized as
"data hiding" as a result.

Coupling in Java
Coupling is the term used to describe the connection that exists between two groups. It signifies an
object or class having a knowledge of another item or class. If one class modifies its behaviours or
properties, the other class will experience repercussions since those adjustments are reliant on the first
class. Because of this, the level of reliance that exists between the two groups will be the determining
factor in these shifts. There are two distinct types of coupling, and they are a tight coupling and a loose
connection.
Tight coupling: When one class has a close link to another, we say that they are tightly coupled.

public class College


{
public void status()
{
[Link]("College is open today");
}
}
public class Student {
College obj = new College();
public void goToCollege() {
[Link]();
}
}

The student class in the above code sample is dependent on the college class. In other words, each
change in a college class necessitates a change in the student classes. As a result, the student class and
the college class are closely related in this situation.

58
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Loose coupling: Loose coupling describes a link between two classes that is relatively weak. Coupling
that is both tight and strong is preferred over coupling that is either weak or weak and sloppy. As can
be shown below, interfaces may be used to help a class reach this goal.

public interface College


{
void status();
}
class CollegeStatus1 implements College
{
public void status() {
[Link]("College is open from monday to friday");
}
}
class CollegeStatus2 implements College
{
public void status()
{
[Link]("College is open on Saturday");
}
}
public class Student
{
College obj = new CollegeStatus1();
public void goToCollege()
{
[Link]();
}
}

CollegeStatus1 and CollegeStatus2 are loosely connected in the aforementioned code sample. In this
instance, the CollegeStatus1 or CollegeStatus2 classes are not closely or directly related to the student
class. A dependency injection approach is used to establish loose coupling, allowing students to enroll
in college with any class that has created a college interface. Additionally, it implies that anytime the
college is open on Saturday, we may utilize CollegeStatus2.

Cohesion in Java
Java Cohesion is a metric that evaluates how tightly related and intently focused a class's methods and
properties are on carrying out a particular, well-defined purpose for the system. This is a term that is

59
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

used to explain about how concentrated the exclusive duty of a class is. It is preferable to preserve the
classes that make the most sense in order to facilitate the reuse of code. It may be challenging to keep
up with low-cohesive classes since the methods and attributes of these classes do not make sense
when taken together. It is often preferable to have courses that collaborate well with one another so
that students may concentrate on a single endeavour.
Low Cohesion: We have a class named Book in the code below. However, it lacks cohesion since the
class's characteristics and methods are less concentrated and independent. There should be material
in this class that relates to the Book. As a result, the way of using the Raju's name and age is helping to
make this classless.

class Book
{
int price = 299; //related attribute
String name = "Sam"; //unrelated attribute
//related methods to Book class
public String author(String name)
{
return name;
}
public String title(String subject)
{
return subject;
}
public int id(int number)
{
return number;
}
//unrelated methods to Book class
public int age (int age)
{
return age;
}
}

High Cohesion: People say that the class is very cohesive when it has one clear goal or assignment. So, if
we take out the information about the Raju from the code sample above, the class becomes very clear,
as you can see below.

60
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Class Book
{
int price = 299; //related attribute
//related methods to Book class
public String author(String name)
{
return name;
}
public String title(String subject)
{
return subject;
}
public int id(int number)
{
return number;
}
}

Association in Java
A relationship between two distinct classes that is established by the items of both classes is known as
an association. Identifies the relationship between two or more separate things. Relationships of a one-
to-one, one-to-many, many-to-one, and many-to-many nature are all within the realm of possibility.
Take into consideration the interaction that takes place between the bus and its passengers as a means
of gaining a better understanding of these ideas via the application of real-world instances. Each bus
is restricted to have just one driver at a time (one-to-one). There might be a lot of passengers on the
bus (many-to-one). It's possible for one Raju to transfer onto many buses (one-to-many). In addition, a
great number of people could be able to relate to the various buses (many-to-many). The linking of two
different things is required in order to get access to the features and functions offered by a third entity.

//class bus
class Bus
{
private String name;
// bus name
Bus(String name)
{
[Link] = name;
}

61
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

public String getBusName()


{
return [Link];
}
}
//passenger class
class Passenger
{
// passenger name
private String name;
// passenger seat id number
private int seatId;
Passenger(String name, int seatId)
{
[Link] = name;
[Link] = seatId;
}
public String getPassengerName()
{
return [Link];
}
public int getPassengerId()
{
return [Link];
}
}
//Association between both the
//classes in the main method
class Demo
{
public static void main (String[] args)
{
Bus bus = new Bus("VRL Travels");
Passenger psg = new Passenger("Raju", 52);
[Link]([Link]() + " with seat number " + [Link]()
+ " is a passenger of " + [Link]());

62
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

}
}

Output: Raju with seat number 52 is a passenger of VRL Travels

A relationship between two distinct classes that is established by the items of both classes is known as
an association. Identifies the relationship between two or more separate things. Relationships of a one-
to-one, one-to-many, many-to-one, and many-to-many nature are all within the realm of possibility.
Take into consideration the interaction that takes place between the college and its students as a
means of gaining a better understanding of these ideas via the application of real-world instances. Each
college is restricted to have just one Principal at a time (one-to-one). There might be a lot of students in
the college (many-to-one). It is possible for one Principal to get connected onto many colleges(one-to-
many). In addition, a great number of people could be able to relate to the various colleges (many-to-
many). The linking of two different things is required in order to get access to the features and functions
offered by a third entity.

//class college
class College
{
private String name;
// college name
College (String name)
{
[Link] = name;
}
public String getCollegeName()
{
return [Link];
}
}
//Student class
class Student
{
// student name
private String name;
// student rollno id number
private int rollid;
Student(String name, int rollid)
{

63
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

[Link] = name;
[Link] = rollid;
}
public String getStudentName()
{
return [Link];
}
public int getStudentrollid()
{
return [Link];
}
}
//Association between both the
//classes in the main method
class Demo
{
public static void main (String[] args)
{
College c=new College("Bhavans");
Student s = new Student("Raju", 25);
[Link]([Link]() + " with roll number " + [Link] id()
+ " is a student of " + [Link]());
}
}

Output: Raju with rollnumber 25is a student of Bhavans.


Explanation:
Objects inside the class Demo link together the previously mentioned Bus and Passenger classes. We
may use the concept of association to draw a line between these two distinct groupings. A one-to-many
relationship may be established since there might be several individuals sharing a bus. Association is of
two types, they are:
1. Aggregation
2. Composition

Aggregation
Aggregation is a kind of weak association that is used to depict the connection that exists between an
item that also includes other objects. This exemplifies the connection between a component and a
whole, demonstrating that a portion may exist independent of a whole. As an example, let's take a look

64
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

at the connection that exists between a group and an individual. One Raju may have membership in a
number of different groups. Therefore, a Group may be composed of more than one Raju. However, the
Raju object will not be deleted even if a Group is removed from the database. The Has-a relationship,
which is also often called a one-way or unidirectional association, is shown by the aggregate. For
example, the group may have individuals, but it is impossible for the people to have the group, hence
this relationship is unidirectional. Since both of these submissions in this category have a fighting
chance of making it on their own, removing one of them will not have an effect on the other one. As a
consequence of this, it is possible to separately aggregate both items.

Considering the following code example:

import [Link].*;
//Raju class
class Raju
{
private String name;
private int age;
Raju(String name, int age)
{
[Link] = name;
[Link] = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
/* Group class contains the list of Rajus
Objects. It is associated with the Raju
class through its Object(s). */
//group class
class Group
{
private String groupName;
private List<Raju> Rajus;
Group(String groupName, List<Raju> Rajus)

65
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

{
[Link] = groupName;
[Link] = Rajus;
}
}

//main method
class Demo
{
public static void main (String[] args)
{
//creating objects of Raju class
Raju a = new Raju("Sai", 17);
Raju b = new Raju("Sam", 18);
Raju c = new Raju("Pitu", 19);
Raju d = new Raju("Ruchi", 20);
//making a list of Rajus belongs to social welfare group
List<Raju> p1 = new ArrayList<>();
[Link](a);
[Link](c);
//making a list of Rajus belongs to flexgroup
List<Raju> p2 = new ArrayList<>();
[Link](b);
[Link](d);
//creating objects of group class
Group swGrp = new Group("Social Welfare", p1);
Group dfGrp = new Group("Drama Fest", p2);
//before deleting flexgroup
[Link]("List of Rajus in Flexgroup:");
for(Raju p : p2) {
[Link]("Raju name: " + [Link]() + ", Age:" + [Link]() + ", Group: Drama Fest");
}
//deleting flexgroup
dfGrp = null;
//after deleting flexgroup
//Raju list will not destroy

66
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

[Link]("List of Rajus after deleting Flexgroup:");


for(Raju p : p2) {
[Link]("Raju name: " + [Link]() + ", Age: " + [Link]());
}
}
}

Output:
List of Rajus in Flex group:
Raju name: Sam, Age:18, Group: Flex group
Raju name: Ruchi, Age:20, Group: Flex group
List of Rajus after deleting Flex group:
Raju name: Sam, Age: 18
Raju name: Ruchi, Age: 20

Explanation:
We can see that the two classes, Raju, and Group, are connected to one another in this instance using
objects. There are two organizations: flex and social welfare. We used the Raju class to construct these
groupings. There is a list of people in the group. According to the output, Sam and Ruchi are two of the
individuals in our Flex group. By changing the instance of group equals to null after that, we eliminated
this group. Despite the group being removed, our list of people is still intact because of the weak
relationship, or aggregation.

Composition in Java
Composition is the name given to the association that represents a part of a connection that cannot
exist on its own apart from the whole connection. As an example, let us take a look at the connection
that exists between a classroom and a living space. The structure that houses the school is comprised
of many rooms. If there is not already a school object in the room, there is no chance that there will
be a dependent item there. This is because if the school object spontaneously disappears, then all of
the other things in the room will likewise vanish. Because of this, they are connected in a way that is
referred to as composition. If a component of anything is taken away, the complete thing as a whole
must likewise go. As a result, connectivity may be thought of as an aspect of composition.
When two things are combined to form a new entity, the existence of the new item is contingent on the
continued existence of the original thing. Because of this, the fundamental components of both entities
are inextricably linked to one another.

Consider the example:

import [Link].*;
// activity room class
class ActivityRoom

67
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

{
public String subject;
public int id;
ActivityRoom(String subject, int id)
{
[Link] = subject;
[Link] = id;
}
}
// department class
class Department
{
private String name;
//list of activity rooms in a department.
private List<ActivityRoom>ar;
Department(List<ActivityRoom>ar)
{
[Link] = ar;
}
// Getting total number of colleges
public List<ActivityRoom>getActivityRoomsInDepartment()
{
return ar;
}
}
class Demo {
public static void main(String[] args)
{
// Creating the Objects of activity room class.
ActivityRoom a1 = new ActivityRoom("Teach", 601);
ActivityRoom a2 = new ActivityRoom("Learn", 602);
ActivityRoom a3 = new ActivityRoom("Transfer", 603);
// making the list of activity rooms.
List<ActivityRoom> act = new ArrayList<ActivityRoom>();
act. add(a1);
[Link](a2);

68
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

[Link](a3);
// Creating the Object of department class.
Department d = new Department(act);
// making the list of activity rooms in department.
List<ActivityRoom>arlist = [Link]();
for (ActivityRooma :arlist)
{
[Link]([Link] + " activity room with id " + [Link]);
}
}
}

Output:
Teach activity room with id 601
Learn activity room with id 602
Transfer activity room with id 603

Explanation:
Here, we have two different courses. Space designated for both events and the department. a section
that has multiple activity rooms that are devoted to a certain topic. Because the activity room cannot
exist without the department, all the activity rooms that make up that department will likewise be
annihilated if the department is wiped away. As a result of this, it has a composition.

Advantages of OOPs Concept


Re-usability: The phrase "write it once, use it numerous times" alludes to the concept of reusability,
which is the practice of reusing certain facilities rather than continuously building them. Utilizing classes
is one method for accomplishing this goal. It is adaptable to several uses according to requirements.
Data redundancy: It is among the most major benefits offered by Object Oriented Programming. This
condition occurs at the data storage when the same piece of data is stored in two different places. If we
want to apply the same functionality to several classes, we can easily establish generic class definitions
for comparable features by inheriting them. If we do this, we can apply the functionality across all of
the classes.
Code maintenance: Because new objects may be formed with only small differences from the ones
that already exist, it is straightforward to modify or maintain the code that is already in place. Because
of this, users may avoid engaging in labour that is repetitive and can avoid updating older scripts by just
making new alterations.
Security: Data hiding and abstraction are used to filter out restricted exposure, ensuring that only the
data that is essential for viewing is made available while maintaining security. Design benefits Better
designs are produced as a result of the designers' longer and more thorough design phases. It will be
simpler to program each non-oop independently after the program has hit its critical constraints.

69
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Easy troubleshooting: Encapsulation object usage is self-restrictive. Therefore, any issues that
developers go through may be quickly resolved. Additionally, there won't be any chance for coding
fraud.

Disadvantages of OOPs Concept


• Effort – A lot of work is put into creating these programs.
• Speed – These programs are slower compared to other programs.
• Size – OOPs programs are bigger when compared to other programs.

Exercise
MCQ Questions:
1. Which of the following is not an OOPS concept in Java?
a) Polymorphism b) Inheritance
c) Compilation d) Encapsulation

2. Which of the following is a type of polymorphism in Java Programming?


a) Multiple polymorphism b) Compile time polymorphism
c) Multilevel polymorphism d) Execution time polymorphism

3. Which statement is true about Java?


a) Java is a sequence-dependent programming language
b) Java is a code dependent programming language
c) Java is a platform-dependent programming language
d) Java is a platform-independent programming language

4. Which among the following doesn’t come under OOP concept?


a) Data hiding b) Message passing
c) Platform independent d) Data binding

5. Which is the correct syntax of inheritance?


a) class base_classname :accessderived_classname{ /*define class body*/ };
b) class derived_classname : access base_classname{ /*define class body*/ };
c) class derived_classname :base_classname{ /*define class body*/ };
d) class base_classname :derived_classname{ /*define class body*/ };

70
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

6. Which among the following, for a pure OOP language, is true?


a) The language should follow at least 1 feature of OOP
b) The language must follow only 3 features of OOP
c) The language must follow all the rules of OOP
d) The language should follow 3 or more features of OOP

7. Which was the first purely object-oriented programming language developed?


a) Kotlin b) SmallTalk
c) Java d) C++
8. When OOP concept did first come into picture?
a) 1980’s b) 1995
c) 1970’s d) 1993

9. What is encapsulation in OOP?


a) It is a way of combining various data members and member functions that operate on those data
members into a single unit
b) It is a way of combining various data members and member functions into a single unit which
can operate on any data
c) It is a way of combining various data members into a single unit
d) It is a way of combining various member functions into a single unit

10. Which of the following is not true about polymorphism?


a) Helps in redefining the same functionality
b) Increases overhead of function definition always
c) It is feature of OOP
d) Ease in readability of program

[Link] Describe the features of Java as programming


language such as platform independent, multithreading,
distributed, etc.
The fundamental design objectives for the programming language Java were for it to be as portable,
easy to use, and secure as possible. In addition to these, this language has a number of other wonderful
traits that considerably contribute to the fact that it is so widely used. A different moniker for the Java
features is the term "Java buzzwords."
A list of the most important features of the Java language is given below.
• Simple
• Object-Oriented
• Portable

71
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

• Platform independent
• Secured
• Robust
• Architecture neutral
• Interpreted
• High Performance
• Multithreaded
• Distributed
• Dynamic

Fig. 2.1.3: Features of Java

Simple
Java is quite easy to learn, and its language is clean, concise, and basic to grasp. Sun Microsystem
asserts that Java is an easy-to-learn programming language since its syntax is based on C++, making
it easier for programmers to learn after C++. Numerous difficult but hardly ever features, like explicit
pointers and operator overloading, have been removed from Java. Since Java's garbage collection is
automated, there is no need to delete of unreferenced objects.
Object-oriented
Java is a platform that may be used for object-oriented programming. In Java, every element is an
object. Because it is object-oriented, the software that we use is structured as a collection of different
objects, each of which has data and activity associated with it. The method of programming known as
object-oriented programming (OOPs) simplifies the process of creating and maintaining software by
providing a set of fundamental standards.
Basic concepts of OOPs are:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation

72
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Platform Independent
Because Java is a write-once, run-anywhere language, it is distinct from other languages like C, C++,
etc. that are compiled into platform specific machines. The hardware or software environment that a
program operates in is referred to as a platform. Software-based and hardware-based platforms are
the two different categories. A platform based on software is offered by Java. Because it is a software-
based platform that operates on top of other hardware-based platforms, the Java platform is unique
from most other [Link] has two components:
• Runtime Environment
• API(Application Programming Interface)

Fig. 2.1.4: Platform independency

Code written in Java may be executed on many different operating systems, including but not limited to
Windows, Linux, Sun Solaris, and Mac OS. Java source code is processed by the compiler, which results
in the creation of bytecode. This particular bytecode is known as "Write Once and Run Anywhere"
(WORA) bytecode due to the fact that it may be used on several platforms (WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:
No explicit pointer
Java Programs run inside a virtual machine sandbox

Fig. 2.1.5: Secured

73
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Class loader: The Java Runtime Environment's (JRE) class loader is used to dynamically load Java classes
into the Java Virtual Machine. By isolating the package for local file system classes from those that are
imported from network sources, it increases security.
Bytecode Verifier: This program scans code fragments for unauthorized code that could violate object
access rights.
Security Manager: It establishes which resources, such as reading and writing to the local disc, a class
is permitted access to.
These security features are included by default with Java. A developer of an application can also
expressly offers some security using SSL, JAAS, cryptography, etc.

Robust
The English mining of Robust is strong. Java is robust because:
• A powerful memory management strategy is used.
• Any potential vulnerabilities are eliminated when pointers are not present.
• A Java application may make use of the Java Virtual Machine's automatic garbage collection feature
to get rid of objects that are no longer being used by the program. This feature functions on the
Java platform.
• Java includes both an exception management system and a type checking mechanism in its
programming language. The resilience of Java may be attributed to the combination of these
characteristics.

Architecture-neutral
Java is not tied to any certain architecture since there are no implementation-dependent properties in
the language, such as fixed-size basic types. When using the C programming language, the int data type
takes 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. On the
other hand, it uses up 4 bytes of memory in both the 32-bit and 64-bit versions of Java's architecture.

Portable
Java is portable because it makes it easy to move Java bytecode between different platforms. It doesn't
need to be put into practice.

High-performance
Java's bytecode is "near" to native code, which makes it quicker than other conventionally interpreted
programming languages. Even so, it is still somewhat slower than a compiled language (like C++).
Because Java is an interpreted language, it executes more slowly than compiled languages like C, C++,
etc.

Distributed
Java is a distributed programming language because it gives users the ability to build distributed
applications. RMI and EJB are tools that are used in the application development process for networked
computing. Because of a characteristic of Java, we may view the files and call the methods on any
machine that is connected to the internet from wherever we are.

74
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Multi-threaded
A thread is essentially a separate program that runs in parallel with other threads. By using several
threads, Java programs are able to accomplish a multitude of tasks all at once. The fact that individual
threads do not have to be allocated memory is the primary advantage of using multi-threading. It makes
use of a shared memory space. Threads are an essential component for multimedia, Web applications,
and other types of software.
A thread is the most fundamental component of processing; it is essentially a very small subprocess.
Both multiprocessing and multithreading are necessary in order to do several tasks at once. However,
as threads make use of a shared memory space, multithreading is the approach that we choose above
multiprocessing. They reduce the amount of memory used by not creating distinct memory regions,
and the process of context switching between the threads is sped up as a result. The most common
applications of Java multithreading are computer-animated movies and video games.

Dynamic
A dynamic language is Java. The dynamic loading of classes is supported. It indicates that classes are
loaded when needed. Additionally, it supports C and C++ native language functions.
Java offers automated memory management and dynamic compilation (garbage collection).

Exercise
MCQ Questions:
1. What is Portability offered by Java language?
a) Small code size easy to carry occupying less disk space
b) Generating suitable Byte Code for each machine by the Compiler
c) Ability to run the Byte on different machines producing the same behaviour and output
d) Java does not actually provide portability

2. Which one of the following is not a Java feature?


a) Object-oriented b) Use of pointers
c) Portable d) Dynamic and Extensible

3. The feature by which one object can interact with another object is _____________
a) Message reading b) Message Passing
c) Data transfer d) Data Binding

4. Which is not a feature of OOP in general definitions?


a) Efficient Code b) Code reusability
c) Modularity d) Duplicate/Redundant data

75
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

5. Which feature of OOP indicates code reusability?


a) Abstraction b) Polymorphism
c) Encapsulation d) Inheritance

6. Which feature of OOP reduces the use of nested classes?


a) Inheritance b) Binding
c) Abstraction d) Encapsulation

7. Which among the following best describes the Inheritance?


a) Using the data and functions into derived segment
b) Using already defined functions in a programming language
c) Using the code already written once
d) Copying the code already written

8. Single level inheritance supports _____________ inheritance.


a) Language independency b) Multiple inheritance
c) Compile time d) Runtime
9. Encapsulation and abstraction differ as ____________
a) Hiding and hiding respectively b) Binding and Hiding respectively
c) Hiding and Binding respectively d) Can be used any way

10. Which feature of OOP is exhibited by the function overriding?


a) Polymorphism b) Encapsulation
c) Abstraction d) Inheritance

11. ___________ underlines the feature of Polymorphism in a class.


a) Virtual Function b) Inline function
c) Enclosing class d) Nested class

[Link] Outline the terminology used in java programming


such as bytecode, JVM, JDK, JRC, etc.
Java Bytecode
What is Java Bytecode?
Java bytecode is the component that makes up the instruction set of the Java Virtual Machine. It
operates in a manner that is similar to that of an assembler, which is another name for C++ code. After
an application written in Java is compiled, bytecode written in Java is generated. To be more precise,

76
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

machine code in the form of a class file is what Java refers to as bytecode. With the assistance of java
bytecode, we are able to render Java to be platform independent.

How does it work?


After we have finished writing a Java program, the compiler will go through the program one last time
and generate bytecode for the specific area of code that was just written. If we so want, we may utilize
any other platform to execute the .class file in question. Following the first compilation, the Java Virtual
Machine, rather than the processor being taken into account, is the one to carry out the execution of
the generated bytecode. This basically means that on any computers on which we intend to execute our
code, we just need to have a minimal installation of Java on those systems in order to do so. The Java
Virtual Machine sends a request to the processor, asking it to provide the resources required to execute
the bytecode. The processor will next react by assigning the resources in the manner specified in the
request. JVMs are stack-based, which means that in order for them to read codes, implementations
need to stack.

Fig. 2.1.6: Java Byte code

Advantage of Java Byte code:


The provision of platform independence was one of the primary motivations for James Gosling's
creation of Java, and our bytecode implementation makes it possible for us to fulfil this goal. Because
of this, bytecode is an essential component of each Java program. Even while every system can parse
bytecode, the JVM commands that are available on each system may be unique. It is essential to keep in
mind that bytecodes are inherently unexecutable programs that can only be executed in the presence
of an interpreter. This is where the Java Virtual Machine (JVM) comes into play.
The Java Virtual Machine employs a language known as bytecode, which operates at the machine
level. When a class is loaded, it is presented with a stream of bytecode that corresponds to each of the
methods that it implements. When a method is called several times while a program is being executed,
the bytecode associated with that method is ultimately called upon. In addition to compiling the
program, Javac is responsible for producing the program's bytecode. Because of the way the bytecode
implementation is designed, we are able to comprehend that Java is a platform-independent language.

77
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

JVM
The JVM, which stands for Java Virtual Machine, is an example of an abstract machine. Because it is
a virtual computer, there is no physical representation of it. It is a runtime option that may be used
for the execution of Java bytecode, and it is offered as a standard. In addition to this, it is able to run
programs that were originally written in a different language but then converted into Java byte code.
JVMs are available for use on a variety of platforms, both hardware and software. The JVM, JRE, and
JDK are all platform-dependent since the configuration of each operating system is different. Java, on
the other hand, can run on almost any platform. There are three different components that make up
the JVM: the instance, the implementation, and the specification.

The JVM performs following operation:


• Loads code
• Verifies code
• Executes code
• Provides runtime environment

JVM provides definitions for the:


• Memory area
• Class file format
• Register set
• Garbage-collected heap
• Fatal error reporting etc.

JVM Architecture
Let us have a look at the JVM's internal structure, shall we? Included components include the class
loader, memory space, execution engine, and many more.

Fig. 2.1.7: JVM Architecture

Class loader
JVM's Classloader subsystem is used to load class files. The classloader loads the java application first
whenever we execute it. In Java, there are three built-in classloaders.

78
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Bootstrap Classloader: The initial classloader, which is the Extension classloader's super class, is this
one. It loads the [Link] file, which contains all the Java Standard Edition class files, such as the [Link],
[Link], [Link], [Link], and [Link] package classes.
Extension Class Loader: This is the parent classloader of the System classloader and the child classloader
of Bootstrap. The jar files in the $JAVA HOME/jre/lib/ext directory are loaded.
System/Application Class Loader: The Extension classloader's child classloader is this. The classpath
is used to load the classfiles. The classpath's default setting is the current directory. Using the "-cp" or
"-classpath" switch, you can modify the classpath. It also goes by the name of "application classloader."
//Let's see an example to print the classloader name

public class ClassLoaderExample


{
public static void main(String[] args)
{
// Let's print the classloader name of current class.
//Application/System classloader will load this class
Class c=[Link];
[Link]([Link]());
//If we print the classloader name of String, it will print null because it is an
//in-built class which is found in [Link], so it is loaded by Bootstrap classloader
[Link]([Link]());
}
}

Output:
[Link]$AppClassLoader@4e0e2f2a
null

These are the classloaders that Java offers internally. You must extend the ClassLoader class in order to
make your own classloader.

Class(Method) Area: Per-class structures like the runtime constant pool, field and method data, and
method code are stored in the Class(Method) Area.
Heap: The place where objects are allocated is called the runtime data area.
Stack: Frames are kept in Java Stack. It takes part in the invocation of the method as well as its return,
and it is responsible for maintaining local variables and incomplete results. At the same time that a
thread is being constructed, its associated private JVM stack is also being constructed. A new frame is
generated each time a method is used, so that there is always one available. A frame is discarded after
the method it corresponds to has been called.

79
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Program Counter Register: The address of the Java virtual machine instruction presently being executed
is stored in the PC (program counter) register.
Native Method Stack: It includes every native method employed by the program.

Execution Engine
It contains:
1. A virtual processor
2. Interpreter: executes the instructions after reading the bytecode stream.
3. JIT compiler, which stands for just-in-time: It is used in order to improve performance. JIT reduces
the amount of time needed for compilation by simultaneously compiling byte code parts that have
the same functionality as one another. In this context, the term "compiler" refers to a translator
that converts the instruction set of a Java virtual machine (JVM) to the instruction set of a certain
central processing unit (CPU).
Java Native Interface: The Java Native Interface (JNI) architecture enables communication with
programs written in other languages, such as C, C++, Assembly, etc. To connect with OS libraries or
transmit output to the Console, Java employs the JNI framework.

JRE
"Java Runtime Environment" is what the abbreviation "JRE" stands for. Java RTE is an additional method
of writing it. Programming in Java requires the usage of a set of software tools that are grouped together
under the name Java Runtime Environment. It is used because it is capable of providing the runtime
environment. It is the method through which the JVM is put together. It is not a myth; it is a fact. It
contains a collection of libraries and other items that are used by the JVM when it is being executed.
In addition to Sun Microsystems, a number of other firms actively release the JVM implementation.
The Java Development Kit includes the Java Run-time Environment (JRE) (JDK). It is a free software
package that includes a Java Class Library, particular tools, and a standalone JVM. It is the most prevalent
environment for running Java programs on devices. Java bytecode is generated once the source Java
code is compiled. JRE is required to run this bytecode on any platform. The JRE loads classes, validates
memory access, and obtains system resources. JRE is a layer that sits on top of the operating system.
It also contains:
• Java Web Start is one of the deployment technologies.
• User interface toolkits such as Java 2D.
• Java Database Connectivity (JDBC) and Java Naming and Directory Interface are examples of
integration libraries (JNDI).
• Lang and util libraries are examples.
• Java Management Extensions (JMX), Java Native Interface (JNI), and Java for XML Processing are
some more foundation libraries (JAX-WS).

JRE is made up of the following parts:


Deployment technologies such as deployment, Java plug-in, and Java Web Start are examples of
deployment technologies.
• Abstract Window Toolkit (AWT), Swing, Java 2D, Accessibility, Image I/O, Print Service, Sound, drag
and drop (DnD), and input methods are examples of user interface toolkits.

80
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

• Interface Definition Language (IDL), Java Database Connectivity (JDBC), Java Naming and Directory
Interface (JNDI), Remote Method Invocation (RMI), Remote Method Invocation Over Internet Inter-
Orb Protocol (RMI-IIOP), and scripting are examples of integration libraries.
• International support, input/output (I/O), extension mechanism, Beans, Java Management
Extensions (JMX), Java Native Interface (JNI), Math, Networking, Override Mechanism, Security,
Serialization, and Java for XML Processing are among the other fundamental libraries (XML JAXP).
• The fundamental libraries for Lang and Utilities include Lang and Utilities, zip, Java Archive (JAR),
instrument, reflection, Collections, Concurrency Utilities, management, versioning, Logging,
Preferences API, Ref Objects, and Regular Expressions.
• Server Virtual Machine and Java HotSpot Client are both parts of the Java Virtual Machine (JVM).

JDK
The phrase "Java Development Kit" is really an acronym for something longer. For the purpose of
developing Java applications and applets, a software development environment known as the Java
Development Kit (JDK) is used. It is not a myth; it is a fact. The JRE and several developer tools are
bundled together. The Java Development Kit (JDK) is an implementation of any of the Java Platforms
mentioned below; Oracle Corporation made all of these platforms accessible to the public.
• Standard Edition Java Platform
• Enterprise Edition Java Platform
• Micro Edition Java Platform

Fig. 2.1.8: JDK

The Java Development Kit (JDK) includes a private Java Virtual Machine (JVM) as well as a few additional
resources, such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation
generator (Javadoc), and so on. These resources are necessary for the completion of the creation of a
Java application.
JRC: Java Remote Control is a remote control application that may show the screen of another computer
on your screen when connected to the internet or a network. With the help of the application, you may
remotely operate another PC using your keyboard and mouse. It implies that you may access a remote

81
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

computer from wherever you are and use it just as though you were sitting in front of it. The application
enables you to collaborate with several distant computers at once, from any location in the globe. You
may even be able to forget that you are using a remote computer because the application is so quick
and comfy.

Exercise
MCQ Questions:
1. What does JVM stands for?
a) Java Variable Machine b) Java Virtual Machine
c) Java Virtual Mechanism d) None of the above

2. What is JVM?
a) JVM is the confined memory area
b) All java programs run inside JVM memory
c) JVM provides security to the computer by giving controlled access to Files and Memory on a
computer
d) All the above

3. When was first Version of Java i.e. Java 1.0 was released?
a) 1991 b) 1994
c) 1996 d) 1999

4. What is Ahead of Time Compiler in Java?


a) Ahead of time compiler compiles java files as and when you type and save.
b) Ahead of time compiler turns byte code to executable code line by line based on requirement
c) Ahead of time compiler is a replacement for JIT compiler to translate all byte code to a single
executable file or code to run the program fast and efficient.
d) None of the above

5. What is JIT in Java?


a) Java In Timer b) Java In Time Thread
c) Just In Time Compiler d) Just In Time Runnable

6. Choose the correct statement about Java?


a) JIT Compiler produces Byte Code from Java file.
b) JIT Compiler takes chunks of Byte Code as input and produces Executable code on that particular
machine.

82
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

c) JIT Compiler assists the actual JAVAC compiler to compile fast


d) None of the above

7. What happens in the absence of JIT Compiler in Java?


a) Byte code is produced slowly
b) Executable Code is produced slowly because of line by line Interpreting
c) Executable Code is produced without portability
d) None of the above

8. Which component is used to compile, debug and execute java program?


a) JVM b) JDK
c) JIT d) JRE

9. Which component is responsible for converting bytecode into machine specific code?
a) JVM b) JDK
c) JIT d) JRE

10. Which component is responsible to run java program?


a) JVM b) JDK
c) JIT d) JRE

[Link] Explain how Java can act as both compiled and


interpreted language
Java implementations typically use a compilation process that takes place across two stages. A byte
code representation of Java source code is produced by the Java compiler. The byte code is executed
by a Java Virtual Machine (JVM). Just-in-time (JIT) compilation is a technique that modern JVMs use to
dynamically transform byte code into native instructions that can be processed by hardware CPUs. This
technique is also known as just-in-time compilation.
Instead of JIT translating the byte code to machine code first, certain JVM implementations may choose
to execute the byte code directly from memory. Despite the fact that this is still referred to as an
"interpreter," it is quite different from interpreters that read and execute high-level source code (i.e. in
this case, Java source code is not interpreted directly, the byte code, output of Java compiler, is.)
Java can first be compiled down to native code, and the resulting binary may then be executed. The
Java source code may potentially be directly interpreted, which is a possibility. To sum up, byte code can
be any of the following depending on the execution environment:
• After being precompiled, native code is put through its paces in the same manner as the vast
majority of C++ compilers.
• Interpreted code
• Direct processing by a suitable processor
• Just-in-time compilation and execution (bytecode is the native instruction set of some CPUs)

83
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Fig. 2.1.9: Java Compile time and Runtime

When we first start learning how to program in Java, one of the questions that often arises is whether
or not Java is interpreted, compiled, or both. In addition, the interviewer may ask you this question
if they are interested in hiring someone for a job that is linked to Java. The question may easily be
answered because to the fact that Java can be interpreted in addition to being compiled. It is not
evident if Java is compiled or interpreted; the choice is left up to the user. Compiling a source file does
not result in the creation of machine code, nor does it understand a source file in order to execute code
line by line. In order to provide a solution to this problem, we need to have an understanding of how
the Java programming language works across several platforms. This indicates that Java code produced
for one platform may work on other platforms such as hardware operating systems without the need
for any adjustments being made to the code. Therefore, your capacity to appreciate how Java achieves
platform independence will determine whether or not you are able to provide a complete solution to
this topic.
Java is completely portable; this means that the same Java code will operate faultlessly on many
different platforms, regardless of whether or not the hardware is compatible with the operating
system. The JVM is able to execute rapidly and effectively because the source code is compiled into
byte code. In addition to this, the portability of the Java programming language is provided through its
use of byte code. It permits the execution of this code on any JVM that is appropriately implemented
on a computer, regardless of the hardware, software, or settings of the system. Moreover, it is not
dependent on whether or not the machine is running Windows or Linux. The Java Virtual Machine
(JVM) is a component that can be found in almost all web browsers and is responsible for running Java
applet [Link] can execute a Java application by following two steps.
• Compile the Java program
• Execute the application

Compile the Java application:


To compile the Java program, execute the below command: javac [Link]
The above command will compile the Java program and produce [Link] file that houses the Java
application's byte code.

84
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Fig. 2.1.10: Java compilation

The result shown above demonstrates that a class file is generated following the compilation of the
Java application. The Java program's byte code may be found in this file. This byte code may be run on
any system that supports the JVM.

Execute the Application:


To execute this application, execute the below command:
• java Basic

The above command will execute the byte code and perform the functionality of the program:

From the above output, we have printed a simple statement.

Step by Step execution of the Java program:


• Write some Java code and save it as [Link] file.
• This file is going to be compiled using the Java compiler, which is known as javac.
• The Java Compiler will convert the Java file into byte code and produce a class file (which is not
actually a machine code, unlike the C compiler). The byte code that is produced by the Java Compiler
cannot be executed; therefore, an interpreter is required to translate the byte code into machine
code. It is handled by the JVM in this case.
• Now, the Java Virtual Machine (JVM) will execute these bytes of code in order to execute Java bytes
on a computer.
• The process will now be carried out by our software, which will thereafter deliver the desired
outcomes.

Java is seen as being both compiled and interpreted. To fully run a Java program on a system, it requires
the Java compiler (javac) and JVM, which is basically a software-based interpreter.

85
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Exercise
MCQ Questions:
1. What is the extension of java code files?
a) .js b) .txt
c) .class d) .java

2. What are the valid White Spaces available in Java language?


a) Space b) Enter
c) Tab d) All the above

3. A valid Identifier or name in Java language can start with which character?
a) a-z, A-Z b) $, _
c) 0-9 d) A and B

4. What is an Interpreter?
a) An interpreter converts instructions line by line
b) An Interpreter converts source code to low-level code
c) Interpreters are slow to execute
d) All the above

5. What is a Compiler?
a) A Compiler converts all instructions in one go.
b) A compiler converts source code to low-level code
c) Compilers work fast
d) All the above

6. Bytecode is given as input to _______________.


a) JRE b) Linker
c) JVM d) Assembler

7. Output of a Java compiler is ________________.


a) non executable code
b) executable code

8. Output of the Java Compiler is Executable.


a) True b) False

86
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

9. Byte code is set of highly optimized code. Is it true or false?


a) False b) True

10. JVM will differ from platform to platform but still all understand the Same Java Bytecode
a) True b) False

[Link] List the tools used for programming in Java


Java has been around for twenty-six years already, and it is still one of the most popular programming
languages in use today. Things have definitely moved in a different direction ever since Oracle
Corporation seized control of Sun Microsystems. On the other hand, it doesn't seem like Java's
popularity is going anywhere anytime soon (much to the dismay of its opponents). Over the course of
time, both the number of people who use Java and the number of people who produce software using
Java has substantially expanded, as has the ease with which Java may be programmed.
In the early days of the Java programming language, a text editor was a Java programmer's most trusted
companion. Programmers had a lot of obligations in the past, but now there are a lot of tools available,
both free and commercial, that may help alleviate some of those tasks. The modern Java programmer
has access to a broad variety of tools, some of which include complete code editors, debuggers, and
profilers, in addition to tools for performance assessment, version control, and other things. And this
was accomplished in a fraction of the time that previous Java developers had to spend in order to
accomplish the same task.
The developers of today are in the fortunate position of having access to a broad array of tools;
nevertheless, this may also be seen as a disadvantage. It is not unusual for a piece of software or
hardware to become obsolete in a matter of months while at the same time 10 new alternatives emerge
to take its place. When faced with such situations, it might be difficult to decide which Java coding tool
to learn and utilize, which is particularly true for new developers. In order to address this issue, we have
compiled a list of eleven Java tools that every Java developer need to have in their toolboxes and have
identified these tools. Therefore, courageous soldier (programmer), continue your march and find the
materials you'll need to boost your Java programming abilities.

Java Tools
Before we go on to the list of Java tools, let us stop for a second and briefly go over what is meant by
the term "Java tool." Technically speaking, any software program that was developed to build, manage,
test, debug, troubleshoot, and monitor Java applications is considered to be a Java tool. As you may
have guessed, the primary objective of a Java tool is to facilitate the production and dissemination of
Java applications on a broad scale by providing programmers with the means to do so. These tools are
extensions to the Java programming language that provide it with functionality that is lacking in the
standard version of the language. For example, SonarLint is an integrated development environment
(IDE) plugin that provides assistance to programmers in the process of writing clean and secure code.
This is a capability that Java lacks by default. Tools for developing with Java were formerly considered
novelties; nevertheless, nowadays, all Java developers, regardless of their degree of expertise, utilize
these tools on a regular basis.

NetBeans IDE
For the purpose of developing desktop, internet, mobile, and other kinds of applications, Java
programmers use a piece of software called the Netbeans IDE (integrated development environment),

87
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

which is more often referred to simply as Netbeans. Imagine it as an enhanced version of the Java text
editor that you are familiar with.
Initially released in 1997 as a Java integrated development environment (IDE) project for students,
Netbeans was once known as Xelfi. Before Sun Microsystems, the company that originated Java,
purchased Netbeans in 1999, a few different iterations of the software had already been developed
and made available.
Since then, Netbeans has undergone a number of upgrades and changes, propelling it to a position
among the most popular Java integrated development environments (IDEs). It is an open-source
integrated development environment (IDE) that is composed of modules, which are sets of Java classes
that collaborate with the Netbeans APIs to provide specific functionality to Java applications, and a
graphical user interface (GUI) (GUI).
The all-inclusive Java development tool known as Netbeans supports all of the most current editions
of the Java programming languages, including Java SE, JavaFX, and Java EE, out of the box. In addition,
the version control system Git and the Maven tool, which is used to automate Java builds, are also
supported. It is also the official integrated development environment (IDE) for Java 8.
Netbeans is supported by a number of well-known operating systems, including Windows, Mac OS,
Linux, and Solaris. In addition to this, it is compatible with languages other than Java, including HTML5,
PHP, and C++ (albeit via extensions). Choose NetBeans if you are just starting started with Java and
need an integrated development environment (IDE) that is both capable and user-friendly to novices.

Eclipse IDE
The Eclipse IDE is another incredibly well-liked Java integrated development environment (IDE), and
what separates it from the competition is its extensive support for plug-ins. This open-source integrated
development environment comes with a PDE, which stands for "plug-in development environment."
This makes it simpler for users to design and make use of a wide variety of plug-ins. The PDE comes with
its own set of tools, which may be used to construct, test, create, and deploy Eclipse plug-ins, plug-in
fragments, application features, and other similar things.
Another feature that really sets the Eclipse IDE apart from the competition is the Rich Client Platform
(RCP). The RCP makes it possible for developers to construct independent client applications that are
packed with features by supplying them with a variety of plug-ins as well as an extra framework. The
functionality of RCP-built applications is comparable to that of native desktop software. Both NetBeans
and Eclipse are popular choices when it comes to developing Java software. It also allows for the
building of programs written in a variety of other programming languages, such as C, C++, C#, COBOL,
JavaScript, Perl, PHP, Python, R, and Ruby, amongst others, via the use of plug-ins.
One of the many advantages of using Eclipse is that, according to its proponents, it is able to easily
handle large projects and has a graphical development environment (PDE). Because Eclipse is notorious
for its unreliability, complexity, and sluggish performance, it is safe to say that it is not exactly user-
friendly for those just starting out. Therefore, if you wish to replace your current integrated development
environment (IDE) with one that is larger, more feature-rich, and more scalable, you should investigate
Eclipse.

SonarQube
Now that we have our Java IDE priorities in order, it is time to work on improving the quality of the Java
code that we have written. There are a lot of tools for ensuring the quality of code that are accessible
online, but SonarQube is one of the best. The primary function of SonarQube, which is an open-
source platform for doing continuous code inspection, is to perform static code analysis. SonarSource
developed SonarQube, an application that does automated code analysis to identify issues like as

88
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

mistakes, security flaws, faulty code, and many types of technical debts.
In addition to this, it integrates seamlessly as a plug-in with integrated development environments
(IDEs) such as Eclipse and IntelliJ as well as build automation tools such as Maven and Gradle, among
others (SonarLint).
The reports generated by SonarQube emphasize a variety of variables, including code complexity,
security, test coverage, style, and others, to assist programmers in writing code that is both secure and
readable.
Java is one of the amazing number of programming languages that are supported by the SonarQube
platform, which has earned great acclaim across the industry.

Spring
Spring is a well-known and comprehensive open-source Java application framework that is often used
by developers to construct Java Enterprise and Internet applications. Spring is a framework that enables
developers to construct secure, dependable, and scalable applications in a short amount of time.
It conforms to the programming paradigms of aspect-oriented programming (AOP) and dependency
injection (DI), which is basically where its power lies. Spring is a meta-framework composed of sub-
frameworks such as Spring Web Flow, Spring MVC, and Spring ORM. Spring's IoC (inversion of control)
containers offer an advantage over other application frameworks. The IoC programming paradigm
requires objects to declare their dependencies. The mentioned dependencies are then injected by the
container into the corresponding objects, thus the term Dependency Injection.
The IoC container is responsible for establishing and maintaining the object lifecycle, which includes
producing new objects, executing initialization methods on existing objects, and linking objects
together. Since its founding in 2002, Spring has amassed a substantial developer community. These
characteristics make it an established and well-maintained framework that all Java programmers should
be acquainted with.

Junit
Unit testing is an essential component of software development since it serves the purpose of ensuring
that an application fulfils all of the required quality standards prior to being made available to users.
It is a technique of testing that involves carrying out tests on units, often known as code modules, and
ensuring that their integrity has not been compromised. In light of the relevance of unit testing, it is
very necessary to have a solid unit testing tool at one's disposal. This is when JUnit comes into play in
the scenario.
Use the open-source JUnit testing framework while developing Java unit tests by following the
instructions provided. A vital component of the test-driven development methodology is the unit testing
framework known as JUnit, which is a part of the xUnit family (TDD). JUnit is a unit testing framework
that is widely used by Java programmers and has become so widespread that it has essentially become
the industry standard. In point of fact, according to a research that was published in 2017, the JUnit
library was used in some capacity by 97 percent of all Maven-based projects that were hosted on
GitHub.

89
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Fig. 2.1.11: Java tools stats

The simplicity of JUnit and the fact that it is so easy to use make it one of its primary selling points. In
addition to this, it provides annotations, which are a kind of metadata that increase the readability of
code by describing the purpose of a test.
Test suites are another one of JUnit's many strengths. At their core, these suites are collections of
test cases (and perhaps even additional test suites) that engineers are able to run in parallel. Another
aspect is the tendency that developers have for using automated testing, which JUnit has become more
popular for. JUnit can run automated tests, collect data, and offer immediate feedback all at the same
time.
When everything is taken into account, JUnit is a dependable testing tool that every Java developer
need to have in their arsenal of tools.

Android Studio
You may use a variety of high-quality integrated development environments (IDEs) to develop
applications for the Android operating system, such as NetBeans, Eclipse, IntelliJ IDEA, and so on.
However, if you are serious about enhancing your skills to design applications for Android devices, your
best choice is to make use of Android Studio. The official integrated development environment (IDE)
for Android is known as Android Studio, and it is based on the IntelliJ IDEA IDE developed by JetBrains.
It is a faster, more effective, and more dependable alternative to Eclipse, which was a popular platform
for the development of Android apps in the past.
You are able to create applications for almost all Android devices by using a tool called as Android
Studio, which is a comprehensive software package. It also comes with a full Android emulator, which
allows users to test their applications on a variety of Android device configurations. Android Studio
offers a plethora of features, such as code templates, example applications, an intelligent code editor, a
wide variety of testing tools and frameworks, and simple integration for Flutter, Git version control, and
other features, to facilitate quick and efficient programming. Among these features are: code templates;
example applications; an intelligent code editor; a large range of testing tools and frameworks; and
more. In addition, it has a method known as "apply modifications," which enables programmers to
make alterations to the application code without having to restart the application that is now being
used.
Android Studio, which is backed by Google and JetBrains, is packed to the gills with tools and features
that simplify and expedite the process of developing Android apps. In addition, there is no valid reason
for you not to make advantage of them in order to increase the quality of the mobile apps you create.

90
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Apache Maven
Maven is described as an open-source "project management tool and comprehension tool" on its
official website, which states that the Apache Software Foundation is the organization that developed
and maintains Maven. To put it simply, it is a build automation tool that provides developers with a
comprehensive framework for the whole build life cycle of all of their projects. Programmers use the
tool known as Maven to build, publish, and deploy projects written in languages such as Java, C#, Ruby,
Scala, and others. Maven based its business on the POM (Project Object Model). All of the information
that is required by the project, including the dependencies, files, plug-ins, and any other external
components, is stored in a file that is essentially [Link] file. This file also contains the information
about the project itself.
Within the POM paradigm, the only thing that developers are need to do is specify the exceptions for a
project, which drastically cuts down on the complexity that is often involved with project management.
Additionally, Maven offers a standardized build system that has a consistent manner of operation and
a shared directory structure. When a user is familiar with the build process for one project, it may be
quite simple for them to go through several projects.
In addition, the website for the Apache Maven project provides information on a number of subtle
features and development best practices. This is done with the goal of assisting users in becoming
acquainted with the tool in a more expedient manner.

Gradle
Gradle, an open-source, multilingual, general-purpose build automation tool, promises to execute faster
and scale more efficiently than its competitors. Gradle, a relatively new participant in the field of build
automation, targets Maven and Apache Ant and even use the former for performance assessment. The
website's statistics indicate that Gradle is always at least twice as fast than Maven.
Gradle requires a JVM, thus Java developers may benefit from integrating popular Java APIs, such as
custom tasks and plugins, into their build logic. Gradle can work on most systems due to its dependency
on the JVM; installing the JDK is all that is required (s). Gradle is well suited for the construction of
many projects with scaling possibilities. It is a powerful tool that can be integrated into a number of
integrated development environments, including Android Studio, NetBeans, Eclipse, IntelliJ IDEA, and
Eclipse. Google also released Gradle as the official build automation framework for Android Studio in
2013. Gradle is substantially less user-friendly and more difficult to master than Maven. Additionally, it
has integration concerns with IDEs. However, according to its website, the development team is always
working to improve its various features and increase its use for developers.

Jenkins
An open-source servlet container, such as Apache Tomcat, is where Jenkins runs. It is a server-based
DevOps automation tool. Jenkins, a Java-based tool for software development, speeds up the process
by automating steps including the creation, testing, and distribution of software.
When it comes to adopting the CI/CD (continuous integration and continuous deployment) software
development paradigm, Jenkins is a well-liked option. It enables developers to quickly incorporate
changes into the source code and continually build and test their software applications.
Jenkins supports more than 1000 plug-ins, which is one of its main benefits. With the help of these
plug-ins, users may utilize Jenkins to automate software development for many platforms. Jenkins
also offers a robust developer community as a result of being free and open-source, which is another
motivation for you to jump on the Jenkins train.

91
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Exercise
MCQ Questions:
1. Choose a correct statement about Java source files.
a) Java files are human readable
b) Java files contain Classes with Methods and Variables
c) Import statements import library Classes into our class
d) All the above

2. What is the output of Compilation of Java Program?


a) .class file b) .cla file
c).jc file d) .javax file

3. What is the file name extension of a Java source program?


a) .j b) .ja
c) .java d).jax

4. What are the main Distribution types of Java Software?


a) Java SE (Java Standard Edition) b) Java EE (Java Enterprise Edition)
c) Java ME (Java Micro Edition) d) All the above

5. What is the Java distribution type used to build Web Apps in Java?
a) Java SE b) Java EE
c) Java ME d) Java Embedded

6. What is LTS mentioned along with Java Version names like Java SE 11 LTS?
a) LTS stands for Long Term Support
b) LTS Versions are patched for security vulnerabilities for up to 5 Years from the release date.
c) Java SE 8 LTS (supported up to March 2022) and Java SE 11 LTS (supported up to September
2023) are available as of now.
d) All the above

7. What is a Java Editor?


a) Java editor is simply an IDE like Notepad to type or edit java programs. It does not have ability
Compiling or Running java programs without installing separate Java Packages on the PC.
b) Java editor is like Eclipse IDE that has shortcut options or buttons to compile and run java
programs without using CMD or Command Line.
c) Java IDE searches for the installed Java location for JAVAC, JAVA and JAWAH to compile and run
programs for you.
d) All the above

92
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

8. Which of below is not a dependency management tool?


a) Ant b) Maven
c) Gradle d) Jenkins

9. Which of the following is not a maven goal?


a) clean b) package
c) install d) debug

10. Which file is used to define dependency in maven?


a) [Link] b) [Link]
c) [Link] d) [Link]

[Link] Demonstrate the elements of imperative


programming such as variables, flow control and Methods
Variables
Implementation of Variables in Java
Data values are stored in containers called variables.
There are several sorts of variables in Java, including:
• String – strings stores text, such as "Hello". String values are surrounded by double quotes
• int – int stores integers (whole numbers), without decimals, such as 111 or -111
• float – float stores floating point numbers, with decimals, such as 19.90 or -19.90
• char – char stores single characters, such as 'A' or 'z'. Char values are surrounded by single quotes
• Boolean - Boolean stores values with two states: true or false

Declaring (Creating) Variables


A variable must have a type and a value before being created:

Syntax:
type variableName = value;
where variableName is the name of the variable and type is one of the Java types, such int or string
(such as x or name). The variable is given values by using the equal sign.
Take a look0 at the example below to learn how to build a variable that should hold text:
Example: Create a variable called name of type String and assign it the value "John":
Input:
String name = "Jan";
[Link](name);

93
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Output:
Jan

Take a look at the example below to learn how to build a variable that should hold a number:
Example: Create a variable called myNum of type int and assign it the value 15:

Input: int num = 10;


[Link](num);

Output:10

Another option is to declare a variable without giving it a value and give it one later:
Example
Input: int myNum;
myNum = 10;
[Link](myNum);

Output:10

Be aware that if you give an existing variable a new value, the old value will be replaced:

Example
Change the value of myNum from 15 to 20:
Input: int myNum = 10;
myNum = 20; // myNum is now 20
[Link](myNum);
Output: 20

Final Variables: Use the final keyword to designate the variable as "final" or "constant," which implies
unchangeable and read-only, if you don't want anyone (or yourself) to modify the values:

Example:
Input: final int myNum = 15;
myNum = 22; // will generate an error: cannot assign a value
Output: [Link]: error: cannot assign a value to final variable myNum
myNum = 22;
^

94
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

1 error

Other Types: An example of declaring variables of different types:


Example int myNum = 50;
float myFloatNum = 5.9f;
char myLetter = 'X';
booleanmyBool = true;
String myText = "hello";

Print (Display) Variables


To print variables, the println() function is frequently used.
Use the + symbol to combine text and a variable:

Example
Input: String name = "World";
[Link]("Hello " + name);
Output: Hello World

Additionally, you may add a variable to another variable by using the plus sign (+):
Example
Input:
String firstName = "Hello ";
String lastName = "World!!";
String fullName = firstName + lastName;
[Link](fullName);
Output: Hello World!!

The + symbol functions as a mathematical operator for numeric values (note that we are using int
(integer) variables here):

Example
Input:
int x = 5;
int y = 5;
[Link](x + y); // Print the value of x + y
Output: 10

95
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

From the example above, you can expect:


• x stores the value 5
• y stores the value 5
• Then we use the println() method to display the value of x + y, which is 10.

Declare Many Variables


Example
Instead of writing:
Input:
int x = 5;
int y = 6;
int z = 52;
[Link](x + y + z);

You can simply write:


Input:
int x = 5, y = 6, z = 52;
[Link](x + y + z);

Output: 63

One Value to Multiple Variables


Also, you may set the same value for several variables in a single line:
Example
Input:
int x, y, z;
x = y = z = 70;
[Link](x + y + z);
Output: 210

Java Identifiers
All Java variables must have unique names to identify them.
We refer to these special names as identifiers.
Example
Input:
// Good
int minutesPerHour = 60;

96
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

// OK, but not so easy to understand what m actually is


int m = 60;

Output:
60
60

The general rules for naming variables are:


• Letters, numbers, underscores, and dollar signs can all be used in names.
• Names have to begin with a letter.
• Names cannot contain any spaces and must begin with a lowercase letter.
• In addition, names can start with $ and _
• Case sensitive names only ("myVar" and "myvar" are different variables)
• Names cannot contain reserved terms (such as Java keywords like int or boolean).

Flow Control
In programming, control flow statements regulate the order in which statements from a file are
executed by the computer. They enable us to control how our software executes.
Java offers a wide range of control statements to assist govern the program's flow. The decision-making
statements in Java will be the main subject of this article's examination. Let's get started and learn
more about them.

Introduction to Java Control Flow Statements


Consider the possibility that the covid virus, which is spreading across India, may reach your campus.
You must decide whether to remain enrolled or to withdraw after a brief absence.
Our decision will decide which path we choose in this circumstance. Many of these issues arise in our
daily lives, and we must make judgments about how to proceed. Java's control flow statements allow
us to program for such situations.
Every programming language follows the sequence of the script, beginning with the first line and ending
with the last. Using control flow statements, we may direct the execution of the program. Without
them, the interpreter would simply execute the code in the order it was written in the file, preventing
us from modifying the order or flow.

Types of Control Flow Statements in Java


There are three types of Control Flow Statements in Java:
• Decision-Making Statement
• Loop Statements
• Jump Statements

97
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Decision-Making Statement:
Enable in decision-making It determines when and which statement should be executed. Java has the
ability to use selection structures or statements to make judgments. They assess the choice in light of
the given circumstances and carry on with the program's flow in that particular direction.

Java provides two types of decision-making statements:


• if Statement
• switch Statement

A decision-making process is selection. Which method the system employs is determined by the result
of a decision.
For instance, a program may inform a user that they are old enough to operate a vehicle. The system
will take one path and take one action if the user is old enough to drive; otherwise, it will take a
different path and do a different action.

If Statement
The simplest decision-making statement is a "if" statement. Based on the test condition, it is used to
determine if a block of code should be run or not. The block is carried out if the condition is true; else,
it is skipped.
Syntax of If statement:
if(condition) {
block of code // is executed if the condition is true
}
In this case, the condition will either be true or falsely assessed. A block of code will be run if the value
is true. If not, it will disregard it and move on to the sentence immediately after the if instruction.
Below is the flow diagram of the

If-statement:
If-Statement flow
As shown in the diagram above, the test expression is first evaluated. If the evaluation produces a true
result, the body of the if statement is then run; if not, the 'if' block is bypassed, and execution occurs
below it.
Let's understand with an example:
public class IfExample {
public static void main(String args[]) {
int covid_cases = 50;
if (covid_cases >= 45) {
[Link]("home!");
}
[Link]("Raju is staying in college!");

98
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

}
}
Output: home!

The program in the above example determines its direction based on the circumstances. The statement
inside the if command is carried out if the number of covid cases is greater than 45. If the number of
covid instances is less than 45, the condition is false, and the statement within the if command goes to
the following sentence.
Note: If we don't add curly brackets after the if condition, the immediate one statement will automatically
be seen as being inside the block of code.

If-Else statement
An addition to the If-statement is "If-Else." The if statement only specifies a course of action if the
condition is true. When the condition is false, there is no information provided. When the condition is
false, the else block provided by If-Else is carried out. It has a clause that allows for the addition of one
extra block of code.
As an illustration, if it is pouring outside, bring an umbrella; otherwise, leave it at home.
Syntax of if-else:

if(condition) {
block of code // executes if the condition is true

else {
block of code // executes if the condition is false
}

The condition is first determined to be true or false in this case. The program runs the block of code
inside the if statement if the value is true; otherwise, if the value is false, the program runs the block
of code inside the else statement.

Flow Diagram of If-Else Statement:

Fig. 2.1.12: If-Else statement

99
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

The body of the if statement will include the test expression if it returns true; otherwise, the body of
the otherwise statement will contain the test expression if it returns false.

Let's get a clear understanding through an example:


public class IfElseExample {
public static void main(String args []) {
boolean rainy = false;
if (rainy) {
[Link]("umbrella");
}
else {
[Link]("No umbrella");
}
}
}
Output: No umbrella

The above program condition affects whether or not it is raining. Because it returns a false result, the
program avoids the if command and enters the else block, where it executes the line "No need for an
umbrella." Using Decision Making Statements allows us to make judgments rapidly.
If-Else-If Ladder: An if statement is followed by several else-if statements in a "If-Else-If" ladder. It is
employed to test a condition over several statements. The series of if statements is carried out bottom-
up.
A second else if condition is evaluated when a first if condition evaluates to false, and so on until the
last else if condition is examined. It can be ended with either an else block or an else if block.

Syntax of If-Else-If Ladder:


if (condition) {
statement;
} else if (condition) {
statement;
}
.
.
.
else {
statement;
}

100
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

The software examines each if condition, and if any of them return true, it executes the statement
contained in that if block and skips the rest of the ladder. If none of the conditions evaluate to true, the
program executes the statement in the last else block.

For Example:
public class IfElseLadderExample {
public static void main(String args[]) {
int age = 55;
if (age >= 60) {
[Link]("Raju is double-vaccinated");
} else if (age >= 50 && age < 60) {
[Link]("Raju is vaccinated with single-dose only");
} else if (age >= 40 && age < 50) {
[Link]("Raju is not vaccinated");
} else {
[Link]("Raju is not eligible for vaccine ");
}
}
}
Output: Raju is vaccinated with single-dose only

The computer code in the previously described illustration searches for the initial if condition. Whenever
it obtains a value that is not true, it proceeds to the else if block that comes next. The program executes
the line inside the second otherwise if block and skips the sentences below because the condition
evaluates to true since the value of age falls between 60 and 50. This allows the software to perform
the line within the second otherwise if block.

Below is the flow diagram of If-else-if ladder:

Fig. 2.1.13: If-else-if ladder Flow chart

101
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

The condition is evaluated by the program shown in the flow diagram above first, and if it is found to
be true, the program proceeds to execute the code contained inside the first if condition while ignoring
the other conditions. In the event that this is not the case, the next condition is evaluated, and if it too
is determined to be false, the process continues on to the next condition. It will continue to do this until
it has investigated every possible scenario.

Nested-If
The term "nested-if" refers to the use of an if statement inside of another if statement. Java enables us
to stack if statements inside of another if or else if clause.

Syntax of nested-if:
if(condition1) {
statement1 //executes when condition1 is true

if(condition2) {
statement2 //executes when condition2 is true
}
}
One if statement serves as the purpose of another if or else in nested if. If the first if condition evaluates
to true, the program proceeds to the nested if, if, and only if; otherwise, it goes to the next section.

Here is an example of the nested-if statement:


public class NestedIf {
public static void main(String args[]) {
int age = 20, weight = 50;
if(age >= 18) {
[Link]("Raju is allowed to vote");
if(weight >= 45) {
[Link]("Raju is allowed to vote and is fit to donate blood");
}
else {
[Link]("Raju is not fit to donate blood");
}
}
else {
[Link]("Raju is not allowed to vote");
}
}

102
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Output:
Raju is allowed to Vote
Raju is allowed to vote and is fit to donate blood
As the age is more than 18 in the example above, the first condition results in a true value, prints the
statement thereafter, thus the program analyses the second condition and executes the line within the
nested if block.

Flow-Diagram of Nested-if:

Fig. 2.1.4: Nested-if flow chart

Nested-If checks the nested test condition and, depending on the outcome, jumps directly to the body
of the if or nested else block if the test condition evaluates to false. Otherwise, if it evaluates to true, it
checks the nested test condition and, depending on the outcome, jumps to the body of the else block.
It then exits and moves to the code immediately below the if expression after analysing the nested
condition.
• We make use of statements that govern the flow of the program.
• In order to reach conclusions, Java may make use of selection structures or statements.
• If a test condition is used to decide whether or not to execute a chunk of code, the statement will
be executed even if the test condition is false.
• If-Else is a sentence that may be added to the If-statement. If the condition is not met, the else
block that was supplied by the If-Else statement is executed.
• In an if-else-if ladder, an if statement is followed by a number of subsequent if statements that
evaluate to false. It is used to determine if a condition is true over several assertions.

103
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

• In nested-if syntax, the purpose of one if statement is to be the aim of another if statement. In the
event that the first if condition is found to have a true value, the program will go on to the nested
if, if, and only if block; otherwise, it will move to the next section.

Loop Statements
A section of the program is repeatedly iterated using the Java for loop. Use of a for loop is advised if
the number of iterations is fixed.
There are three types of for loops in Java.
• Simple for Loop
• For-each or Enhanced for Loop
• Labeled for Loop

Java Simple for Loop


The C/C++ for loop is straightforward. The variable can be initialised, the condition tested, and the
value incremented or decremented. There are four sections to it:
• Initialization: When the loop begins, the first condition is the one that is run once. Here, we have
the option of initializing the variable or using one that has already been initialized. It's an optional
requirement.
• Condition: Every time the loop's state is tested, the second condition is what is carried out. Until
the condition is false, execution keeps on. Either true or false must be returned as a boolean value.
It's an optional requirement.
• Increment/Decrement: The variable value is increased or decreased as a result. It's an optional
requirement.
• Statement: Every time the second condition is met, the loop's statement is carried out.

Syntax:
for(initialization; condition; increment/decrement){
//statement or code to be executed
}

Example:
[Link]

//Java Program to demonstrate the example of for loop


//which prints table of 1
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
[Link](i);

104
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

}
}
}

Output:
1
2
3
4
5
6
7
8
9
10

Java Nested for Loop


Nested for loops are for loops that are contained within other loops. Every time the outer loop runs,
the inner loop also does.
Example:
[Link]

public class NestedForExample {


public static void main(String[] args) {
//loop of i
for(int i=1;i<=3;i++){
//loop of j
for(int j=1;j<=3;j++){
[Link](i+" "+j);
}//end of i
}//end of j
}
}

Output:
11
12

105
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

13
21
22
23
1
2
33

Java LabeledFor Loop


Each Java for loop can have a name. We utilize label before the for loop to do this. We may break/
continue a particular for loop, which is helpful when employing nested for loops.
Syntax:
labelname:
for(initialization; condition; increment/decrement) {
//code to be executed
}
Example:
[Link]
public class LabeledForExample {
public static void main(String[] args) {
//Using Label for outer and for loop
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
[Link](i+" "+j);
}
}
}
}

Output:
11
12

106
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

13
21
The default behaviour of any loop is to break the inner loop only if you use the break bb;

Java Infinitive for Loop


The for loop becomes infinite if two semicolons are used, or ;;.

Syntax:
for(;;)
{
//code to be executed
}

Example:
[Link]

//Java program to demonstrate the use of infinite for loop


//which prints an statement
public class ForExample {
public static void main(String[] args) {
//Using no condition in for loop
for(;;){
[Link]("infinitive loop");
}
}
}

Output:
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c
Now, you need to press ctrl+c to exit from the program.

107
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Jump Statements
By jumping to another section of code inside the program, jump statements assist in changing the
execution flow. Because they alter the execution flow in this way, they are often referred to as branching
statements.

The Break Statement


With iteration statements like for, while, and do-while loops, the break statement is frequently utilised.
To exit loops and switch situations, use break statements. If a loop contains a break statement, the
control stops the loop from running and moves on to the next set of statements, if any.

Example:
public class Main
{
public static void main(String args[])
{
int i;
for(i = 1; i<= 10; i++)
{
if (i == 5) break;
[Link](i + " ");
}
}
}
Output:1 2 3 4

Every block of instructions in a switch case finishes with a break statement. This makes sure that the
remaining switch case situations are disregarded and skipped.

Example:
public class Main
{
public static void main(String args[])
{
int i = 3;
switch(i){
case 1: [Link]("One");
break;
case 2: [Link]("Two");

108
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

break;
case 3: [Link]("Three");
break;
case 4: [Link]("Four");
break;
default: [Link]("Other");
}
}
}
Output: Three

The Continue Statement


When bypassing the current iteration of a loop, the continue statement is used. It enables the control
to momentarily leave the loop and disregard the subsequent assertions. The control instantly advances
with the following iteration of the same loop after this jump.
Example:
public class Main
{
public static void main(String args[])
{
for (int i = 10; i>0 ;i--)
{
if (i%2 == 0)
continue;
[Link](i+ " ");
}
}
}

Output: 9 7 5 3 1

The Return Statement


The return keyword is used to provide control back to the calling application from a method. Return is
also a jump statement since the control switches between different program sections.

Example:
public class Main

109
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

{
public static int add(int a, int b){
int sum = a+b;
return sum;
}
public static void main(String[] args) {
int x = 5, y = 10;
int sum = add(x, y);
[Link]("Sum of a and b: " + sum);
}
}

Output: Sum of a and b: 15

Methods in Java
A Java method may be thought of as a chunk of code or a collection of statements that are used to
carry out a certain operation or activity. The reusability of the code may be accomplished by applying
this a number of times. In addition to this, it makes the code legible and editable in an easy manner.
The execution of a method does not begin until it is "called," also known as "invoked." There are two
distinct categories of methods that may be used in Java: pre-defined and user-defined. The names
of the methods that are already defined for use in Java class libraries are referred to collectively as
predefined methods. When a user or a programmer is responsible for the creation of a method, we talk
about that method as being user-defined. The user-defined procedures may be altered to better fit the
current circumstances. Let us discuss:
• Static method in Java
• The abstract method in Java
• Finalize method in Java
• Equals method in Java

Static Method in Java


The declarations of methods are considered to be static if they include the "static" keyword. To put
it another way, a static method is a method that is associated with a class itself rather than with an
instance of a class. The construction of a static method may also be accomplished by prefixing the
name of the method with the word "static." The most significant benefit of a static method is that
it may be invoked without first requiring the creation of an object. It has access to the members of
static data and control over those elements, as well as access to create instance methods. The main()
function is an excellent example of a static method in its normal form.

Example:
public class Demo
{

110
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

public static void main(String[] args)


{
displaymethod();
}
static void displaymethod()
{
[Link]("It is an example of static method.");
}
}
Output: It is an example of a static method.

Abstract Method in Java


An abstract method is one that uses the term abstract in its declaration. There is no implementation,
body of code, or block of code for the abstract method. If a class has an abstract method, it should be
marked abstract. The abstract method must always be stated in an abstract class. A class should be
declared abstract if it contains an abstract method, but the reverse is not true, therefore an abstract
class need not require an abstract method to be present. Additionally, if a regular class extends an
abstract class, the extending class must either implement all the abstract methods of the abstract
parent class or be explicitly designated abstract.

Example:
//abstract class area
abstract class Area{
/* These two are abstract methods, the child class
must implement these methods
*/
public abstract int areaSquare(int s);
public abstract int areaRectangle(int l, int b);
//Normal method
public void display(){
[Link]("Normal method in abstract class Area");
}
}
//Normal class extends the abstract class
class Demo extends Area{
/* If we don't provide the implementation of these two methods, the
program will throw compilation error.
*/

111
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

public int areaSquare(int s){


return s*s;
}
public int areaRectangle(int l, int b){
return l*b;
}
public static void main(String args[]){
Area a = new Demo();
[Link]("Area of square " + [Link](9));
[Link]("Area of rectangle " + [Link](3,4));
[Link]();
}
}

Output:
Area of square 81
Area of rectangle 12
The normal method in abstract class Area

Final Method in Java


A final technique is one that has been deemed to be the last one. A final technique is inviolable. As
a result, the child class can still call the parent class final method without any issues, but it is not
permitted to override it. This is so that the method cannot be modified by the subclass, which is the
fundamental goal of declaring a method final.

Example:
class DemoParent{
final void method(){
[Link]("Parent class final method");
}
}

class Demo extends DemoParent{


//error
void method(){
[Link]("final method modified inside child class");
}

112
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

public static void main(String args[]){


Demo d = new Demo();
[Link]();
}
}

The above code will throw an error as we are trying to modify the final method inside the child
class(demo) of the parent class(demoParent).
Instead of modifying the method, we can use it as shown below:
class DemoParent{
final void method(){
[Link]("Parent class final method");
}
}

class Demo extends DemoParent{


public static void main(String args[]){
Demo d = new Demo();
[Link]();
}
}

Output:
Parent class final method

Equals Method in Java


.equals() is a method in Java that, as its name suggests, is used to determine whether or not two
objects are the same. Java'[Link]() function is called upon to determine whether or not the values of
the two strings are comparable. It examines each individual one of their characters. It is important to
differentiate between [Link]() function and the == operator. The String equals() function compares
the two strings based on the information contained inside the strings, while the == operator is used
to compare the addresses of the strings. If the contents of two strings are exactly the same, then the
equals() function will return true; otherwise, it will return false. In the event that none of the characters
are a match, the function returns false.

Let us understand this with the help of an example:


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

113
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

String s1 = "GreatLearning";
String s2 = "GreatLearning";
String s3 = new String("GreatLearning");
[Link](s1 == s2); // true
[Link](s1 == s3); // false
[Link]([Link](s2)); // true
[Link]([Link](s3)); // true
}
}

Even though s1 and s3 are created with the same field(content), they are pointing to two different
objects in memory. Hence at different addresses. Therefore == operator gives false [Link]() method
gives true as both contain similar content greatLearning.

Message Passing in Java


In terms of computers, message passing is a phenomenon that occurs when processes communicate with
one another. In object-oriented programming, it is a method of communication. In Java, transmitting a
message from one thread to another thread is the same as sending an object. It is used when shared
memory is not available and when communicating across threads is not possible using shared variables
like monitors. When a program uses message passing, it sends a message to a process, which it then
uses to execute its own functionality or code. Message passing is simple to use, performs well, and
allows us to create extremely large parallel models.
There are two types of it: Synchronous and Asynchronous.
• Synchronous message passing occurs when the objects run at the same time.
• In the case of an Asynchronous message passing, the receiving object can be down or busy when
the requesting object sends the message.

Can Polymorphism, Encapsulation and Inheritance work together?


The programming environment we create when we mix inheritance, polymorphism, and encapsulation
facilitates the creation of programs that are far more durable and scalable than those that follow the
program-oriented approach. The foundation for reusing the code that we have invested time, effort,
and testing in is a well-designed conceptual model of the hierarchy of classes. We may move our
implementations over time without affecting code that depends on the open interfaces of our classes
thanks to encapsulation. We can write understandable, legible, and tidy code thanks to polymorphism.
As we all know, the processes of encapsulation, polymorphism, and inheritance are used to combine
separate pieces to create an object, such as a vehicle, phone, etc. In the case of computer programs,
this is accurate. The many components of complicated programs are combined using object-oriented
concepts to create a solid, dependable, and manageable whole.
Java's built-in class libraries, which depend heavily on encapsulation, polymorphism, and inheritance,
contain many of the capabilities that the language offers.
Let us look at a real-world illustration. From one perspective, humans are a sort of heredity, but
automobiles are more like to the programs we create. All drivers rely on their ancestry to operate
various kinds of automobiles. Due to the wide variety of vehicles available to us, some of which have

114
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

unique features, people interact with the features of all sorts of automobiles. Engine, brake, and other
device implementation falls under encapsulation before reaching polymorphism. We have a variety of
alternatives for the anti-lock braking system, conventional braking system, and power braking system
on the same car. Polymorphism refers to a single vehicle with many braking system configurations. This
illustration demonstrates how polymorphism, inheritance, and encapsulation are integrated.

Exercise
MCQ Questions:
1. An IF-ELSE statement is also called ___.
a) Branching statement b) Control statement
c) Block statements d) All

2. An IF or ELSE IF statement accepts ___ as input before branching.


a) boolean b) int
c) float d) char

3. An IF statement in Java is also a ___ statement.


a) boolean b) conditional
c) iterative d) optional

4. Java style IF-ELSE statements are similar to ___.


a) C style b) C++ Style
c) Both C and C++ style d) None

5. State TRUE or FALSE. Every IF statement must be followed by an ELSE of ELSE-IF statement.
a) TRUE b) FALSE

6. A SWITCH case statement in Java is a _______ control statement.


a) Iteration b) Loop
c) Selection d) Jump

7. Which is the alternative to SWITCH in Java language?


a) break, continue b) for, while
c) if, else d) goto, exit

8. What are the keywords used to implement a SWITCH case in Java language?
a) switch, case b) default
c) break d) All

115
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

9. What are the parts of a SWITCH in java?


a) switch input condition b) case constants
c) case statements d) All

10. Java method signature is a combination of _________.


a) Return type b) Method name
c) Argument List d) All the above

[Link] Familiarize with the IDE to be used for java


programming
How to create, build and run a Java Hello World program with Eclipse IDE:
This step-by-step tutorial will guide you through the process of creating your first Java application using
Eclipse if you are new to Java programming and the Eclipse IDE. Additionally, Eclipse will allow you to
create and run your software.

Download and Install Eclipse IDE


The most well-liked Integrated Development Environment (IDE) for creating Java applications is Eclipse.
It is a reliable, feature-rich, user-friendly, and potent IDE that is the top choice of practically all Java
programmers worldwide. It is also completely free.
Neon is the most recent Eclipse release as of right now (fall 2016). (Version 4.6). To download Eclipse,
click the following link:
[Link]

The download page will look as follows:

Fig. 2.1.15: Eclipse Download page

116
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Eclipse installation may be done using either the Eclipse Installer or a package (zip file). You should
download by package, in my opinion. Eclipse has a variety of packages for various types of development.
As you can see above, there are two primary packages for Java:
To create Java EE applications, use the Eclipse IDE for Java EE developers (web applications using
Servlets & JSP).
Java developers may create Java SE applications, a subset of the Java EE Developer package, using the
Eclipse IDE.
Since this section only teaches you how to create Java console programs, you can install the Eclipse
IDE for Java EE Developers package. However, you will eventually need to create Java web applications.
You will see the package name like this: eclipse-jee-neon-R-win32-x86_64.zip
Extract this ZIP file into a directory on your computer. You will see a directory called eclipse containing
Eclipse’s installed files:

Choose a Workspace Directory


Eclipse uses workspaces to organize the many projects that it manages. A workspace is essentially a
directory on your computer that houses a group of interrelated tasks in one convenient location. When
you first run Eclipse, you will be prompted to choose a location for your workspace for the following
reasons:

Eclipse automatically generated the workspace directory under USER HOMEworkspace. Click Browse to
select a different directory. I choose a different workspace here:

Check If you don't want to be prompted every time you open Eclipse, set this as the default and don't
ask again. When Eclipse is running, changing the workspace is always an option.

117
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Click OK. You should see the welcome screen:

Now, we are ready to create a Java project.

Change Perspective
Get acquainted with Perspective before starting a new Java project. Consider a viewpoint as a
predetermined configuration tailored for a particular step in the development process, such as Java,
Java EE, debugging, database development, web development, etc. During a development session, you
can alternate between several views according to your needs.
The default perspective is Java EE as a result of the installation of Eclipse IDE for Java EE Developers.
Navigate to Window > Viewpoint > Open Perspective > Other to alter your perspective. You'll see a brief
dialogue box detailing all of the possible perspectives:

118
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

In this case, we pick Java viewpoint. Select OK. The Java viewpoint would seem as follows:

Enter HelloWorld as the project name. After leaving everything else alone, click Finish.
In the Package Explorer window, the HelloWorld project should appear as follows:

Making a package for your project is advised. New > Package may be chosen from the context menu by
performing a right-click on the project:

Enter the name of your package in the New Java Package window. I now type [Link]:

119
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Click Finish. You should see the newly created package appears:

It's now time to write a Java class for your application's hello world functionality.

Write Your First Java Program


Right-click on the package and choose New > Class from the context menu to add a new Java class to it:

Type HelloWorld into the New Java Class dialogue box, and then choose the option to automatically
construct the main() function.

120
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

And click Finish. The HelloWorld class is generated like this:

Currently, enter the following code in the main() function to output "Hello World" to the console:

That’s it. We have created a Java hello world program using Eclipse IDE.

Compile, Build and Run Your First Java Program


Eclipse immediately builds the code as you type by default. Additionally, it will display build errors as
follows in the Problems view at the bottom:

121
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

To disable the automatic build option, choose Project from the menu, then uncheck Build Automatically:

The auto build mode should be kept, though, as it makes problems easier to spot right away.
Let us now launch the hello world program. When you choose Run from the menu (or when you press
Ctrl and F11), Eclipse will launch the program and display the results in the Console view:

That’s it! The HelloWorld program has run and printed the output “Hello World” and terminates.

Exercise
MCQ Questions:
1. What is the Java command used to compile a java program from Command Line or Command
Prompt or CMD?
a) >java [Link] b) >javac [Link]
c) >javacomp [Link] d) >javacmd [Link]

2. What is the command used to Run a Java program form Command Line or Command Prompt or
CMD?
a) javac hell b) java [Link]
c) java hell d) java [Link]

122
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

3. What are the valid White Spaces available in Java language?


a) Space b) Enter
c) Tab d) All the above

4. Common Public License is re-licensed under _________.


a) Eclipse Public License b) General Public License
c) Eclipse Platform d) Eclipse plug-in

5. How can we add a library to the classpath of a plug-in?


a) The JAR can be added to the boot classpath
b) The JAR can be added to the declared libraries for a plug-in
c) Create a new plug-in that can be added to the library
d) All of these

6. What does an Eclipse IDE allow?


a) Editing the program
b) Compiling the program
c) Both editing and compiling
d) Editing, building, Debugging, Compiler

7. What are the names of the different versions of Eclipse IDE?


a) Oxygen b) Neon
c) Mars d) Luna
e) All of these

8. Development environment include the __________


a) Eclipse VisualAge b) Classpath
c) Eclipse JDT d) IcedTea

9. The major visible parts of an eclipse window are?


a) Views b) Editors
c) Menu Bar d) All of the above

10. What is included in a rich client platform?


a) Eclipse Runtime b) JFace
c) Workbench d) All of the above

123
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

UNIT 2.2: Introduction to Data Structures and Databases

Unit Objectives
By the end of this unit, the participants will be able to:
1. Explain various datatypes, variables, operators (arithmetic, relational, logical, bitwise), strings and
arrays
2. Explain the concepts of strings and arrays in the context of Java programming
3. Discuss the concepts of memory allocation
4. Explain the concepts of relational database management system
5. Create expressions, statements, and blocks in Java
6. Demonstrate the use of type conversions
7. Use arrays, strings and oprators to declare variables
8. Demonstrate the use of RDBMS in Java programming

2.2.1 Data types


Data type is used to specify the type of data a variable can store.
Java has two categories in which data types are segregated:
• Primitive Data Type: boolean, char, int, short, byte, long, float, and double
• Non-Primitive Data Type or Object Data type: String, Array

[Link] Primitive Data Types


1. Boolean:
• The size of the boolean data type is dependent on the virtual machine.
• Can only store either true or false.
• Type conversion is not allowed for boolean types.

Syntax:
boolean varName;
• Size: Virtual machine dependent
• Values: true or false

Example:
// Java program to demonstrate boolean primitive datatype

class GFG {

public static void main(String args[]) {

124
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

// Setting variables a to false and b to true


boolean a = false;
boolean b = true;

// If conditions
if (b == true) {
[Link]("Hi");
}
if (a == false) {
[Link]("Hello");
}
}
}

Output:
Hi
Hello

2. Byte:
• The byte data type refers to an 8-bit unsigned integer.
• When dealing with very large arrays, the byte data type can be used to conserve memory.

Syntax:
byte varName;

• Size: 1 byte (8 bits)


• Values: -128 to 127

Example:
// Java program to demonstrate byte data type

class GFG {
public static void main(String args[]) {
byte a = 126; // byte is 8-bit value
[Link](a);
a++;
[Link](a);

125
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

a++; // Overflow as value is not in range


[Link](a);
a++; // Loops back within the range
[Link](a);
}
}

Output:
126
127
-128
-127

3. Short:
A 16-bit signed integer.
Similar to byte type but can be used to conserve memory in sizable arrays when saving memory is
crucial.

Syntax:
short varName;

• Size: 2 bytes (16 bits)


• Values: -32768 to 32767

4. Integer:
It is a 32-bit signed integer.

Syntax:
int varName;

• Size: 4 bytes (32 bits)


• Values: -2,147,483,648 to 2,147,483,647

5. Long:
• A 64-bit signed integer.
• Used when the data to be stored is beyond the range of an int type.

126
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Syntax:
long varName;

• Size: 8 bytes (64 bits)


• Values: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

6. Float:
A 32-bit floating-point data type with a single precision.
Syntax:
float varName;

• Size: 4 bytes (32 bits)


• Values: upto 7 decimal digits

Example:
// Java program to illustrate float primitive data type

class GFG {
public static void main(String[] args) {
// Declaring and initializing float value
// float value1 = 9.87; //ERROR: float values should be suffixed with f

float value2 = 9.87f;


[Link](value2);
}
}

Output:
9.87

7. Double:
A double-precision 64-bit IEEE 754 floating-point is the double data type.
This data type is typically the default selection for decimal numbers.

Syntax:
double varName;

127
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

• Size: 8 bytes (64 bits)


• Values: upto 16 decimal digits

8. Char:
• The char data type is a single 16-bit Unicode character.

Syntax:
char charVar;

• Size: 2 bytes (16 bits)


• Values: ‘\u0000’ (0) to ‘\uffff’ (65535)

Example:
// Java program to demonstrate primitive data types

class GFG {
public static void main(String args[]) {
// Creating and initializing custom character
char a = 'G';

// Integer data type is generally used for numeric values


int i = 89;

// use byte and short if memory is a constraint


byte b = 4;

// ERROR as the number is larger than byte range


// byte b1 = 7888888955;

short s = 56;

// ERROR as the number is larger than short range


// short s1 = 87878787878;

// By default fraction value is double in Java

128
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

double d = 4.355453532;

// For float use 'f' as suffix


float f = 4.7333434f;

//Used to hold big range of numbers


long l = 12121;

[Link]("char: " + a);


[Link]("integer: " + i);
[Link]("byte: " + b);
[Link]("short: " + s);
[Link]("float: " + f);
[Link]("double: " + d);
[Link]("long: " + l);
}
}

Output:
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121

[Link] Non-Primitive Data Types


Variables of non-primitive data types store the memory address of the variable’s value. Therefore these
types are called reference types that do not directly store the variable’s value . These types may refer
to text data known as strings, object data, array data and so on.

1. String:
A collection of characters is referred to as a "String". In Java, a character array is a collection of
individual char type entities whereas a string is used to store a set of characters in a single variable.
In contrast to strings used in C and C++, Java strings do not terminate with a null character.

129
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Syntax:
String varName = “<set_of_characters>”;

Example:
// Java program to demonstrate String non-primitive data type

class GFG {
public static void main(String args[]) {
// Declare String without using new operator
String s = "Demo";
[Link](s);

// Declare String using new operator


String s1 = new String("Demo1");
[Link](s1);
}
}

2. Class:
A user-defined class serves as a template or prototype from which objects can be built.
It stands for the collection of attributes or operations that are shared by all objects of a particular
type.

The following elements can typically be found in class declarations:


• Modifiers: A class may have default access or can be made public.
• Class name: The naming convention followed is Camel case wherein the name of the class
starts with a capitalized letter.
• Superclass (if any): If there is one, the term extends is followed by the name of the class's
parent (superclass). In Java, only one parent can be extended (sub-classed) by a class.
• Interfaces (if any): A list of the interfaces that the class, if any, implements, separated by
commas, should be included. A class may support several interfaces.
• Body: The class body is surrounded by braces { }.

3. Object:
An object is a representation of a real-time entity in Object-Oriented Programming languages such
as Java. There can be multiple objects in a Java program that communicate with each another by
calling the other object’s methods.
Every object has the following:
• Identity: a special name given to the object to communicate with other objects.

130
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

• State: properties that describe the object.


• Behaviour: methods that define the behaviour of an object. It also shows how one object
interacts with other objects.

4. Interface:
An interface is similar to a class that has variables and methods. However, the methods in an
interface are abstract by default (method signature with no body). Interfaces allow the developer
to define not how but rather what a class must be able to do. This served as the outline for the class.
Consider a Player interface, for example wherein any class that implements it must be able to move
(or must implement moving).
A class must be defined as abstract if it implements an interface but does not provide method
bodies for all of the methods listed in the interface.
Comparator interface is a good example of a Java library. A class can be used to sort a collection if
it implements this interface.

5. Array:
An array is a collection of homogeneous values with the same name. Arrays in Java are represented
differently as compared to arrays in C++.

The following are some characteristics of arrays in Java:


• Because Java considers arrays to be objects, the length attribute can be used to get the number
of elements in the array. Alternately, the sizeof operator is used determine the array length in
C and C++.
• A Java array variable is declared using [ ] after the data type.
• The elements in the array can be accessed using index 0 to n-1, where ‘n’ is the number of
elements in the array.
• In Java, an array may be a local variable, a static field, or an argument to a method.
• You can specify the size of an array using an integer in the array declaration.
• The Object class serves as the immediate superclass for array types in Java.
• Every array in Java implements the Cloneable and [Link] interface.

Exercise
Answer the following questions:
1. The Java interpreter is used for the execution of the source code.
a) true b) false

2. On successful compilation, a file with the .class extension is created.


a) true b) false

131
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

3. The Java source code can also be created using a Notepad editor.
a) true b) false

4. The Java program is enclosed in a class definition


a) true b) false

5. What declarations are required for every Java application?

6. What are the two parts in executing a Java program and their purposes?

7. What are the three main OOPs principles? Define them.

8. What is a compilation unit?

9. What is the output of executing the following statement?


[Link]("// Looks like a comment");
a) // Looks like a comment
b) The statement results in a compilation error
c) Looks like a comment
d) No output is displayed

10. In order for a source code file containing the public class Test, to successfully compile, which of the
following must be true?
a) It must have a package statement
b) It must be named [Link]
c) It must import [Link]
d) It must declare a public class named Test

2.2.2 Variables
In Java, a variable is a container that stores data values during the execution of a Java program. Every
variable has a data type assigned to it that specifies the kind and number of values it can store. A
memory location is given a name called the variable. It serves as a program's fundamental unit of
storage. A variable's value may be modified while a program is running. All variables in Java must be
declared before use.

132
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

[Link] Variable Declaration


We can declare variables in Java as illustrated below.

Variable declaration

The example demonstrates that there are two things to think about when defining a variable:
1. Datatype: The kind of data that can be stored in the variable.
2. Name: The variable's name.

[Link] Variable Initialization


There are two ways to assign values to variables:
a) Initializing variables b) accepting input and assigning value

The following three factors help to perceive the way in which variables are initialized:
• datatype: The kind of data the variable can store.
• name: The variable's name.
• value: Actual data stored in the variable.

Fig. 2.2.1: Variable initialization

Examples:
float simpleInterest;
// Declaring float variable

int time = 10, speed = 20;


// Declaring and initializing integer variable

133
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

char var = 'h';


// Declaring and initializing character variable

[Link] Type of Variables in Java


1. Local Variables
2. Instance Variables
3. Static Variables

Fig. 2.2.2: Variable types

1. Local Variables
A variable is said to be local if it is declared inside a particular block, method, or function.
Variables are created within the block or function in which they have been declared and get
destroyed when the execution of the statements inside the block/function is completed.
Because the scope of these variables only extends to the block in which they are declared, the local
variable must first be initialized before it can be used inside the scope that has been specified for it.
These variables are only available within the block in which they are defined.

Example:
class GFG {

public static void main(String[] args) {


// Declaring a local variable
int var = 10; // This variable can be accessed in the main method only

[Link]("Local Variable: " + var);


}
}

134
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Output:
Local Variable: 10

2. Instance Variables
• Instance variables are those that are defined directly within the class and not within a method or
block.
• Since instance variables are defined inside a class, memory is allocated when an instance of the
class (object) is created and memory is deallocated when the object goes out of scope.
• Access specifiers may be used to allow/restrict use of instance variables. In contrast, access
specifiers cannot be used on local variables. If no access specifier is mentioned, the default access
specifier is considered.
• It is not mandatory to initialize an instance variable. 0 is assigned for integers by default and 0.0 is
assigned for floating point numbers.
• Access to instance variables is only possible through the object of that class.

Example:
class GFG {

public String str1; // Declared Instance Variable

public GFG() { // Default Constructor


this.str1 = "Sai"; // initializing Instance Variable
}

public static void main(String[] args) {


// Object Creation
GFG name = new GFG();

// Displaying O/P
[Link]("Name is: " + name.str1);
}
}

Output:
Name is: Sai

3. Static Variables
Static variables are also known as class variables.

135
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

• These variables are declared in the same way as are instance variables. However, the static
keyword is used while declaring the variable inside the class.
• Memory is allocated only once for static variables and shared by all objects of the class in which
they are declared.
• Creation of static variables happens even before the object is created as soon as the execution
of the program begins, and they are deleted as soon as the execution is completed.
• Initialization of static variables is not necessary at this time. 0 is assigned by default for integers,
0.0 for floating points and null for object types.
• The instance variable can be directly accessed using the class name. However, it can be also be
accessed through the object of the class.

Example:
class GFG {
//Declaring a static variable
public static String str1 = "Sai";

public static void main(String[] args) {


//str1 variable can be accessed without object creation
//accessed using the class name
[Link]("Name is: " + GFG.str1);
}
}

Output:
Name is: Sai

Exercise
Answer the following questions:
1. What are identifiers and what is the naming convention?
2. What is the return type of the program’s main( ) method?
3. What is the argument type of program’s main( ) method?
4. Which characters are valid as the first character of an identifier?
5. What are the different types comments used in Java?
6. What is the difference between a constructor method and instance method?
7. What is the use of bin and lib in JDK?

136
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

2.2.3 Operators
Java operators are symbols that can be used to process values stored in variables (operands).
Consider the mathematical expression "4 plus 2 equals 6." The numbers 4 and 2 make up the operands,
while the plus symbol (+) serves as the operator. In addition, operator precedence and operator
associatively will be discussed in this lesson.

[Link] Types of Java Operators


1. Unary Operators
2. Arithmetic Operators
3. Assignment Operators
4. Logical Operators
5. Shift Operators
6. Bitwise Operators
7. Ternary Operators
8. Relational Operators

Let us take a look at each one of these operators separately.

1. Unary Operator:
Unary operators requires only a single operand. This operator is used to increment or decrement
the value of a number, negate an expression or invert a boolean value.

Operator Description
++ (Increment) This operator is used to increment the existing number by 1. There
are two types of unary increment operators, i.e., post-increment
(a++) and pre-increment (++a)
-- (Decrement). This operator is used to decrement the value by 1. There are two
types of unary decrement operators, i.e., post-decrement (a--)
and pre-decrement (--a)
! (Invert) This operator is used to invert a boolean value (!a).

Example:
class GFG {
public static void main(String[] args) {
int a = 10;
boolean b = true;
[Link](a++); //First use value of 'a' and then increment
[Link](++a); //First increment the value of 'a' and then use
[Link](a--); //First use value of 'a' and then decrement
[Link](--a); //First decrement the value of 'a' and then use
[Link](!b); //invert value of b

137
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

}
}

Output:
10
12
12
10
false

2. Arithmetic Operator:
Addition, subtraction, multiplication, division as well as modulus(remainder) are all called binary
arithmetic operations. These operators work on two operands.

Operator Description
+ ( Addition ) Used to add the values of the two operands.
– ( Subtraction ) Used to subtract the value of the second operand from the first.
* ( Multiplication ) Used to multiply the value of the operands.
/ ( Division ) Used to divide the first operand by the second operand.
% ( Modulus ) Used to return the remainder of the first operand divided by the
second operand.

Example:
class GFG {

public static void main(String[] args) {


int a = 10, b = 20;
[Link](a + b);
[Link](a - b);
[Link](a * b);
[Link](a / b);
[Link](a % b);
}
}

Output:
30
-10
200

138
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

0
10

3. Assignment Operator:
Use the assignment operator to assign a new value to a variable. On the left side of the assignment
operator is the variable name and the right side is the new value to be assigned.

Operator Description
= Assign the value of the right operand to the operand on the left.
+= Adds right operand to the left operand and assigns the result to the
left operand.
-= Subtracts right operand from the left and assigns the result to the
left operand.
*= Multiplies right operand with the left and assigns the result to the
left operand.
/= Divides left operand by the right one and assigns the result to the
left operand.
^= Raises left operand to an exponent of right operand and assigns the
result to the left operand.
%= Divides left operand by the right and assigns the result to the left
operand.

Example:
class GFG {
public static void main(String[] args) {
int a = 10, b = 20, c;
[Link](c = a);
[Link](b += a);
[Link](b -= a);
[Link](b *= a);
[Link](b /= a);
[Link](b ^= a);
[Link](b %= a);
}
}

Output:
10
30
20

139
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

200
20
30
0

4. Logical Operator:
Logical operators are used whenever there are more than one conditions to be checked.

Operator Description
&&(Logical AND) Returns true if both the conditions are true, else returns false.
|| (Logical OR) Returns true if at least one condition is true, else returns false.
! (Logical AND) Returns true if expression is false and returns false if it is true.

Example:
class GFG {

public static void main(String[] args) {


int a = 5;
[Link](a < 5 && a < 20);
[Link](a < 5 || a < 20);
[Link]( !(a < 5 && a < 20) );
}
}

Output:
false
true
true

5. Shift Operator:
The shift operator may be used to shift the bits of a number to the left or the right by either
multiplying or dividing the integers that make up the number respectively.

Operator Description
<<(Left Shift) Left shifts the bits of the first operand by the number of places to
shift.
>>(Right Shift) Right shifts the bits of the first operand by the number of places to
shift.

140
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Example:
class GFG {

public static void main(String[] args) {


int a = 58;
[Link](a << 2);
[Link](a >> 2);
}
}

Output:
232
14

6. Bitwise Operator:
The bitwise operator can be used on a bit string, a binary number, or a bit array to perform
operations. It is fast, simple, and the central processing unit (CPU) directly supports it. Bitwise
operation is also known as bit-level programming and bit-level programming.

Operator Description
& (Bitwise AND) Does a bitwise-AND on the corresponding bits of the two numbers.
| (Bitwise OR) Does a bitwise-OR on the corresponding bits of the two numbers.
^ (Bitwise XOR) Does a bitwise-XOR on the corresponding bits of the two numbers.
~ (Bitwise NOT) Inverts all bits of the given number.

Example:
class GFG {

public static void main(String[] args) {


int a = 58, b = 13;
[Link](a & b);
[Link](a | b);
[Link](a ^ b);
[Link](~a);
}
}

Output:
8

141
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

63
55
-59

7. The ternary operator:


This is a conditional operator that reduces the number of lines of code used in a if statement. It is
sometimes referred to as the conditional ternary if, or an inline if operator.

Syntax:
( Condition ) ? ( Statement1 ) : ( Statement2 );
Here, Condition is the expression to be evaluated which returns a boolean value.
If the Condition is true then Statement1 is executed.
If the Condition is false then Statement2 is executed.

Example:
class GFG {
public static void main(String[] args) {
int a = 10;
int b = 40;
int min = (a < b)? a : b;
[Link](min);
}
}

Output :
10

8. Relational operator:
The relational operator compares two operands and returns a boolean result.

Operator Description
< (Less than) Returns true, if the left operand’s value is less than the right operand,
else it returns false.
> (Greater than) Returns true, if the value of the left operand is greater than the value
of the right operand, else it returns false.
<= (Less than or Returns true, if the value of the left operand is less than or equal to
equal to) the value of the right operand, else it returns false.
>= (Greater than Returns true, if the value of the left operand is greater than or equal
or equal to) to the value of the right operand, else it returns false.

142
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Operator Description
== (Equal to) Returns true, if two operands are equal, else it returns false.
!= (Not equal to) Returns true, if two operands are not equal, else it returns false.

Example:
class GFG {
public static void main(String[] args) {
int a = 10, b = 20;
[Link](a < b);
[Link](a > b);
[Link](a <= b);
[Link](a >= b);
[Link](a == b);
[Link](a != b);
}
}

Output:
true
false
true
false
false
true

2.3.2 Java Operator Precedence and Associativity


Each operator in an expression can have a precedence (priority) over other operators. The operator with
the highest precedence executes first. Similarly, the expression is evaluated based on the precedence
of the operators used.
Associativity of operators is considered when an expression contains two operators with the same
precedence.

Operator Precedence Associativity


Postfix expr++ expr-- left to right
Unary ++expr --expr + expr – expr ~ ! right to left
Multiplicative */% left to right
Additive +– left to right
Shift << >> >>> left to right

143
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Operator Precedence Associativity


Relational < > <= >= instanceof left to right
Equality == != left to right
bitwise AND & left to right
bitwise exclusive OR ^ left to right
bitwise inclusive OR | left to right
logical AND && left to right
logical OR || left to right
Ternary ?: right to left
Assignment = += -= *= /= %= &= ^= |= <<= >>= >>>= right to left

In general, operators make up an essential part of the Java programming language and are necessary
for the execution of a wide variety of data operations. There are many diverse kinds of operators that
may be used in Java, and each one serves a particular purpose.

Exercise
Answer the following questions:
1. What is meant by variable?
2. What are the various kinds of variables in Java and their uses?
3. How are variables declared?
4. What are variable types?
5. How do you assign values to variables?
6. What is a literal? How many types of literals are there?
7. What is an array?
8. How do you declare an array?
9. Does Java support multidimensional arrays?
a) true b) false
10. An array of arrays can be created
a) true b) false
11. What is a String?
12. Strings are instances of the class String.
a) true b) false
13. When a string literal is used, Java automatically creates instances of the string class.
a) true b) false

144
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

14. Which operator is used to create and concatenate strings?


15. Which of the following declare an array of string objects?
a) String[ ] s; b) String [ ]s:
c) String[s]: d) String s[ ]:
16. What is the value of a[3] as the result of the following array declaration?
int[] a = { 0, 1, 2, 3, 4, 5 };
a) 1 b) 2
c) 3 d) 4
17. Which of the following are primitive types?
a) byte b) String
c) int d) float
18. What is the range of the char type?
a) 0 to 216 b) 0 to 215
c) 0 to 216-1 d) 0 to 215-1
19. What are primitive data types?
20. What are default values of different primitive types?
21. Converting primitive types to objects can be done explicitly
a) true b) false
22. How can the values of elements in the array be changed?
23. What is a final variable?
24. What is a static variable?

2.2.4 Strings in Java programming


Working with Strings
In Java programming, one common way to store collections of characters is in the form of "strings."
Strings are considered as objects in Java. The String class can be used to create and manipulate strings.
In the statement below, “Hello world!" is a string literal containing a group of letters enclosed in double
quotes.
String greeting = "Hello world!";

Every time a string literal is encountered in the code (“Hello world!”), the compiler automatically
creates a String object and assigns it to the identifier on the left (greeting).
Alternately, String objects may be created using the new keyword.
There are multiple constructors in the String class that let you initialise a string from various sources,

145
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

including an array of characters.


Example:
class GFG {
public static void main(String[] args) {
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
[Link](helloString);
}
}

Output:
hello.

The String class is immutable, therefore once a String object has been created, individual characters
cannot be altered in any way. Some of the string-editing techniques available in the String class are
discussed here. Because strings cannot be modified after they have been written, these methods build
and return a new string that contains the result of the action.

1. String length:
Accessor methods are techniques used to retrieve information about an object. The length()
accessor method returns the number of characters in the string object.

Example:
class GFG {
public static void main(String[] args) {
String palindrome = "Dot saw I was Tod";
int len = [Link]();
[Link]("Length of the palindrome: " + len);
}
}

Output:
Length of the palindrome: 17

A palindrome is a string that reads the same in the forward or backward direction. Below is an
example to invert a given string. The ith character of the string is returned by using the charAt(i)
method of the String class.
Example:

146
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

class GFG {
public static void main(String[] args) {
String palindrome = "Dot saw I was Tod";
int len = [Link]();
char[] tempCharArray = new char[len];
char[] charArray = new char[len];

// put original string in an array of chars


for (int i = 0; i < len; i++) {
tempCharArray[i] = [Link](i);
}

// reverse array of chars


for (int j = 0; j < len; j++) {
charArray[j] = tempCharArray[len - 1 - j];
}

String reversePalindrome = new String(charArray);


[Link](reversePalindrome);
}
}

Output:
doT saw I was toD

As seen in the code above, first the array of characters is transformed into a separate array using
the first for loop, and then it is converted back to a string using the second for loop.
Because the getChars() function of the String class can convert a string or a portion of a string into
an array of characters, we were able to replace the first for loop in the prior program with this one.
[Link](0, len, tempCharArray, 0);

2. Concatenating Strings
The String class includes the concat method for concatenating two strings:
[Link] (string2);

The above statement returns a new string ‘string1’ with ‘string2’ appended to it.
You can also use the concat() method with string literals as follows.

147
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

"My name is ".concat("Raju");


Strings are more commonly concatenated with the + operator as follows.
"Hello," + " world" + "!"
which results in
"Hello, world!"
The + operator is widely used in print statements. For example:
String string1 = "saw I was ";
[Link]("Dot " + string1 + "Tod");
which prints
Dot saw I was Tod
For each object that is not a String, use the toString() method to convert it to a String.

For lengthy statements in the code, use the + concatenation operator at the end of each line to
include a multi-line string. The same can be used in print statements too.

Example:
class GFG {
public static void main(String[] args) {
String quote =
"Now is the time for all good " +
"men to come to the aid of their country.";
}
}

3. Creating Formatted Strings:


The printf method in Java can be used to output a formatted string to the console using various
format specifiers. For example,

[Link](
"The value of the float " +
"variable is %f, while " +
"the value of the " +
"integer variable is %d, " +
"and the string is %s",
floatVar,
intVar,
stringVar

148
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

);

As opposed to a single print command, we can construct a formatted string that can be reused by
using the static format() function of the String type. For example,

Example:
class GFG {
public static void main(String args[]) {
float floatVar = 12.5f;
int intVar = 25;
String stringVar = "hello";

String fs = [Link](
"Value of the float variable is %f, " +
"while the integer is %d, " +
"and the string is %s",
floatVar,
intVar,
stringVar
);
[Link](fs);
}
}

Output:
Value of the float variable is 12.500000, while the integer is 25, and the string is hello

Exercise
Answer the following questions:
1. What are operators and what are the various types of operators available in Java?
2. The ++ operator is used for incrementing and the -- operator is used for decrementing.
a) true b) false
3. Comparison/Logical operators are used for testing and magnitude.
a) true b) false

149
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

4. Character literals are stored as Unicode characters.


a) true b) false
5. What are the Logical operators?
6. What is the % operator?
7. What is the value of 111 % 13?
a) 3 b) 5
c) 7 d) 9
8. Is &&= a valid operator?
a) true b) false
9. Can a double value be cast to a byte?
a) true b) false
10. Can a byte object be cast to a double value?
a) true b) false
11. What is order of precedence and associativity?
12. Which Java operator is right associativity?
13. What is the difference between prefix and postfix of -- and ++ operators?
14. What is the result of expression 5.45 + "3.2"?
a) The double value 8.6
b) The string "8.6"
c) The String "5.453.2"
d) Results in an error
15. What are the final values of x and y, if the following code is executed?
x = 5;
y = ++x;
16. What are the final values of x and z, if the following code is executed?
x = 5;
z = x++;

150
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

2.2.5 Arrays
Arrays are used to store a fixed-size sequential collection of items of the same type.
An array can also be treated as a collection of variables having the same name.
If we need to store a large amount of data of the same kind, and then the same needs to be sorted,
Java provides parallel sorting algorithms as well. The term "array" refers to a data structure that is both
static and capable of storing many values. Arrays, like any other Java variable, can be sent as arguments
to the methods of a program.

[Link] Declaring an Array in Java


An array is a grouping of similar data types. Additionally, we may define an array as a type of data
structure used to store comparable data items. This uses a single variable to hold data of a similar type.
Consider the pupils in a class wherein the student's IDs are to be stored. For 1000 students, we will
need 1000 different variables to store each student’s ID, as illustrated below.

int student1 = 1;
int student2 = 2;
int student3 = 3;
int student4 = 4;
.
.
int student1000 = 1000;

Declaring variables 1000 times is incredibly laborious and time-consuming. This is where arrays would
be useful. Let us see how to declare and use arrays as a single variable containing multiple values.
int student[]=new int[1000];

The student array is pictorially represented in the following diagram:

Student[]

Here, in a single variable, we can store as many values as required. Variable is nothing but the reference
to the memory location.
As seen in the declaration statement above, the student array is created using the new keyword. This
means that arrays are treated as objects in Java. In fact, arrays are inherited from the Object base class.
Arrays are allocated memory on the heap. The heap memory is used to store not just the array objects
but all of Java's other objects as well. As a result, we have a single point of reference for all of the values.

151
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

[Link] Initializing Arrays


The initialization process involves assigning of a value to a variable. There are several ways in which
arrays can be initialized in Java. The first way has already been discussed in the above example.

int student[]=new int[1000];

Next method shows how to initialize an array at the time of decalaration:

int student[] = {1, 2, 3, 4, 5, 6, …., 1000};

While accessing elements in an array, we may encounter an error called exceptions. The exception refers
to the error that is detected at runtime and handled in the appropriate manner. Arrays are subject to an
exception called "Array Index Out of Bounds".

[Link] Accessing Array Elements


We have discussed how to create an array and initialize its contents. Here, we discuss how to access the
elements of an array. Consider the student array already discussed above. Let us see how to retrieve
the value of a specific element in an array.
Array elements can be accessed using index numbers. For example, look at the diagram below. Index
positions start with 0 (zero) till length-1.

In order to access the fourth student’s ID, we can use student[3]. In general, for an array with ‘n’
elements, valid indexes that can be used to access any element in the array would be 0 to n-1.

[Link] Type of Arrays in Java


When an array is declared using the new keyword, the elements of the array are instantly initialized to
either null, 0 (zero for types that represent numbers), or false (for booleans) based on the data type of
the array.
Arrays are dynamically allocated memory on the heap in Java. There are two types of arrays that can be
created and used as illustrated in the diagram.

Fig. 2.2.3: A Array Types

152
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

There are two types of arrays as follows:

1. Single Dimensional Array:


Single dimensional arrays have a single row or a single column. We can declare a single dimensional
array as follows:
int[ ] a; (OR)
int a[ ]; (OR)
int [ ]a; (OR)
int[ ]a;

But the most preferred way is int[] a;

Observe that we are not declaring the size of the array here. For example, int[5] a; is not valid in
Java. At the time of declaration, the size of an array cannot be specified. However, the size can be
specified later using the new operator as shown below.

int[] a; // Declaration of the array


a = new int[5]; // Memory allocation of the array based on the size

At the time of array creation, providing the size of an array is very important. Alternately, we can
declare and create an array in a single line as shown below.

int[] a =new int[5];

Now let us look at how to initialize the array. Suppose you have to store elements in an array, then
you will add it to a particular index no. as below:

a[0] = 100; // Adding value 100 at the 0th position in the array
a[1] = 200;
a[2] = 300;

Now you have seen how to initialize the array. But what if an invalid index number is used that does
not exist in the array.

a[10] = 11; // suppose we had an array of size 5 only

The above statement throws an ArrayIndexOutOfBoundsException. You cannot access index values
beyond the size of an array.

153
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Now, we declare, create and initialize the array in a single statement as below:

int[] a = {1, 2, 3, 4, 5}; // Declare, create, initialize

Another method is as follows.

int[] a = new int[]{1, 2, 3, 4, 5};

Next, let us see how to retrieve elements from a single-dimensional array.

Example:
class GFG {
public static void main(String args[]) {
int[] a = new int[] { 1, 2, 3, 4, 5 };
for (int i = 0; i <= [Link] - 1; i++) {
[Link](a[i]);
}
}
}

Output:
1
2
3
4
5

2. Multi-Dimensional Array:
The multi-dimensional array contains two-dimensional and three-dimensional arrays. Multi-
dimensional arrays are also known as array of arrays. Sometimes, it is also referred to as "jagged
arrays".

Now let us look at how to declare a two-dimensional array.

int [][] a; // declared array a

After declaring the array, we allocate memory for the array as shown below.

154
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

a = new int[2][4];

After this, we initialize the array elements using the corresponding row and column as index positions
as follows.

a[0][0] = 10
a[0][1] = 20
a[0][2] = 30
a[0][3] = 40

We can easily initialize the array with row and column.

Also, declaration, creation, and initialization can all be done in a single line as follows.

int[][] a ={ {10, 20, 30}, {100, 200, 300} }; // a[2][3]

Example:
class GFG {
public static void main(String args[]) {
int[][] a = { { 10, 20, 30 }, { 100, 200, 300 } };
[Link](a[1][2]);
}
}

155
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Output:
300

The ability to obtain an array's elements using the array's index number is one of the benefits of using
arrays. This makes it possible for us to easily sort, retrieve, search, and carry out any other needed
activities on the members of those arrays. The array is a pretty straightforward concept that may be
executed in a relatively short amount of time.

2.2.6 Type of Arrays in Java


The process of memory management in Java includes allocating and releasing memory to objects that
are kept in locations called the Stack and the Heap respectively. The Java programming language has
a feature known as the Garbage Collector that may automatically allocate memory. In this section,
we discuss about certain Java memory management concepts as well as the operation of the JVM's
garbage collector.

[Link] Memory Management in Java


Java requires the necessary deletion of unreferenced objects before it can allocate working memory
space to new objects. This is done to provide place for the new object allocations that are being made.
The Java garbage collector takes care of memory deallocation on their behalf and runs automatically.
As a result, developers often do not have to deal with this issue directly.
Memory management in Java is handled automatically and does not need any additional code. It is
the responsibility of the Garbage Collector to purge the working memory of any data that is no longer
required by the application (RAM).
Programmers often continue to make references to objects long after they have completed utilizing
those objects, which may result in memory leaks or other problems that the Java Virtual Machine
is unable to resolve (JVM). Hence, Java memory management is required in order to design useful
programs that do not suffer from memory leaks. Because of this, it is imperative that programmers
have an understanding of the automatic memory management that Java utilizes.

[Link] Types of Java Memory Management in Java


The major concepts in Java Memory Management include the following.
1) JVM Memory structure 2) Working of Garbage Collector.

1. JVM Memory Structure


The Java memory model shows how different threads in a Java program interact with one another
by using the memory to pass information back and forth. Objects belonging to the programs are
saved in different locations across the memory structure of the JVM.

156
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

The JVM Memory is divided into multiple parts as illustrated below.

• Method Area:
The method area is a logical component that is produced as part of the heap space during the
setup of the virtual machine. The data associated with a class's methods, class hierarchies,
Object fields, interfaces, and special methods are stored in a class's method area. This region is
called the method area.
• Heap Area:
The heap area is a shared storage space that exists during runtime and may be assigned to
individual instances and arrays of actual objects of any type. Depending on how the system is
setup, the size of the heap may either be static or it can change on its own on the go. It begins
running concurrently with the initialization of the Java Virtual Machine. The Garbage Collector
is responsible for reclaiming the heap memory that was assigned to the objects.
By default, the heap is capable of holding up to 64 megabytes of data. When you use the new
keyword, memory is allotted on the heap for an object, and a variable from the thread stack is
used to refer to that memory. When you use the new keyword.
A Java Virtual Machine process running always has a single [Link] trash collector removes
the items after the heap is full.
• JVM Stack Area
The stack is used to temporarily store data that are method-specific and link other objects that
are allocated memory on the heap. When it is constructed, the size may or may not be based
on anything else and may either be dynamic or fixed. The term "scope" refers to the visibility of
the variables that are being stored on the stack.
A stack frame is a kind of data structure that stores information about a thread. The status of
the thread as it pertains to the current method is represented by the thread data.
ᴑ The stack frame is also responsible for dynamic linking, in addition to storing data and
partial results.
ᴑ The Operand Stack, Local Variable Array (LVA), and Frame Data (FD) are all unique to each
frame (OS)
ᴑ The sizes of LVA, FD, and OS are determined during the compilation process.
ᴑ In a single thread of control, there is only ever one frame—the present frame—that is active
at any one moment.
ᴑ This particular frame is referred to as the current frame, and the class of the method is
referred to as the current class.
ᴑ In the case that the currently active method calls another method or is completed, the
frame terminates the active method.
ᴑ Any references to the frame may only be made by the thread that first created it.
• Program Counter (PC) Registers
There is a PC register assigned to each newly formed JVM thread. The non-native method has

157
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

a Program Counter that stores the address of the JVM instructions presently being executed,
but the native method's Program Counter's value is unknown. Additionally, it keeps a return
address or the native pointer.
• Native Method Stack
The Native Method stack is sometimes referred to by its alternative name, the C stack. Native
method stacks are written in a variety of different computer languages apart from Java. The
Java Native Interface is the one that makes calls to the native stack (JNI). When a thread is first
established, a portion of memory of this sort is allotted to it. It is similar to other types in that
it may be static or dynamic. There is a correlation between the performance of the native stack
and the operating system.

[Link] Garbage Collector in Java


When a Java program is executed, memory is distributed among the objects on the heap. The Garbage
Collector makes an attempt to keep a significant portion of the working memory free at all times. The
heap is the only portion of Java memory in which garbage collection is even remotely possible. The
Heap region is often referred to as the "Garbage Collectable Heap" due to the fact that it is the only
part of the Java memory structure in which garbage collection is possible.

1. What is Java Garbage Collection?


Clearing up memory that has been occupied by unreferenced objects is known as garbage collection.
The JVM determines when to activate the garbage collector. When the JVM notices that the working
memory resources are not readily available, garbage collection is initiated.

2. Criteria for an object to be eligible for garbage collection


The trash collection procedure is managed by the JVM. It causes the GC to deallocate memory held
by unreferenced objects, easing the strain on programmers. Other processes stall during garbage
collection. Several GC-based strategies can be used to increase the program's performance and
solve this issue. This is known as garbage collector tuning. Another method used is the generational
garbage collection. Objects are categorised according to how many clock cycles they have endured
(age). Garbage Collection is dispersed in this manner.

3. Basic Ways of Garbage Collection


The garbage collector is responsible for locating and marking the objects of working memory that
the application is no longer making use of.
i. Normal Deletion: The Garbage Collector gets rid of things in working memory that aren't being
used in order to create space for new ones.
ii. Deletion with Compacting: After the garbage collection, all of the objects that were able to
survive are relocated so that they are in close proximity to one another. This is done in order to
increase the efficiency with which memory is allocated to the objects of more recent programs.

158
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

[Link] Garbage Collector in Java


When a Java program is executed, memory is distributed among the objects on the heap. The Garbage
Collector makes an attempt to keep a significant portion of the working memory free at all times. The
heap is the only portion of Java memory in which garbage collection is even remotely possible. The
Heap region is often referred to as the "Garbage Collectable Heap" due to the fact that it is the only
part of the Java memory structure in which garbage collection is possible.

1. What is Java Garbage Collection?


Clearing up memory that has been occupied by unreferenced objects is known as garbage collection.
The JVM determines when to activate the garbage collector. When the JVM notices that the working
memory resources are not readily available, garbage collection is initiated.

2. Criteria for an object to be eligible for garbage collection


The trash collection procedure is managed by the JVM. It causes the GC to deallocate memory held
by unreferenced objects, easing the strain on programmers. Other processes stall during garbage
collection. Several GC-based strategies can be used to increase the program's performance and
solve this issue. This is known as garbage collector tuning. Another method used is the generational
garbage collection. Objects are categorised according to how many clock cycles they have endured
(age). Garbage Collection is dispersed in this manner.

3. Basic Ways of Garbage Collection


The garbage collector is responsible for locating and marking the objects of working memory that
the application is no longer making use of.
i. Normal Deletion: The Garbage Collector gets rid of things in working memory that aren't being
used in order to create space for new ones.
ii. Deletion with Compacting: After the garbage collection, all of the objects that were able to
survive are relocated so that they are in close proximity to one another. This is done in order to
increase the efficiency with which memory is allocated to the objects of more recent programs.

2.2.7 Relational database Management System (RDBMS)


RDBMS is the foundation of every contemporary database management system, including SQL, MS SQL
Server, IBM DB2, ORACLE, My-SQL, and Microsoft Access.

[Link] Brief History of RDBMS(RDBMS)


• E.F. Codd produced a study in 1970 to 1972 proposing the use of a relational database model.
• E.F. Codd's creation of the relational model served as the foundation for RDBMS.

159
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

[Link] How it works


The most popular type of database is a relational database. In relational databases, data is represented
in a table (relation) as rows of tuples. It has a number of tables, each with a unique primary key. Data
access in an RDBMS becomes easy because of a collection of a well organized set of tables.

Following are the various terminologies of RDBMS:

Fig. 2.2.4: RDBMS Terms

1. What is a table (relation)?


Everything in a relational database is saved in the form of relationships between the various
tables. The RDBMS database organizes its data into tables for storage. A table is a collection of data
elements that are connected in some way, and it stores information in rows and columns. Each
table is meant to represent a real-world entities, such as an event or place, for which information
is gathered. The term "logical view" refers to the orderly compilation of data into a relational table,
which is what's meant by "logical view" of the database.

2. Properties of a Relation:
Following are the properties of a relation:
• Each relation has a unique name by which it is identified in the database.
• Relation does not contain duplicate tuples.
• The tuples of a relation have no specific order.
• All attributes in a relation are atomic, i.e., each cell contains exactly one value.

A table is the simplest representation of data stored in a relational database.

ID Name AGE COURSE


1 Virinchi 24 [Link]
2 Dhansuh 20 C.A
3 Akarshana 21 BCA
4 Archita 22 MCA
5 Sandeep 26 BSC

160
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

3. What is a row or record?


A row in a database may also be referred to as a record or a tuple. It provides each table entry with
all of the relevant information that pertain to that entry. It is shown as a horizontal element in the
table.
For instance, there are 5 records in the table that is illustrated above.

Properties of a row:
• No two tuples are identical to each other in all their entries.
• All tuples of the relation have the same format and the same number of entries.
• The order of the tuple is irrelevant. They are identified by their content, not by their position.

Let us see one record/row in the table.

ID Name AGE COURSE


1 Virinchi 24 B.E

4. What is a column/attribute?
A column is a vertical item that exists inside a table and stores all of the information that pertains
to a particular field. For instance, all of the information on a student's name may be found in the
"name" column of the table that is shown above.

Properties of an Attribute:
• Every attribute of a relation must have a name.
• Null values are permitted for the attributes.
• Default values can be specified for an attribute automatically inserted if no other value is
specified for an attribute.
• Attributes that uniquely identify each tuple of a relation are the primary key.

Name
Virinchi
Dhanush
Akarshana
Architha
Sandeep

5. What is a data item (cell)?


The individual data item is the smallest type of data in the table. It is the value stored at the
intersection of a tuple and attribute.

Properties of data items:


• Data items are atomic in nature.
• The data items for an attribute should be drawn from the same domain.

161
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

In the below example, the data items in the student table are the individual values such as 1,
Virinchi, 24 and B.E.

ID Name AGE COURSE


1 Virinchi 24 B.E

6. Degree:
The total number of attributes in a relation is called the degree of the relation. For example, the
student table has 4 attributes, and therefore its degree is 4.

ID Name AGE COURSE


1 Virinchi 24 [Link]
2 Dhanush 20 C.A
3 Akarshana 21 BCA
4 Architha 22 MCA
5 Sandeep 26 BSC

7. Cardinality:
• The cardinality of a table is the total number of tuples (rows) present in a relation.
• An empty table is a relation whose cardinality is 0.

For example, the following student table has 5 rows, and therefore its cardinality is 5.

ID Name AGE COURSE


1 Virinchi 24 [Link]
2 Dhanush 20 C.A
3 Akarshana 21 BCA
4 Architha 22 MCA
5 Sandeep 26 BSC

8. Domain:
The possible values that each attribute may have are described with regard to the domain.
It may be specified using a variety of standard data types including integers, floating point numbers,
characters and others.
For example, the value "married" or "single" can be the only two valid options for a certain
characteristic named "Marital Status".

9. NULL Values
The value "NULL" in the table indicates that the corresponding field for the given record has not
been assigned a value yet.
NULL is not the same as a white space.

162
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

10. Data Integrity:


There are many different types of data integrity that are included in every RDBMS, including the
following:
• Entity integrity: It specifies that a table shall not have any rows that are identical to other
tables' rows.
• Domain integrity: It secures correct inputs for a particular column by putting limits on the kind
of data, the format of the data, or the range of possible values.
• Referential integrity: Indicates that the records from one table that are being referred to by
particular rows in another table cannot be deleted.
• User-defined integrity: It is responsible for carrying out a limited number of user-defined
business rules.

Java connection to a relational database


Step 1: Embed
 the component into your webpage
If Flexmonster is not yet embedded, set up an empty component in your webpage:
let pivot = new Flexmonster({
container: "pivotContainer",
toolbar: true
});

Step 2: Setup the Data Compressor on the server


Add the following dependencies to your project:
An appropriate database driver
[Link] – located in the Pivot Table for Databases/server/java/ folder of the
download package.
Below is a connection and query sample for a MySQL database:
[Link]("[Link]").newInstance();
String connectionString = "jdbc:mysql://localhost:3306/foodmart";
Connection connection =
[Link](connectionString, "user", "pass");
String query = "SELECT * FROM customer";
Statement statement = [Link]();
ResultSet resultSet = [Link](query);
Then the following line of code will convert ResultSet to an InputStream :
InputStream inputStream = [Link](resultSet);
Now you can create a response from the InputStream . For simple cases, it is suitable to read all
content at once:
Scanner s = new Scanner(inputStream).useDelimiter("\\A");
String output = [Link]() ? [Link]() : "";

163
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

It is also possible to create a streaming response. This means that the end user will get the response
with minimal delay and the server will use less memory. This is the recommended approach for large
datasets:
[Link]("text/plain");
OutputStream outputStream = [Link]();
int length = 0;
byte[] buffer = new byte[10240];
while ((length = [Link](buffer)) > 0) {
[Link](buffer, 0, length);
[Link]();
}

Step 3: Enable cross-origin resource sharing (CORS)


By default, the browser prevents JavaScript from making requests across domain boundaries. CORS
allows web applications to make cross-domain requests. Here are some useful links explaining how to
setup CORS on your server:
Tomcat – Configuration Reference (CORS Filter)
Jetty – Jetty/Feature/Cross Origin Filter
JBOSS – CORS Filter Installation

Step 4: Configure the report with your own data


Now it’s time to configure the pivot table on the webpage. Let’s create a minimal report for this (replace
filename and other parameters with your specific values):
var pivot = new Flexmonster({
container: "pivotContainer",
toolbar: true,
report: {
dataSource: {
type: "csv",
/* URL to the Data Compressor Java */filename: "[Link]
get"
}
},
licenseKey: "XXXX-XXXX-XXXX-XXXX-XXXX"
});

Launch the webpage from a browser — there you go! A pivot table is embedded into your project.
Check out the example on JSFiddle.

164
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Java Compressor API


Processing for streams:
InputStream compressStream(InputStream inputStream, char delimiter)
InputStream compressStream(InputStream inputStream)
Processing for Databases:
InputStream compressDb(ResultSet resultSet)
Examples: Saving to a file

[Link]("[Link]").newInstance();
String connectionString = "jdbc:mysql://localhost:3306/foodmart";
Connection connection =
[Link](connectionString, "user", "pass");
String query = "SELECT * FROM customer";
Statement statement = [Link]();
ResultSet resultSet = [Link](query);

InputStream inputStream = [Link](resultSet);


OutputStream outputStream = new FileOutputStream("[Link]");
int length = 0;
byte[] buffer = new byte[10240];
while ((length = [Link](buffer)) > 0) {
[Link](buffer, 0, length);
}
[Link]();
[Link]();

2.2.8 Expressions, Statements, and Blocks


In this section, we learn about expressions, statements, and blocks. A statement is made up of core
components called expressions. They involve computations, and they may be constructed with the use
of operators. Statements can be broken down into blocks.

[Link] Expressions
A construct that consists of variables, operators, and method calls and is built using the
language's syntax is known as an expression. An expression evaluates to a single value.
Examples of expressions are highlighted in bold below. These have been used in the demos illustrated
earlier.

165
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

int cadence = 0;
anArray[0] = 100;
[Link]("Element 1 at index 0: " + anArray[0]);

int result = 1 + 2; // result is now 3


if (value1 == value2) {
[Link]("value1 == value2");
}

The evaluated result of an expression is what determines the data type that it has.
In in above code, the result of the equation cadence = 0 is an int. This is because the assignment
operator generates a result of the same data type as its left-hand operand, which is an integer here.
As you can see from the other expressions, an expression may also result in various sorts of values, such
as boolean or string, depending on the context.
It is possible to construct compound expressions out of simpler expressions as long as the data types
needed by each component of an expression are compatible with one another.
Take a look at the following comma-separated expression:
1*2*3

Since the above expression contains only multiplicative operators, the order in which the expression is
evaluated is irrelevant. Not every expression falls under this category, though. For instance, if you want
to add two values and then divide by 100, the following phrase yields incorrect results.
x + y / 100 // ambiguous

Solution is to use parenthesis to determine how an expression will be evaluated.

For instance, you may use the following to clarify the prior expression.
(x + y) / 100 // unambiguous, recommended

With no parenthesis used, higher precedence operators are evaluated first. As an illustration, the
division operator takes precedence over the addition operator.
Consequently, these two claims are equivalent:
x + y / 100
x + (y / 100) // unambiguous, recommended

It is always a good practice to use parentheses to denote which operators should be evaluated first
when creating compound expressions are used. Code is easier to read and maintain as a result.

166
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

[Link] Statements
An entire unit of execution is a statement. The following expressions can be converted into statements
by adding a semicolon at the end of the expression (;).
• Assignment expressions
• Unary operations ++ or --
• Method invocations
• Object creation expressions

Such statements are called expression statements. Here are some examples of expression statements.

// assignment statement
aValue = 8933.234;

// increment statement
aValue++;

// method invocation statement


[Link]("Hello World!");

// object creation statement


Bicycle myBike = new Bicycle();

Declarative statements and control flow statements are two additional types of statements in addition
to expression statements. A variable is declared in a declaration statement.
You've already encountered a lot of declaration statements in practice:
// declaration statement
double aValue = 8933.234;
The sequence in which statements are performed is regulated by control flow statements.

[Link] Statements
An entire unit of execution is a statement. The following expressions can be converted into statements
by adding a semicolon at the end of the expression (;).
• Assignment expressions
• Unary operations ++ or --
• Method invocations
• Object creation expressions

Such statements are called expression statements. Here are some examples of expression statements.

167
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

// assignment statement
aValue = 8933.234;

// increment statement
aValue++;

// method invocation statement


[Link]("Hello World!");

// object creation statement


Bicycle myBike = new Bicycle();

Declarative statements and control flow statements are two additional types of statements in addition
to expression statements. A variable is declared in a declaration statement.
You've already encountered a lot of declaration statements in practice:
// declaration statement
double aValue = 8933.234;
The sequence in which statements are performed is regulated by control flow statements.

[Link] Blocks
A collection of zero or more statements that are enclosed in balanced braces may be referred to as a
block. The following example explains how to make use of blocks.

Example:
class GFG {
public static void main(String args[]) {
boolean condition = true;

if (condition) { // begin block 1


[Link]("Condition is true.");
} // end block one
else { // begin block 2
[Link]("Condition is false.");
} // end block 2
}

168
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Output:
Condition is true.

2.2.9 Type Conversion in Java


Type conversion helps to modify the data type of the variables while using the values in an expression
as required. In Java, there are primarily two different kinds of type conversions.
1. Explicit Type Conversion
2. Implicit Type Conversion

The size hierarchy of data types is necessary to comprehend this. Let us examine each of them in the
list below in order of increasing importance.
• byte
• short
• int
• long
• float
• double

[Link] Implicit Type Conversion


Shorter data types are automatically transformed to bigger data types in Java if larger variables are
assigned to shorter data types. This is called widening.
For example, if you assign a short value to an int variable, the resultant type would be automatically
transformed to an int type variable. This is because an int variable can only store integer values.

Example:
// Java program to illustrate automatic type conversion

class GFG {

public static void main(String args[]) {


// Declaring variables of different data types
int numberInt;
short numberShort;
byte numberByte;
float numberFloat;

169
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

double numberDouble;
long numberLong;

// Setting a value to the shorter datatype.


numberByte = 21;
numberShort = numberByte;
numberInt = numberShort;
numberLong = numberInt;
numberFloat = numberLong;
numberDouble = numberFloat;

[Link]("The short value is " + numberShort);


[Link]("The byte value is " + numberByte);
[Link]("The int value is " + numberInt);
[Link]("The long value is " + numberLong);
[Link]("The float value is " + numberFloat);
[Link]("The long value is " + numberDouble);
[Link]("This is implicit conversion");
}
}

Output:
The short value is 21
The byte value is 21
The int value is 21
The long value is 21
The float value is 21.0
The long value is 21.0
This is implicit conversion

Note how the value stored in the short variable was converted to an int automatically. This takes place
in Java if a variable with a lower size is assigned to a variable with a bigger size.
However, if you attempt to change the data type of a larger size to a smaller size, it is not supported by
the compiler and would result in an error.

170
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Example:
// Java program to discuss the problem with type conversion
class GFG {
public static void main(String args[]) {
int a = 57;
byte b = a; // Error as int cannot be assigned to byte
[Link](b);
}
}

Output:
error: incompatible types: possible lossy conversion from int to byte
byte b = a;
^
As observed in the output above, it is a lossy conversion since the size of the variable int is more than
the size of the data type byte. The compiler doesn’t allow this and hence returns an error as otherwise
it would result in the loss of data.
The solution for this is to use explicit type conversion that is discussed next.

[Link] Explicit Type Conversion


We will have to explicitly convert the value of a certain data type of larger size to one that is of a lower
size. To do this, we need to insert the name of the data type contained in rounded brackets in front of
the name of the variable. This is termed as narrowing.

Example:
// Java program to discuss explicit type conversion

class GFG {

public static void main(String args[]) {


int a = 257;
byte b = (byte) a; // Explicit type conversion
[Link](b);
}
}

171
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Output:
1

Let us discuss the output above. A single byte has 8 bits. Therefore, the value assigned to the byte type
variable is N mod 256 (28). In this instance, 257 mod 256 equals 1, hence the result only displays 1.
The loss the compiler was referring to earlier is this one. Programming requires a lot of expertise and
knowledge, and selecting the right data type based on its usage is very crucial.

[Link] Type Promotion in Expressions


When the compiler encounters an expression in a Java program, it promotes all the short, byte, and
char types to the int datatype in the given statement. However, if the expression contains float and
double data types, the result is promoted to the data type with the highest value.

Example:

// Java program to illustrate the promotion of type in expressions

class GFG {

public static void main(String args[]) {


[Link](
"This program will illustrate the automatic type promotion of Java"
);
int a = 76;
long l = 65123l;
float f = 70.26f;
double d = 98.9898d;
char c = 'z';

[Link](a + c / d - f + l);
}
}

Output:
This program will illustrate the automatic type promotion of Java
65129.97244807581
Observe that the resulting data type is double. Promotion of this type is automatic.

172
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

[Link] Explicit Type Casting in Expressions


Whenever any operation is performed on a shorter datatype, we have seen that Java automatically
changes the data to a bigger data type.
What should we do if we do not want the type of the variable to change? In order to do this, we will
need to make use of explicit type conversion, much like the one described in the prior section.
If we want the type of the resulting variable to be preserved after we have carried out the relevant
actions, we must conduct an explicit conversion from the resultant variable to the desired type. Let us
see how to do this.

Example:
// Java program to illustrate the use of explicit type casting in expressions

class GFG {

public static void main(String args[]) {


[Link](
"This program will illustrate the automatic type promotion of Java"
);
byte a = 127;
a++;
[Link]("Now the datatype of a has changed to int. a => " + a);
a = (byte) a; //explicit conversion of int c to char c.
[Link]("Now it's back to a byte. a=> " + a);
}
}

Output:
This program will illustrate the automatic type promotion of Java
Now the datatype of a has changed to int. a => -128
Now it's back to a byte. a=> -128

Let us look at another example on characters for a better understanding.

Example:
// Java program to illustrate the use of explicit type casting in expressions

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

173
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

[Link](
"This program will illustrate the automatic type promotion of Java");
char c = 's';
int a = 1;
int b = c + a;
[Link]("This means that b is now an int value " + b);
[Link](
"We can explicitly typecast it to a character like this " + (char) (b)
);
}
}

Output:
This program will illustrate the automatic type promotion of Java
This means that b is now an int value 116
We can explicitly typecast it to a character like this t

Exercise
Answer the following questions:
1. What are the programming constructs?
2. What is output of the following program?
class conditional {
public static void main(String args[]) {
int i = 20;
int j = 55;
int z = 0;
z = i < j ? i : j; // ternary operator
[Link]("The value assigned is " + z);
}
}
3. The switch statement does not require a break.
a) true b) false

174
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

4. The conditional operator is otherwise known as the ternary operator.


a) true b) false
5. The while loop repeats a set of code while the condition is false.
a) true b) false
6. The do-while loop repeats a set of code at least once before the condition is tested.
a) true b) false
7. What is the difference between break and continue?
8. The for loop repeats a set of statements a certain number of times until a condition is matched.
a) true b) false
9. Can a for statement loop indefinitely?
10. What is the difference between while statement and a do statement?

175
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

UNIT 2.3: Core JAVA Concepts

Unit Objectives
By the end of this unit, the participants will be able to:
1. Discuss various control flow statements (if, then, while, for, nested if, etc.) in Java programming
2. Explain the concepts and various types of methods/functions, constructors, and class
3. Explain the ways to create objects in Java
4. Discuss key aspects of encapsulation, inheritance, abstraction, polymorphism, interfaces, and
multithreading
5. Explain the concepts of packages and file handling in Java
6. Distinguish between overloading and overriding
7. Study the concepts of I/O channels, java streams, and APIs
8. Outline advanced topics and latest additions to Java such as lambda expressions, collections,
generics, JDBC, etc.
9. Outline MVC architecture layers in Java
10. Demonstrate the use of control flow statements as part of java code
11. Create an object from a class using suitable methods
12. Demonstrate the three steps: declaration, instantiation, and initialization
13. Use and create packages and interfaces in Java
14. Demonstrate encapsulation, inheritance, abstraction, polymorphism, interfaces and multithreading
using suitable examples
15. Perform file operations and use I/O streams in Java
16. Demonstrate suitable examples for advanced topics qand latest additions to Java
17. Create applets in java using graphical user interface

2.3.1 Java Control Statements


The Java compiler runs the code from beginning to end. The statements are executed in the order that
they appear. However, Java has statements that can be used to manage how Java code is executed.
These sentences are referred to as control flow statements.
Java provides three types of control flow statements.
1. Decision Making statements
i. if statements
ii. switch statement
2. Loop statements
i. do while loop
ii. while loop
iii. for loop
iv. for-each loop
3. Jump (Loop Control) statements
i. break statement
ii. continue statement

176
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

[Link] Decision-Making statements


Decision-making statements allow us to decide which statements to run and when. Depending on the
outcome of the condition given, decision-making statements assess the boolean expression and impact
the program flow.
In Java, there are two different categories of decision-making statements -if statements and switch
statements. Let us see the use of these statements with examples.

1. The if statement:
The "if" statement in Java is used to assess a condition. Depending on the unique circumstance,
the control of the program is changed. The If statement's condition returns a Boolean value, either
true or false.
The four different sorts of if-statements in Java are listed below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement

Let us understand the use of if-statements one by one.


• Simple if statement:
Among all Java's control flow statements, it is the simplest. It tests a boolean expression and, if it
returns true, allows the program to execute the corresponding block of code.

Syntax:
if(condition) { // this block of code executes only when the condition is true
//block of statements
}

Example:

class GFG {
public static void main(String args[]) {
int x = 10;
int y = 12;
if (x + y > 20) {
[Link]("x + y is greater than 20");
}
}
}

177
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Output:
x + y is greater than 20

• The if-else statement:


The above if statement checks for the condition being true. But in case the condition evaluates
to false, we can use the if-else statement. That is, when the if condition is false, the else block is
executed.

Syntax:
if(condition) { // this block of code executes only when the condition is true
//block of statements
}
else { // this block of code executes when the condition evaluates to false
//block of statements
}

Example:
class GFG {
public static void main(String args[]) {
int x = 10;
int y = 12;
if (x + y < 10) {
[Link]("x + y is less than 10");
} else {
[Link]("x + y is greater than 20");
}
}
}

Output:
x + y is greater than 20

• The if-else-if ladder:


When there are multiple conditions to check, we use the if-else-if ladder unlike the if-else statement
that is based on a single condition only.

Syntax:

178
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

if(condition1) { // this block of code executes when condition 1 is true


//block of statements
}
else if(condition2) { // executes when condition 1 is false and condition 2 is true
//block of statements
}
.
.
else if(conditionN) { // executes when condition N is true
//block of statements
} else { // executes when none of the conditions specified are true
//block of statements
}

Example:
class GFG {
public static void main(String args[]) {
String city = "Hyd";
if (city == "Mumbai") {
[Link]("city is Mumbai");
} else if (city == "Mumbai") {
[Link]("city is Punjab");
} else if (city == "Agra") {
[Link]("city is agra");
} else {
[Link](city);
}
}
}

Output:
Hyd

• Nested if statement
If any of the control structures (if, if-else, if-else-if) discussed above are embedded inside the block
of another control structure, then the nested if statement can be used.

179
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Syntax:

if(condition1) { // this block of code executes when condition 1 is true


//block of statements
if(condition2) { // this nested block executes when condition 2 is true
//block of statements
}
//block of statements
}
else { // this block of code executes when condition 1 is false
//block of statements
}

Example:
class GFG {
public static void main(String args[]) {
String address = "Delhi, HYD";
if ([Link]("HYD")) {
if ([Link]("Mumbai")) {
[Link]("Your city is Mumbai");
} else if ([Link]("Punjab")) {
[Link]("Your city is Punjab");
} else {
[Link]([Link](",")[0]);
}
} else {
[Link]("You are not living in HYD");
}
}
}

Output:
Delhi

180
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

[Link] The switch statement


In the switch statement, depending on the value of the variable being switched, the block of code
corresponding to the matched case gets executed. Switch statements can be used in place of if-
else-if statements wherever possible. In addition to that, it makes the program simpler and more
straightforward to understand.

Points to be noted about switch statement:


• The type of the case values can be int, short, byte, char, or enumeration. String type is also supported
since version 7 of Java.
• Cases cannot be duplicate.
• The default block gets executed when any of the given cases do not match the value of expression.
It is optional.
• The break statement terminates the switch block when the condition is satisfied. If break is not
used, the next case gets executed irrespective of whether the value is matched or not.
• While using switch statements, the case expression should be of the same type as the variable
being switched.

Syntax:
switch (expression) {
case value1:
//block of statements
break;
.
.
case valueN:
//block of statements
break;
default:
//block of statements
}

Example:
class GFG {
public static void main(String[] args) {
int num = 2;
switch (num) {
case 0:
[Link]("number is 0");
break;
case 1:

181
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

[Link]("number is 1");
break;
default:
[Link](num);
}
}
}

Output:
2

Note that only int, short, byte, char, string or enum type variables are allowed to be used when the
switch is active.

Exercise
Answer the following questions:
1. What happens when the if condition is false?
A. Block corresponding to the if condition will be executed
B. Block corresponding to the if condition will not be executed
C. Block of else will be executed (in case it exists)
D. Both B and C

2. What is the output of the following program?


public class ControlStatement1 {
public static void main(String[] args) {
if (true) {
[Link]("If condition true");
}
}
}
A. Compile time Error B. Run time Error
C. If condition true D. Error

182
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

3. What is the output of the following program?

public class ControlStatement {


public static void main(String[] args) {
int x = 5;
int y = 10;
if (x > y) {
[Link]("X greater than Y");
} else {
[Link]("X less than Y");
}
}
}

A. X greater than Y B. X less than Y


C. Both A and B D. Error

4. What is the output of the following program?


class ControlStatement {
public static void main(String[] args) {
int x = 2;
switch (x) {
case 1:
[Link]("X1 ");
case 2:
[Link]("X2 ");
case 3:
[Link]("X3 ");
default:
[Link]("Default ");
}
}

183
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

A. X2 X2 X3 Default B. X2
C. X2 X3 Default D. Default

5. What will be the output of the program?

class ControlStatement {
public static void main(String[] args) {
int x, y;
x = 15;
y = 20;
if (x > 15) if (y > 15) {
[Link]("y is " + y);
} else {
[Link]("x is " + x);
}
}
}

A. Error B. y is 20
C. x is 15 D. No output

6. Which statement is true for the function defined below?

public void test(int x) {


int odd = 1;
if (odd) {
[Link]("odd");
} else {
[Link]("even");

184
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

}
}

A. Compilation fails.
B. "odd" will always be output.
C. "even" will always be output.
D. "odd" will be output for odd values of x, and "even" for even values.

7. Which of this statement is incorrect?


A. The switch statement is more efficient than a set of nested ifs
B. Two case constants in the same switch can have identical values
C. The switch statement can only test for equality, whereas if statement can evaluate any type of
boolean expression
D. It is possible to create a nested switch statements

8. State whether the following statements for if statement are true or false.
i) When if statements are nested, the last else gets associated with the nearest if without an else.
ii) One if can have more than one else clause.
A. true, false B. false, true
C. true, true D. false, false

[Link] Loop Statements


Sometimes, it may be necessary to continually run a block of code based on a certain condition being
true. A given set of instructions can be executed repeatedly using looping statements.
In Java, we have three types of loops that can be used. However, there are differences in their syntax
and condition checking time.
• for loop
• while loop
• do-while loop

1. The for loop:


Java's for loop is similar to those in C and C++. With just one line of code, we can initialize the loop
variable, test the condition, and increment or decrement. Only when we are certain of the number
of times we want to run the block of code do we utilize the for loop.

185
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Syntax:
for(initialization; condition; increment/decrement) {
//block of statements
}

The flow chart for the for loop is given below.

Fig. 2.3.1: for loop Flowchart

Example:
class GFG {
public static void main(String[] args) {
int sum = 0;
for (int j = 1; j <= 10; j++) {
sum = sum + j;
}
[Link]("The sum of first 10 natural numbers is " + sum);
}
}

Output:
The sum of first 10 natural numbers is 55

2. The for-each loop:


The for-each loop is useful when we need to iterate through a list of elements stored in collections
and arrays. When using the for-each loop, we don't need to worry about the three steps of
initialization, condition checking and increment/decrement used in the for loop.

Syntax:
for(data_type var : array_name/collection_name) {
//block of statements

186
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Example:
class GFG {
public static void main(String[] args) {

String[] names = { "Java", "C", "C++", "Python", "JavaScript" };

[Link]("Printing the content of the names array:");


for (String name : names) {
[Link]("\t" + name);
}
}
}

Output:
Printing the content of the names array:
Java
C
C++
Python
JavaScript

3. The while loop:


The while loop is also used to repeatedly loop through the set of statements. However, this loop is
used when we are not sure of the number of iterations. In contrast to the for loop, the while loop's
initialization and increment/decrement operations do not happen inside the loop statement.

Since the condition in a while loop is verified at the beginning of the loop, it is sometimes referred
to as the entry-controlled loop. If the condition is satisfied, the body of the loop gets executed;
otherwise, the loop is skipped and statements after the loop will be run.

Syntax:
while(condition) {
//block of statements
}

187
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

The flow chart for the while loop is given below.

Fig. 2.3.2: For each loop flowchart

Example:
class GFG {
public static void main(String[] args) {
int i = 0;
[Link]("Printing the list of first 10 even numbers");
while (i <= 10) {
[Link]("\t" + i);
i = i + 2;
}
}
}

Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10

188
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

4. The do-while loop:


Use do-while loops when the number of iterations is unknown but we need to run the statements
in the loop at least once. After running the loop statements, the do-while loop verifies the condition
at the end of the loop. Due to the fact that the condition is not checked beforehand, it is often
referred to as the exit-controlled loop.

Syntax:
do {
//block of statements
} while (condition);

The flow chart of the do-while loop is given in the following image.

Fig. 2.3.3: Do-while loop flowchart

Example:
class GFG {
public static void main(String[] args) {
int i = 0;
[Link]("Printing the list of first 10 even numbers");
do {
[Link]("\t" + i);
i = i + 2;
} while (i <= 10);
}
}

189
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10

[Link] Jump Statements


Jump statements are also called loop control statements as these are used to control the flow of the
program. The break and continue statements are the two types of jump statements supported by Java.

1. The break statement:


The break statement is used to interrupt the program's current flow and pass control to the
following statement outside of a loop or switch statement. In the case of a nested loop, it just
breaks the inner loop.
The break statement can only be included in a loop or switch statement as it cannot be used
independent of these in a Java application.

Example:
class GFG {
public static void main(String[] args) {
for (int i = 0; i <= 10; i++) {
[Link](i);
if (i == 6) {
break;
}
}
}
}

Output:
0
1
2
3

190
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

4
5
6

By default, the break statement only exits the inner loop placed inside an outer loop. But we can also
use the break statement in labeled for loops to transfer control as required.

Example:
class GFG {
public static void main(String[] args) {
a:for (int i = 0; i <= 10; i++) {
b:for (int j = 0; j <= 15; j++) {
c:for (int k = 0; k <= 20; k++) {
[Link](k);
if (k == 5) {
break a;
}
}
}
}
}
}

Output:
0
1
2
3
4
5

2. The continue statement:


The continue statement is used when we want to skip the remaining statements in the loop and
instantly move onto the next iteration. Unlike the break statement which exits the loop, continue
statement skips the current iteration only.

191
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Example:
class GFG {
public static void main(String[] args) {
for (int i = 0; i <= 2; i++) {
for (int j = i; j <= 5; j++) {
if (j == 3) {
continue;
}
[Link](j + " ");
}
[Link]();
}
}
}

Output:
01245
1245
245

As observed in the program output above, number 3 is not displayed because we chose to continue
to the next iteration when j value matches 3.

Exercise
Answer the following questions:
1. Which of the following is not a valid loop control statement?
a) break b) goto
c) continue d) return

2. The while loop repeats a set of code as long as the condition is not met?
a) true b) false

3. Which of the following for loop declaration is not valid?


a) for ( int i = 99; i >= 0; i / 9 ) b) for ( int i = 7; i <= 77; i += 7 )
c) for ( int i = 20; i >= 2; - -i ) d) for ( int i = 2; i <= 20; i = 2* i )

192
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

4. Which of the following is an iteration statement?


a) switch b) if-else
c) if d) do-while

5. Which of the following loops will execute the body of loop even when condition controlling the
loop is initially false?
a) do-while b) while
c) for d) none of the mentioned

6. What will be the output of the following Java program?


class Output {
public static void main(String args[]) {
int x = 2;
int y = 0;
for (; y < 10; ++y) {
if (y % x == 0)
continue;
else if (y == 8)
break;
else
[Link]( y + " " );
}
}
}

a) 1 3 5 7 b) 2 4 6 8
c) 1 3 5 7 9 d) 1 2 3 4 5 6 7 8 9

7. What will be the output of the following Java program?

class Output {
public static void main(String args[]) {
final int a = 10, b = 20;

193
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

while (a < b) {
[Link]("Hello");
}
[Link]("World");
}
}

a) Hell b) run time error


c) Hello world d) compile time error

8. By using ____________, you can force immediate termination of the loop, bypassing the conditional
expression and any remaining code in the body of the loop.

9. The __________ loop is especially useful when you process a menu selection.

2.3.2 Types of Methods/Functions, Constructors and Classes


in Java
In this section, we shall discuss about the various types of methods, constructors and classes available
in Java. We start by discussing about methods.

[Link] Methods in Java


A method is a block of code that performs a well defined task. It allows for reuse of code. Using methods,
code is well organized and easily editable. This section explains the different kinds of methods, how to
declare a method, and how to invoke a method in Java.

1. Method Declaration:
Details pertaining to method properties, such as visibility, return-type, name, and parameters,
are provided in the method declaration. As illustrated in the diagram below, method declaration
includes six components collectively known as the method header.

194
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Fig. 2.3.4: Method declaration

• Method Signature
A method signature is a part of every method declaration. The method name and argument list are
included in it.
• Access Specifier
The method's access type is an access specifier or modifier. It specifies the method's visibility. Java
has four different kinds of access specifiers:
ᴑ Public: When the access specifier is defined as public, the method is accessible to all classes.
ᴑ Private: The method is only accessible in the classes in which it is declared when we use the
private access specifier.
ᴑ Protected: The method is available inside the same package or by subclasses in a different
package when we use the protected access specifier.
ᴑ Default: When no access specifier is mentioned in the method declaration, Java automatically
uses the default access specifier. These methods are accessible from within the same package.
ᴑ Return Type: The data type the method returns is known as the return type. It could be an
object, collection, void, primitive data type, etc. We use the keyword void if the method returns
nothing.
• Method Name
It is a special name that is used to specify a method's name. It must be compatible with the
method's capabilities. Consider that we create a method for subtracting two numbers, then we
would appropriately call it subtract(). Using its name, the method is called whenever required.
• Parameter List
It is the list of parameters enclosed in a pair of parentheses and separated by commas. It includes
the variable name and data type. Leave the parenthesis empty if the method doesn't take any
parameters.
• Method Body
The method body includes every step that needs to be taken. Statements are placed within a block
of code using two curly braces.

2. Naming a Method
When defining a method, the method name must begin with a lowercase letter and represent a
verb. If the method name includes more than one word, the first part must be a verb, thereafter
subsequent words start with uppercase and can be an adjective or a noun. Each word in the multi-
word method name, except for the first, must begin with an uppercase letter.

195
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

For instance:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
It is also possible that a method has the same name as another method name in the same class, it
is known as method overloading.

[Link] Types of Methods


There are two types of methods in Java:
• Predefined Method
• User-defined Method

1. Pre-defined Methods:
Predefined methods in Java refer to the methods that are already defined in the Java class libraries.
It is often referred to as the built-in or standard library methods. These methods can be used
immediately by simply calling them within the application at any point. Some examples of pre-
defined methods are sqrt(), compareTo(), length(), and equals().
There are several predefined methods declared within every library class. For instance, the java.
[Link] class defines a method called print(). The statement that we enter inside the method
is printed. As an illustration, call to print("Java") prints the string Java to the console.

Example:
class GFG {
public static void main(String[] args) {
[Link]("The maximum number is: " + [Link](1, 2));
}
}

Output:
The maximum number is: 2

The three predefined methods main(), print(), and max() were utilized in the example above.
Because they are predefined, we have used these methods directly without the need to declare
them. The [Link] class's print() method displays the outcome on the console. The
[Link]() returns the larger of two values. The following diagram shows the signature of the
max() method.

196
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Fig. 2.3.5: Method Signature

The method signature in the example above contains the following characteristics: public access
specifier, static non-access modifier, int return type, method name max(), and parameter list (int a, int
b). Programming becomes simpler and faster using predefined methods.

2. User-defined Methods:
A user-defined method is one that has been written by a user or programmer. These methods are
created based on the given task to be performed.

• Creating a User-defined Method


Assume we want to create a user-defined method that determines whether the given integer is
even or odd. We define the method as follows.

// user-defined method
public static void findEvenOdd(int num) {
//method body
if (num%2 == 0) {
[Link](num+" is even");
} else {
[Link](num+" is odd");
}
}

The findEvenOdd() method mentioned above has been defined. It has an int-type parameter named
num. We used void since the method does not return anything. The logic to determine whether
a number is even or odd are written in the method body. The method displays the corresponding
information accordingly.

197
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

• Invoking a User-defined Method


A method can be called once it has been defined. It is easy to invoke a method and the program
control is transferred to the called method. Let us see the program that invokes the above method.

Example:
import [Link];

class GFG {

// user-defined method
public static void findEvenOdd(int num) {
//method body
if (num % 2 == 0) {
[Link](num + " is even");
} else {
[Link](num + " is odd");
}
}

public static void main(String[] args) {


//creating Scanner class object
Scanner scan = new Scanner([Link]);

//reading input from the user


[Link]("Enter the number: ");

int num = [Link]();

//method calling
findEvenOdd(num);
}
}

Output (Run #1):


Enter the number: 12
12 is even

198
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Output (Run #2):


Enter the number: 99
99 is odd

• Returning a value from the method


Let us create a user-defined method called add(), that adds two integer-type parameters, and
returns the result back to the caller of the method.

Example:
class GFG {

//user defined method


public static int add(int n1, int n2) { //n1 and n2 are formal parameters
int s;
s = n1 + n2;
return s; //returning the sum
}

public static void main(String[] args) {


int a = 19;
int b = 5;

//method call
int c = add(a, b); //a and b are actual parameters
[Link]("The sum of " + a + " and " + b + " is= " + c);
}
}

Output:
The sum of 19 and 5 is = 24

[Link] Static Methods


Static methods are those that contain the keyword static. In other terms, a static method is a method
that belongs to a class rather than an instance of a class. By placing the term "static" before the method
name, we declare that the method is static.
A static method's key benefit is that we can call it without creating an object of that class. It has the
ability to access and modify the static data members of the class. The class name is used to invoke static

199
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

methods. The main() method is the ideal illustration of a static method.


Calling one static method from another static method of the same class does not require the class
name or object to be used during invocation. The same is illustrated in the example below.

Example:
class GFG {

// static method
static void show() {
[Link]("It is an example of static method.");
}

public static void main(String[] args) {


// calling the static method
show();
}
}

Output:
It is an example of a static method.

[Link] Instance Methods


A non-static method defined inside the class is referred to as an instance method. Instance methods
can be invoked only by objects of its class. Let us look at an instance method example.

Example:
class InstanceMethodExample {

// user-defined instance method as static keyword is not used


public int add(int a, int b) {
int s = a + b;
//returning the sum
return s;
}

public static void main(String[] args) {

200
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

//Creating an object of the class


InstanceMethodExample obj = new InstanceMethodExample();

//invoking instance method


[Link]("The sum is: " + [Link](12, 13));
}
}

Output:
The sum is: 25

[Link] Accessors and Mutators


In order to set values to the attributes of an object and thereafter retrieve the attribute’s values, Java
allows us to create the following types of instance methods:
• Accessor Method
• Mutator Method

1. Accessor Methods:
The accessor method is the name given to the method that reads the instance variables. The word
"get" is prefixed to the method, differentiating it from other instance methods. Accessor methods
are also called as getters. It is generally used to return values of private attributes and the return
type is same type as that of the corresponding instance variable.

For instance,

public int getId() {


return Id;
}

2. Mutator Methods:
These methods are used to modify the values of instance variable(s). The word "set" is prefixed to
a mutator method. Mutators are also called modifiers or setters. They don’t return a value. The
mutator method accepts a field-dependent parameter of the same data type. Generally, values of
private attributes are set using these methods.

For instance,

public void setRoll(int roll) {

201
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

[Link] = roll;
}

Example:
class Student {

private int roll; // instance variable


private String name;

public int getRoll() { //accessor method


return roll;
}

public void setRoll(int roll) { //mutator method


[Link] = roll;
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public void display() { //instance method


[Link]("Roll No: " + roll);
[Link]("Student Name: " + name);
}

public static void main(String[] args) {


//creating a student object
Student student = new Student();

//calling the mutators to set attribute values


[Link](11);

202
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

[Link]("Raj");

//displaying the details of a student using the accessor and instance method
[Link](
"Details of student with roll number " + [Link]()
);
[Link]();
}
}

Output:
Details of student with roll number 11
Roll No: 11
Student Name: Raj

[Link] Abstract Methods


Methods without a method body are termed as "abstract methods". In other terms, an abstract method
is one that does not have an implementation. An abstract class is a class with at least one abstract
method. Such a class must be declared abstract. We use the keyword abstract to define an abstract
method.

Syntax:
abstract void methodName(args);

Example:
abstract class Demo { //abstract class

//abstract method declaration


abstract void display();

//non-abstract instance method


public void greet(String name) {
[Link]("Hello " + name);
}
}

public class MyClass extends Demo {

203
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

//method impelmentation
void display() {
[Link]("Implementing the abstract method here");
}

public static void main(String args[]) {


//creating an object
Demo obj = new MyClass();

//invoking the non-abstract method


[Link]("Raj");

//invoking abstract method


[Link]();
}
}

Output:
Hello Raj
Implementing the abstract method here

Exercise
Answer the following questions:
1. What is the return type of a method that does not return any value?
a) int b) float
c) void d) double

2. Which of following statement is incorrect?


a) All objects of a class are allotted memory for the all the variables defined in the class
b) If a method is defined as public, it can be accessed by objects of other classes only by inheritance
c) The main() method of a class must be made public
d) All objects of a class are allotted memory for the methods defined in the class

204
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

3. All Java methods must have a return type


a) true b) false

4. In Java, add a _______ to a constructor to convert it into a method.


a) if statement b) static
c) return type d) semicolon

5. Choose the correct identifier as per the naming convention used in Java.
a) 1show b) $hide
c) *show$ d) 3_click

2.3.3 Classes and Objects in Java


Object-Oriented Programming languages including Java have the ability to represent real-world entities
through the use classes and objects.
1. A class is a collection of objects that share common traits, behaviours, and attributes.
2. A class does not exist in the real world. It merely serves as a model, blueprint, or prototype from
which objects can be made.
3. A class is a collection of variables with various kinds of data and operations. There is no memory
allocated with a mere declaration of a class.
4. Memory allocation for non-static members is done only when an instance of that class is created.

Example of classes: Animal, Student, Bird, Vehicle, Company

A class in Java can contain:


1. data members
2. methods
3. constructors
4. nested classes and interfaces

Syntax to declare a class:


access_modifier class<class_name> {
data members;
methods;
constructors;
nested clases;
interfaces;
}

205
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Example:
class Student {
//data members (also known as instance variables)
int id;
String name;

public static void main(String args[]) {


Student s1 = new Student(); //creating an object of Student class
[Link]([Link]);
[Link]([Link]);
}
}

Output:
0
null

A user-defined class serves as a template or prototype from which objects are made. It contains
attributes or operations that are shared by all objects of a particular type. The following elements can
typically be found in class declarations:
• Modifiers: A class can be public or has default access.
• Class keyword: The class keyword is used to create a class.
• Class name: The name should begin with a capital letter (capitalized by convention).
• Super class (if any): The name of the class’s parent (superclass), if any, preceded by the keyword
extends. In Java, a class can only extend (subclass) from 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 as required.
• Class body: The class body is surrounded by braces { }.

New objects are initialised using constructors. While methods are used to implement the action of the
class and its objects, fields are variables that give the state of the class and its objects.
Real-time applications use a variety of class types, including nested classes, anonymous classes, and
lambda expressions.

Create an object from a class using suitable methods


As we all know, a class serves as the blueprint for objects, and you construct an object from a class.
There are various ways to create objects of a class in Java. This idea is underappreciated and occasionally
shows to be useful because it is disregarded by many programmers and occasionally even comes up.
In Java, there are numerous ways to construct objects. To demonstrate the internal workings by which
we can build objects in Java, let's list them and discuss them later after taking each one in turn with the

206
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

aid of programs.
• Using new keyword
• Using new instance
• Using clone() method
• Using deserialization
• Using newInstance() method of Constructor class

Using New Keyword


The simplest method for creating an object in Java is to use the new keyword. The most typical method
of creating an object in Java is this one. This is how almost all objects are made. This method allows us
to invoke any function Object() we desire (no argument or parameterized constructors).

// Java program to Illustrate Creation of Object


// Using new keyword

// Main class
class GFG
{

// Declaring and initializing string


// Custom input string
String name = "Author” ;

// Main driver method


public static void main(String[] args)
{
// As usual and most generic used we will
// be creating object of class inside main()
// using new keyword
GFG obj = new GFG();

// Print and display the object


[Link]([Link]);
}
}

Output: Author

207
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Using New Instance


If the class has a public default function Object() and we are aware of its name, we can generate
an object with the [Link] method. It can be used to construct Class Objects. [Link]
doesn't actually generate any Objects; instead, it simply loads the Class in Java. You must utilise the new
Instance Method of the Class to create an Object of the Class.

// Java program to Illustrate Creation of Object


// Using new Instance

// Main class
class GFG {

// Declaring and initializing string


String name = "Author";

// Main driver method


public static void main(String[] args)
{
// Try block to check for exceptions
try {

Class cls = [Link]("GFG");

// Creating object of main class


// using instance method
GFG obj = (GFG)[Link]();

// Print and display


[Link]([Link]);
}

// Catch block to handle the exceptions

// Catch block 1
// Handling ClassNotFound Exception
catch (ClassNotFoundException e) {

208
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

// Display the exception along with line number


// using printStacktrace() method
[Link]();
}

// Catch block 2
// Handling InstantiationException
catch (InstantiationException e) {

[Link]();
}

// Catch block 2
// Handling IllegalAccessException
catch (IllegalAccessException e) {

[Link]();
}
}
}

Output: Author

Using Clone() Method


Whenever clone() is called on any object, the JVM actually creates a new object and copies all content of
the previous object into it. Creating an object using the clone method does not invoke any constructor.
In order to use the clone() method on an object we need to implement Cloneable and define the
clone() method in it.

Example:
// Java program to Illustrate Creation of Object
// Using clone() method

// Main class
// Implementing Cloneable interface
class GFG implements Cloneable {

209
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

// Method 1
@Override
protected Object clone()
throws CloneNotSupportedException
{
// Super() keyword refers to parent class
return [Link]();
}

// Declaring and initializing string


String name = "Author ";

// Method 2
// main driver method
public static void main(String[] args)
{
GFG obj1 = new GFG();

// Try block to check for exceptions


try {

// Using the clone() method


GFG obj2 = (GFG)[Link]();

// Print and display the main class object


// as created above
[Link]([Link]);
}

// Catch block to handle the exceptions


catch (CloneNotSupportedException e) {

// Display the exception


// using printStackTrace() method
[Link]();

210
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

}
}
}

Output:
Author

User deserialization
JVM generates a unique object each time we serialise and then deserialize an object. JVM doesn't utilise
a function Object() to generate the object during deserialization. We must implement the Serializable
interface in the class in order to deserialize an object.

Example
// Java Program Illustrate Serializing an Object

// Importing input output classes


import [Link].*;

// Main class
// Implementing the Serializable interface
class GFG implements Serializable {

// Member variables
private String name;
GFG(String name)
{
// This keyword refers to current object itself
[Link] = name;
}

// Main driver method


public static void main(String[] args)
{
// Try block to check for exceptions
try {
// Creating object of class in main() method
GFG d = new GFG(" Author ");

211
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

FileOutputStream f
= new FileOutputStream("[Link]");
ObjectOutputStream oos
= new ObjectOutputStream(f);
[Link](d);
[Link]();

// Freeing up memory resources


[Link]();
}

// Catch block to handle the exceptiona


catch (Exception e) {
// Display the exception along with line number
// using printStacktrace() method
[Link]();
}
}
}

Output: Author

Using newInstance() method of the constructor class


This is comparable to a class's newInstance() function. The [Link] class contains
a single newInstance() method that can be used to build objects. Using the newInstance() method,
it is also possible to call the private function Object() and the parameterized function Object(). Both
newInstance() techniques are recognised as reflective approaches to object creation. In actuality, the
function Object() class's newInstance() method is used internally by the class's newInstance() method.

Example:
// Java program to illustrate creation of Object
// using newInstance() method of Constructor class

// Importing required classes from [Link] package


import [Link].*;

// Main class

212
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

class GFG
{

// Member variables of this class


private String name;

// Constructor of this class


GFG() {}

// Method 1
// To set name ofthe string
public void setName(String name)
{
// This method refers to current object itself
[Link] = name;
}

// Main driver method


public static void main(String[] args)
{
// Try block to check for exceptions
try {
Constructor<GFG> constructor
= [Link]();

GFG r = [Link]();

// Custom passing
[Link]("Author");
[Link]([Link]);
}

// Catch block to handle the exceptions


catch (Exception e)
{

213
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

// Display the exception on console


// using printStackTrace() method
[Link]();
}
}
Output:
Author

2.3.4 Constructors in Java


A constructor is a block of Java code that is similar to an instance method. However, the constructor
of the class is called automatically when a class instance is created, explicit invocation is not needed.
Object variables are allocated memory and initialized with the given values using the constructor.
The term constructor is appropriate as it constructs the instance variables when the object is created.
A class does not require a constructor to be written. If a class doesn't have a constructor, the Java
compiler produces one.

Points to remember about constructors:


• The method is a unique kind that is used to initialize the object.
• The new() keyword calls at least one constructor each time an object is created.
• If the class doesn't have a constructor defined, the compiler calls the default constructor that is
provided implicitly by Java.
• We can use access modifiers while declaring a constructor. It controls the way the object is created.
In other words, we can have private, protected, public or default constructors in a Java class.

[Link] Rules for defining the Java constructor


There are two rules defined for the constructor.
• Constructor name must be the same as its class name
• A Constructor must have no explicit return type
• A Java constructor cannot be abstract, static, final, and synchronized

214
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

The image given below explains the difference between constructors and methods in a class.

Fig. 2.3.6: Differences

[Link] Type of constructors in Java


Java has two different type of constructors:
• Default constructor (no-arg constructor)
• Parameterized constructor

Fig. 2.3.7: Constructor types

215
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

1. Default Constructor:
A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax:
<class_name>() {
// constructor body
}

Let us see an example of creating the no-arg constructor in the Bike class. It will be invoked at the
time of object creation.

Example:
//Java program to create and call a default constructor

class Bike {

//creating a default constructor


Bike() {
[Link]("Bike is created");
}

public static void main(String args[]) {


//calling a default constructor when the object is created
Bike b = new Bike();
}
}

Output:
Bike is created

The below diagram illustrates a scenario where the class does not have any constructor defined. In
this case, the default constructor is implicitly provided by the compiler and is used to construct the
object of the class.

Fig. 2.3.8: default constructor

216
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Example:
// Program to illustrate a class without a default constructor

class Student {

int id;
String name;

//method to display the value of id and name


void display() {
[Link](id + " - " + name);
}

public static void main(String args[]) {


//creating objects
Student s1 = new Student();
Student s2 = new Student();

//displaying values of the object


[Link]();
[Link]();
}
}

Output:
0 - null
0 – null

As observed in the above class, there is no constructor defined and so the compiler provides a
default constructor. Here, 0 and null values are default values (based on the data types) provided
by the default constructor.

2) Parameterized Constructor:
A constructor which has a specific number of parameters is called a parameterized constructor.

Syntax:
<class_name>( argument-list ) {

217
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

// constructor body
}

Let us see an example of the Student class having a constructor with two parameters. However, we
can have any number of parameters in the constructor.

Example:
// Program to illustrate a class without a parameterized constructor

class Student {

int id;
String name;

//creating a parameterized constructor


Student(int i, String n) {
id = i;
name = n;
}

//method to display the value of id and name


void display() {
[Link](id + " - " + name);
}

public static void main(String args[]) {


//creating objects and passing values
Student s1 = new Student(111, "Raju");
Student s2 = new Student(222, "Aryan");

//displaying values of the object


[Link]();
[Link]();
}
}

218
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Output:
111 - Raju
222 - Aryan

[Link] Constructor Overloading in Java


A constructor is a method in Java which doesn't have a return type. Similar to other Java methods,
constructors too can be overloaded.
Constructor overloading is a mechanism where multiple constructors are used, each with a unique set
of parameters. They are set up so that each constructor is capable of carrying out a distinct function.
The compiler distinguishes them based on the types, number and order of arguments in the list.

Example:
//Java program to overload constructors
class Student {

int id;
String name;
int age;

//creating a two-arg constructor


Student(int i, String n) {
id = i;
name = n;
}

//creating a three-arg constructor


Student(int i, String n, int a) {
id = i;
name = n;
age = a;
}

void display() {
[Link](id + " - " + name + " - " + age);
}

219
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

public static void main(String args[]) {


Student s1 = new Student(111, "Raju"); // calls the two-arg constructor
Student s2 = new Student(222, "Aryan", 25); // calls three-arg constructor

[Link]();
[Link]();
}
}

Output:
111 - Raju - 0
222 - Aryan - 25

[Link] Java Copy Constructor


By default, Java doesn't have a copy constructor. However, similar to the copy constructor in C++, we
can copy values from one object to another.

In Java, there are numerous techniques to copy values from one object to another as follows:
• Using the constructor
• By assigning the values of one object into another
• Using the clone() method of the Object class

Let us see an example on how to copy the values of one object into another using a Java constructor.

Example:
//Java program to copy the values of one object to another object.

class Student {

int id;
String name;

//constructor to initialize integer and string


Student(int i, String n) {
id = i;
name = n;

220
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

//copy constructor to initialize another object


Student(Student s) {
id = [Link];
name = [Link];
}

void display() {
[Link](id + " - " + name);
}

public static void main(String args[]) {


// creating an object using the parameterized constructor
Student s1 = new Student(111, "Raju");

// creating an object from another object using the copy constructor


Student s2 = new Student(s1);

[Link]();
[Link]();
}
}

Output:
111 - Raju
111 - Raju

[Link] Copying Values Without Using The Constructor


We can duplicate the values of one object into the other by assigning each variable’s value to the other
object’s variables. The copy constructor would not be needed for the given situation.

Example:
class Student {

int id;

221
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

String name;

// default constructor
Student() {}

// parameterized constructor
Student(int i, String n) {
id = i;
name = n;
}

// instance method
void display() {
[Link](id + " - " + name);
}

public static void main(String args[]) {


//creating the objects
Student s1 = new Student(111, "Raju");
Student s2 = new Student();

//assigning values of one object to the other, one at a time


[Link] = [Link];
[Link] = [Link];

[Link]();
[Link]();
}
}

Output:
111 - Raju
111 - Raju

222
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

[Link] Ways to create objects in Java


As discussed earlier, a class serves as the blueprint for objects, and we can construct an object from a
class. There are various ways to create objects of a class in Java.
In Java, there are numerous ways to construct objects. Let us list them and discuss them one at a time
as follows.
• Using the new keyword
• Using newInstance() method
• Using clone() method
• Using deserialization
• Using newInstance() method of Constructor class

1. Using the new Keyword:


The simplest method for creating an object in Java is to use the new keyword. This is the most
commonly used method in Java for creating an object. This is how almost all objects are made.
This method allows us to invoke any constructor we desire (no-argument or parameterized
constructors).

Example:
// Java program to create an object using the new keyword
class GFG {

// Declaring and initializing a custom input string


String name = "Raju";

public static void main(String[] args) {


// creating an object of the class using new keyword
GFG obj = new GFG();

// Print and display the object


[Link]([Link]);
}
}

Output:
Raju

223
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Exercise
Answer the following questions:
1. What is the process of defining more than one method in a class differentiated by method signature?
A) Function overriding B) Function overloading
C) Function doubling D) None of the mentioned

2. What is the output of the below Java program?

public class TestingConstructor {

void TestingConstructor() {
[Link]("A1");
}

TestingConstructor() {
[Link]("A2");
}

public static void main(String[] args) {


TestingConstructor tc = new TestingConstructor();
}
}

A) A2 B) A1
C) No output D) Compiler error

3. In Java, a constructor with one or more arguments or parameters is called a ___ constructor.

4. _________ of constructors in Java means adding more than one constructors with different
argument list.

5. What is the output of the below Java program with constructors?

public class Constructor2 {

int count = 10;

Constructor2(int count) {
[Link]("Count=" + count);
}

public static void main(String[] args) {


Constructor2 con = new Constructor2();

224
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

}
}

A) Count=0 B) Count=10
C) Compiler error D) None of the above

6. Choose the correct way of calling the second constructor from the first constructor in the below
code options.

A) Constructor5() {
int a = 30;
this('A');
}
Constructor5(char c) {
//
}

B) Constructor5() {
int a=30;
this('A');
[Link]("Success");
}
Constructor5(char c) {
//
}

C) Constructor5() {
this('A');
[Link]("Success");
}

Constructor5(char c) {
//
}

D) All the above

7. Can we overload constructors in Java?


A) Yes B) No

8. Can a private constructor be declared in Java class?


A) Yes B) No

225
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

9. The default constructor is used for _________.


A) Calling default methods
B) Intializing default values to objects
C) Deferencing default objects
D) All of above

[Link] Ways to create objects in Java

2. Using the newInstance() Method:


If the class has a public default constructor and we know the required class name, we can generate
an object with the [Link] method. It simply loads the Class in Java. You can use the
newInstance() method of the class to create an object of the given class.

Example:
// Java program to create an object using the newInstance() method

class GFG {

// Declaring and initializing a string


String name = "Raju";

public static void main(String[] args) {


// Try block to check for exceptions
try {
Class cls = [Link]("GFG");

// Creating object of main class


// using instance method
GFG obj = (GFG) [Link]();

// Print and display


[Link]([Link]);

} catch (ClassNotFoundException e) { // Catch block 1


// Display the exception along with line number using printStacktrace()
[Link]();

226
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

} catch (InstantiationException e) { // Catch block 2


[Link]();

} catch (IllegalAccessException e) { // Catch block 3


[Link]();
}
}
}

Output:
Raju

3. Using clone() Method:


Whenever clone() is called on any object, the JVM actually creates a new object and copies all
content of the other object into it. Creating an object using the clone method does not invoke any
constructor. In order to use the clone() method on an object, we need to implement Cloneable and
define the clone() method in it.

Example:
// Java program to create an object using the clone() method

// Implementing Cloneable interface


class GFG implements Cloneable {

// Method 1
@Override
protected Object clone() throws CloneNotSupportedException {
// Super() keyword refers to parent class
return [Link]();
}

// Declaring and initializing string


String name = "Raju ";

// Method 2
public static void main(String[] args) {

227
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

GFG obj1 = new GFG();

// Try block to check for exceptions


try {
// Using the clone() method
GFG obj2 = (GFG) [Link]();

// Print and display the object created above


[Link]([Link]);
} catch (CloneNotSupportedException e) {
// Display the exception using printStackTrace() method
[Link]();
}
}
}

Output:
Raju

4. Object deserialization:
Object serialization is the process of converting an object into a byte stream so as to persist it in a
file. This is useful when we need to transmit an object from one machine to another as a stream of
bytes (file).

Deserialization is the reverse process of constructing the object back from the byte stream.
Therefore, we can use deserializtion as another method of creating an object rather than calling a
constructor.

JVM generates a unique object each time we serialize and then deserialize an object. JVM doesn't
utilise a constructor to generate the object during deserialization. We must implement the
Serializable interface in the class in order to deserialize an object.

The example below illustrates how to serialize an object.

Example:
// Java program to illustrate Serializing an Object

// Importing input output classes

228
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

import [Link].*;

// Implementing the Serializable interface


class GFG implements Serializable {

// Member variables
private String name;

GFG(String name) {
// This keyword refers to current object itself
[Link] = name;
}

public static void main(String[] args) {


// Try block to check for exceptions
try {
// Creating object of class in main() method
GFG d = new GFG("Raju");

// Serializing the object to a file


FileOutputStream f = new FileOutputStream("[Link]");
ObjectOutputStream oos = new ObjectOutputStream(f);
[Link](d);
[Link]();

// Freeing up memory resources


[Link]();
} catch (Exception e) {
[Link]();
}
}
}

Output:
As seen in the above output, the object having a data variable name with value ‘Raju’ is serialized
to [Link].

229
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

5. Using newInstance() Method of the Constructor Class:


This is similar to a class's newInstance() method. The [Link] class contains a
single newInstance() method that can be used to build objects. Using the newInstance() method,
it is also possible to call the private constructor and the parameterized constructor, in general, the
declared constructor of the class.

Example:
// Java program to illustrate creation of Object
// using newInstance() method of Constructor class
// Importing required classes from [Link] package
import [Link].*;

class GFG {

// Member variables of this class


private String name;

// Constructor of this class


GFG() {}

// Method 1
// To set name of the string
public void setName(String name) {
// This method refers to current object itself
[Link] = name;
}

public static void main(String[] args) {


// Try block to check for exceptions
try {
//Getting the declared constructor of the class
Constructor<GFG> constructor = [Link]();

//Calling the newInstance() method on the constructor


GFG r = [Link]();

// Custom passing

230
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

[Link]("Raju");
[Link]([Link]);
} catch (Exception e) {
[Link]();
}
}
}

Output:
Raju

Exercise
Answer the following questions:
1. In Java programming language, the code is placed inside ___
A) Classes, Interfaces B) Methods
C) Blocks D) All the above

2. The source code of an abstract class or interface is kept inside a .java file.
A) false B) true

3. Which is the best definition of an object?


A) An object is a real-world entity
B) An object is a runtime entity
C) The object is an instance of a class
D) All of above

4. The following program is an example of


class Student {
int id;
String name;
}

class MainStudent {
public static void main(String args[]) {
Student s1 = new Student();
[Link] = 100;
[Link] = "Sadiq";
[Link]([Link] + " " + [Link]);
}

231
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

A) initialization by reference variable


B) initialization by instance method
C) initialization by constructor
D) None of above

5. The following program is an example of _________.

public class MainStudent {


public static void main(String[] args) {
Student s1 = new Student();
[Link](100, "Sadiq");
[Link]();
}
}

class Student {
int id;
String name;

void insertRecord(int id, String name) {


[Link] = id;
[Link] = name;
}

void showInfo() {
[Link]("Id: " + [Link] + " Name: " + [Link]);
}
}

A) initialization by reference variable


B) initialization by instance method
C) initialization by constructor
D) None of above

2.3.5 Abstraction, Encapsulation, Inheritance, Polymorphism,


interfaces and Multithreading
In this section, we discuss about various object-oriented programming characteristics such as abstraction,
encapsulation, inheritance and polymorphism. We also will see the concept of multithreading.

232
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

[Link] Abstraction
One of the most important use of object-oriented programming is abstraction. Through the use of
abstraction, irrelevant information may be "hidden" from the user, and only "relevant" information can
be shown.
Consider the login use case in an ecommerce scenario. Everything that happens behind the scenes
when we hit the login button, including how the input data is transferred to the server and how it is
validated etc., is abstracted from us. We don't need to worry about all the logic involved in processing
the request.
Another example of abstraction is a car which is composed of many smaller things such as a gearing
system, steering mechanism, and engine. A car is made up of many subsystems, each of which is
responsible for a specific operation. Despite the fact that its inner workings remain unknown to most
humans, still a car is considered as a single item that can be controlled.

[Link] Encapsulation
Encapsulation is:
• Connecting the code that manipulates the data with it.
• It protects the code and data from outside intervention.

Consider the example of an automobile's power steering system as a point of reference. The power
steering system of a car is rather complex, since it is comprised of several different components that
all work together in unison to drive the vehicle in the right direction. Even the power that is sent from
the engine to the steering wheel may be controlled by it. On the other hand, there is just one interface
that can be accessed from the outside world, and the rest of the complexity is hidden. In addition,
the steering unit may operate completely independently of any outside influence. The action of this
mechanism has no effect on any other mechanisms.
The same encapsulation principle can be used in code. The following qualities should be present in
encapsulated code:
• Everyone is aware of how to get to it.
• Regardless of implementation details, is simple to use.
• The code shouldn't have any unintended consequences for the remaHyder of the application.

The class of [Link] is an illustration of encapsulation. The user is simply aware of the fact
that we can store data in a hashtable in the form of key/value pairs and that we can retrieve that data
in a variety of ways. However, the we need not be aware of the actual implementation details, such
as how and where this data is actually kept. The user need not worry about the implementation of a
hashtable when storing key/value pairs.

[Link] Inheritance
With examples from real-world scenarios, this section explains the concept of inheritance. The process
by which one object obtains some or all of another object's properties is known as inheritance.
Inheritance is basically used for reusability so we don’t have to start writing code from scratch.
For instance assume that we have a class FourWheeler and a subclass of it called Car since the car is a
four-wheeled vehicle. Here, Car gains the characteristics of the FourWheeler class. Other sub-types of
the FourWheeler class may include Jeep, Tempo, Van, etc.

233
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Car (referred to as a sub-class) inherits the characteristics of a FourWheeler and has some unique
characteristics that set it apart from other FourWheeler categories, such as luxury, comfort, shape, size,
usage, etc.
A car can be further divided into categories like an open car, sports car, little car, huge car, etc., which
combine the characteristics of both a car and a four-wheeler while maintaining some distinctive
characteristics. In this manner, any level can be added to the hierarchy.

[Link] Polymorphism
The concept of polymorphism relates to something existing in many forms. In this section, the concept
of polymorphism is explained through examples from everyday life
Polymorphism is all about processing objects differently depending on their data type. In other words,
it denotes the use of a same approach for a variety of different types of actions. And depending on the
circumstance, the implementation to be used is determined at runtime (i.e., data type of the object)
Designing a generic interface that offers generic methods for a specific class of activity and allows for
the implementation of generic methods across various classes can accomplish this.
Continuing with the car example, a gear transmission system is a part of a car. It includes one backward
gear in addition to four front gears. The amount of power and movement provided to the car when
the engine is accelerated depends on which gear is engaged. The action is the same when applying
gear, but it takes on varied behaviours depending on the type of gear, or you could say it manifests in a
variety of ways (polymorphism means many forms)
There are two types of polymorphism:
• Overloading a method is static polymorphism
• Overriding a method is dynamic polymorphism

Having many methods with the same name that function differently depending on the arguments given
when invoking the method is known as overloading. This is referred to as static because the compilation
process determines which method will be invoked.
A derived class implementing a method from its super class is said to be overriding. Runtime
polymorphism is a means of resolving the call to an overridden method at runtime.

[Link] Multithreading
Multithreading in Java is about running two or more threads concurrently to optimize the use of the
CPU. In Java, a thread is a thin process that uses fewer resources to build and distribute the process
resources.
Both multiprocessing and multithreading are used for multitasking in Java, however we favour
multithreading. This is due to the shared memory space that the threads use, which helps conserve
memory, as well as the fact that content switching between the threads is a little quicker than the
process.
Additional benefits of multithreading include:
• Time can be saved by multithreading since several tasks can be completed simultaneously.
• The user can execute numerous activities at once without being blocked. Additionally, if an error
occurs in one thread, it has no bearing on the other threads.

234
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Evolution of a Thread
A thread must pass through five states during the course of its life. The JVM is in charge of this life cycle
(Java Virtual Machine).

Following are the states of a thread:


a. New
b. Runnable
c. Running
d. Non-Runnable (Blocked)
e. Terminated

[Link] Interfaces in Java


An interface is an abstract type containing only abstract methods. It is referred to as a type that
determines the behaviour of a class. An interface written in Java may have components such as static
constants and abstract methods.
Java's primary method for implementing abstraction is via the usage of its interfaces. Only abstract
methods are permitted to be included in the Java interface; concrete method bodies are never included.
Basically it is used for the purpose of multiple inheritance and abstraction in the Java programming
language. The Java interface also represents the IS-A connection between the two classes.
An interface, like a class, can have variables and methods, but by default, all the methods defined in an
interface are abstract (only method signature, no body).

Points to remember about interfaces in Java:


• Interfaces define what a class must do, and not how to do it.
• A class must be defined as abstract if it implements an interface but does not provide method
bodies for all of the abstract methods listed in the interface.
• When declaring an interface, we use the interface keyword. When implementing an interface, the
implements keyword should be used.
• All methods in an interface must have empty bodies by default, and all of the fields are made
public, static, and final by default.
• A class that "implements" an interface is required to provide concrete implementations for every
method declared in the interface else the class becomes abstract and cannot be instantiated.
• The Comparator Interface is a good example of a Java library. A class can be used to sort a collection
if it implements this interface.

Syntax:
interface {
// declare constant fields
// declare methods that abstract
// by default.
}

235
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Exercise
Answer the following questions:
1. Choose the correct statement about Java Interfaces.
A) Interface contains only abstract methods by default.
B) A Java class can implement multiple interfaces
C) An Interface can extend or inherit another Interface
D) All the above

2. What is the output of the below Java program with an Interface?


interface Bus {
void move();
}

class ElectricBus implements Bus {


public void move() {
[Link]("Implemented move() method.");
}
}

public class InterfaceTest1 {


public static void main(String[] args) {
new ElectricBus().move();
}
}

A) No output
B) Implemented move() method.
C) Compiler error
D) None of the above

3. What is the output of the below Java program using an interface?


interface Car {
int basePrice = 1000;
}

public class InterfaceTest2 implements Car {


void changePrice() {
basePrice = 2000;
[Link](basePrice);
}

public static void main(String[] args) {

236
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

new InterfaceTest2().changePrice();
}
}

A) 1000 B) 2000
C) Compiler error D) None of the above

4. A java interface can contain__________.

5. Consider interfaces A and B. Assume, class C wants to implements both the interfaces. Which one
is the correct declaration for implementing two interfaces?

A) class C implements A, B
B) class C implements A, implements B
C) class C implements A extends B
D) All are valid

[Link] Concepts of Packages, Interfaces and File Handling in


JAVA
Interfaces in JAVA
An interface is an abstract type that, when used in the Java programming language, is referred to as
a type that determines the behaviour of a class. In Java, the blueprint for a class is referred to as an
interface. An interface written in Java may have components such as static constants and abstract
methods.
Java's primary method for implementing abstraction is via the usage of its interfaces. Only abstract
methods are permitted to be included in the Java interface; method bodies are never included. It is
used to accomplish multiple inheritance and abstraction in the Java programming language. To phrase
it another way, interfaces have the capacity to hold abstract versions of methods and variables. There
is no way that the method body could exist. The Java interface also represents the IS-A connection
between the two classes.
An interface, like a class, can have variables and methods, but by default, the methods stated in an
interface are abstract (only method signature, no body).
• Interfaces define what a class must do, not how it must do it. It serves as the curriculum's guide.
• A Player interface, for example, may be about capabilities, and any class that implements it must
be able to move (or must implement moving) (). Consequently, it lists a number of methods that
the class must implement.
• A class must be designated abstract if it implements an interface but does not provide method
bodies for all of the functions listed in the interface.
• Comparator Interface is a good example of a Java library. A class can be used to sort a collection if
it implements this interface.

237
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Syntax:

Interface
{
// declare constant fields
// declare methods that abstract
// by default.
}
When declaring an interface, you should use the interface keyword. This method is used so that total
abstraction may be achieved. All of an interface's methods are defined to have empty bodies by default,
and all of the fields in an interface are made public, static, and final by default. A class that "implements"
an interface is required to provide concrete implementations for each and every one of the interface's
public methods. When implementing an interface, the implements keyword should be used.

[Link] Packages in Java


In Java, a package is used to bundle together related classes, sub-packages, and interfaces.

Uses of packages include:


• Avoiding name conflicts. For example, [Link] is an online buyer whereas the app.
[Link] is an account holder. These are two different classes having the name Customer in
two different packages.
• Making classes, interfaces, enumerations, and annotations easier to find and reuse.
• Protected and default have access control at the package level. Classes in the same package and
its subclasses can access a protected member. Classes belonging to the same package are the only
ones with access to a default member (without any access specifier).
• Packages also act as an example of data encapsulation (or data-hiding).
• Package name should be the same as the directory name in which it is defined.

A package is a container for a collection of related classes, some of which are kept for internal usage
while others are made available and exposed. Some classes are kept private while others are shared
with the public. It is possible for us to reuse already existing classes from the packages unlimited
number of times in our applications as required.

1. How are packages used?


There is a significant connection between the organization of directories and names of packages. If
the package name is [Link], for example, then we need to add the parent directory
containing the app package to the CLASSPATH environmental variable to be able to access the app
package. More precisely, the variable CLASSPATH contains the path of the package’s parent directory.
package mypack;
public class Simple{

238
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

public static void main(String args[]){


[Link]("Welcome to package");
}
}

2. Adding a class to a package:


Use the package keyword along with the name of the package at the beginning of the program and
place it in the package directory. We can also add new classes to a package that has already been
defined. To declare a public class, we must create a new java file; otherwise, we may just add the
new class to an existing java file and recompile it.

3. Subpackages:
Subpackages are packages that are contained within a larger package. These must be specifically
imported because they are not imported by default. Additionally, members of a subpackage are
treated as a different package for protected and default access specifiers because they have no
access privileges. For example, in import [Link].*; statement, util is a subpackage created inside
the java package.

Example:
/* Java program to demonstrate accessing of members when
corresponding classes are imported and not imported. */

import [Link];

public class ImportDemo {


public ImportDemo() {
// [Link] is imported, hence we are
// able to access directly in our code.
Vector newVector = new Vector();

// Since [Link] is not imported, we need


// to specify the fully qualified name of the class
[Link] newList = new [Link]();
}

public static void main(String arg[]) {


new ImportDemo();
}
}

239
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

[Link] Types of Packages


The diagram below illustrates the type of packages that are available in Java.

Fig. 2.3.9: Package types

1. Built-in Packages:
These packages consist of a large number of classes which are a part of the Java API.
Some of the commonly used built-in packages are:
a) [Link]: Contains language support classes (e.g classes which define primitive data types,
math operations, etc.). This package is automatically imported.
b) [Link]: Contains classes for performing input/output operations.
c) [Link]: Contains generic utility classes that implement data structures like linked lists,
dictionary and also support date/time operations.
d) [Link]: Contains classes for creating Applets.
e) [Link]: Contain classes with components for graphical user interfaces (like button, menus
etc.).
f) [Link]: Contain classes for performing networking operations.

2. User-defined packages:
User-defined packages are created by programmers for reusability.
To begin, let us create a directory called myPackage (directory name should be same as the package
name we intend to create). Next, create the [Link] file within the directory with code as
shown below.

Example:
package myPackage;

public class MyClass {


public void getNames(String s) {
[Link](s);
}
}

240
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

[Link] File Handling in Java


The File class in Java allows us to perform operations on files. This File class is located in the [Link]
package. To start working on files, create an object of the File class by passing the file name as the
parameter to the File class constructor.

Why is file handling necessary?


Any programming language must include file handling since it enables us to store content into a file for
further processing.
File handling is the act of reading from and writing to a file.

Example:
// Importing File Class
import [Link];

class GFG {
public static void main(String[] args) {
// File name specified
File obj = new File("[Link]");
[Link]("File Created!");
}
}

Output:
File Created!

The Directory Structure of Packages


Two major results occur when a class is placed in a package −
The name of the package becomes a part of the name of the class, as we just discussed in the previous
section.
The name of the package must match the directory structure where the corresponding bytecode
resides.
Here is simple way of managing your files in Java −
Put the source code for a class, interface, enumeration, or annotation type in a text file whose name is
the simple name of the type and whose extension is .java.

For example −

// File Name : [Link]


package vehicle;

241
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

public class Car {


// Class implementation.
}
Now, put the source file in a directory whose name reflects the name of the package to which the class
belongs −

....\vehicle\[Link]
Now, the qualified class name and pathname would be as follows −

Class name → [Link]


Path name → vehicle\[Link] (in windows)
In general, a company uses its reversed Internet domain name for its package names.

Example − A company's Internet domain name is [Link], then all its package names would start
with [Link]. Each component of the package name corresponds to a subdirectory.

Example − The company had a [Link] package that contained a [Link] source file, it
would be contained in a series of subdirectories like this −

....\com\apple\computers\[Link]
At the time of compilation, the compiler creates a different output file for each class, interface and
enumeration defined in it. The base name of the output file is the name of the type, and its extension
is .class.

For example −

// File Name: [Link]


package [Link];

public class Dell {


}

class Ups {
}
Now, compile this file as follows using -d option −

$javac -d . [Link]

242
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

The files will be compiled as follows −

.\com\apple\computers\[Link]
.\com\apple\computers\[Link]
You can import all the classes or interfaces defined in \com\apple\computers\ as follows −

import [Link].*;
Like the .java source files, the compiled .class files should be in a series of directories that reflect the
package name. However, the path to the .class files does not have to be the same as the path to the
.java source files. You can arrange your source and class directories separately, as −

<path-one>\sources\com\apple\computers\[Link]

<path-two>\classes\com\apple\computers\[Link]

By doing this, it is possible to give access to the classes directory to other programmers without revealing
your sources. You also need to manage source and class files in this manner so that the compiler and
the Java Virtual Machine (JVM) can find all the types your program uses.
The full path to the classes directory, <path-two>\classes, is called the class path, and is set with the
CLASSPATH system variable. Both the compiler and the JVM construct the path to your .class files by
adding the package name to the class path.
Say <path-two>\classes is the class path, and the package name is [Link], then the
compiler and JVM will look for .class files in <path-two>\classes\com\apple\computers.
A class path may include several paths. Multiple paths should be separated by a semicolon (Windows)
or colon (Unix). By default, the compiler and the JVM search the current directory and the JAR file
containing the Java platform classes so that these directories are automatically in the class path.

[Link] Overloading vs Overriding


Method Overloading Method Overriding
• Compile-time polymorphism • Run-time polymorphism
• Helps to increase readability of the program • Used to grant specific implementation of
the method which is already provided by its
parent class or superclass
• It occurs within the class • It is performed between classes with a
inheritance relationship
• May or may not require inheritance • Always needs inheritance.
• In method overloading, methods must have • In method overriding, methods must have
the same name with different signatures the same name and same signature
• The return type can or need not be the same, • The return type must be the same or co-
but parameter list should vary variant.

243
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Method Overloading Method Overriding


• Static binding is being used for overloaded • Dynamic binding is being used for overriding
methods methods
• Poor performance due to compile-time • Gives better performance as binding of
polymorphism overridden methods is being done at runtime
• Private and final methods too can be • Private and final methods cannot be
overloaded overridden
• Argument list should be different while • Argument list should be the same in method
performing method overloading. overriding

Exercise
Answer the following questions:
1. Which of these keywords is used to define packages in Java?
a) pkg b) Pkg
c) package d) Package

2. Which of the following is the correct way of importing an entire package ‘pkg’?
a) import pkg; b) import pkg.;
c) import pkg.*; d) import pkg*;

3. What will be the output of the following Java program?

package pkg;

class output {
public static void main(String args[]) {
StringBuffer s1 = new StringBuffer("Hello");
[Link](1, 'x');
[Link](s1);
}
}
a) xell b) xxxxx
c) Hxll d) Hexlo

4. Packages that are inside another package are called _________.

5. An interface in Java is like a 100% ____.


a) inner class b) public class
c) abstract class d) anonymous class

244
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

2.3.7 I/O Channels


An I/O Channel has complete control over input/output operations. These have the capacity to carry
out I/O instructions by using a processor designed specifically for use on an I/O channel. The CPU is not
directly responsible for carrying out the I/O commands. In order for the CPU to begin an input/output
(I/O) transfer, the I/O channel must first be instructed to execute a memory-based program.
The program specifies the following: Device(s), Memory Area(s), Priority, and Error Condition Actions.

[Link] Types of I/O Channels

Fig. 2.3.10: I/O Channels

1. The Selector Channel:


The selector channel is a DMA controller that is responsible for managing a wide variety of high-
speed devices. It is designed to facilitate the movement of data between one device and another.
A controller or an I/O module is responsible for managing each individual device that is part of a
selector channel as illustrated in the diagram.

Fig. 2.3.11: Selector channel

2. The Multiplexer Channel:


This is a DMA controller that can manage many devices concurrently is known as a multiplexer
channel. It can transfer blocks for several devices at once as shown in the figure below.

Fig. 2.3.12: Multiplexer

245
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

This channel employs two different varieties of multiplexers:


• Byte Multiplexer: Use for devices that operate at low speeds. It either transmits or receives
characters. Mixes bits from multiple devices.
• Block Multiplexer: Has the ability to receive or transmit blocks of character data. It is possible
to combine the byte sequences from a number of different devices. Used by very quick devices.

Java streams
Processing collections of objects is done using Java 8's new Stream API, which was introduced in that
version. One definition of a stream describes it as "a collection of items that may support many actions
and be pipelined to generate the desired end."The capabilities of Java stream include:
A stream is not a data structure, but it may take input from other things like arrays and collections as
well as I/O channels.
Streams are just responsible for delivering the results of the pipelined processes; they do not in any
way modify the underlying data structure.
As a result of the fact that each intermediate action is executed in a lazy fashion and generates a stream
as a by-product, several intermediate operations may be pipelined together. Terminal operations, which
also yield the result, are used to denote the end of the stream.
The [Link] package provides almost every class required for input and output (I/O) in Java. Each of
these streams is both an input source and an output destination. The stream in the [Link] package
supports a wide range of data types, including primitives, objects, and localized characters.
Stream: A stream can be defined as a data sequence. Streams are classified into two types.
• Input stream The InputStream reads data from a source.
• Output stream The OutputStream is used to write data to a specific location.

Although this lesson only covers extremely fundamental features regarding streams and I/O, Java offers
robust yet customizable support for I/O linked to files and networks. We'll go through the most popular
instances one at a time.
8-bit byte input and output are handled by Java byte streams. Although there are several classes related
to byte streams, FileInputStream and FileOutputStream are the most often used classes. The example
that uses these two classes to transfer an input file into an output file is provided below.

Example

import [Link].*;
public class CopyFile {

public static void main(String args[]) throws IOException {


FileInputStream in = null;

246
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

FileOutputStream out = null;

try {
in = new FileInputStream("[Link]");
out = new FileOutputStream("[Link]");

int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}

Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams
are used to perform input and output for 16-bit unicode. Though there are many classes related to
character streams but the most frequently used classes are, FileReader and FileWriter. Though internally
FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is
that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an input file (having
unicode characters) into an output file −

Example
import [Link].*;
public class CopyFile {

public static void main(String args[]) throws IOException {


FileReader in = null;
FileWriter out = null;

try {

247
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

in = new FileReader("[Link]");
out = new FileWriter("[Link]");

int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}

Standard Streams
All the programming languages provide support for standard I/O where the user's program can
take input from a keyboard and then produce an output on the computer screen. If you are
aware of C or C++ programming languages, then you must be aware of three standard devices
STDIN, STDOUT and STDERR. Similarly, Java provides the following three standard streams

• Standard Input − This is used to feed the data to user's program and usually a keyboard is used as
standard input stream and represented as [Link].
• Standard Output − This is used to output the data produced by the user's program and usually a
computer screen is used for standard output stream and represented as [Link].
• Standard Error − This is used to output the error data produced by the user's program and usually
a computer screen is used for standard error stream and represented as [Link].

Following is a simple program, which creates InputStreamReader to read standard input stream until
the user types a "q" –

Example

import [Link].*;
public class ReadConsole {
public static void main(String args[]) throws IOException {

248
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

InputStreamReader cin = null;


try {
cin = new InputStreamReader([Link]);
[Link]("Enter characters, 'q' to quit.");
char c;
do {
c = (char) [Link]();
[Link](c);
} while(c != 'q');
}finally {
if (cin != null) {
[Link]();
}
}
}
}

Reading and Writing Files


As described earlier, a stream can be defined as a sequence of data. The InputStream is used to read
data from a source and the OutputStream is used for writing data to a destination.
The two important streams are FileInputStream and FileOutputStream, which would be discussed in
this tutorial.
This stream is used for reading data from the files. Objects can be created using the keyword new and
there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the file

249
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

InputStream f = new FileInputStream("C:/java/hello");

Following constructor takes a file object to create an input stream object to read the file. First we create
a file object using File() method as follows −
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods which can be used to
read to stream or to do other operations on the stream.

[Link]. Method & Description


1 public void close() throws IOException{}
This method closes the file output stream. Releases any system resources associated
with the file. Throws an IOException.
2 protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of this
file output stream is called when there are no more references to this stream. Throws an
IOException.
3 public int read(int r)throws IOException{}
This method reads the specified byte of data from the InputStream. Returns an int.
Returns the next byte of data and -1 will be returned if it's the end of the file.
4 public int read(byte[] r) throws IOException{}
This method reads [Link] bytes from the input stream into an array.
Returns the total number of bytes read. If it is the end of the file, -1 will be
returned.
5 public int available() throws IOException{}
Gives the number of bytes that can be read from this file input stream. Returns an int.

There are other important input streams available, for more detail you can refer to the following links

FileOutputStream
FileOutputStream is used to create a file and write data into it. The
stream would create a file, if it doesn't already exist, before opening it for
output.
Here are two constructors which can be used to create a FileOutputStream
object.
Following constructor takes a file name as a string to create an input stream object to write the file

OutputStream f = new FileOutputStream("C:/java/hello")

Following constructor takes a file object to create an output stream object


to write the file. First, we create a file object using File() method as follows

File f = new File("C:/java/hello");

250
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

OutputStream f = new FileOutputStream(f);

Once you have OutputStream object in hand, then there is a list of helper methods, which can be
used to write to stream or to do other operations on the stream.

[Link]. Method & Description


1 public void close() throws IOException{}
This method closes the file output stream. Releases any system resources associated with
the file. Throws an IOException.
2 protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of this
file output stream is called when there are no more references to this stream. Throws an
IOException.
3 public void write(int w)throws IOException{}
This methods writes the specified byte to the output stream.
4 public void write(byte[]
w)
Writes [Link] bytes from the mentioned byte array to the OutputStream.

Example
import [Link].*;
public class fileStreamTest {
public static void main(String args[]) {
try {
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("[Link]");
for(int x = 0; x < [Link] ; x++) {
[Link]( bWrite[x] ); // writes the bytes
}
[Link]();
InputStream is = new FileInputStream("[Link]");
int size = [Link]();
for(int i = 0; i < size; i++) {
[Link]((char)[Link]() + " ");
}
[Link]();
} catch (IOException e) {
[Link]("Exception");
}
}

251
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

The above code would create file [Link] and would write given numbers in binary format. Same would
be the output on the stdout screen.

Different Operations On Streams-


• map: The map method is used to returns a stream consisting of the results of applying the given
function to the elements of this stream.
• List number = [Link](2,3,4,5);
• List square = [Link]().map(x->x*x).collect([Link]());
• filter: The filter method is used to select elements as per the Predicate passed as argument.
• List names = [Link]("Reflection","Collection","Stream");
• List result = [Link]().filter(s->[Link]("S")).collect([Link]());
• sorted: The sorted method is used to sort the stream.
• List names = [Link]("Reflection","Collection","Stream");
• List result = [Link]().sorted().collect([Link]());
• Terminal Operations:
• collect: The collect method is used to return the result of the intermediate operations performed
on the stream.
• List number = [Link](2,3,4,5,3);
• Set square = [Link]().map(x->x*x).collect([Link]());
• forEach: The forEach method is used to iterate through every element of the stream.
• List number = [Link](2,3,4,5);
• [Link]().map(x->x*x).forEach(y->[Link](y));
• reduce: The reduce method is used to reduce the elements of a stream to a single value.

The reduce method takes a BinaryOperator as a parameter


List number = [Link](2,3,4,5);
int even = [Link]().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);

Here, is a simple program to demonstrate streams

//a simple program to demonstrate the use of stream in java


import [Link].*;
import [Link].*;

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

252
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

// create a list of integers


List<Integer> number = [Link](2,3,4,5);

// demonstration of map method


List<Integer> square = [Link]().map(x -> x*x).
collect([Link]());
[Link](square);

// create a list of String


List<String> names =
[Link]("Reflection","Collection","Stream");

// demonstration of filter method


List<String> result = [Link]().filter(s->[Link]("S")).
collect([Link]());
[Link](result);

// demonstration of sorted method


List<String> show = [Link]().sorted().collect([Link]());
[Link](show);

// create a list of integers


List<Integer> numbers = [Link](2,3,4,5,2);

// collect method returns a set


Set<Integer> squareSet = [Link]().map(x->x*x).collect([Link]());
[Link](squareSet);

// demonstration of forEach method


[Link]().map(x->x*x).forEach(y->[Link](y));

// demonstration of reduce method


int even = [Link]().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);

[Link](even);

253
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

}
}

Output:

[4, 9, 16, 25]


[Stream]
[Collection, Reflection, Stream]
[16, 4, 9, 25]
4
9
16
25
6

2.3.9 API: Application Programming Interface


The abbreviation "API" stands for "Application Programming Interface." A programmer who is developing
application software is granted the ability to make a request to the Operating System thanks to the
API (using graphical user interface or command interface). It is a compilation of processes, standards,
and resources that may be used in the production of software and applications. It may be a database
system, an operating system, or a web-based system; in other words, it could be any kind of system.

Fig. 2.3.13: Example of API

[Link] API Usage


• API in procedural languages: It specifies a set of functions and routines that help in completing a
task.

254
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

• API in object-oriented languages: It simply shows how an objet works in a given Object-Oriented
language. It is expressed as a set of classes with an associated list of class methods.
• API in libraries and frameworks: It is related to Software libraries and Software Framework.
• API and Protocols: It can be the implementation of Protocols.
• API sharing and reuse via virtual machine: Languages running on virtual machines can share an
API.

[Link] API Designs


When creating application programming interfaces (APIs), many concepts are employed. It is based
on the idea that a program may be broken up into modules, each of which must adhere to a certain
interface in order to function properly.
One more is software architecture, which is the process of designing, constructing, and maintaining
high-level software structures.

2.3.10 Advanced topics and latest additions to Java


In this section, we shall discuss about some advanced concepts such as Lambda Expressions.

[Link] Lambda Expressions


Java SE 8 introduced the new and crucial lambda expression feature of the Java programming language.
It provides a straightforward and uncomplicated technique for using an expression to describe a single
function interface. Filtering, iterating, and extracting data from a collection can be done.
Utilizing the Lambda expression allows for the provision of an implementation of an interface that
features a functional interface. A substantial amount of code is preserved. In the case of a lambda
expression, the method does not need to be declared again in order to give the implementation. Only
the code necessary for the implementation is published here.

A Java lambda expression is considered to be a function.

1. Functional Interface:
The lambda expression is what provides the actual implementation of the functional interface.
An interface is considered to be functional if it only has a single abstract method. Using the @
FunctionalInterface annotation in Java, an interface may be marked to indicate that it is a functional
interface.

Syntax of a Java Lambda Expression:


(argument-list) -> {body}

Java lambda expression consists of three components.

255
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

1. Argument-list: It can be empty or non-empty as well.


2. Arrow-token: It is used to link arguments-list and body of expression.
3. Body: It contains expressions and statements for lambda expression.

• No Parameter Syntax:
() -> {
//Body of no parameter lambda
}

• One Parameter Syntax:


(p1) -> {
//Body of single parameter lambda
}

• Two Parameter Syntax


(p1,p2) -> {
//Body of multiple parameter lambda
}

Example:
//Program for Java Lambda expression event listener

import [Link];
import [Link];
import [Link];

class GFG {

public static void main(String[] args) {


JTextField tf = new JTextField();
[Link](50, 50, 150, 20);

JButton b = new JButton("click");


[Link](80, 100, 70, 30);

// lambda expression implemented here.


[Link](e -> {

256
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

[Link]("hello swing");
});

JFrame f = new JFrame();


[Link](tf);
[Link](b);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](null);
[Link](300, 200);
[Link](true);
}
}

Output:

Java Programming Language


Lambda Expressions, a new language feature, has been introduced in this release. They enable you
to treat functionality as a method argument, or code as data. Lambda expressions let you express
instances of single-method interfaces (referred to as functional interfaces) more compactly.
Method references provide easy-to-read lambda expressions for methods that already have a name.
Default methods enable new functionality to be added to the interfaces of libraries and ensure binary
compatibility with code written for older versions of those interfaces.
Repeating Annotations provide the ability to apply the same annotation type more than once to the
same declaration or type use.
Type Annotations provide the ability to apply an annotation anywhere a type is used, not just on a
declaration. Used with a pluggable type system, this feature enables improved type checking of your
code.
• Improved type inference.
• Method parameter reflection.

257
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Collections
• Classes in the new [Link] package provide a Stream API to support functional-style
operations on streams of elements. The Stream API is integrated into the Collections API, which
enables bulk operations on collections, such as sequential or parallel map-reduce transformations.
• Performance Improvement for HashMaps with Key Collisions

Compact Profiles contain predefined subsets of the Java SE platform and enable applications that
do not require the entire Platform to be deployed and run on small devices.

Security
• Client-side TLS 1.2 enabled by default
• New variant of [Link] that enables code to assert a subset of its privileges,
without preventing the full traversal of the stack to check for other permissions
• Stronger algorithms for password-based encryption
• SSL/TLS Server Name Indication (SNI) Extension support in JSSE Server
• Support for AEAD algorithms: The SunJCE provider is enhanced to support AES/GCM/NoPadding
cipher implementation as well as GCM algorithm parameters. And the SunJSSE provider is enhanced
to support AEAD mode based cipher suites. See Oracle Providers Documentation, JEP 115.
• KeyStore enhancements, including the new Domain KeyStore type [Link].
DomainLoadStoreParameter, and the new command option -importpassword for the keytool utility
• SHA-224 Message Digests
• Enhanced Support for NSA Suite B Cryptography
• Better Support for High Entropy Random Number Generation
• New [Link] class for configuring revocation checking of X.509
certificates
• 64-bit PKCS11 for Windows
• New rcache Types in Kerberos 5 Replay Caching
• Support for Kerberos 5 Protocol Transition and Constrained Delegation
• Kerberos 5 weak encryption types disabled by default
• Unbound SASL for the GSS-API/Kerberos 5 mechanism
• SASL service for multiple host names
• JNI bridge to native JGSS on Mac OS X
• Support for stronger strength ephemeral DH keys in the SunJSSE provider
• Support for server-side cipher suites preference customization in JSSE

JavaFX
• The new Modena theme has been implemented in this release. For more information, see the blog
at [Link].
• The new SwingNode class enables developers to embed Swing content into JavaFX applications.
See the SwingNode javadoc and Embedding Swing Content in JavaFX Applications.
• The new UI Controls include the DatePicker and the TreeTableView controls.
• The [Link] package provides the public classes for the JavaFX Printing API. See the javadoc for
more information.

258
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

• The 3D Graphics features now include 3D shapes, camera, lights, subscene, material, picking,
and antialiasing. The new Shape3D (Box, Cylinder, MeshView, and Sphere subclasses), SubScene,
Material, PickResult, LightBase (AmbientLight and PointLight subclasses) , and SceneAntialiasing
API classes have been added to the JavaFX 3D Graphics library. The Camera API class has also been
updated in this release. See the corresponding class javadoc for [Link].Shape3D,
[Link], [Link], [Link], [Link].
SceneAntialiasing, and the Getting Started with JavaFX 3D Graphics document.
• The WebView class provides new features and improvements. Review Supported Features of HTML5
for more information about additional HTML5 features including Web Sockets, Web Workers, and
Web Fonts.
• Enhanced text support including bi-directional text and complex text scripts such as Thai and Hindi
in controls, and multi-line, multi-style text in text nodes.
• Support for Hi-DPI displays has been added in this release.
• The CSS Styleable* classes became public API. See the [Link] javadoc for more information.
• The new ScheduledService class allows to automatically restart the service.
• JavaFX is now available for ARM platforms. JDK for ARM includes the base, graphics and controls
components of JavaFX.

Tools
• The jjs command is provided to invoke the Nashorn engine.
• The java command launches JavaFX applications.
• The java man page has been reworked.
• The jdeps command-line tool is provided for analyzing class files.
• Java Management Extensions (JMX) provide remote access to diagnostic commands.
• The jarsigner tool has an option for requesting a signed time stamp from a Time Stamping Authority
(TSA). Javac tool
• The -parameters option of the javac command can be used to store formal parameter names and
enable the Reflection API to retrieve formal parameter names.
• The type rules for equality operators in the Java Language Specification (JLS) Section 15.21 are now
correctly enforced by the javac command.
• The javac tool now has support for checking the content of javadoc comments for issues that could
lead to various problems, such as invalid HTML or accessibility issues, in the files that are generated
when javadoc is run. The feature is enabled by the new -Xdoclint option. For more details, see the
output from running "javac -X". This feature is also available in the javadoc tool, and is enabled
there by default.
• The javac tool now provides the ability to generate native headers, as needed. This removes the
need to run the javah tool as a separate step in the build pipeline. The feature is enabled in javac
by using the new -h option, which is used to specify a directory in which the header files should be
written. Header files will be generated for any class which has either native methods, or constant
fields annotated with a new annotation of type [Link]. Javadoc tool
• The javadoc tool supports the new DocTree API that enables you to traverse Javadoc comments as
abstract syntax trees.
• The javadoc tool supports the new Javadoc Access API that enables you to invoke the Javadoc tool
directly from a Java application, without executing a new process. See the javadoc what's new page
for more information.
• The javadoc tool now has support for checking the content of javadoc comments for issues that
could lead to various problems, such as invalid HTML or accessibility issues, in the files that are

259
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

generated when javadoc is run. The feature is enabled by default, and can also be controlled by the
new -Xdoclint option. For more details, see the output from running "javadoc -X". This feature is
also available in the javac tool, although it is not enabled by default there.

Internationalization
• Unicode Enhancements, including support for Unicode 6.2.0
• Adoption of Unicode CLDR Data and the [Link] System Property
• New Calendar and Locale APIs
• Ability to Install a Custom Resource Bundle as an Extension

Deployment
• For sandbox applets and Java Web Start applications, URLPermission is now used to allow connections
back to the server from which they were started. SocketPermission is no longer granted.
• The Permissions attribute is required in the JAR file manifest of the main JAR file at all security
levels.

Date-Time Package - a new set of packages that provide a comprehensive date-time model.

Scripting
• The Rhino JavaScript engine has been replaced with the Nashorn JavaScript Engine

Pack200
• Pack200 Support for Constant Pool Entries and New Bytecodes Introduced by JSR 292
• JDK8 support for class files changes specified by JSR-292, JSR-308 and JSR-335

IO and NIO
• New SelectorProvider implementation for Solaris based on the Solaris event port mechanism.
To use, run with the system property [Link] set to the value [Link].
[Link].
• Decrease in the size of the <JDK_HOME>/jre/lib/[Link] file
• Performance improvement for the [Link](byte[], *) constructor and the [Link].
getBytes() method.

[Link] and [Link] Packages


• Parallel Array Sorting
• Standard Encoding and Decoding Base64
• Unsigned Arithmetic Support

JDBC
• The JDBC-ODBC Bridge has been removed.
• JDBC 4.2 introduces new features.

260
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Java DB
• JDK 8 includes Java DB 10.10.

Networking
• The class [Link] has been added.
• In the class [Link], if a security manager is installed, calls that request to
open a connection require permission.

Concurrency
Classes and interfaces have been added to the [Link] package.
• Methods have been added to the [Link] class to support
aggregate operations based on the newly added streams facility and lambda expressions.
• Classes have been added to the [Link] package to support scalable updatable
variables.
• Methods have been added to the [Link] class to support a common pool.
• The [Link] class has been added to provide a capability-based lock
with three modes for controlling read/write access.

Java XML - JAXP


HotSpot
• Hardware intrinsics were added to use Advanced Encryption Standard (AES). The UseAES
and UseAESIntrinsics flags are available to enable the hardware-based AES intrinsics for Intel
hardware. The hardware must be 2010 or newer Westmere hardware. Note: AES intrinsics are
only supported by the Server VM. For example, to enable hardware AES, use the following flags:
-XX:+UseAES -XX:+UseAESIntrinsicsTo disable hardware AES use the following flags: -XX:-UseAES
-XX:-UseAESIntrinsics
• Removal of PermGen.

Default Methods in the Java Programming Language are supported by the byte code instructions for
method invocation.

2.3.11 Collections in Java


A collection of objects is any grouping of separate things that may be treated as a single entity when
they are gathered together. JDK 1.2 introduced the concept of a distinct framework for Java known as
the "Collection Framework." This framework includes all collection classes and interfaces.
The [Link] and [Link] are the two fundamental interfaces that are considered to
be the "root" interfaces of Java collection classes.

261
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

[Link] What is a framework?


A framework, which is just a collection of classes and interfaces, will already have an architecture
established for it. Before implementing a new feature or class, there is no need to first build a framework.
This is not a prerequisite. The most effective object-oriented design, on the other hand, consists of a
framework that is comprised of a number of classes that all perform the same sort of function.

[Link] The Collection Framework in Java


Before the release of the Collection Framework (also known as JDK 1.2), the most frequent techniques
for arranging Java objects were called arrays, vectors, and hashtables (or collections). These collections
did not have a unified user experience or interface. Because of this, even if the fundamental objective of
each collection is the same, there is no link between how each collection was executed and how it was
intended. This is despite the fact that the primary purpose of each collection is the same. Additionally,
users find it incredibly difficult to remember all of the many constructors, methods, and syntax that
are accessible in each collection class. This is a problem since collection classes have a large number of
these features.

Let us use the addition of an element to a hashtable and a vector as an example to better grasp this.

Example:
// Java program to demonstrate why collection framework was needed
import [Link].*;
import [Link].*;

class GFG {

public static void main(String[] args) {


// Creating instances of the array, vector and hashtable
int arr[] = new int[] { 1, 2, 3, 4 };
Vector<Integer> v = new Vector();
Hashtable<Integer, String> h = new Hashtable();

// Adding the elements into the vector


[Link](1);
[Link](2);

// Adding the element into the hashtable


[Link](1, "peers");
[Link](2, "4peers");

262
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

// Array instance creation requires [],


// while Vector and hashtable require ()
// Vector element insertion requires addElement(),
// but hashtable element insertion requires put()

// Accessing the first element of the


// array, vector and hashtable
[Link](arr[0]);
[Link]([Link](0));
[Link]([Link](1));
// Array elements are accessed using [],
// vector elements using elementAt()
// and hashtable elements using get()
}
}

Output:
1
1
Peers

2.3.12 Generics in Java


Generics are types that include parameters in their definition. The intention is to enable types (including
user-defined kinds) to be sent as a parameter to methods, classes, and interfaces.
Examples of types include integers, strings, and others. Using generics, it is possible to construct classes
that are able to work with many different data types. A class, interface, or function may all be examples
of generic entities since they all operate on types that can be parameterized.

[Link] Why use generics?


An object reference is used to refer to any object, regardless of its class, since all other classes are
derived from the Object class. It is lacking in type safety across several characteristics.
In Java, generics mimic C++ templates. For example, generics are used in an efficient manner by classes
such as HashSet, ArrayList, HashMap, and others. The two approaches to dealing with generic types are
somewhat different from one another in a number of important aspects.

263
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

[Link] Java Generics Types


A generic Java method is one that first carries out some kind of action and then returns some kind of
result. A generic method, which is comparable to a conventional function, has type parameters that are
specified in accordance with the real type. Because of this, the generic method may be used to a wider
variety of situations. Programmers are able to create code more rapidly since they are not needed to
do time-consuming hybrid individual type casts due to the fact that the compiler manages type safety.
The implementation of a generic class is the same as the implementation of a class that is not generic.
The only difference between the two is that one of them has a type parameter section. There may be
many sorts of parameters, and each one would be denoted by a comma. If a class accepts one or more
arguments, it is said to be parameterized and given the name parameterized classes or parameterized
types.

[Link] Generic Class


Like C++, we use angular braces < > to specify parameter types in generic class creation. To create
objects of a generic class, we use the following syntax.

Syntax:
// To create an instance of a generic class
BaseType <Type> obj = new BaseType <Type>()

Example:
// Java program to show working of user defined generic classes

// We use <> to specify the generic parameter type


class Test<T> {

// An object of type T is declared


T obj;

// constructor
Test(T obj) {
[Link] = obj;
}

public T getObject() {
return [Link];
}
}

264
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

// Driver class to test above


class Demo {

public static void main(String[] args) {


// instance of Integer type
Test<Integer> iObj = new Test<Integer>(15);
[Link]([Link]());

// instance of String type


Test<String> sObj = new Test<String>("Raju");
[Link]([Link]());
}
}

Output
15
Raju

Exercise
Answer the following questions:
1. Which of the following classes is not part of Java’s collection framework?
a) Maps b) Array
c) Stack d) Queue

2. What will be the output of the following Java program?


import [Link].*;
class Array {
public static void main(String args[]) {
int array[] = new int[5];
for (int i = 5; i > 0; i--) array[5 - i] = i;
[Link](array, 1, 4, 8);
for (int i = 0; i < 5; i++) [Link](array[i]);
}
}

a) 12885 b) 12845
c) 58881 d) 5488

265
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

3. Which of these methods deletes all the elements from the collection?
a) clear() b) reset()
c) delete() d) refresh()

4. Can elements of a Set be traversed without using Iterator?


a) Yes b) No

5. List, Set and Queue __________ Collection.


a) extends b) implements
c) both of the above d) none of the above

2.3.13 JDBC
Java Application Programming Interface (API) known as JDBC (Java Database Connectivity) helps us
to establish a connection to a database, and governs how instructions and queries are sent to the
database, and how result sets are handled after being returned from the database.
JDBC was one of the earliest Java language libraries, and it was first released in 1997 as a component
of the JDK 1.1 software package.
JDBC was first conceived of as a client-side API that would enable Java clients to interface with a data
source. This was the original intention for the API. The introduction of an optional package that enabled
server-side JDBC connections was one of the changes that JDBC 2.0 brought about in this regard. Since
that time, every new version of JDBC has contained updated versions of both the client-side package
([Link]) and the server-side package ([Link]). The most current release of JDBC, known as JSR 221,
became available to users in September of 2017 as a component of Java SE 9.

[Link] How JDBC works


As a developer, you can use JDBC to interact with a database from within a Java program. JDBC acts as
a bridge from your code to the database, as shown in the following figure.

Fig. 2.3.14: JDBC working

[Link] ODBC versus JDBC


Open Database Connectivity (ODBC), which is a language-independent standard methodology, was the
method that programmers used to access relational database management systems (RDBMS) prior to
the development of JDBC. This is in contrast to JDBC, which is only compatible with Java and offers a
programming-level interface for controlling how Java programs interact with databases. JDBC is only
available for use with Java.

266
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

[Link] The Architecture of JDBC


The JDBC interface is composed of two different layers:
• The Java application and the JDBC manager are able to interact with one another because of the
JDBC application programming interface (API);
• The JDBC manager and database driver are able to communicate with one another because of the
JDBC driver.

The JDBC API is rich in features, lightning fast, and completely reliable. The diagram below illustrates
the architecture of JDBC.

Fig. 2.3.15: Architecture of JDBC

[Link] JDBC Drivers


Following are the distinct kinds of JDBC drivers:
• The JDBC-ODBC bridge driver: This is a lightweight Java layer makes use of the ODBC driver behind
the scenes.
• Native API driver: Provides a Java-to-native database client interface. This interface may be used to
access native databases.
• Driver for middleware: A driver that directly implements the vendor-specific protocol in Java
is known to as a pure Java driver. A common interface (or "middleware") between Java and the
vendor-specific protocol of the RDBMS.

Exercise
Answer the following questions:
1. What are the major components of the JDBC?
A. DriverManager, Driver, Connection, Statement, and ResultSet
B. DriverManager, Driver, Connection, and Statement
C. DriverManager, Statement, and ResultSet
D. DriverManager, Connection, Statement, and ResultSet

2. What is the correct sequence to create a database connection?


i. Import JDBC packages.
ii. Open a connection to the database.
iii. Load and register the JDBC driver.
iv. Execute the statement object and return a query resultset.

267
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

v. Create a statement object to perform a query.


vi. Close the resultset and statement objects.
vii. Process the resultset.
viii. Close the connection.

A. i, ii, iii, v, iv, vii, viii, vi


B. i, iii, ii, v, iv, vii, vi, viii
C. ii, i, iii, iv, viii, vii, v, vi
D. i, iii, ii, iv, v, vi, vii, viii

3. Which of the following is used to call a stored procedure?


A. Statement B. PreparedStatement
C. CallableStatment D. CalledStatement

4. Which of the following is not a JDBC connection isolation levels?


A. TRANSACTION_NONE
B. TRANSACTION_READ_COMMITTED
C. TRANSACTION_REPEATABLE_READ
D. TRANSACTION_NONREPEATABLE_READ

5. Which is responsible for getting a connection to the database?

2.3.14 MVC architecture in Java


The Model-View-Controller architecture is one of the architectural patterns is used in web application
development. Struts and Ruby on Rails, which are two of the most popular frameworks for developing
websites, both integrated MVC Architecture in their first releases.
In the field of software engineering, a design pattern is a strategy for solving an issue that crops up
regularly in the process of producing software.
The process of creating a model involves outlining the kind of architecture that will be used while
resolving the problem or developing the model itself.
Two sorts of design models exist: Model 1 and Model 2 (MVC) architectural models.

[Link] What does Java's MVC architecture mean?


When developing software, model designs that are based on MVC architecture must conform to the
MVC design pattern in order to properly separate the application logic from the user interface. As its
name implies, the MVC pattern is composed of three levels, and these layers are as follows:
• Model: This component represents the business layer of the application.
• View: The presentation of the program is controlled by the View setting.
• Controller: This component monitors the flow of the application.

268
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Fig. 2.3.16: MVC Architecture

The Model contains the business logic and uses the standard Java classes, the View displays the data,
and the Controller is used to direct the flow to the appropriate model. In Java, Controller code is written
using servlets. Because of this separation, user requests are dealt with in the following manner:
1. The controller is housed on the server, and it is the browser on the client computer that sends the
request for a page to the controller.
2. The response from the controller is an invocation of the model to obtain the required data, after
which the controller supplies the view with the data that was retrieved.
3. The rendered view is sent to the client, and the browser is responsible for displaying it.
These three distinct components of a software program should always be kept separate from one
another so as to increase scalability and reduce dependency.

2.3.15 Sample Programs

[Link] Create an object from class


public class CreateObjectExample1 {

void show() {
[Link]("Welcome to the world");
}

public static void main(String[] args) {


//creating an object using new keyword
CreateObjectExample1 obj = new CreateObjectExample1();
//invoking method using the object

269
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

public class CreateObjectExample1 {

void show() {
[Link]("Welcome to the world");
}
public static void main(String[] args) {
//creating an object using new keyword
CreateObjectExample1 obj = new CreateObjectExample1();
//invoking method using the object
[Link]();
}
}

Output:
Welcome to the world

[Link] Program to demonstrate declaration


package [Link];

public abstract class Student {

// member variables or fields


int studentRollNo;
String studentName;
int studentAge;

// abstract method
public abstract void getStudentDetails();
}

[Link] Program to demonstrate instantiation


package [Link];

public class Student {

270
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

// member variables or fields


int studentRollNo = 1001;
String studentName = "Pup";
int studentAge = 35;

// instance method of a class


public void getStudentResult() {

[Link]("Sample method "


+ "invocation for Student with details: \n");
[Link]("Roll No.:- " + studentRollNo);
[Link]("Name:- " + studentName);
[Link]("Age:- " + studentAge);
}

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

// instantiate or create an Object of type Student


Student student = new Student();

// invoking method using newly instantiated Student Object


[Link]();
}
}

Output:
Sample method invocation for Student with details:
Roll No.:- 1001
Name:- Pup
Age:- 35

[Link] Program to demonstrate initialization


package [Link];

public class Student {

271
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

// member variables or fields


int studentRollNo = 1001;
String studentName = "Pup";
int studentAge = 35;

// instance method of a class


public void getStudentResult() {
// method definition goes here
}
}

[Link] Program to demonstrate applets in Java


//[Link]
import [Link];
import [Link];

public class First extends Applet {


public void paint(Graphics g) {
[Link]("welcome to applet", 150, 150);
}
}

Execution:
c:\> javac [Link]
c:\> appletviewer [Link]

Create applets in java using graphical user interface


GUI
graphical user interface, or GUI. We Use The Screen In Two Different Ways One uses a console,
while the other uses a graphical user interface. In a console-based application, we interact with
text commands, such as command prompts, but in a graphical user interface (GUI), we interact with
graphical components, sometimes referred to as visual indicators, such as [Link] Graphical
User Interface There Are Two Types Of Application Programming Interface (API’s) And They Are AWT
(Abstract Windowing Toolkit) And Swing.

272
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

AWT:
The Abstract Windowing Toolkit is made up of twelve packages. Only two of the twelve packages are
Java. Java and aww. [Link] is often used.

[Link] : The [Link] Package Contains The Core AWT, Graphic Classes.
• GUI Component Classes Consist Of Button, Textfield, And Label.
• GUI Container Classes Consist Of Frame, Panel, Dialog, And ScrollPane.
• Layout Managers Consist Of FlowLayout, BorderLayout, And Grid Layout.
• Custom Graphics Classes Consist Of Graphics, Color, And Font.

[Link]: The [Link] Package Supports Event Handling.


• Event Classes Consist Of ActionEvent, MouseEvent, KeyEvent, And WindowEvent.
• Event Listener Interface Consists Of ActionListener, MouseListener, KeyListener, And WindowListener.

Container
1. Each graphical user interface program has a top-level container. In AWT, the most often used top-
level containers are frames, dialogs, and applets in Java.
2. Frame: A Frame Is The Top-Level Container Of An AWT GUI Program. A-Frame Consists Of A Title
Bar (Containing An Icon, A Title And The Minimize And The Maximize, Close Buttons), An Optional
Menu Bar, And The Content Display Area.
3. Panel: A Panel Is A Rectangular Area Used To Group Related GUI Components. The Panel Is A Sub-
Container. The Panel Is Used To Make Sections In The Container.

Applet
A Java applet is a simple Java program. The applet may also be seen in a web browser. Applets, like
frames, are container classes. The Java is also extended via an applet. Applet. Applet Type. Thus, applets
must be embedded into an HTML page. A JVM is required to see an applet.
In An Applet, We Can Not Make The Main( ) Function Even If It Is Written In Java. It Is Called A Stand-
Alone Application. Compile Same As Java File.
We Can Not Run As Java For That We Have Two Options:
• Browsers Run HTML Embed.
• Applet Viewer.

Applet’s Life Cycle:


• JVM Creates An Instance Of The Applet Class And Invokes Various Methods During The Applet’s
Lifetime.
• When We Open Any HTML File Containing An Applet Class In The Browser Called JVM And JVM
Creates An Object Of Our Applet Class Which Is A Child Class Of Applet By Default That Object Has
Five Functions From The Parent Class Which Is Required For The Life Cycle.
• Methods In The Applet Class Give You The Framework On Which You Can Build Any Applet
Application.

273
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Following Are The Default Methods That JVM Calls Automatically.


1. Init(): Run At The Start And It Is Used For Initializing Purposes. It Runs Only Once.
2. Start():Call Automatically Once The Init() Function Is Ended. It May Also Called One Or Many Times.
3. Stop(): If We Navigate To Another Webpage Then It Stops The Start() Function. It May Be Called One
Or Many Times.
4. Destroy(): It Ends The Applet Lifestyle If We Close The Webpage. It Runs Only Once.
5. Paint(): It Is Not A Life Cycle Part But It Is Important And Called After Start().

Components In Applet In Java:


An applet is a container, and components are the elements found in applets, which include the
following: button, textfield, label, checkbox, choice and list, and so on. We add components to the
applet container so that users may interact with it in Java. All of these components are obtained from
the [Link] package. Let's Take A Step-By-Step Approach To Creating Applet Components Using The
Following Example: We Can Add Two Numbers Here.

1. The Basic Structure Of An Applet:


We Run Our Applet In Java Through Applet Viewer. Following A Few Lines Of Code Is The Basic
Skeleton Of An Applet In Java.

2. Creating Component Reference Variables:


In Java Create Reference Variables Before Creating An Object. L1 And L2 Are The Reference Variables
Of The Label And Similarly T1and T2 For Textfeild And B1 For A Button.

274
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

3. Initialize Components:
As We Know When The Browser Makes An Object Of The Applet Then It Automatically Calls The
Init() Function. So, We Override The Init() Method And Initialize Components In The Init() Method.

4. Adding Components To The Applet:


• In The Step, We Add All Components That Are Required.
• If The Setting Layout Is Already Set(By Default) Then The Sequence Of Adding The Components
Is Arranged According To The Set Layout.
• If We Set The Setting Layout To Null Then We Have To Design The Setting Layout Then
Components Are Arranged According To Our Setting Layout.

5. Setting Layout:
• There Are Many Setting Layouts According To Our Need If That Type Of Setting Is Available Then
Pass That Setting Layout Object.
• We Can Also Do The Layout With The Help Of SetLayout() Function.

275
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

[Link](Left,Top,Width,Height);
B1 From Left Side, Top Side, Width Of B1 And Height Of B1 In Pixels.

Advantages:
• It Also Increases The Interactivity Of Users.
• Easy To Use.

Disadvantages:
• All Browsers Thus Do Not Support Applets.
• JavaScript Is More Used In Browsers.

276
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

UNIT 2.4: Testing and Execution

Unit Objectives
By the end of this unit, the participants will be able to:
1. Describe various frameworks/ methods used in testing a Java program
2. Explain the steps involved in debugging a Java program
3. Distinguish between development, stage and production environments
4. Explain various exceptions and exception handling methods
5. Discuss coding standards and best practices related to Java
6. Create suitable test cases to identify bugs using suitable tools such as JUnit
7. Demonstrate how to debug a Java program in an IDE
8. Demonstrate the ways to execute a Java program
9. Implement exception handling methods in Java

2.4.1 Various Frameworks used in Testing a Java


Testing frameworks are used in order to be able to develop reliable software or applications. The
utilization of these testing frameworks is done mostly to lessen the possibility of generating errors, to
improve efficiency, and to cut down on expenses. In this section, we will take a look at some of the most
well-known frameworks for testing in Java. The following is a list that contains numerous important
Java testing frameworks.

1. Selenium
Selenium is a framework for testing web applications. It is accessible for free and its source code
is open source. It operates on a number of different platforms. Selenium is used for automated
testing for web applications. In addition to being a tool, Selenium is a comprehensive suite that can
serve the various testing needs of an organization. It is possible to credit a significant portion of
Selenium's worldwide adoption to the fact that it is both open source and free to use. Moreover,
it is not dependent on any one platform and is compatible with a wide range of operating systems.
Selenium may be used with a number of other Java technologies, such as Maven and Docker.

Pros:
• support for several browsers
• support for multiple languages and frameworks
• Simple to implement
• Simple to implement periodic
• Frequent update

Cons:
• Making test cases takes a disproportionately long period.
• Lack of an integrated reporting mechanism
• Only functions with web apps

277
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

2. Serenity
Earlier known as Thucydides, an open-source platform that is mostly used for behaviour-driven
testing. With the help of tranquillity, you'll be able to draft acceptance criteria for test automation
projects that are both clear and well-organized. In addition to that, using this framework makes it
easy to generate test results that are useful, and it has the potential to enhance the capabilities of
both Web Driver and JUnit.

Pros:
• enables a variety of automated acceptability testing programs
• After the tests, document generation happened fairly quickly.
• It is simple to integrate with a variety of other frameworks

Cons:
• It takes a little longer to develop feature files. Participants in the project must stay in constant
contact.

3. JUnit
This specific framework intends to carry out unit testing by making use of functions or methods,
and it allows for the inclusion of a piece of code at various points along the journey. When working
with a method that is driven by tests, it is best practice to draft the code for the unit tests first
before working on the real code. It is necessary to execute the test cases first before putting a code
snippet that a developer has produced into production. Following the insertion of each new piece
of code, the test cases are run once again to ensure that all of the test scenarios are successful and
that the code does not include any errors. This framework distinguishes out from others since it is
far faster and more effective than other frameworks that are of a similar type as other frameworks.

Pros:
• JUnit supports test assertions.
• Faster test reporting
• A mechanism for deploying automated test scenarios that is simple
• possesses the capacity to create self-verifying test scenarios

Cons:
• Consistently fails when using testing suites that are somewhat larger.
• Post-testing HTML report generation is not possible.
• No assistance with dependency testing

4. TestNG
TestNG is a free and open-source testing framework that borrows ideas and concepts from JUnit
and NUnit, two other popular testing frameworks. TestNG has some additional functions that
have been added to it. This framework, whose name literally means "Next Generation," excels at
demonstrating its capabilities throughout the testing process. In this particular instance, the testing
technique does not involve an unduly elaborate series of steps; rather, we may test the scenarios
by inquiring of the framework whether or not it will test the front ends or the databases. An HTML

278
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

report may also be extracted, which is a feature that comes in quite handy for the testing that are
being carried out.

Pros:
• assistance with parallel testing
• allows for log generation
• ability to produce HTML reports after testing
• It is possible to arrange related test cases together.
• Priority for test case execution can be set.

Cons:
• More time is required to set up TestNG.
• If you don't need to prioritise the test cases, avoid doing this.

5. Watermelon
The testing framework known as Cucumber is very popular among testers. This is due to the fact
that it merges the specifications and documentation into a single report document and that it is
built in Ruby.

Pros:
• Better readability is a plus.
• supports step reuse, which eliminates the need to repeatedly write the same code.
• With the use of some sample tables, the testing can be automated.

Cons:
• Adding cucumber and gherkin to the dish makes it more complicated.
• In situations where a straightforward generic code would suffice, testers and developers place
a greater emphasis on designing scripts that are reusable.

6. JBehave
This is a testing framework written in Java that makes behaviour-driven programming easier to
implement. It is typically used with selenium drivers in testing applications (BDD). It comes with a
reporting tool that enables users to produce reports in text, XML, or HTML format, as the case may
be.

Pros:
• helps users with excellent documentation
• supports HTML reporting after post-testing
• Effective and simple to use
• outside the norm JUnit assistance

279
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Cons:
• Only stories are supported; there is no support for the features.

7. Mockito
Mockito is the name of an open-source framework that is based on Java and is used for behaviour-
driven testing. The primary advantage of using this framework is the elimination of the need for the
construction of fake items via its automated production.

Pros:
• assistance with exceptions
• Annotations can be used to generate mocks.
• The foundation for the return values
• There is no need to manually write mock objects
• Mocking of local variables is not supported
• Private and static methods aren't supported
• There is no control over the private fields for any subclass we write.

Exercise
Answer the following questions:
1. Use the run > outfile command to:
a. edit an outfile file
b. enter an outfile file
c. jump to an outfile file
d. direct the output to the outfile file

2. Which of these is NOT involved in the process of debugging?


a. Fixing b. Test
c. Isolating d. Identifying

3. Without arguments, the ‘set args‘ are capable of:


a. No change
b. Showing all the arguments
c. Removing all the arguments
d. Initialising all the arguments

4. Which of these does not affect a program’s execution?


a. Control b. I/O
c. Environment d. Arguments

280
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

5. The h command would provide us with ________.


a. Description of all the commands
b. A list of those commands that start from h
c. Display of all the programs
d. Display of the command’s short description

6. Which of these do we write if we want to get help in GDB?


a. assistant b. assiss
c. h d. he

7. What is the examination of a program known as step by step?


a. Stepping b. Testing
c. Tracing d. Controlling

2.4.2 What is Debugging?


During the development stage of a software program, it is subjected to exhaustive testing, as well as
upgrades, maintenance, and troubleshooting. The application will often have bugs and errors, most of
which will eventually be addressed. The process of locating and fixing errors in software is referred to
as debugging.
It is the process of locating, investigating, and eliminating mistakes. This procedure kicks off when the
program is unable to run as intended and comes to a conclusion after the underlying issue has been
resolved and the product has been tested satisfactorily. However, due to the fact that faults need to be
fixed at each level of the debugging process, this activity is seen as being highly difficult and laborious.

[Link] Exactly why is Debugging Necessary?


Error finding, analysis, and correction are all aspects that are discussed. This technique begins when
the program does not function as expected and continues until the problem has been resolved and
the software has been successfully tested. Debugging is considered to be a very challenging and time-
consuming process due to the fact that errors must be corrected at each level of the process.
• It notifies the user of an incorrect condition in a timely manner. Identifying faults early the process
of developing software less stressful and difficult.
• Debugging enables the developer to avoid creating complex, one-use testing code, which saves
time and effort during the development of the application. Debugging helps the developer gets rid
of information that is superfluous and distracting.

281
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

[Link] Steps involved in Debugging


The different steps involved in the process of debugging are:

Fig. 2.4.1: Debugging steps

1. Determine the Nature of the Mistake: Incorrect error identification might lead to wasted time
spent on development. Users often alert us of production errors that are obscure, and sometimes
the information we get is intentionally misleading. It is of the utmost importance to identify the
actual error.
2. Locate the Error Location: Once you have correctly identified the problem, the next step is to
search the code in order to establish precisely where the error is located. You shouldn't be focusing
on attempting to analyze the problem right now; rather, you should be concentrating on finding it.
3. Analyze the Issue: In order to complete the third step, you will need to begin at the position of
the error and assess the code working your way from the bottom up. This should help you better
understand where you went wrong. When investigating a defect, there are primarily two goals
to work toward: determining the possibility of introducing any collateral harm into the fix, and
searching for more errors that may exist in the surrounding area.
4. Provide Evidence for Your Hypothesis: Once you have done investigating the first problem, the
next step is to search for a few other faults that may arise inside the program. At this point in the
process, you will be writing automated tests for these portions by using a test framework.
5. Cover Lateral Damage: At this point, you need to either create or build all of the unit tests for the
code that you want to edit. If you don't, you might cause lateral damage. Now, if you run all of these
unit tests, you should see that they all pass.
6. Fixing all of the issues and validating the system is the last step, and it involves running all of the
test scripts to see whether they are successful.

Debugging Strategies
It is important to study the system in depth in order to understand the system. It helps the debugger to
construct different representations of systems that are to be debugged.
Backward analysis of the problem traces the program backward from the location of failure message
in order to identify the region of faulty code. You need to study the region of defect thoroughly to find
the cause of defects.
Forward analysis of the program involves tracking the program forward using breakpoints or print
statements at different points in the program. It is important to focus on the region where the wrong
outputs are obtained.
You must use the past experience of the software to check for similar problems. The success of this
approach depends on the expertise of the debugger.

282
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

2.4.3 Debugging Tools


A debugging tool is a piece of software designed to test and correct other pieces of software. Free
debugging tools such as gdb and dbx are available. They also provide console-based command-line
interfaces. Instruments for automating the debugging process include code-based tracers, profilers,
interpreters, and others.
Some of the most popular debuggers are as follows:
• Radare2
• WinDbg
• Valgrind

At some time in your life, you will most likely be exposed to one of these three settings. Every
environment calls for a specific approach due to its unique qualities and functions. Understanding the
settings' functions will shed light on the sheer quantity of them required.
The main three environments are: development, stage, and production.

Exercise
Answer the following questions:
1. Which of these is a freeware GNU Debugger?
a. FNB b. FDB
c. GNB d. GDB

2. The statement “The examination of a variable’s changing values is known as stepping” is __________.
a. false b. true

3. Where does a suggestion for fixing a given error appear?


a. Error detection window b. Error correction window
c. Properties window d. Error location window

4. Which of these do we use so as to improve a number appearing in an interface?


a. Appear function b. Number function
c. Format function d. Val function

5. Which of these functions would convert a string to a number and return the number temporarily?
a. Convert b. Integer
c. Value d. Val

6. Which of these refers to a predefined procedure used to perform a specific task?


a. Function b. Flowchart
c. Errors d. Pseudocode

7. The ____ of documentation refers to the process of putting a given documentation in some safe

283
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

place.
a. Printing b. Assembling
c. Testing d. Debugging

8. Which of these would occur when we forget to enter an instruction or when we enter these
instructions in the wrong order?
a. Syntax errors b. Application shut down
c. Logical errors d. Exceptions

9. Which of these would occur when we break the rules constituting a language?
a. Application shut down b. Exceptions
c. Syntax errors d. Logical errors

10. In a program, errors are also known as _________.


a. Exceptions b. Invalid data
c. Errors d. Bugs

[Link] Development
The configuration of the development environment differs typically from that of the user's workspace.
So that you can create your code without affecting the actual data, it will be connected to a local
database or a phoney database. You will also be in charge of any branch merging because there will be
several employees working in the development environment.
You cannot change what people currently see when they access the website in the development
environment. You and the other web developers only need to use this to test out updates and new
features.
In this setting, a lot of preliminary testing will take place. Before releasing your code, at the very least,
make sure it functions locally. Examine your code as carefully as you can to reduce the number of bugs
that make it to the next environment.

[Link] Stage
The production environment and the stage environment are as similar as they may be. This time, rather
than having the code on a local machine, it will be located on a server. Without affecting the production
environment, it will attempt to connect to as many services as it can
Here is where the hard core testing takes place. Both database migrations and configuration
modifications will be tested here. The stage environment assists you in identifying and
resolving any difficulties that may arise when doing significant version updates.
If you have a client, this is the time to demonstrate how things operate and appear to them.
They will be able to see how things will function after they go live and can provide you with
any input you require. Consider the performance environment as a place where you polish and do final
checks.

284
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

[Link] Production
This is the setting you are referring to each time you discuss making your project live. Users can view
the final code in the production environment after all updates and testing. This habitat is the most
crucial of all the others.
Companies make their money here, therefore you can't make any disastrous errors. You must first
complete all of the testing in the other two environments. Any faults or errors thatare still present once
you go into production will be discovered by a user, and you can only hope they are minimal.
Roll-outs to the production environment are something some individuals enjoy doing. In other words,
they roll out modifications to a small number of people before gradually releasing them to everyone.
Not every upgrade needs to be made available in the production environment simultaneously.
To address load difficulties or ensure that no significant problems manage to slip through, you may
in some situations roll out your updates on a schedule. Although it's not something you want to
do frequently, you can deploy changes to the production environment without going via the stage
environment in an emergency.

[Link] Create suitable test cases to identify bugs using


suitable tools such as JUnit
• It is an open-source testing framework for java programmers. The java programmer can create test
cases and test his/her own code.
• It is one of the unit testing frameworks. Current version is junit 4.
• To perform unit testing, we need to create test cases. The unit test case is a code which ensures that
the program logic works as expected.

The [Link] package contains many interfaces and classes for junit testing such as Assert, Test, Before,
After etc.

Types of unit testing


There are two ways to perform unit testing: 1) manual testing 2) automated testing.
1. Manual Testing
If you execute the test cases manually without any tool support, it is known as manual testing. It is
time consuming and less reliable.
2. Automated Testing
If you execute the test cases by tool support, it is known as automated testing. It is fast and more
reliable.

Annotations for Junit testing


The Junit 4.x framework is annotation based, so let's see the annotations that can be used while writing
the test cases.
@Test annotation specifies that method is the test method.
@Test(timeout=1000) annotation specifies that method will be failed if it takes longer than 1000
milliseconds (1 second).
@BeforeClass annotation specifies that method will be invoked only once, before starting all the tests.

285
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

@Before annotation specifies that method will be invoked before each test.
@After annotation specifies that method will be invoked after each test.
@AfterClass annotation specifies that method will be invoked only once, after finishing all the tests.

Assert class
The [Link] class provides methods to assert the program logic.

Methods of Assert class


The common methods of Assert class are as follows:
1. void assertEquals(boolean expected,boolean actual): checks that two primitives/objects are
equal. It is overloaded.
2. void assertTrue(boolean condition): checks that a condition is true.
3. void assertFalse(boolean condition): checks that a condition is false.
4. void assertNull(Object obj): checks that object is null.
5. void assertNotNull(Object obj): checks that object is not null.

Required jar files


You need to load [Link] and [Link] files.

Simple JUnit example in eclipse IDE


Let's see the directory structure of this example.

Write the program logic


Let's write the logic to find the maximum number for an array.
package [Link];
public class Calculation {

public static int findMax(int arr[]){


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

286
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

if(max<arr[i])
max=arr[i];
}
return max;
}
}

Write the test case


Here, we are using JUnit 4, so there is no need to inherit TestCase class. The main testing code is written
in the testFindMax() method. But we can also perform some task before and after each test, as you can
see in the given program.
package [Link];

import static [Link].*;


import [Link].*;
import [Link];

public class TestLogic {

@Test
public void testFindMax(){
assertEquals(4,[Link](new int[]{1,3,4,2}));
assertEquals(-1,[Link](new int[]{-12,-1,-3,-4,-2}));
}
}
To run this example, right click on TestLogic class -> Run As -> 1Junit Test.
Let's see the output displayed in eclipse IDE.

287
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

As you can see, when we pass the negative values, it throws AssertionError because second time
findMax() method returns 0 instead of -1. It means our program logic is incorrect.

Correct program logic


As you can see, program logic to find the maximum number for the given array is not correct because it
doesn't return -1 in case of negative values. The correct program logic is given below:
package [Link];
public class Calculation {

public static int findMax(int arr[]){


int max=arr[0];//arr[0] instead of 0
for(int i=1;i<[Link];i++){
if(max<arr[i])
max=arr[i];
}
return max;
}
}
If you run the junit program again, you will see the following output.

Another example of Junit framework


Write the program code
package [Link];

288
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

public class Calculation {


//method that returns maximum number
public static int findMax(int arr[]){
int max=0;
for(int i=1;i<[Link];i++){
if(max<arr[i])
max=arr[i];
}
return max;
}
//method that returns cube of the given number
public static int cube(int n){
return n*n*n;
}
//method that returns reverse words
public static String reverseWord(String str){

StringBuilder result=new StringBuilder();


StringTokenizer tokenizer=new StringTokenizer(str," ");

while([Link]()){
StringBuilder sb=new StringBuilder();
[Link]([Link]());
[Link]();

[Link](sb);
[Link](" ");
}
return [Link]();
}
}

Write the test case


package [Link];

import static [Link];

289
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class TestCase2 {

@BeforeClass
public static void setUpBeforeClass() throws Exception {
[Link]("before class");
}
@Before
public void setUp() throws Exception {
[Link]("before");
}

@Test
public void testFindMax(){
[Link]("test case find max");
assertEquals(4,[Link](new int[]{1,3,4,2}));
assertEquals(-2,[Link](new int[]{-12,-3,-4,-2}));
}
@Test
public void testCube(){
[Link]("test case cube");
assertEquals(27,[Link](3));
}
@Test
public void testReverseWord(){
[Link]("test case reverse word");
assertEquals("ym eman si nahk",[Link]("my name is khan");
}
@After
public void tearDown() throws Exception {

290
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

[Link]("after");
}

@AfterClass
public static void tearDownAfterClass() throws ception {
[Link]("after class");
}
}
Class

2.4.4 Exception Handling In Java


When an exception is encountered during the execution of the program, the execution is halted. Since
this is an unexpected conclusion, the system will produce and show a notice as soon as it can. The
output of the system's messages may be indecipherable or cryptic, similar to the structure of some
codes.
As a result, a normal user need to be able to determine what brought to the unexpected termination
of the software and appreciate the reasons why it took place. It's possible that the messages that the
system generated as a reaction to the exception aren't very helpful. In Java, we have the ability to
handle exceptions and provide the user with helpful notifications about the nature of the issue they
are experiencing.
The way in which exceptions are managed, sometimes known as "exception management," is one of
the most important aspects of programming in Java.

[Link] The Exception Occurs Because


Exceptions are possible due to a number of factors. If the problem stems from the input, it might be due
to inaccurate or illegible information being submitted.
If we get an error for file I/O, it's possible that the files we're trying to access don't really exist.
Inaccuracies might occur later on due to factors like downed networks, unusable printers, etc. It's not

291
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

only rare cases that might occur in code; sometimes there are just bugs. Therefore, it's important to
know the differences between a mistake and an exception in order to handle exceptions effectively.
Errors are typically indicative of a more serious issue with the program and should not be tried to
be detected by the application. A decent software will try to account for the exception, though.
Consequently, the consequences of an application's crashing due to a mistake are more severe.
However, errors occur in programming, and the programmer may fix them by providing workarounds.

Exercise
Answer the following questions:
1. Which of these is the process of locating errors and then correcting them?
a. Debugging b. Testing
c. Correcting d. Retransforming

2. Which of these types of data refers to the data that an application expects a user to enter?
a. Invalid b. Valid
c. Character d. Numeric

3. Which of the following keywords is used for throwing exception manually?


a) finally b) try
c) throw d) catch

4. Which of the following classes can catch all exceptions which cannot be caught?
a) Runtime Exception b) Error
c) Exception d) Parent Exception

5. Which of the following is a super class of all exception type classes?


a) Catchable b) RuntimeExceptions
c) String d) Throwable

6. Which of the following operators is used to generate instance of an exception which can be thrown
using throw?
a) thrown b) alloc
c) malloc d) new

7. Which of the following keyword is used by calling function to handle exception thrown by called
function?
a) throws b) throw
c) try d) catch

8. Which of these is a super class of all exceptional type classes?


a) String b) RuntimeExceptions
c) Throwable d) Cacheable

292
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

9. Which of these class is related to all the exceptions that can be caught by using catch?
a) Error b) Exception
c) RuntimeExecption d) All of the mentioned

[Link] A Brief Explanation of Exception Handling


Exception handling is a method that is used by Java in order to maintain the normal flow of the program.
To handle any exceptions or problems that may occur during the execution of a program, we make use
of a robust framework. A section of program code that is used in the process of handling an exception
is referred to as a "exception handler." A handler for an exception will look into the circumstances
around the occurrence of the exception. This signifies that the Java program has been restored to
enable regular operation to continue after reading the variable values that were in scope when the
exception occurred. This may be done after reading the exception-related variable values.

Benefits of Exception Handling


Exception handling is a method that is used by Java in order to maintain the normal flow of the program.
To handle any exceptions or problems that may occur during the execution of a program, we make use
of a robust framework. A section of program code that is used in the process of handling an exception
is referred to as a "exception handler." A handler for an exception will look into the circumstances
around the occurrence of the exception. This signifies that the Java program has been restored to
enable regular operation to continue after reading the variable values that were in scope when the
exception occurred. This may be done after reading the exception-related variable values.

Exception Hierarchy in Java


The hierarchy of exceptions in Java is depicted in the diagram below. The [Link] class.
The root class of a Java exception is called Throwable, which is an Object class descendant.
This class is the ancestor of the classes Exception and Error. The basic class for all additional exceptions
is called the exception class.
• A hierarchy of Exception classes in Java is shown here. This hierarchy will lay out all of the significant
exceptions that a Java programmer need to be aware of.

293
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Fig. 2.4.2 Exception Hierarchy

Exception Class in Java


The class Throwable contains two direct subclasses, Exception and Error. The Exception class contains
descriptions of exceptions that come from outside sources.
The constructors of the Exception class are identical to those of the Throwable class, and calling each
constructor { [native code]} also calls its equivalent Throwable function Object.

The Constructors and Methods that the Exception class uses are presented below.
Constructors

Constructor Description
public Exception() A default constructor that constructs a new
exception with the message as null.

294
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Constructor Description
public Exception(String message) Constructor to construct a new exception with
the given message. In this case, the cause is not
initialized, and a subsequent call to Throwable.
initCause ([Link]) may be used to
initialize the cause.
public Exception(String message,Throwable Constructs a new exception using a given
cause) message and cause.
public Exception(Throwable cause) Constructs a new exception with the given cause
and a message given by
(cause==null ? null: [Link]()) (which
typically contains the class and detail message of
cause).
protected Exception(String message, Constructs a new exception with the given
Throwable cause, booleanenableSuppression, message, cause, suppression (enabled or
booleanwritableStackTrace) disabled), and the writable stack trace (enabled
or disabled).

Methods:
Exception Example
We then provide a Java program to provide a simple exception scenario. Here, we offer a string variable
with a null initial value. AN exception is raised when we attempt to print this variable since a string
value cannot be null.
class Main
{
public static void main(String args[]){
//declare a String variable and initialize it to null
String myStr = null;
//print the string
[Link]([Link]());

}
}

Output

295
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Types of exceptions in Java


Java supports three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error

1. Checked Exception
During the process of compiling the code, some exceptions are investigated. These atypical
occurrences have been "verified." A compilation error is generated by the Java programming
language if it determines that the code of a program has the potential to include mistakes. We are
able to take care of the compilation problems that are thrown by checked exceptions if we manage
the exceptions, which we can do either by enclosing the code in a trycatch block or by using the
throws keyword.

The class that directly inherits from Exception in the Exception hierarchy is
• Throwable classes such as IOException, ClassNotFoundException, and others, including
RuntimeException and Error, are all checked exceptions. The only exceptions to this rule are the
classes RuntimeException and Error. These exclusions do not have their boxes ticked.

The following Java application provides examples of the FileNotFoundException, the IOException,
and the Checked Exception classes of exceptions. Within the context of our program, we try to
open and read from a file that does not exist. Because the file does not exist, the open file function
generates an exception of type FileNotFoundException. When we make an effort to read the
contents of the file and then to shut the file, the method calls raise an IOException.
import [Link].*;
class Main {
public static void main(String args[])
{
FileInputStreamfis = null;
//Open a file
fis = new FileInputStream("C:/[Link]");
int k;

//read contents of the file


while(( k = [Link]() ) != -1)
{
[Link]((char)k);
}

//close the file

296
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

[Link]();
}
}

Output:

In the above output, as the exception handler is absent, we get compilation errors for checked
exceptions.

Now let us provide a throws clause for this program. As FileNotFoundException’s parent is
IOException, we will just specify the IOException after the throws clause.
import [Link].*;
class Main {
public static void main(String args[]) throws IOException
{
FileInputStreamfis = null;
//Open a file
fis = new FileInputStream("C:/[Link]");
int k;

//read contents of the file


while(( k = [Link]() ) != -1)
{
[Link]((char)k);
}
//close the file

297
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

[Link]();
}
}

Output

As seen from the output, when we handle the exception, it provides more meaningful output
instead of the compilation errors.

2. Unchecked Exception
The exceptions that are checked at runtime are those that are unchecked. A compilation of programs
will therefore be successful despite exceptions. The majority of unchecked exceptions are raised
as a result of the program's use of inaccurate [Link] exceptions are those classes that
inherit "RuntimeException". Unchecked exceptions include those that are ArrayIndexOutofBounds
Exception, ArithmeticException, NullPOinterException, etc.

The following program demonstrates a runtime unchecked exception that is caused by dividing
a number by zero.
class Main {
public static void main(String args[])
{
int num1=10;
int num2=0;
//divide both numbers and print the result
int result=num1/num2;
[Link](result);
}
}

298
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Output:

We see that the program is compiled successfully and then the ArithmeticException is thrown at
runtime.

Examples of Unchecked Exception:


• ArrayIndexOutOfBoundsException
• NullPointerException
• IllegalArgumentException
• NumberFormatException

Apart from the above two exceptions, there are few more Checked exceptions including:
• SQLException
• InvocationTargetExecption

3. Error
When an error occurs in a program, the program terminates because mistakes are often events
that cannot be recovered from and cannot be undone. A few examples of errors that may occur in
software include the OutOfMemoryError, AssertionError, and VirtualMachineError errors, as well
as other blunders. Error may trace its lineage back to the Throwable class, which was one of its
ancestors. An instance of a scenario that cannot be managed and results in the termination of
a program is referred to as an error. Let us discuss the OutOfMemory error in this section as an
example of error.
Every single Java object, that has been brought to our attention, is allotted using the new operator
and stored on the heap. When there is insufficient memory on the heap, the Java Virtual Machine
(JVM) will be unable to allocate the object. The garbage collector is unable to free any memory at
the same time because there are too many open memory slots. The error "out of Memory" occurs
as a direct consequence of this circumstance.

The OutOfMemoryError in Java will look as shown below:


"exception in thread \"main\" [Link]: java heap space"

When a program comes across an OutOfMemoryError, it indicates that the program is either
processing an excessive amount of data or keeping objects for an excessive amount of time.
Memory may also be used up by a library that is not directly associated with the application.

299
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Causes Of Out Of Memory Error


1. Java Heap Space
If an application has an excessive number of finalizers, the garbage collector will queue up the
class objects with the Finalize method for finalisation rather than immediately reclaiming them.
OutOfMemoryError can occur when finalisation cannot keep up with time and heap memory fills
up. Another reason for OutOfMemoryError is that the heap size specified may be insufficient for
the application.
The following code demonstrates the OutOfMemoryError that can occur because of a huge data
size declared for an array.

import [Link].*;
public class Main {
static List&amp;lt;String&amp;gt; list = new ArrayList&amp;lt;String&amp;gt;();
public static void main(String args[]) throws Exception
{
Integer[] array = new Integer[100000 * 100000];
}
}

Output

2. PermGen Space
An OutOfMemory issue might potentially be brought on by the Permanent Generation Area of the
RAM running out of space.
The size of the PermGen zone is decided when the JVM is launched. In the event that the user does
not select the size, the platform-specific default dimension is used.
Even while the first two are often the most significant reasons, there may be more causes, such as
an array size that is larger than the limit for the VM.

List Of Exceptions In Java


Given below is a list of the major exceptions that occur in Java. We have provided programming
examples for some of these exceptions. Note that these are built-in exceptions supported by Java.

1. ArithmeticException: Arithmetic abnormalities like divide by zero results in ArithmeticException.

The below program demonstrates the occurrence of ArithmeticException.


class Main {

300
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

public static void main(String args[])


{
try {
//define two numbers
int num1 = 100, num2 = 0;
int result = num1 / num2; // divide by zero
//print the result
[Link]("Result = " + result);
}
catch (ArithmeticException e) {
[Link]("ArithmeticException:Division by Zero");
}
}
}

Output

2. ArrayIndexOutOfBoundsException: The ArrayIndexOutOfBoundsException is raised if an array


element is accessed by using an invalid index. Either the array's size is more than the index being
used, or the index itself is negative.
3. ClassNotFoundException: The ClassNotFoundException is thrown if the class definition cannot be
found, as its name suggests.
4. FileNotFoundException: The FileNotFoundException error message is shown when the file in
question either does not exist or cannot be opened.
5. IOException: An input-output operation that fails or is interrupted will result in the IOException
being issued.
6. InterruptedException: Whenever a thread is doing processing, sleeping, or waiting, it will throw
InterruptedException in order to cause the thread to be terminated.
7. The NoSuchFieldException is an exception that is thrown by a class when that class does not have
a certain field or variable that has been provided.
8. NoSuchMethodException: The NoSuchMethodException error message is shown if the method
that is being requested cannot be found.
9. NullPointerException: A NullPointerException will be thrown if a reference is made to a null object.
This is the most significant and widespread exception in the Java programming language.
10. NumberFormatException: This exception is thrown when a method is unable to transform a string
into a format that can represent numbers.
11. RuntimeException: A RuntimeException is any exception that happens while the program is being
executed.
12. StringIndexOutOfBoundsException: The String class will throw this exception if the index value

301
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

exceeds the size of the String object or is negative. This error message also indicates that the index
value is beyond the allowed range.
13. The EOFException is an exception that is issued by the [Link] package when the end of the file is
reached while the file is being read.
14. IllegalArgumentException An IllegalArgumentException is raised whenever a method is called with
illegal or incorrect parameters. For instance, the improper data type, a null value when a non-null
value is needed, or parameters that are outside of the allowed range.

The below Java program demonstrates the IllegalArgumentException.


public class Main
{
int m;
public static void setMarks(int marks)
{
if(marks &amp;lt; 0 || marks &amp;gt; 100) //throw exception if marks are not in range
throw new IllegalArgumentException([Link](marks));
else
[Link]("Marks Entered: " + marks);
}
public static void main(String[] args)
{
setMarks(45);
setMarks(101);
}
}

Output

In the above program, the IllegalArgumentException is thrown in the second call to setMarks function
where we enter the marks that are out of range (> 45).
15. InputMismatchException: InputMismatchException is thrown when the input read does not
match a pattern specified. For example, if the program expects integer and reads a float, then the
InputMismatchException is raised.
16. NoSuchElementException: NoSuchElementException is thrown when the next element accessed
does not exist.

302
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

For example, in Enumeration, the nextElement () method is used to access the next element in the
enumeration. If the element does not exist, then NoSuchElementException is thrown. Mostly Java
Collections throw this exception.

The program given below demonstrates this.


import [Link].*;
public class Main {
public static void main(String[] args) {
Set hash_Set = new HashSet(); //create an empty hashSet.
//This throws NoSuchElementException since hashSet is empty
hash_Set.iterator().next();
}
}

Output

17. Concurrent Modification Exception: ConcurrentModificationException is usually thrown by


Collection classes. This exception is thrown when the objects try to modify a resource concurrently.

The following example demonstrates the ConcurrentModificationException.

import [Link];
import [Link].*;
public class Main {
public static void main(String[] args) {
ArrayList&amp;lt;Integer&amp;gt; A_list = new ArrayList&amp;lt;&amp;gt;();
//add elements to the ArrayList
A_list.add(10);
A_list.add(20);
A_list.add(30);
Iterator&amp;lt;Integer&amp;gt; it = A_list.iterator();
while ([Link]()) {

303
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Integer value = [Link]();


[Link]("ArrayList Value:" + value);
if ([Link](30))
A_list.remove(value);
}
}
}

Output

In the above program, while the ArrayList is being printed, we try to delete an element at the same
time. This is the concurrent access and thus an exception is thrown.

Custom Exceptions In Java


Up until this point, each of the built-in and provided exceptions that the Java programming language
has to offer have been discussed. We are allowed to make our own exceptions, in addition to any that
are already in place. These are called user-defined exceptions or custom exceptions, depending on who
defines them.
By creating our own custom exceptions, we may tailor them to meet our own requirements.

The following example shows the custom exception that we defined for an Integer value
//custom exception definition
class InvalidValueException extends Exception
{
InvalidValueException(String s)
{
super(s);
}
}

304
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

class Main{
static void validate(int int_val)throws InvalidValueException
{
if(int_val&amp;lt;10) //value is valid if &amp;gt; 10 else throw exception
throw new InvalidValueException("Invalid value");
else
[Link]("This is valid integer");
}

public static void main(String args[])


{
Try
{
validate(9);
}
catch(Exception m){[Link]("Exception occured: "+m);}

[Link]("Code after Exception");


}
}

Output

Exercise
Answer the following questions:
1. What will be the output of the following Java code?
classexception_handling
{
publicstaticvoidmain(Stringargs[])
{
try
{
[Link]("Hello"+" "+1/0);

305
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

}
finally
{
[Link]("World");
}
}
}
a) Hell b) World
c) Compilation Error d) First Exception then World
2. What will be the output of the following Java code?
classexception_handling
{
publicstaticvoidmain(Stringargs[])
{
try
{
inti, sum;
sum =10;
for(i=-1;i<3;++i)
{
sum =(sum /i);
[Link](i);
}
}
catch(ArithmeticException e)
{
[Link]("0");
}
}
a) -1 b) 0
c) -10 d) -101

3. Which of these keywords is used to generate an exception explicitly?


a) try b) finally
c) throw d) catch

4. Which of these class is related to all the exceptions that are explicitly thrown?
a) Error b) Exception
c) Throwable d) Throwv

5. What will be the output of the following Java code?


classexception_handling
{

306
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

publicstaticvoidmain(Stringargs[])
{
try
{
[Link]("A");
thrownewNullPointerException("Hello");
}
catch(ArithmeticException e)
{
[Link]("B");
}

}
a) A b) B
c) Hell d) Runtime Exception

6. What will be the output of the following Java code?


public class San
{
public static void main(String[]args)
{
try
{
return;
}
finally
{
[Link]("Finally");
}
}
}
a) Finally
b) Compilation fails
c) The code runs with no output
d) An exception is thrown at runtime

7. What will be the output of the following Java code?


publicclass San
{
publicstaticvoidmain(Stringargs[])
{
try

307
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

{
[Link]("Hello world ");
}
finally
{
[Link]("Finally executing ");
}
}
}
a) The program will not compile because no exceptions are specified
b) The program will not compile because no catch clauses are specified
c) Hello world
d) Hello world Finally executing

8. What is the use of try & catch?


a) It allows us to manually handle the exception
b) It allows to fix errors
c) It prevents automatic terminating of the program in cases when an exception occurs
d) All of the mentioned

2.4.5 Coding Standards


[Link] Variable Scopes, Readability, and Lambda Expression
Every variable that is defined in Java is assigned a scope. This indicates that the usage of the variables
and their visibility must be restricted to the scope that contains them. When it comes to a local variable,
its visibility spans the whole of the method or code block in which it was defined, all the way through to
its conclusion. It is a good idea to declare a variable near to where it could be utilized in the program.
This not only makes the code easier to understand, but it also makes it simpler to debug.

try
Connection con = [Link](DATABASE_URL,
USERNAME,PASSWORD);
Statement stmt = [Link]();
ResultSetrs = [Link](SQL_QUERY)
){
//...
}catch(SQLException e){
[Link]();

308
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

}
Observe how the code snippet confines the range of application for the local variables to the block in
which those variables are defined. After the block is finished, the variables will no longer be shown on
the screen. Additionally, the code becomes less cluttered, more legible, and easier to comprehend.
However, beginning with Java 8, we will be able to utilize lambda expressions in order to write code that
is both clearer and shorter. Take notice of the way in which we may exemplify the notion by combining
multiple different utility expressions into a single line of lambda code.

Integer[] nums={90,71,26,34,42,35,66,57,88,89};
Prints original numbers.
final List<Integer> l1 = [Link](nums);
[Link]("Original :%s%n",l1);
Now we use lambda expression to print numbers after sorting in ascending order.
final List<Integer> l2 = [Link](nums)
.sorted().collect([Link]());
[Link]("After sorting: %s%n",l2);
We can apply more utility, such as printing only those numbers that are greater than, say, 50, after sort
them in ascending order.
final List<Integer> l3 = [Link](nums).filter(num ->num> 50).collect([Link]());
[Link]("Sorting only of numbers > 50 : %s%n", l3);

1. Class Fields
Methods in Java can either be a part of a class or an interface. As a result, there's a potential
that the programmer accidentally gave local variables the same name as a class member
variable. However, the Java compiler has the ability to select the appropriate one from the
scope. Modern IDEs are also capable enough to spot the conflict.

In any case, since the outcome can be quite disastrous, programmers themselves should be
responsible enough to prevent such disputes.
The following code demonstrates how, if we ignore variable name conflicts, we end up with a
drastically different outcome.
public classTestClass {
private double commission = 5.5d;
public doubleincreaseCommission(final doublenewComm){
double commission = newComm;
commission += commission;
return commission;
}
public doublegetCommission(){

309
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

return commission;
}
public static void {TestClass m = newTestClass();
[Link]([Link](3.3));
[Link]([Link]());
}
}

Using the this keyword is another technique to prevent confusion with the field names of
the class with local variables. As an illustration, [Link] would only ever refer to the class
[Link] in order to minimise field name conflicts, experience suggests it's preferable to use entirely
separate names in methods other than constructors.
Treating Method Arguments as Local Variables
In Java, a variable may be used several times after it has been defined. As a direct consequence of
this, it is possible to assign new values to the nonfinal local variables that have been defined in the
method parameters. This, however, is not a good idea due to the fact that the variable transmits
the initial value that the method will operate on as an argument to the method. This value is the
value that it has brought. If we change the value, then the presentation of the technique's original
content will be utterly ruined.
Instead, we have to copy the value into a separate variable and then proceed with the processing
that is necessary. Nevertheless, by using the final keyword, we are able to completely restrict the
scope of the input variable and turn it into a constant.

public double calculate(final doublenewVal)


{
doubletmp = newVal;
// ...
returntmp;
}

2. Boxing and Unboxing


Boxing and unpacking are Java programming techniques that are the polar opposite of the method
known as conversion between basic types and their corresponding wrapper classes. Wrapper
classes, which are nothing more than the "class" versions of basic types such as int to Integer,
float to Float, double to Double, char to Character, byte to Byte, boolean to boolean, and so on,
are nothing more than that. Wrapper classes are only the "class" versions of simple types. The
conversion of, for example, int to int is referred to as boxing, whereas the conversion of int back to
int is referred to as unpacking.
Autoboxing is the process of the compiler performing the conversion in the background. But
occasionally, this autoboxing could result in an unexpected outcome, so we must be cautious of it.
public static void update(final doublenewVal)

310
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

{
// ...
}

final Double val = null;


update (val);

Java does not complain during compilation, but as we execute this code, NullPointerException is
thrown. This is an example to show that autoboxing does not always produce the result we want.
We should be aware and give a thought if autoboxing would suffice in the present context or not.

3. Interfaces
Because interfaces are not reliant on the concrete classes that they extend, we are obligated to make
good use of them when we do not need concrete classes (apart from default methods). Interfaces
are comparable to contracts in the sense that there is a great deal of leeway and adaptability in
the way that they are organized. Concrete classes are in a position to make use of the flexibility to
expand and replenish their commercial agenda.
This is especially true and frequently evident when using an external system or services for the
implementation.
[Link];
public interface Payable {
public doublecalcAmount();
}

[Link];
public class Invoice implements Payable {
private String itemNumber;
private String itemName;
private int quantity;
private double unitPrice;
public Invoice(String itemName, int quantity,
doubleunitPrice) {
// ...
}
public intgetQuantity() {
// ...
return quantity;
}
public doublegetUntPrice() {

311
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

// ...
return unitPrice;
}
@Override
public doublecalcAmount() {
returngetQuantity()*getUntPrice();
}
}

4. Strings
String is the only Java type that has received as many extensions as it has. Java strings are objects
that cannot be changed and are encoded using the UTF16 character set. This suggests that a new
string object is produced every time an operation, such as concatenation, that asks for modifying
the original string is done. Examples of such operations include adding characters to an existing
string.
Utilizing this intermediate string object, which was just created so that the necessary process could
be carried out, is both wasteful and inefficient.
This is because the generation of intermediate objects is both superfluous and dependent on trash
collection, despite the fact that we have the ability to eliminate the former condition.
There are two related classes that go by the names StringBuffer and StringBuilder, and they are
designed for the type of string manipulation that we could want. Because of this, these two classes
came into being. The sole difference between StringBuffer and StringBuilder is that the former
supports thread safety while the latter does not. When we need to alter strings quite a bit, rather
to utilizing an immutable String instance, we may make heavy use of these two classes instead.
StringBuilder stringBuilder = new StringBuilder();
[Link]( "Hello" );
[Link]( 108 );
[Link]( 0 );
[Link]( 0, "h" );
[Link]( [Link]() - 3,
[Link](), "." );
[Link](stringBuilder);

5. Naming Conventions
The Java name conventions are a set of naming principles that are intended to guarantee that Java
code is presented in a uniform manner across all Java projects and libraries. These are not hard and
fast laws, but rather guidelines for excellent programming practices that should be adhered to. As
a result, it is not a good idea to violate the sanctity of the code's homogeneity and uniformity out
of hurry or outrage.
The guidelines are quite basic.
• Package names are types in lowercase: [Link], [Link], [Link].

312
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

• Class, enum, interface, and annotation names are typed in uppercase: Thread, Runnable, @
Override.
• Methods and field names are typed in a camel case: deleteCharAt, add, isNull.
• Constants are types in uppercase separated by an underscore: SIZE, MIN_VALUE.
• Local variables are typed in camel case: employeeName, birthDate, email.

Because these rules are now an integral part of Java, almost every programmer adheres to them
in an extremely strict manner. As a consequence of this, any adjustment to this seems ludicrous
and absurd. The fact that the coding style will match that of the library or framework might be
considered the most evident advantage of adhering to these norms. In addition to this, it makes it
easier for other programmers to rapidly take up the code when they need to, which enhances the
readability of the code as a whole.

6. Standard Libraries
Java is well-known for having a diverse collection of libraries at its disposal. However, even if not all
library buildings are perfect examples of architecture, the vast majority of libraries are. Java releases
brand new libraries on occasion and is always working to enhance the functionality of the libraries
it currently offers. As a consequence of this, it is strongly suggested that the classes, methods,
interfaces, enums, and annotations provided by the library be used wherever it is feasible to do
so. This might cut the total amount of time needed for manufacturing by a substantial amount.
Additionally, the functionality has been subjected to extensive testing.
Make use of a template from the library if it is feasible to do so rather than developing something
from scratch. Because the Java platform is continually changing, it is very necessary for us to keep
a close check on whatever features we include from other libraries or frameworks and determine
whether or not they are already present in the Java Standard Library. Before withdrawing funding
from external sources, it is standard practice to exhaust all available internal resources first.

7. Immutability
The concept of immutability is very important. Because immutability means that the object may
be used nearly everywhere without running into any problems caused by concurrent change, it is
necessary to assess whether or not the classes that we want to design can be made immutable.
The creation of an immutable version of every class is currently impossible. However, you should
know that we should always behave in this manner. As a direct consequence of this, life has become
easier.

8. Testing
The Java community recognizes test-driven development, sometimes known as TDD, as an indicator
of high-quality code.
Testing is an important part of modern Java development, and the Java Standard Library provides a
framework called Junit to assist developers with this process.
Because of this, a beginner Java programmer shouldn't be nervous about include test cases with
the code. The examinations must to be kept short and uncomplicated, focused on a single topic at
a time. A real-world scenario can include the presence of hundreds of test cases. The ability to get
immediate feedback on the features that are being created is one of the most apparent benefits of
writing test cases.

313
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

2.4.6 Best Practices related to java


1. Use Proper Naming Conventions
Before you start creating any code for your Java project, you should first decide on a decent naming
convention for the project. Prepare ahead of time by naming all of the classes, interfaces, methods,
and variables. If you and several other developers are working on the same project, the other
developers should follow your lead so that everything is consistent. Because everything in the code,
from classes to interfaces, can be identified by their names, having a sensible naming system is
very necessary. Instead than assigning names at random only to please the compiler, choose names
that have some kind of significance and are self-explanatory. Because of this, the code will be more
readable, and those of you, your coworkers, quality assurance engineers, and staff members who
will be managing project maintenance will have an easier time understanding it.

2. Class Members must be accessed privately


In Java, one of the best practices is to make sure that class fields are as inaccessible as is humanly
possible. This is done in order to ensure the fields' safety. Using the private access modifier is the
most effective way to achieve that goal. It is recommended to use this strategy since encapsulation
is one of the fundamental concepts behind OOP.
Even though it is a very basic principle in object-oriented programming, many beginner programmers
are aware of it; yet, they opt to leave the access modifiers of classes set to public since it is more
convenient for them to do so.

Consider this class where fields are made public:


1. public class Teacher {
2. public String name;
3. public String subject;
4. }

The encapsulation is compromised here as anyone can change these values like this,
1. Teacher T01 = new Teacher();
2. [Link] = "Sam";
3. [Link] = “Science”;

Using private access modifier with class members keeps the fields hidden preventing a user to
change the data except for setter methods.
Here is another example using private access modifier:
public class Teacher {
private String name;
private String subject;
public void setName(String name)
{
[Link] = name;
}

314
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

public void setSubject(String subject)


[Link] = subject;
}
}

3. Use Underscores in lengthy Numeric Literals

This feature was introduced in Java 7 that helps in writing lengthy numeric literals in a much more
readable way. So instead of writing in the old and common way like this,
int num = 58356823;
You can assign a lengthy number like this
int num = 58_356_823;
Adapting one of such java best practice makes your code readable, well-structured and unique.

4. Never leave a Catch Blocks empty


When handling exceptions, top-tier developers always follow the Java best practice recommended
by Oracle, which is to provide a relevant and informative message in the catch block. It is common
practice for young developers, when they are the only ones working on the code at first, to leave
the catch block empty. On the other hand, when an exception is caught by a catch block that is
empty, the application will not show any information. This makes debugging a more challenging
and time-consuming process.

5. Use StringBuilder or StringBuffer for String Concatenation


The "+" operator is widely used to combine Strings as a standard operation in a wide variety of
computer languages, one of which being Java.
When you need to concatenate multiple strings, using the "+" operator is inefficient even though
doing so is a common practice and is not incorrect. This is because the Java compiler first constructs
a large number of intermediary Text objects before constructing the final string that is concatenated.
The most efficient way to use Java in this scenario is to make use of the "StringBuilder" or
"StringBuffer" classes. A time and memory savings are realized via the use of these built-in methods
that modify a String without creating any extra String instances.

For instance,

String sql = "Insert Into Users (name, age)";


sql += " values ('" + [Link]();
sql += "', '" + [Link]();
sql += "')";

The above-mentioned code could be written using StringBuilder like this,

315
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

StringBuilder sqlSb = new StringBuilder("Insert Into Users (name, age)");


[Link](" values ('").append([Link]());
[Link]("', '").append([Link]());
[Link]("')");
String sqlSb = [Link]();

6. Avoid Redundant Initializations


The practice of initializing member variables with the values 0 or false or null is not advised,
despite the fact that it is rather common. These values are already the default initialization for the
member variables in Java; Java uses these values. As a result, it is strongly advised to avoid manually
initializing member variables and to instead pay attention to the parameters that are used for their
default initialization.

7. Using enhanced for loops instead of for loops with counter


Even though the "For" loop may be used with a counter variable, every top Java developer suggests
that you use the enhanced for loop rather than the classic basic For loop. This is because the
improved for loop is more efficient. It won't make much of a difference which one you choose to
use in the vast majority of situations; nevertheless, the counter variable may on occasion be quite
error-prone. If the counter variable is modified by mistake, utilized later in the program, or if the
index is begun at 1 rather than 0, the code may be disrupted at different points. Getting rid of this
issue could become easier if you use a refined version of the for loop.

Consider the following code snippet:

String[] names = {"Sam", "Mike", "John"};


for (int i = 0; i<[Link]; i++) {
method1(names[i]);
}
Here variable “I” is used as a counter for a loop as well as the index for the array names. It can get
problematic later in the code so We can avoid the potential problems by using an enhanced for loop
like shown below:

for (String Name1 : names)


{
method1(Name1);
}

8. Proper handling of Null Pointer Exceptions


In Java, null pointer exceptions are extremely often seen. An instance of this exception is generated
whenever an attempt is made to invoke a method that is associated with a Null Object Reference.
For example, have a look at the piece of code that is described below: int noOfEmployees = office.

316
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

listEmployees (). count;


This piece of code does not include any errors; nevertheless, if the object "office" or the function
"listEmployees()" is null, the program will generate a "null pointer exception," which is an error
message. Null pointer exceptions are unavoidable; nonetheless, there are certain coding best
practices in Java that should be adhered to ensure that they may be handled more effectively.
Before beginning execution, it is critical to do a check for nulls. This enables you to remove any nulls
that are found and modify your code so that it can effectively deal with the new situation.
A corrected version of code is show below,

private int getListOfEmployees(File[] files) {


if (files == null)
throw new NullPointerException("File list cannot be null");

A corrected version of code is show below,

9. Float or Double: the right choice


Even if they understand the principles, inexperienced programmers usually make the same
judgment regardless of the context because they are unable to differentiate between the Double
and Float data types.
The best practices for utilizing Java advocate making use of float and double where appropriate.
Implementing best practices not only boosts the functionality of your code but also makes it
simpler to read and comprehend. When it comes to accuracy, double is by far the superior option
to Float, which is why it is recommended that you make use of double wherever possible. Float is
a more space-efficient alternative to double that may be used instead of double in situations when
accuracy is not as important.

10. Use of single quotes and double quotes


In spite of the fact that single quotes are intended to represent characters and double quotes are
used to represent strings, there are a few peculiar circumstances in which things might disappear.
When it is required to combine characters to generate a string, Java's best practice suggests using
double quotes for the characters that are going to be concatenated. If you use single quotes,
the widening primitive conversion won't take the integer values of the characters into account;
however, if you use double quotes, the characters will be handled as a basic string, and there won't
be any problems. If you use double quotes, however, the integer values of the characters will be
taken into account.

public class classA


{
public static void main(String args[])
{
[Link]("A" + "B");
[Link]('C' + 'D');

317
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

}
}

Here the output should be ABCD on the screen but you will be seeing AB135 because AB is fine but
because C and D are in single quotes, their ASCII values are used and added together due to “+”
operator resulting in AB135 on screen.

2.4.7 Demonstrate how to debug a Java program in an IDE


Debugging
In its most general sense, debugging refers to the act of locating and fixing faults that are present in a
computer program.
You are going to have to deal with a variety of various types of faults. Syntax mistakes, for example,
are simple to identify since the compiler takes care of most of their possible manifestations. When the
issue can be immediately detected by looking at the stack trace, which helps you determine out where
the mistake occurred, this is another simple example that can be handled with ease.
However, there are faults that may be incredibly difficult to identify and fixing them might take an
extremely long time. For instance, a little logic mistake that occurred early in the program may not
present itself until quite late, and it may be a great problem to sort things out when this happens.
The debugger is helpful at this point in the process. The debugger is a powerful tool that provides an
insight into the underlying activities of a program. This allows you to detect flaws much more quickly
than you could without it. This may be accomplished by halting the execution of the program and
doing an in-depth inspection of the variables and the way in which they are altered line by line. You
have complete command over everything when you are debugging it. In order to get you started with
debugging, we will cover some of the fundamentals in this handbook.

Examine the code


Let us try a simple debugging case. Imagine we have the following application:

publicclassAverageFinder{
publicstaticvoidmain(String[]args){
[Link]("Average finder v0.1");
doubleavg=findAverage(args);
[Link]("The average is "+avg);
}

privatestaticdoublefindAverage(String[] input){
double result =0;
for(String s : input){
result +=[Link](s);

318
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

}
return result;
}
}

The program is supposed to calculate the average of all values passed as command-line arguments.
It compiles and runs without issues; however, the result is not what one would expect. For instance,
when we pass 1 2 3 as the input, the result is 6.0.
First of all, you need to think about where the suspected error might be coming from. We can assume the
problem is not in the print statements. Most likely, unexpected results are coming from our findAverage
method. In order to find the cause, Let us examine its behaviour in the runtime.

[Link] Set Breakpoints


To examine how the program operates at runtime, we need to suspend its execution before the
suspected piece of code. This is done by setting breakpoints. Breakpoints indicate the lines of code
where the program will be suspended for you to examine its state.
• Click the gutter at the line where the findAverage method is called.

[Link] Run the Program in Debug Mode


Now Let us start the program in debug mode.
Since we are going to pass arguments for running and debugging the program, make sure the run/
debug configuration has these arguments in place.

1. Click the Run icon in the gutter, then select Modify Run Configuration.

319
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

2. Enter arguments in the Program arguments field.

3. Click the Run button near the main method. From the menu, select Debug.

Analyze the program state


After the debugger session has started, the program runs normally until a breakpoint is hit. When this
happens, the line where the program paused gets highlighted and the Debug tool window appears.

320
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

The highlighted line has not been executed yet. The program now waits for further instructions from
you. The suspended state lets you examine variables, which hold the state of the program.
As the findAverage method has not been called yet, all its local variables like result are not yet in scope,
however, we can examine the contents of the args array (args is in scope for the main method). The
contents of args are displayed inline where args is used:

You can also get information about all variables that are currently in scope in the Variables panel.

Step through the program


Now that we are comfortable with the Debug tool window, it's time to step into the findAverage method
and find out what is happening inside it.
1. To step into a method, click the Step Into button or press F7.

Another line gets highlighted in the editor because we advanced the execution point one step
forward.
2. Continue stepping with Step Over F8. Notice how it is different from Step Into. While it also advances
the execution one step forward, it doesn't visit other methods like [Link]() along the way.

321
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Let us keep stepping and see how the local variable result is declared and how it is changed with
each iteration of the loop.

Right now the variable s contains the value "3". It is going to be converted to double and be added to
result, which currently has the value of 3.0. No errors so far. The sum is calculated correctly.
3. Two more steps take us to the return statement, and we see where the omission was. We are
returning result, which has the value of 6.0, without dividing it by the number of inputs. This was
the cause of incorrect program output.

To continue the program execution after it has been suspended, press ⌥⌘ R or select Run | Debugging
Actions | Resume from the main menu.
4. Let us correct the error:
return result /[Link];

Stop the debugger session and rerun the program


In order to check that the program works fine, Let us stop the debugger session and rerun the program.
1. Click the Stop button or press F2.

2. Click the Run button near the main method. . From the menu, select Run.

3. Verify that the program works correctly now.

322
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Demonstrate the ways to execute a Java program


Running code in your integrated development environment (IDE) is simple, but you don't typically get
to see how it runs your code (even if you can always check the command in the terminal!).
However, it is excellent practice to have a solid understanding of how the code you write really runs and
how it generates the results it does.
It's possible that a good number of you have heard that experienced and professional programmers
also utilize the terminal to run the programs they write. This provides them with more clarity and helps
them understand how the code is operating, including where it is delivering the intended result, where
the issue could be, and so on.
Executing Java code straight from the terminal is a pretty simple action that may be performed for a
variety of different reasons.
I will demonstrate to you how you may run Java applications straight from the terminal window of your
choice. Have no dread! The process is really straightforward, and by the time you have finished reading
this article in its entirety, you should be able to execute your own Java code in the terminal.

How to Run Java Code in the Terminal


The process I am going to show you in this article is applicable to any operating system whether that is
Windows, MacOS, or Linux.
I will be using the following Java code in the next step.

Public class Main


{
publicstaticvoidmain(String[]args)
{
[Link]("Hello, World!");
}
}

Step 1 – Go to the directory where your source code is


If you have already written your Java code in an editor, then simply go into that directory. You can go
straight into the directory through your file manager if you want.

How to go into the directory where the source code is: for Windows
Suppose I have the source code ( [Link] ) inside This PC > Documents folder. I can simply go there
through my file explorer.

323
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Or, if I want, I can also go there using my terminal. I need to use cd to indicate that I want to change
directory.
In this case, I can use cd "C:\Users\Md. Fahim Bin Amin\Documents". As my user name contains white
spaces, I have used " " to enclose them.
Then if I check all the files under that directory, then I will get the [Link] file as well.
I placed the [Link] file under my D drive this time. So I went in that directory using the cd command.

I get my Java file in the terminal as well.

How to go into the directory where the source code is: for Linux 🐧
You can go into the directory where you have kept your source code either by following the typical GUI
way or from the terminal using the cd command as well.

using the typical GUI way

324
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Using the cd command

How to Compile the Java Code


Before running our Java code, we need to compile it first. To compile a Java code/program, we get the
class file. Then we need to execute/run the class file.

How to compile Java code using the terminal


We need to use the command javacfile_name_with_the_extension. For example, as I want to compile
my [Link], I will use the command javac [Link]. The c in javac indicates compile.

If the compilation process is successful, then we will not get any errors.

This will create the class file we need under the same directory.

Keep in mind that we run the class file, not the .java file.
The same process is applicable for all of the operating systems out there.

325
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Linux OS

How to Run the Java Code


We run the .class file to execute the Java programs. For that, we use the command java class_file_
name_without_the_extension. Like, as our .class file for this is [Link], our command will be java
Main.

The Java program has been executed successfully!


The exact same procedure is also applicable for the other operating systems as well.

How to Run a Java program with Packages


The term "package" refers to a folder in its most basic form. Earlier, I walked you through the process
of utilizing the terminal to run any ordinary Java code. Within that portion of the Java code, I did not
make use of any packages.

326
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Now that we have that out of the way, I will demonstrate how you can execute any Java code that has
packages that have been defined inside it. This time around, I will be use the Java code that is shown
below.

[Link];
publicclassMain
{
publicstaticvoidmain(String[]args)
{
[Link]("Hello, World!");
}
}
In the first line, I have written the package as package [Link]. This indicates that I want
to create a folder named myJavaProgram. Then, I want to create another folder under that named
Source. Finally, I want to create the class file of my Java code inside the Source folder.

The directory tree looks like this: myJavaProgram> Source.


For compiling this type of Java code with the packages, we use the command javac -d . file_name_with_
the_extension.
As for now, I am using the [Link] file, so I will apply the command javac -d . [Link]. This will create
a folder named myJavaProgram, then create another folder named Source under the myJavaProgram
folder under the directory where my source file is now.

• The_Directory_Where_I_Have_Kept_My_Source_Code
ᴑ myJavaProgram folder
• Source folder

It instantly creates the myJavaProgram folder.

327
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Within the folder, it creates the Source folder.

Inside the Source folder, it creates our .class file. We need this file to run the Java program.

Now if we want to run the .class file, then we need to change the command a little, as we need to
provide the directory of the .class file in the terminal window.
We use the command to run the Java program with packages, java directory_of_the_class_file.the_
class_file_name_without_the_extension.
As I am using [Link] and I need to run the [Link] file, my command will be java myJavaProgram.
[Link]. It will run the Java code like below.

If you're wondering why we are changing the command now, it's because earlier, we did not declare
any packages. So the Java compiler created the .class file within the directory where our source code
was. So, we could get the .class file directly from there and execute the class file as well.
But if we declare packages inside the source code like this, then we are telling the compiler to create
the .class file in another place (not within the directory where our source code currently is). This means
that we do not get the class file directly there.
As we want to run the class file, we need to tell the compiler explicitly where the class file currently is
so that it can get the class file and execute it.

328
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

If you think that you might mess up this step, then you can copy the directory directly from your Java
code.
In line 1, we have declared the package directory (where we want the class file to be generated). So if
we simply copy the directory and add the .class file name without the extension ( .class ) later with a
period ( . ), then it satisfies the condition for executing any Java code that has packages declared in the
source code.
The same process is also applicable for the other operating systems as well. I am providing screenshots
from a Linux OS here:

Running Java codes having packages within a Linux Machine


Great job! You can now run any Java code/programs directly using a terminal

Exercise
Answer the following questions:
1. Which of these keywords are used for the block to be examined for exceptions?
a) try b) catch
c) throw d) check

2. Which of these keywords are used for generating an exception manually?


a) try b) catch
c) throw d) check

3. Which of these statements is incorrect?


a) try block need not to be followed by catch block
b) try block can be followed by finally block instead of catch block
c) try can be followed by both catch and finally block
d) try need not to be followed by anything

329
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

4. What will be the output of the following Java code?


class Output
{
public static void main(Stringargs[])
{
try
{
int a =0;
int b =5;
int c = b / a;
[Link]("Hello");
}
catch(Exception e)
{
[Link]("World");
}
}
}
a) Hell b) World
c) HelloWOrld d) Compilation Error

5. What will be the output of the following Java code?


class Output
{
public static void main(String args[])
{
try
{
int a =0;
int b =5;
int c = b / a;
[Link]("Hello");
}
}
}
a) Hell b) World
c) HelloWOrld d) Compilation Error

330
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer

Notes
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________

Scan the QR codes or click on the link to watch the related videos

[Link] [Link] [Link]

JAVA Packages and libraries Java as Compiled vs Interpreted JAVA-Platform independent and
language architecture-neutral

[Link]

Java Multithreading

331
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

332
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Employability Skills

DGT/VSQ/N0102
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Employability Skills is available at the following location

[Link]

Employability Skills

334
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Annexure

Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook

Page
Module No. Unit No. Topic Name Link for QR Code (s) QR code (s)
No

1.1.1 Telecom [Link]


330
Sector in India be/7PsZBEiNL2o

JAVA Packages
and libraries

2.1.1 The
Evolution of
[Link]
Computer 330
Module 2: t2Xw8_xCUGg
Programming
Develop,
Languages Java as Compiled
Test and vs Interpreted
Execute language
UNIT 2.1:
Software
Introduction
Programs
to Java
as per
Specifica- 2.1.1 The
tions using Evolution of
[Link]
Java Computer 330
alXJU4nM5Yw
Programming
JAVA-Platform
Languages independent and
architecture-
neutral

2.1.1 The
Evolution of
[Link]
Computer 330
be/1DlndReOCvw
Programming
Languages Java
Multithreading

336
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
IT – ITeS Sector Skill Council NASSCOM
Address: Plot No. – 7, 8, 9 & 10 Sector – 126, Noida, U�ar Pradesh – 201303
New Delhi – 110049
Website: [Link]
e-mail: ssc@[Link]
Phone: 0120 4990111 – 0120 4990172

Price: `
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Published By

NASSCOM

Common questions

Powered by AI

Decision-making statements in Java control the flow of a program by altering execution paths based on given boolean conditions. The main types are 'if' statements and 'switch' statements. 'If' statements evaluate conditions and execute different code blocks based on whether conditions are true or false. There are four variations: simple 'if', 'if-else', 'if-else-if ladder', and nested 'if'. Switch statements are used to test a variable against multiple case constants .

Low-Level Design (LLD) provides a detailed description of each module, including the logic of each system component. It transforms a high-level solution into a detailed solution and is developed after the High-Level Design (HLD). The HLD describes the overall system architecture, including databases and platforms, while the LLD focuses on the detailed logic of the components .

Java achieves platform independence through its use of bytecode, which is the intermediate representation of the Java program. After being compiled from source code, the bytecode can be executed on any platform with a Java Virtual Machine (JVM), which interprets this code into machine-specific code. This ensures that the same Java code can run on various platforms without modification .

Several techniques used in Requirements Analysis include Business Process Modeling Notation (BPMN), Unified Modeling Language (UML), flowcharts, and Data Flow Diagrams (DFDs). These techniques help in visually representing processes, identifying system requirements, and understanding the flow of data, thereby ensuring clear communication of the requirements among stakeholders and aligning the development process with business objectives .

In Java, constructors are special methods used to initialize objects. A default constructor initializes objects with default values, while parameterized constructors use given values for initialization. Constructors allow for overloading to support object creation with different initial conditions. This flexibility improves code reusability and readability by allowing diverse object configurations .

The primary purpose of a Data Flow Diagram (DFD) in systems analysis is to represent the flow of data within a system. It helps identify the required input data, the processes that transform this data, the output generated, and the data stores involved. DFDs are useful for visualizing complex systems and determining whether the data store is appropriate for the expected output information .

The Security Manager in Java's security architecture determines the resources a class is permitted to access, such as file reading and writing. It increases application security by enforcing security policies at runtime, thus controlling operations that a Java application can perform. This system is critical to restricting potentially harmful operations, thereby preventing unauthorized code execution .

Unified Modeling Language (UML) offers a graphical notation method to specify, visualize, build, and document software artifacts, which is valuable for object-oriented software development. One advantage is its ability to validate software architecture design. However, a limitation could be the complexity and learning curve associated with mastering its comprehensive set of diagrams and constructs .

Java's exception management system enhances robustness by providing a structured way to handle runtime errors, thus preventing application crashes and allowing graceful recovery. It uses constructs such as try-catch blocks, throw, throws, and finally to intercept, manage, and debug erroneous conditions in the application execution flow, facilitating error isolation and resolution .

Object serialization in Java is the process of converting an object into a byte stream, enabling it to be saved to a file or transmitted over a network. Deserialization is the process of reconstructing the object from the byte stream. This allows Java applications to persist an object's state, enabling it to be shared freely across systems irrespective of their architecture, which is crucial for distributed systems where objects need to be transmitted across different machines .

You might also like