Java Software Programmer Handbook
Java Software Programmer Handbook
English (en-US)
Par�cipant Handbook
Sector
IT-ITeS
Sub-Sector
IT Services
Occupa�on
Applica�on Development
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
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.
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
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
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
2. Develop, Test and Execute Software Programs as per Specifications using Java (SSC/N0510) 37
[Link]
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
2
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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
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).
4
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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.
6
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
7
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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.
8
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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
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
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
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.
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.
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.
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
15
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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
17
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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
18
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
19
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
Business Requirements:
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.
21
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
22
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
23
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
24
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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
26
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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
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.
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?
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 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
The following figure explains four basic key process activities in software development process.
32
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
33
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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?
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
SSC/N0510
37
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
38
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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.)
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.
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.
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
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
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
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
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.
44
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
Exercise
MCQ Questions:
1. Java is procedural programming.
a) True b) False
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
10. The newly introduced Streams API is available in which package of java 8:
a) [Link] b) [Link]
c) [Link] d) [Link]
46
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
Example 1:
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:
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
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
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.
50
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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
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 {
…
}
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.
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
{
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
Short exercise:
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]());
}
}
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.
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.
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
62
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
}
}
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]());
}
}
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.
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
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.
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.
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.
Exercise
MCQ Questions:
1. Which of the following is not an OOPS concept in Java?
a) Polymorphism b) Inheritance
c) Compilation d) Encapsulation
70
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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
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)
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
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
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
75
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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.
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.
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.
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
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).
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
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
82
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
9. Which component is responsible for converting bytecode into machine specific code?
a) JVM b) JDK
c) JIT d) JRE
83
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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
84
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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.
The above command will execute the byte code and perform the functionality of the program:
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
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
86
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
10. JVM will differ from platform to platform but still all understand the Same Java Bytecode
a) True b) False
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
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
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
92
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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:
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
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
Output: 63
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
Output:
60
60
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.
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.
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.
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.
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.
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.
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.
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:
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
Syntax:
for(initialization; condition; increment/decrement){
//statement or code to be executed
}
Example:
[Link]
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
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
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;
Syntax:
for(;;)
{
//code to be executed
}
Example:
[Link]
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.
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
Output: 9 7 5 3 1
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);
}
}
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
Example:
public class Demo
{
110
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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
Output:
Area of square 81
Area of rectangle 12
The normal method in abstract class Area
Example:
class DemoParent{
final void method(){
[Link]("Parent class final method");
}
}
112
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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");
}
}
Output:
Parent class final method
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.
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
5. State TRUE or FALSE. Every IF statement must be followed by an ELSE of ELSE-IF statement.
a) TRUE b) FALSE
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
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:
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
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.
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
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.
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
123
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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
Syntax:
boolean varName;
• Size: Virtual machine dependent
• Values: true or false
Example:
// Java program to demonstrate boolean primitive datatype
class GFG {
124
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
// 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;
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
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;
4. Integer:
It is a 32-bit signed integer.
Syntax:
int varName;
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;
6. Float:
A 32-bit floating-point data type with a single precision.
Syntax:
float varName;
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
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
8. Char:
• The char data type is a single 16-bit Unicode character.
Syntax:
char charVar;
Example:
// Java program to demonstrate primitive data types
class GFG {
public static void main(String args[]) {
// Creating and initializing custom character
char a = 'G';
short s = 56;
128
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
double d = 4.355453532;
Output:
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121
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);
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.
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
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++.
Exercise
Answer the following questions:
1. The Java interpreter is used for the execution of the source code.
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
6. What are the two parts in executing a Java program and their purposes?
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
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.
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.
Examples:
float simpleInterest;
// Declaring float variable
133
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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 {
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 {
// 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";
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.
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 {
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 {
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 {
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 {
Output:
8
141
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
63
55
-59
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
143
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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
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
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];
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
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.";
}
}
[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
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.
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];
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
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".
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.
152
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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.
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.
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.
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:
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".
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
Also, declaration, creation, and initialization can all be done in a single line as follows.
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.
156
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
• 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.
158
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
159
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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.
160
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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.
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
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.
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.
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
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]();
}
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
[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);
[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]);
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
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++;
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++;
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;
168
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
Output:
Condition is true.
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
Example:
// Java program to illustrate automatic type conversion
class GFG {
169
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
double numberDouble;
long numberLong;
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.
Example:
// Java program to discuss explicit type conversion
class GFG {
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.
Example:
class GFG {
[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
Example:
// Java program to illustrate the use of explicit type casting in expressions
class GFG {
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
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
175
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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
176
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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
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
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
Syntax:
178
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 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:
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
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
182
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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
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
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.
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
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
}
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
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) {
Output:
Printing the content of the names array:
Java
C
C++
Python
JavaScript
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
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
Syntax:
do {
//block of statements
} while (condition);
The flow chart of the do-while loop is given in the following image.
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
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
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
192
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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
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
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");
}
}
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.
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
• 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.
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
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.
// 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
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");
}
}
//method calling
findEvenOdd(num);
}
}
198
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
Example:
class GFG {
//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
199
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
Example:
class GFG {
// static method
static void show() {
[Link]("It is an example of static method.");
}
Output:
It is an example of a static method.
Example:
class InstanceMethodExample {
200
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
Output:
The sum is: 25
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,
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,
201
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
[Link] = roll;
}
Example:
class Student {
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
Syntax:
abstract void methodName(args);
Example:
abstract class Demo { //abstract class
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");
}
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
204
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
5. Choose the correct identifier as per the naming convention used in Java.
a) 1show b) $hide
c) *show$ d) 3_click
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;
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.
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
// Main class
class GFG
{
Output: Author
207
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
// Main class
class GFG {
// 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
// Catch block 2
// Handling InstantiationException
catch (InstantiationException e) {
[Link]();
}
// Catch block 2
// Handling IllegalAccessException
catch (IllegalAccessException e) {
[Link]();
}
}
}
Output: Author
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]();
}
// Method 2
// main driver method
public static void main(String[] args)
{
GFG obj1 = new GFG();
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
// 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;
}
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]();
Output: Author
Example:
// Java program to illustrate creation of Object
// using newInstance() method of Constructor class
// Main class
212
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
class GFG
{
// Method 1
// To set name ofthe string
public void setName(String name)
{
// This method refers to current object itself
[Link] = name;
}
GFG r = [Link]();
// Custom passing
[Link]("Author");
[Link]([Link]);
}
213
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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.
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 {
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.
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;
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;
218
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
Output:
111 - Raju
222 - Aryan
Example:
//Java program to overload constructors
class Student {
int id;
String name;
int age;
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
[Link]();
[Link]();
}
}
Output:
111 - Raju - 0
222 - Aryan - 25
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;
220
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
void display() {
[Link](id + " - " + name);
}
[Link]();
[Link]();
}
}
Output:
111 - Raju
111 - Raju
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);
}
[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
Example:
// Java program to create an object using the new keyword
class GFG {
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
void TestingConstructor() {
[Link]("A1");
}
TestingConstructor() {
[Link]("A2");
}
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.
Constructor2(int count) {
[Link]("Count=" + count);
}
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) {
//
}
225
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
Example:
// Java program to create an object using the newInstance() method
class GFG {
226
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
Output:
Raju
Example:
// Java program to create an object using the clone() method
// Method 1
@Override
protected Object clone() throws CloneNotSupportedException {
// Super() keyword refers to parent class
return [Link]();
}
// 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
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.
Example:
// Java program to illustrate Serializing an Object
228
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
import [Link].*;
// Member variables
private String name;
GFG(String name) {
// This keyword refers to current object itself
[Link] = name;
}
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
Example:
// Java program to illustrate creation of Object
// using newInstance() method of Constructor class
// Importing required classes from [Link] package
import [Link].*;
class GFG {
// Method 1
// To set name of the string
public void setName(String name) {
// This method refers to current object itself
[Link] = name;
}
// 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
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
class Student {
int id;
String name;
void showInfo() {
[Link]("Id: " + [Link] + " Name: " + [Link]);
}
}
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).
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
A) No output
B) Implemented move() method.
C) Compiler error
D) None of the above
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
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
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.
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.
238
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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];
239
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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;
240
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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!
For example −
241
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
....\vehicle\[Link]
Now, the qualified class name and pathname would be as follows −
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 −
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
.\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.
243
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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*;
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
244
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
245
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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 {
246
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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 {
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
249
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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.
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")
250
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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.
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.
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
[Link](even);
253
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
}
}
Output:
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.
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.
255
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
• No Parameter Syntax:
() -> {
//Body of no parameter lambda
}
Example:
//Program for Java Lambda expression event listener
import [Link];
import [Link];
import [Link];
class GFG {
256
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
[Link]("hello swing");
});
Output:
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.
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.
Default Methods in the Java Programming Language are supported by the byte code instructions for
method invocation.
261
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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 {
262
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
Output:
1
1
Peers
263
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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
// 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
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
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()
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.
266
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
The JDBC API is rich in features, lightning fast, and completely reliable. The diagram below illustrates
the architecture of JDBC.
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
267
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
268
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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.
void show() {
[Link]("Welcome to the world");
}
269
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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
// abstract method
public abstract void getStudentDetails();
}
270
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
// main() method
public static void main(String args[]) {
Output:
Sample method invocation for Student with details:
Roll No.:- 1001
Name:- Pup
Age:- 35
271
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
Execution:
c:\> javac [Link]
c:\> appletviewer [Link]
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.
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.
273
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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.
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 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
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
280
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
281
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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
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
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
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
[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.
The [Link] package contains many interfaces and classes for junit testing such as Assert, Test, Before,
After etc.
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.
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;
}
}
@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.
288
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
while([Link]()){
StringBuilder sb=new StringBuilder();
[Link]([Link]());
[Link]();
[Link](sb);
[Link](" ");
}
return [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];
@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
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
4. Which of the following classes can catch all exceptions which cannot be caught?
a) Runtime Exception b) Error
c) Exception d) Parent Exception
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
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
293
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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
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;
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;
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.
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.
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
import [Link].*;
public class Main {
static List&lt;String&gt; list = new ArrayList&lt;String&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.
300
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
Output
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.
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.
Output
import [Link];
import [Link].*;
public class Main {
public static void main(String[] args) {
ArrayList&lt;Integer&gt; A_list = new ArrayList&lt;&gt;();
//add elements to the ArrayList
A_list.add(10);
A_list.add(20);
A_list.add(30);
Iterator&lt;Integer&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
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.
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&lt;10) //value is valid if &gt; 10 else throw exception
throw new InvalidValueException("Invalid value");
else
[Link]("This is valid integer");
}
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
4. Which of these class is related to all the exceptions that are explicitly thrown?
a) Error b) Exception
c) Throwable d) Throwv
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
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
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.
310
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
{
// ...
}
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
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
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.
For instance,
315
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
316
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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.
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.
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
3. Click the Run button near the main method. From the menu, select Debug.
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.
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];
2. Click the Run button near the main method. . From the menu, select Run.
322
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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.
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.
324
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Software Programmer
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
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_Where_I_Have_Kept_My_Source_Code
ᴑ myJavaProgram folder
• Source folder
327
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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:
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
329
Training content licensed to Gurusharan Singh, issued on 03-01-2025, edition 2025 by FutureSkills Prime
Participant Handbook
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
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
[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
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
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 .