Java LectureNotes BasicsOfComputerProgramming
Java LectureNotes BasicsOfComputerProgramming
Contents
1 Computer Program 6
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2 Computer programming 14
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1
HaQT Fundamental Programming with Java
3 Learn To Code 34
2
HaQT Fundamental Programming with Java
3.2.8 Advice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
4 Algorithm 40
5 Programming Paradigm 48
5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
3
HaQT Fundamental Programming with Java
6 Procedural Programming 60
4
HaQT Fundamental Programming with Java
7 Program Compilation 71
5
HaQT Fundamental Programming with Java
1 Computer Program
1.1 Introduction
The computer program is essentially a set of instructions which directs the computer
system to perform user specified tasks. The computer program is an essential component
of the computer system.
The computer program is also alternately referred to as software application. The com-
puter programs are generally written using any human readable high level programming
language.
The high level programming language offers a human friendly interface to write the pro-
gram code. This high level code cannot be directly executed by the computer system.
However, the high level program code first needs to be converted into machine code in-
struction in binary that computer can execute and perform user specified operations.
Computer program
The computer system is an digital electronic device that can be used to perform some
meaningful work such data processing, calculations, data storage and other such user
specified work.
6
HaQT Fundamental Programming with Java
However, the computer system needs to be programmed to perform any meaningful work.
The computer system consist of two essential components which includes hardware and
software components.
The software components are computer programs which consist of set of instructions that
directs the computer system hardware components to perform the desired operations. This
set of instructions which directs the computer system is called computer program.
The computer system interprets these program instructions and then performs the desired
operations by executing the program instructions one by one.
As per the computer system architecture, the computer programs can be broadly grouped
into two categories.
– System Programs
– Application Programs
7
HaQT Fundamental Programming with Java
In computer system architecture, the System Software is a program used by the operating
system to communicate with the hardware component.
Each hardware component needs a system software that allows the operating system to
communicate with that hardware component or device and perform the desired operation.
The system software functions as an interface between the operating system and the hard-
ware components part of the computer system. The OS communicates and drives the
hardware components through system software components.
And therefore, whenever a device is connected to the computer system either internally
or externally essentially needs a system software (commonly referred as device driver) to
perform various user specified operations.
The system software components are designed to operate, control and extend the process-
ing capabilities of the computer system and the other hardware devices connected to the
computer system.
The system software is also designed and developed by the computer manufacturer to
8
HaQT Fundamental Programming with Java
communicate with specific hardware components connected to the computer system such
as camera, printer, scanner and other such devices.
Application software
The application programs (software) are designed to provide the user friendly interface to
the computer user to perform various tasks on the computer system.
For example, we generally use Microsoft word program for creating document, Power point
for making presentation and Excel Spreadsheet program for creating the spreadsheets.
The application program is written in high level programming language such as C language,
Java, C++, Python or any other high level programming language.
However, the high level program needs to be converted to machine code instructions in
binary and this conversion is referred as program compilation.
The compiled programs in the form of executable file (e.g, exe file) can be directly executed
by the computer system.
The application software is a term used for the program created for a specific purpose
that provides specific functionality to the user. The application software can be a single
9
HaQT Fundamental Programming with Java
The application software also commonly referred as application or simply an app. All the
programs used in a computer other than system software are referred to as application
software.
The programming languages are generally classified as high and low level language. The
higher level programming languages are more human readable and the lower level pro-
gramming languages are machine readable. However, the computer system can execute
only low level programs in machine code in binary.
The computer programming languages are classified on the basis of ease of readability of
the language, program execution speed and the level of abstraction in the programming
language.
The computer programs are generally written in higher level programming languages such
as Java, C++, Python which provides a high degree of abstraction and mask the com-
plexity of the low level programming language such as assembly language.
10
HaQT Fundamental Programming with Java
The computer programs written in high level programming language must be first con-
verted to machine code in binary. The microprocessor can decode and execute only pro-
gram instructions in binary.
And therefore, the high level computer program is converted to binary code by using a
special system program called compiler. This conversion process is referred as program
compilation.
The program compilation is a process in which a human readable program code written in
a any programming language (C, C++, Java, Python) is converted to a machine readable
code in binary (using only 0’s and 1’s).
The compiler only converts the program source code in to the object code (binary code).
The object code cannot be directly executed by the operating system.
The object code file further needs to be processed by another program called ”linker”.
The linker (type of system software) which is built into the compiler itself.
11
HaQT Fundamental Programming with Java
The compiler may produce number of object code files for a single program source code
file. The object code consist of machine code instructions in binary which is equivalent of
corresponding high level program instructions in program source file.
And therefore, the linking is required to link all object code files and other files together
to create an ”executable” file. The executable code can be directly executed by the CPU.
Interpreter Compilation
The programming languages can be broadly categorized into either interpreted or compiled
language. In case of compiled language, the compiler accepts the program code and
converts into machine code in binary.
For example, the C language compiler converts the entire source code into machine readable
executable code. This executable code can be directly executed by the computer.
Whereas, in the case of interpreted language, the interpreter converts the source code into
intermediate code line by line.
The interpreter first converts the program statement into an intermediate code. Another
system program then converts this code into native machine code. And therefore, the
execution process is relatively slower in case of interpreted language.
12
HaQT Fundamental Programming with Java
For example, the Java program compiler converts the program source code into an inter-
mediate byte code which is platform independent. And the Java virtual machine (JVM)
then converts this intermediate byte code into native machine code.
The computer user initiates the program execution by instructing the operating system
to start the program execution. The operating system then loads the executable program
into the main system memory RAM.
The microprocessor (CPU - Center Processing Unit) is the brain of the computer system
and performs all the arithmetic calculations and logical operations.
The CPU provides the processing power to the computer system and executes the program.
The processor (CPU) initiates the program execution by fetching the program instructions
from main memory one by one.
The CPU makes use of its internal high speed memory registers and cache memory to
optimize the processor execution speed.
The CPU decodes the program instructions and performs then operates on the program
data as per the program instructions.
13
HaQT Fundamental Programming with Java
2 Computer programming
2.1 Introduction
A computer program can be written in any programming language depending upon the
purpose and type of the software being developed.
Computer programming can be defined as the art and science of creating a set of instruc-
tions that computers can decode and execute to perform specific tasks. It involves writing
the code in specific manner, testing, and debugging code to solve specific problems.
At its core, programming is about translating human ideas and logic into a language that
computers understand that is binary. . Programmers use human readable programming
languages ( high level languages ) such as Python, Java, C++, and JavaScript to write code
as per the predefined rules , syntax, and within the limits of other acceptable constrains.
A computer system can also be defined as programmable electronics device that can be
programmed to accept some inputs in terms of data, then process this data as per the
program instructions and provide the output in the desired format that can be used for
some meaningful work.
The computer system must be first programmed to perform a specific job on the computer.
Further, the computer is a digital electronic machine.
That means, the computer can understand and execute instructions on in binary which
consist of only two numbers that is 0 and 1.
14
HaQT Fundamental Programming with Java
The computer programs are written to perform a specific task. For example, a computer
program (software) to play music in your computer or to play game and so on.
Each computer program usually consist of number of program statements. Each program
statement performs a part of the job. The programmer must write the program statements
as the programming language syntax.
15
HaQT Fundamental Programming with Java
Computer program
These programming languages are typically like English language that allows humans to
communicate easily with computers. Such programs are referred as high-level program.
However, as we know computer understands only Binary instructions. Therefore, high
level programs must be converted to low level binary machine code at the execution stage.
In essence, computer programming is the art and science of writing instructions for com-
puters to perform useful tasks. It plays a crucial role in nearly every aspect of modern
science, technology and software development. Programmers use their skills to create
software applications, websites, databases, artificial intelligence systems, and much more.
Each programming language has its own syntax (set of rules) which clearly defines the
manner in which the computer program statements can be constructed.
The programmer can choose any programming language of his choice depending upon the
type of the software application to be developed.
16
HaQT Fundamental Programming with Java
Programming languages provide a set of rules and syntax that programmers use to write
code. There are numerous programming languages available, each with its own strengths
and areas of application. Some popular programming languages include Python, Java,
C++, JavaScript, and Ruby.
Once the programming language is chosen, programmers write code by following the syntax
and rules of that language. They use various tools and Integrated Development Environ-
ments (IDEs) to write, edit, and debug their code. The code consists of instructions that
tell the computer what operations to perform, such as calculations, data manipulation, or
interacting with external devices.
After writing the code, programmers need to test and debug it to ensure that it behaves
17
HaQT Fundamental Programming with Java
as expected and produces the desired output. They identify and fix any errors or bugs
that may cause the program to malfunction. Testing and debugging are essential steps in
the programming process to ensure the reliability and correctness of the program.
Computer programming is a creative and iterative process that often requires problem-
solving skills, logical thinking, and attention to detail. It offers a wide range of career
opportunities, from software development to data analysis, artificial intelligence, and web
development.
Learning computer programming opens up doors to creating your own software appli-
cations, automating repetitive tasks, and understanding the underlying technology that
drives the digital world. It is a skill that empowers individuals to bring their ideas to life
and contribute to the advancement of technology.
18
HaQT Fundamental Programming with Java
Algorithm Development: Problem that needs solution is broken into set of smaller
problems. Programmers often create algorithms, which are step-by-step procedures for
solving a problem. Algorithms serve as the blueprint for writing code.
Debugging And Testing: Once the program or software is created the next stage is
debugging and testing. Programming stage also involves debugging and testing code to
ensure it works correctly. Debugging is the process of finding and fixing errors or ”bugs”
in the code. The end result is software that is ready for deployment.
19
HaQT Fundamental Programming with Java
The computer system only understands and can execute program statements in machine
code which is in binary consisting of only two digits, that is 0 (zero) and 1 (one).
The Central Processing Unit (CPU) is the system brains. The CPU can decode and
execute only program instructions in binary.
And therefore, the computer programs written in any high level programming language
must be first converted into machine code in binary.
The program execution starts when the user gives the command to the operating system
to run any program.
The operating system then initiates the program execution by allocating the necessary
resources such as memory and the processor time.
20
HaQT Fundamental Programming with Java
The operating system then loads the program executable copy and its data into the main
system memory RAM.
The Central Processing Unit (CPU) starts the program execution by fetching the program
instructions and data from the main memory RAM.
The CPU operates on the data as per the program instruction and the processed data
(result) is then either sent to a output device such as display monitor Or could be stored
into any permanent storage (secondary storage) device such as hard disk for future use.
The programming languages are generally classified as high and low level language. The
higher level programming languages are more human readable and the lower level pro-
gramming languages are machine readable. However, the computer system can execute
only low level programs in machine code in Binary.
The computer programming languages are classified on the basis of ease of readability of
the language, program execution speed and the level of abstraction in the programming
language.
21
HaQT Fundamental Programming with Java
The computer programs are generally written in higher level programming languages such
as Java, C++, Python which provides a high degree of abstraction and mask the com-
plexity of the low level programming language such as assembly language.
The high level programming languages are more human readable whereas the low level
programming languages provide least abstraction.
And therefore, it is relatively far more difficult to read and write the program in low level
language such as assembly language.
The program execution speed is higher for the programs written in low level language
whereas the programs written in high level language have relatively lower execution speed.
Depending upon the type of programming language, a computer program can either be
compiled or interpreted during its execution. Compiler and Interpreter are two different
ways to execute a program code.
22
HaQT Fundamental Programming with Java
During the compilation process, a compiler takes the entire program code and converts
it into object code which is typically stored in a file. The object code contains library
references which is replaced by actual binary code by the linker.
The binary code after linking the object code can be directly executed by the computer
system. Examples of compiled programming languages are C and C++.
Interpreter Compilation
Whereas an Interpreter directly executes instructions line by line written either in a pro-
gramming language or scripting language without any prior converting them to an object
code or machine code.
The Python is an examples of interpreted language. Similarly, the Java program is first
compiled to an intermediate byte code, which is then executed by the Java Virtual Machine
(JVM).
23
HaQT Fundamental Programming with Java
System software
The system software is a collection of programs provide interface to interact with computer
hardware. The system programs are designed to operate, control and extend the processing
capabilities of the computer system itself.
The system software programs are usually designed and developed by the computer man-
ufacturer to communicate with specific hardware components connected to the computer
system such as device driver software necessary to connect that hardware to the computer
system.
24
HaQT Fundamental Programming with Java
An Operating System (OS) is an essential component for all computer systems. The oper-
ating system provide an interface to the user to communicate with the system hardware.
The operating system is the most commonly used example of system software. The operat-
ing system manages all the application programs and the hardware components attached
to the computer system.
The operating system makes use of some system software called as utility software which
allows the user to manage the computer system.
There are many different utility programs for different purpose and they may vary across
operating systems. These utility software can be accessed by the user via a special menu
or control panel in the operating system.
The application programs are developed to provide solution to specific user problem. The
application programs are also referred as application software or simply an application.
The application programs provide an interface to the user for using the computer system
for specific purpose.
For example, the user might work on the accounting software for accounting jobs. The
most commonly used application software are Microsoft Word, Excel and PowerPoint.
25
HaQT Fundamental Programming with Java
The application software provide a very user friendly graphical interface to get the specific
job done for which that application software has been designed.
Compilation process
Each computer system has a CPU which is the brain of the system. The CPU is responsible
to decode and execute the program.
The CPU is the main component which performs arithmetic calculations and logical op-
erations.
However, the CPU can understand and execute program instructions only in machine code
which is binary representation consisting of 0 (zero) and 1 (one).
All computer programs must be first converted (either compiled or interpreted) to machine
code before it can be executed by the computer.
26
HaQT Fundamental Programming with Java
This program conversion to binary code is done by using a special program called either
compiler or interpreter depending upon the type of the programming language.
The compiler only converts the program source code in to the Object code (binary code).
The object code cannot be directly executed by the operating system.
The Object code file needs to be further processed by another program called ”Linker”
which is built in to the compiler.
The compiler may produce number of object code files for a single program source code
file. The object code consist of machine code instructions in binary which is equivalent of
corresponding high level program instructions in program source file.
And therefore, linking is needed to link all object code files and other files together to
create an ”executable” file.
The programmer can use these user defined functions and standard function libraries by
simply including these files in the beginning of the program header section.
27
HaQT Fundamental Programming with Java
Since the standard library code is in the object code form which is a pre-compiled format
and can be directly included in the linking stage by the linker while creating an executable
file ([Link]) during the program compilation process.
The programmer can use these user defined functions and standard function libraries by
simply including these files in the beginning of the program header section.
Since the standard library code is in the object code form which is a pre-compiled format
and can be directly included in the linking stage by the linker while creating an executable
file ([Link]) during the program compilation process.
During final stage of compilation process, whenever the linker finds a reference to a library
routine in the object file, it reads the library files, then finds that routine and replaces the
programmer’s reference with the actual code for the routine from the library file.
After it has replaced all the references with actual code from the library files, the linker
then creates an executable binary file which can be executed by the operating system
(OS).
28
HaQT Fundamental Programming with Java
29
HaQT Fundamental Programming with Java
The programming languages can also differ on the basis on organizing the program code
and manner in which data is handled in the program. The programming paradigm defines
a particular style of writing and organizing the program code.
There are many programming paradigms out of which the two most important program-
ming paradigms are the procedural paradigm and the Object-Oriented paradigm (OOP).
Each of these procedures provide solution to part of the problem. These procedures can
be called many times depending upon the algorithm of the program to solve a particular
problem.
The procedural programming languages are generally the first preferred choice for students
to learn the computer programming. Some of the most popular procedural languages
include C, Fortran, Pascal and Basic.
Procedural programming
30
HaQT Fundamental Programming with Java
As the name suggest, in this approach, a group of program statements is written to solve
one task and declared as a procedure.
The program consist of the main function or program block, subroutines, functions, pro-
cedures, header files, includes modules, libraries. During the program execution, the a
procedure may be invoked number of times.
In procedural programming the data (program variables) are mostly global and accessible
to all the functions. For a large programs it is very difficult to keep the track of the changes
in the data being operated upon by many functions simultaneously.
Such changes in the data can adversely affect the functionality of other functions. Similarly,
when the new data is added all the functions operating on that data also need to be
modified accordingly.
The most serious limitation of the procedural programming is the tendency for large
procedural-based programs to turn into ”spaghetti-code” since the data access is not con-
trolled and might get accidentally changed by other functions.
The spaghetti code is functionally useless program code. It is very difficult to debug the
spaghetti program code.
And therefore, programmer should follow the standard best coding practices to avoid
program resulting in to such badly tangled spaghetti code.
Structured programs makes extensive use of the program control structures such as se-
quence, decision / selection and repetitions like loops.
31
HaQT Fundamental Programming with Java
Structured programming
The structured programming is a programming paradigm that helps to improve the clar-
ity, quality, and development time of a computer program by making extensive use of
procedures, block structures and looping structures like for loop, do while loop and while
loop.
32
HaQT Fundamental Programming with Java
ment where all application components are treated as objects. An object is a component
of a program that has its own data and methods.
An object knows how to perform certain actions and how to interact with other elements
of the program. Objects are the basic units of object-oriented programming.
A class is a design time entity used to define the object. Whereas an object is a runtime
entity created during the program execution.
A class is the blueprint, or a plan, or a template, that describes the details of an object.
A class is the blueprint from which the individual objects are created.
The programs once developed and operational continues to be in use for a considerable
period of time even if the support is discontinued. Such code is referred as legacy code.
The legacy code needs to be supported, either to be improved upon (for a new version of
an exist piece of software) or made to work with newer computers and software.
A career in computer programming can be very rewarding and completely worth the time,
efforts and patience which you need to invert while learning the computer programming.
Some people initially find learning computer programming a bit scary and tedious. How-
ever, once you learn your the first language than learning the second programming will be
much easier.
With the help of best learning practices, you can easily learn the computer programming
without much difficulty. If you follow the right learning strategy then you can learn any
programming language without any problem.
33
HaQT Fundamental Programming with Java
3 Learn To Code
Learn to code easily and quickly with the right learning strategy, step by step learning
methodology and using right study material.
A coding is all about writing a computer program to solve a specific problem. The pro-
grammers develop software applications using many programming languages.
Depending upon the type of application to be developed, programmer can decide which
language would be more suitable to code.
A career in computer programming can be very rewarding and completely worth the time,
efforts and the patience, which you need to invest, while learning the programming.
Some people might initially find learning computer programming a bit scary and tedious.
But every programmer has to go through this learning curve and must overcome the
temptation to give up.
However, if you want be financially enough rewarded and want to be a part of industry
that is going to rule every other industry, then you need to be mentally prepared and
commit yourself to take this to the logical end.
If you have the right learning strategy in place and follow the best learning practices, then
you can easily learn the computer programming without much difficulty. Now, let us start
34
HaQT Fundamental Programming with Java
If you aspire to work with top notch companies, then you need to first earn a professional
degree. Many potential employer prefer students with four year degreecourse (graduation).
However, bulk of the jobs in computer science and programming are available in midsize,
small IT companies and also in start-up companies.
In these midsize companies, there is increasing acceptance to three year diploma courses
or two year courses especially from community college primarily due to a major gap in the
demand and supply of qualified professionals.
Most of the universities across the world have already started offering online courses in
computer science, computer engineering and software engineering.
With the advent of e-learning (online courses), you can now access these courses offered
by some of the most reputed and best universities.
The online courses are great option especially for those people who are interested in shifting
their career from other industries such as other branches of engineering, science or other
streams.
The computer programming is just a one part of over all fields of computer science. It is
advisable for a student to first acquire a foundation knowledge in computer science and
programming.
35
HaQT Fundamental Programming with Java
The computer subjects including programming is full of technical jargon. The familiarity
with this technical terms and concepts can be a big comfort factor for a beginner. Most
programming courses assume and these topics are not part of programming language
courses.
The students are expected to be aware of this fundamental knowledge before directly jump
into programming.
For example, a students need to be aware of some of the fundamental concepts in computer
science. These CS fundamental concepts include:
And there are many more such important topics which will help the student to improve
his overall understanding of the subject. This foundation knowledge in computer science
and programming will also offers an excellent starting point for absolute beginner.
36
HaQT Fundamental Programming with Java
You may come across many articles which suggest focus on only practical knowledge
but such approach will seriously limit your understanding of the subject. Many student
struggle simply because of this approach.
It is important to first understand the best programming practices rather than later on
learning the hard way. There is no short cut available if you wish to build your program-
ming skills.
It is equally important to have a solid understanding and knowledge of both the theoretical
concepts and the practical side of the programming.
There are many tools available for programmers to write the program code. These tools are
referred as Integrated Development Environment (IDE) which offers a bundle of programs
which makes the programmers life much easier.
Some of the most popular and commonly used IDE includes NetBeans, eClipse, CLion
and IntelliJ.
However, despite the availability these tools, it is important to learn and practice the best
coding practices. A smallest mistake in program code might flash ten lines of error report.
In case of large programs, debugging is difficult and time consuming.
If you are an absolute beginner, then it is advisable to start with simple procedural pro-
gramming language such as C language.
The C language still continues to be the preferred choice as a starting point for many
students due to its simplicity and straight forwardness nature of the C language.
Most students prefer learning the C language first and then move on to the object-oriented
programming language such as C++ or Java.
Learning the procedural language such as C language gives a fairly good exposure to
37
HaQT Fundamental Programming with Java
language structure which includes, concept of variable, different data types, concept of
functions, function calls, various loops, pointers and the language syntax.
Both Python and JavaScript are also considered to be a good options for budding pro-
grammers as a first programming language.
In case case of JavaScript it is much easier to create a User Interface (UI). The UI will
be an essential feature of your project portfolio that you can showcase to your potential
employer.
However the choice of first programming language really depends on your personal pref-
erences.
IDEs
As a computer programmer, you have options either to start coding in a simple text editor
or use a fully automated programming tool such as Integrated Development Environment
(commonly referred as IDE).
If you choose any IDE tool to start coding your program then you will have all the tools
available such as compiler, debugger, automatic language syntax correction in a single
package. But IDE may not be the best option for an absolute beginner.
Let me explain this with an example. If you wish to learn car driving and if you start
learning on fully automatic car then you will not be able to learn how to change gears,
38
HaQT Fundamental Programming with Java
clutch judgement while changing the gears because these functions are automated.
And therefore it is good practice for beginners to start writing program on a simple text
editor such as Notepad or Notepad++.
In these simple text editors you might initially commit few mistakes but debugging pro-
gram is also an essential part of the experience which every programmer must be prepared
to handle.
Later on all programmers will have to start using IDE once you develop sufficient expertise
in writing the code.
The working on a project will also help you understand how to logically proceed step by
step in a software development project. If you wish to learn swimming then, you got to
jump into the tank.
39
HaQT Fundamental Programming with Java
3.2.8 Advice
Once you learn the first programming language properly, then learning another program-
ming language is relatively going to be much easier.
The Object-Oriented Programming language has relatively steeper learning curve as com-
pared to procedural language.
And therefore, you may start with simple programming language which you can easily
learn and then move on to any Object-Oriented Programming language.
4 Algorithm
An algorithm is a well-defined set of steps that can be followed to solve a particular problem
or perform a specific task. Algorithms are used in many fields, including computer science,
mathematics, and engineering.
In computer science, algorithms are used to develop software and computer programs, and
to solve various problems related to computation. Algorithms are step-by-step procedures
for solving problems, performing computations, or carrying out tasks.
They are used in a wide range of applications, from computer science and engineering to
finance, biology, and many other fields.
40
HaQT Fundamental Programming with Java
What is an algorithm?
There are many different types of algorithms, including sorting algorithms, search algo-
rithms, encryption algorithms, and compression algorithms. Each type of algorithm is
designed to solve a specific problem or perform a specific task.
To analyse algorithms, computer scientists use various measures, including time complexity
and space complexity. Time complexity refers to how long it takes an algorithm to run,
and space complexity refers to how much memory an algorithm requires to run.
Designing and analysing algorithms is an important part of computer science and related
fields. Researchers and practitioners in these fields seek to develop algorithms that are
efficient, accurate, and reliable, and that can handle large volumes of data and complex
problems.
Algorithms are a fundamental part of computer science and play a critical role in devel-
oping software and solving computational problems.
41
HaQT Fundamental Programming with Java
In computer science, algorithms are used to develop software programs and solve various
computational problems. For example, a search algorithm might be used to find a specific
piece of information in a large database, while a sorting algorithm might be used to arrange
a list of items in a specific order.
Algorithms can be classified into many different categories, including sorting algorithms,
searching algorithms, graph algorithms, and optimization algorithms. Each type of algo-
rithm is designed to solve a specific problem or perform a specific task.
Algorithm and computer programming are closely related concepts. Algorithms are the
step-by-step procedures used to solve a problem or perform a task, while computer pro-
gramming involves writing code in a programming language to implement an algorithm
and make it executable by a computer.
When developing a computer program, the first step is to design an algorithm that solves
the problem at hand. The algorithm may be designed using pseudocode, a structured lan-
42
HaQT Fundamental Programming with Java
guage that resembles code but is not tied to any specific programming language. Once the
algorithm is designed, it can be translated into code in a specific programming language,
such as Java, Python, or C++.
The programming language provides the syntax and structure necessary to implement the
algorithm in a way that can be executed by a computer. Programmers use variables, data
structures, conditional statements, loops, and other programming constructs to implement
the algorithm and create a working program.
Good programming practices involve writing clear, efficient, and maintainable code that
implements the algorithm correctly and handles errors and exceptions gracefully. Effective
algorithms and well-written programs are essential for creating software applications that
are reliable, scalable, and easy to use.
Introduction to algorithms.
Algorithms are an essential tool for solving complex problems and making sense of large
amounts of data. They play a critical role in many areas of modern life, from business and
finance to scientific research and engineering.
1. Efficiency: Good algorithms can solve problems quickly and efficiently. This is
particularly important in fields such as computer science and engineering, where
large amounts of data must be processed and analysed in a timely manner.
2. Scalability: Algorithms that are designed to handle large data sets and complex
problems are essential in today’s world, where the amount of data being generated is
increasing exponentially.
43
HaQT Fundamental Programming with Java
Characteristics of algorithm.
44
HaQT Fundamental Programming with Java
4. Finite: An algorithm must terminate after a finite number of steps. This means that
the algorithm must have a stopping condition, so it does not run forever.
5. Correctness: An algorithm must produce the correct output for every possible
input. The algorithm must be designed to handle all possible input values.
6. Efficiency: An algorithm must be efficient, which means that it should use the
minimum amount of time and resources necessary to produce the desired output.
7. Generality: An algorithm must be general, which means that it should be applicable
to a wide range of input data and not be specific to a particular data set or problem.
8. Reusability: An algorithm should be designed in such a way that it can be reused
in different contexts and for different applications.
These characteristics ensure that an algorithm is a reliable and effective solution for a prob-
lem. By possessing these characteristics, an algorithm can be implemented and executed
on a computer system to solve complex computational problems.
45
HaQT Fundamental Programming with Java
Algorithms are critical to solving complex problems and making sense of large amounts
of data in a wide range of applications. Algorithms have a wide range of applications in
various fields, some of which are as follows:
Each type of algorithm has its strengths and weaknesses, and the choice of algorithm will
depend on the specific problem at hand and the resources available. There are several
types of algorithms, as follows:
1. Searching Algorithms: These algorithms are used to search for a specific value in
a collection of data. Examples include linear search and binary search.
2. Sorting Algorithms: These algorithms are used to sort data in a specific order,
such as in ascending or descending order. Examples include bubble sort, quicksort,
and merge sort.
46
HaQT Fundamental Programming with Java
3. Graph Algorithms: These algorithms are used to traverse graphs and find paths
between nodes. Examples include breadth-first search and depth-first search.
4. Divide And Conquer Algorithms: These algorithms break down a problem into
smaller sub-problems and solve each sub-problem independently. Examples include
merge sort and binary search.
5. Greedy Algorithms: These algorithms make decisions based on the current best
option, without considering the long-term consequences. Examples include the knap-
sack problem and minimum spanning tree.
6. Dynamic Programming Algorithms: These algorithms solve complex problems
by breaking them down into smaller sub-problems and storing solutions to those
sub-problems. Examples include the Fibonacci sequence and the longest common
subsequence problem.
7. Backtracking Algorithms: These algorithms explore all possible solutions to a
problem by generating a tree of possibilities and backtracking when a solution is not
found. Examples include the N-Queens problem and the subset sum problem.
8. Randomized Algorithms: These algorithms use a random element to solve a prob-
lem, such as generating a random solution and evaluating its effectiveness. Examples
include randomized quicksort and Monte Carlo algorithms.
Types of algorithms
47
HaQT Fundamental Programming with Java
5 Programming Paradigm
5.1 Introduction
Programming paradigms
The programming paradigm is all about the writing style and organizing the program code
in a specific way. Each paradigm advocates a specific way to organize the program code.
A programming language is essentially a problem solving tool. For each problem there
can be many solutions. Further, each solution can adopt a different approach in providing
solution to the problem.
The computer programs are written using different programming languages. Each pro-
gramming language has unique programming style that implements a specific programming
paradigm.
For example, the C language follows procedural programming paradigm. Whereas the
C++, Python and Java are said to be Object-Oriented Programming (OOP) paradigm.
Each programming paradigm advocates a set of principles and rules that the programming
48
HaQT Fundamental Programming with Java
Programming languages
The word paradigm derives from Greek and Latin. It simply means pattern, model pro-
gramming paradigm or a set of rules that defines a standard.
However, in the context of programming languages, the term paradigm means set of design
principles that defines the program structure.
The programming paradigm is all about how me model and organize the program code.
For example, the OOP paradigm represents everything in the form of objects. Whereas,
the function programming represents the program as set of functions.
A computer software is developed keeping in mind a specific problem and provides solution
to that specific problem.
For example, Microsoft Office word has been developed to provide solution to the user
for creating different types of documents. Similarly, there are software for airline ticket
reservation, stock market analysis, hospital management and so on.
49
HaQT Fundamental Programming with Java
And therefore, a computer program can be developed using different programming lan-
guages that belong to different paradigms. Each approach to the solution will have some
merits and demerits.
Programming approaches
In other words, the programming paradigm is all about different approaches used to find
a software solution to the problem. Each solution to the problem has its own advantages
and disadvantages.
Some programming languages that clearly belong to a specific paradigm. However, there
are programming languages that do not fall under a one specific paradigm. Such languages
might allow the program code that implements more than one paradigm.
The programming paradigm is defined as a set of principles, ideas, design concepts and
norms that defines the manner in which the program code is written and organized.
The programming paradigm does not specify the programming language syntax. The
50
HaQT Fundamental Programming with Java
paradigm simply defines the program structure and the set of principles that the program-
ming language compiler should enforce.
A programming paradigm is a framework that defines how the programmer can concep-
tualize and model complex problem to be solved.
The programming paradigms can be classified into two main types. The paradigm type
depends upon the programming language features and a particular style of organizing the
program code.
1. Imperative Paradigm
2. Declarative Paradigm
Imperative Programming
The imperative paradigm is said to be command driven. The program code in imperative
paradigm programming language directs the program execution as sequence of statements
executed one by one.
51
HaQT Fundamental Programming with Java
The imperative style program consist of set of program statements. Each statement directs
the computer to perform specific task.
In imperative style program, the programmer has to elaborate each statement in details.
Each statement directs what is to be done and how it is to be done.
The execution of the program statements is decided by the control flow statements. And
the program flow can be directed as per the program logic.
The imperative paradigm programming languages include Fortran, Algol, Pascal, Basic.
The declarative paradigm is a programming paradigm that is focused on the logic of the
program and the end result. In this paradigm that control flow is not the important
element of the program.
The main focus of the declarative style of programming is achieving the end result. This
paradigm is straight forward and to the point while writing the program code.
The declarative approach to the programming is pretty much straight forward that leads
to what is do be done.
Let us discuss one simple example that would highlight the fundamental difference in the
programming approach for imperative and declarative paradigm.
In this example, let us imagine that you have to invite your friend to your house. As per
the declarative style, you simply give him your address and let your friend figure out how
to reach your home.
As per the second imperative approach, instead of giving him simply address, you would
rather write down number of statements. Each statement would guide him step by step
to reach your place.
52
HaQT Fundamental Programming with Java
1. Structured Programming
2. Procedural Programming
1. Functional Programming
2. Logic Programming
Structured programming
The structured programming intends to optimize the code by using the program control
flow constructs, decision making (if, if then, else) constructs and the iteration constructs
(for, while loops), blocks and the functions.
53
HaQT Fundamental Programming with Java
The main intent of the structured programming approach is to improve the readability of
the code. This approach also facilitates the re-usability of the code.
The structured programming approach does not advocate the use of unconditional control
statements such as goto constructs. The use of goto constructs can result into a spaghetti
code that is difficult to debug.
In modular (structured) programming, the program code is optimized for readability and
re-usability by dividing the code into semi independent modules. These modules can be
called number of times as may be required.
1. Procedure-Oriented Programming
2. Object-Oriented Programming
54
HaQT Fundamental Programming with Java
The program based on procedural paradigm consist of set of procedures. The procedures
are also referred as function, method or subroutines.
The program structure in procedural programming consist of set of functions. Each per-
forms a specific operation.
The function consist of group of computational steps that directs the computer to perform
specific operation. The function once defined can be called many time in the program to
repeat the same operation.
The programmer can either use standard library functions or create library of user defined
functions.
The C programming language is the most commonly used and popular language that still
used in the software industry.
55
HaQT Fundamental Programming with Java
An object binds the data and associated methods together as single unit. As such the
programmer can control the data access permissions by defining the access specifier.
The OOP programming protects the program data from inadvertent operations by another
methods. And therefore, the object oriented programming offers robust security features.
The OOP paradigm compliant languages such as C++, Java and Python are extensively
used for enterprise level software projects.
The database query language such SQL (Structured Query Language) is the most com-
monly used example of model based language.
The database is vital component of most software projects. Most Relational Database
Management System (RDBMS) support the SQL for database programming.
The software application communicates with the RDBMS with the help of SQL commends.
The RDBMS in turn communicates with the database and executes the SQL commands
to perform the desired database operations.
The database query language is also alternately referred to as model based programming.
56
HaQT Fundamental Programming with Java
The functional programming comes under declarative paradigm. The declarative paradigm
focuses on what is to be solved. Whereas the imperative approach focuses on how it to be
solved.
As the name suggest, the functional programming is based on the mathematical functions.
The functional programming attempts to solve the problem by composing mathematical
functions as program components.
In functional programming style the computer program is created with the application
and composing the mathematical functions.
For example, let us consider one simple mathematical function, In this function - f (x) =
x + 2, the output will be the same.
57
HaQT Fundamental Programming with Java
The immutability is one of the most important feature of the functional programming.
– Var a = 100, the variable value will remain same for the life span of the variable.
– Var b = a + 10, even here the value of a remain the same.
The biggest advantage of the functional programming is that these programs can easily
run on the multi-core and multi-threaded environment.
In functional programming, the functions are treated as first class citizens. Let me explain
the meaning first class citizen in this context.
This simply means that the function can be passed as an argument in a function call
statement. Similarly, the function can also be returned as a value. Just similar to the
variable returned during the function call.
The logic programming is a declarative programming paradigm that is based on the logic
and the control. The term logic essentially means facts and rules. Whereas the control
means an order of rules.
The term Algorithm is defined as logic plus control (logic + Control). The logic defines
what should be solved whereas the control defines how it should be solved.
58
HaQT Fundamental Programming with Java
The main advantage of the logic programming is that the programmer needs to simply
define the what part of the problem. And the system finds the best solution to that
problem.
The program written in logic programming language consist of set of program statements
in the logical form. Each statement is an expression of facts , rules and the order of rules.
The logic programming is an abstract model of computation. It is based on the first order
predicate logic. The predicate logic is also referred to as first order logic.
The clauses are an important element of the logic programming. In other words, a logic
program is a set of clauses.
The prolog is an example of declarative paradigm rule based logic programming language.
The prolog program consist of set of program statements expressed in terms of facts, rules
and the control.
Logic Programming
59
HaQT Fundamental Programming with Java
6 Procedural Programming
The procedural programming aims at dividing the large program into smaller programs
called procedures. The procedures are also alternately referred to as subprograms, sub-
routines, methods or functions.
60
HaQT Fundamental Programming with Java
In procedural programming , the program data is in the form of variables. The functions
operate on the program data. Each function consist of computational statements and
solves a part of the problem.
The procedural programming continues to be the preferred choice for the beginners as a
first programming language. The C procedural language is extensively used in the industry
for the system programming. Despite the advent of other paradigms, the procedural
programming paradigm is still very popular and a part of the syllabus in most of the
educational institutes and universities.
61
HaQT Fundamental Programming with Java
As the name suggest, the procedural programming the program code is organized in the
form of procedures. These procedures are also called as subroutines or functions.
The function can access and operate upon its own local data as well as global data shared
by all the functions. In procedural programming, the function becomes the most important
component of the program and the functions have unrestricted access to the global data.
The procedural paradigm is one of the oldest and most widely used programming paradigms
in computer science. It focuses on a sequence of procedural calls or functions to perform
tasks, typically by breaking down a program into a series of computational steps. This
paradigm is foundational in the development of software and forms the basis for many
modern programming languages.
62
HaQT Fundamental Programming with Java
In this paradigm, the program statements are grouped together based on the functionality.
These group of statements can be named suitably as function as per the language syntax.
For example, we can group program statements that accepts two number as user input,
then add these numbers and return the result value.
Function declaration
Local and Global Variables: Procedural languages use variables to store data. Local
variables are declared within a function and can only be accessed within that function,
63
HaQT Fundamental Programming with Java
while global variables are declared outside all functions and can be accessed by any part
of the program.
Control Structures: The procedural paradigm uses control structures like loops (for,
while) and conditionals (if, else) to manage the flow of the program. These structures
enable the execution of different sections of code based on certain conditions.
Control Structures: The procedural paradigm uses control structures like loops (for,
while) and conditionals (if, else) to manage the flow of the program. These structures
enable the execution of different sections of code based on certain conditions.
Parameter Passing: Procedures often accept inputs known as parameters. These pa-
rameters allow functions to perform operations on different data inputs, increasing the
versatility and reusability of the code.
64
HaQT Fundamental Programming with Java
In procedural programming, when the program size is becomes large then the program
code is split into group of smaller programs called procedures or subroutines.
Each subroutine performs a specific task. For example, the programmer can write a
subroutine to add two or more numbers or subtract numbers. The subroutine or procedure
can be written to perform repetitive task in the program code as per the program logic.
This helps to eliminate the repetition of code.
The well organized procedural program code is relatively much easier to read and debug.
Such code is also easier to maintain. The program code in the procedural programming
is exacted sequentially using a top-down approach.
65
HaQT Fundamental Programming with Java
The procedural programming paradigm has some important features. These features define
the program organization, program execution sequence and the scope of the variables.
The top down approach defines the execution sequence of the program. In this approach
the program execution starts at the top and the program statements are executed one
after another.
However, the programmer has many options to change the program execution sequence
by using program flow control statements.
The header files offers a convenient way to organize the program code in procedural pro-
gramming. The header file inclusion statements are declared at the top section of the
program.
The header files can contain predefined library functions. For example, in C language
programming, the stdio.h (header file) files contains the standard function declarations for
commonly used input and output functions.
The header file can also contain library of used defined functions for common functionality
that can be used in many software projects.
66
HaQT Fundamental Programming with Java
It is simply now possible for the programmer to write all the functions required for the
desired functionality. And therefore, the predefined library functions are used to reduce
the overall development time.
All procedural programming language offer programmer option to write the user defined
functions. The user can define these functions to handle the specific functionality into the
program code.
The programmer can create the library of functions that can be commonly used in many
software development projects.
In simple words, the parameters are the place holders that holds the values passed on to
the function in the function call statement in the program code.
The function declaration defines the list of the parameters that must be sent to the func-
tion. The number of parameters and its data type depends upon the functionality per-
formed by the function.
The function prototype statement and the function declaration defines the number of
parameters, its order and the data type of the arguments (passed values).
The function declaration contains the details of the parameters that are required to be
sent to the function during the function call.
The parameters are variables that works like a placeholder for the values sent to the
function. The values can be passed to the function either by value or by reference.
67
HaQT Fundamental Programming with Java
The scope of the identifier decides the accessibility of that identifier within the program
code. The variable scope defines the accessibility and the visibility of the variable.
For example, a variable declared inside the function block is treated as a local variable.
The local variable can be accessed anywhere inside the function body.
Whereas, the variable declared outside the function block is treated as a global variable.
The global variable can be accessed anywhere in the program code.
Since the global variable can be access and operated by any function makes it vulnerable
inadvertent change and this might affect the functionality of the other functions that also
share the same data.
The procedural programming languages are relatively much easier to learn as first pro-
gramming language for the beginners.
The straight forward program organization makes it ideal choice as a general purpose
language.
The procedural programming language such as C Language is still being used for many
application.
The C language has extensive library of functions suitable for various applications. This
prewritten code already used and tested is readily available to the programmer.
68
HaQT Fundamental Programming with Java
The use of standard library functions bring down significant reduction in the overall de-
velopment cost and time.
The concept of pointers in the procedural programming C language allows low level mem-
ory operations.
The procedural programming is not suitable for large and complex software project.
It is difficult to represent the real world objects realistically in the procedural programming.
Whereas, in object oriented programming, it is much easier to represent the real world
objects.
It is difficult to protect the data from inadvertent changes since most data is generally
global leading to the problem of spaghetti code.
For procedural programming paradigm, the function is the most important component of
the program and the data does not get the due attention.
Let us now understand the difference between the procedural paradigm approach and the
Object-Oriented Programming (OOP) approach.
The procedural paradigm is based on top down approach for program execution.
The procedural paradigm gives unrestricted access to the global data and data access
cannot be controlled using access specifier.
69
HaQT Fundamental Programming with Java
The procedural paradigm cannot bind the data and function together.
The procedural paradigm is not suitable for large and complex software.
OOP Paradigm
The OOP paradigm does not give unrestricted access to the data. The data access can be
tightly controlled using the access specifier.
The OOP paradigm can bind the data and function together as a class.
70
HaQT Fundamental Programming with Java
C Language: One of the most widely used procedural languages, C is known for its per-
formance and control over system resources. It is commonly used in system programming,
embedded systems, and high-performance applications.
Pascal: Designed for teaching programming concepts and structured programming, Pascal
emphasizes clarity and ease of learning. It is often used in educational settings and for
developing small to medium-sized applications.
BASIC: Originally designed for beginners, BASIC provides a simple and easy-to-understand
syntax. It is used for small-scale applications and educational purposes.
7 Program Compilation
71
HaQT Fundamental Programming with Java
The program compilation is defined as the process of translating the high level program
into low level machine code in binary using the compiler.
The computer due to its hardware architecture can execute only binary machine instruc-
tions. And therefore, all programs written in any language other than the machine code
must be first converted to machine instructions.
The program compilation is a multi stage process that converts the human readable high
level computer program into low level machine readable code in binary format.
Compilation
Accepts Input Gives Output Result
Stage
1. Preprocessing Program Source Pre-processed Resolve #include Directive
Code Code Expand #define Directive
Remove Comments
2. Compilation Pre-processed Assembly Code Compiler Produce
Code Instructions Assembly Code
3. Assembly Assembly Code Object Code File Assembler Produce
Instructions Object Code
4. Linking Object Code Files Single Machine Linker Links And Produce
Code Executable Machine Code File
The conversion of program source code into executable file (dot exe) happens in four
stages. These four stages of compilation are pre-processing, compiler, assembly and finally
the linking stage.
However, in most situation all these four stages together is referred as program compilation
process.
The program compilation for a high level programs is a multistage process. The program-
mer writes the program code as per the programming language syntax.
72
HaQT Fundamental Programming with Java
A compiler is a special type of system software is used to translate the program source
code file into machine code. The machine code consist of machine instructions in binary.
The machine instructions are encoded by compiler in specific format called instruction
format. The CPU decodes the machine instruction as directed by the instruction format.
The high level computer programs are compiled by the compiler in four stages. Each stage
of the compilation process takes the input from previous stage.
– Preprocessing
– Compilation
– Assembling
– Linking
The first stage of the compilation process is called the preprocessor stage. Alternately,
this stage is also referred as lexical analysis stage.
The preprocessor stage takes the program source code file as input and provides prepro-
cessed file as output with dot i extension.
73
HaQT Fundamental Programming with Java
The compiler scans the source code file for all preprocessor directives that is all #include
and #define codes.
The preprocessing stage includes all the header files, all macros are resolved by replacing
them with absolute values and the comments are excluded.
Preprocessing
In C programming, the standard library functions are stored into separate header file with
dot h extension. The separate header file helps to better organize the program code and
improves the readability.
The programmer can include the standard function header files as well as other files that
contains the user defined functions into the program depending upon the functionality of
the program.
The compilation is the second stage of the program compilation process. The compiler
accepts the preprocessed file as input and provides the assembly code as output file with
dot s extension.
74
HaQT Fundamental Programming with Java
The compiler converts all high level program instructions into its equivalent assembly
code instructions. These instructions are platform dependent and compiled for a specific
architecture.
Program compilation
The compilation is the second stage of the program compilation process. The compiler
accepts the preprocessed file as input and provides the assembly code as output file with
dot s extension.
75
HaQT Fundamental Programming with Java
The compiler converts all high level program instructions into its equivalent assembly
code instructions. These instructions are platform dependent and compiled for a specific
architecture.
The linking is the final and fourth stage of the compilation process. The main function of
the linking is to produce a single executable file ([Link]) by linking all the object
code files.
The large computer programs are organized into number of manageable files. The user
defined functions are written in a separate file. These files are tied to the main program
file in the header section such as #include in C language.
Similarly, the programming language also provides standard library functions in the pre-
compiled object code format which programmer can readily use to simplify the program-
ming jobs.
The programmer can use these user defined functions and standard function libraries by
simply including these files in the beginning of the program header section.
Since the standard library code is in the object code form which is a pre-compiled format
and can be directly included at the linking stage by the linker while creating an executable
76
HaQT Fundamental Programming with Java
file ([Link] for windows platform) during the program compilation process.
Computer program
The high level programs are programs are developed in high level programming language
such as C language, C++, Python, dot Net, and Java.
The high level programs are human readable. Each high level programming language has
its own syntax and reserve key words which prompts the computer to perform specific
tasks.
77
HaQT Fundamental Programming with Java
The high level programming languages are specially designed keeping in mind the ease
of programming. Most high level programming language keywords use common English
words.
The programmer can use these user defined functions and standard function libraries by
simply including these files in the beginning of the program header section.
Since the standard library code is in the object code form which is a pre-compiled format
and can be directly included at the linking stage by the linker while creating an executable
file ([Link] for windows platform) during the program compilation process.
The high level programs are programs are developed in high level programming language
such as C language, C++, Python, dot Net, and Java.
The high level programs are human readable. Each high level programming language has
its own syntax and reserve key words which prompts the computer to perform specific
tasks.
78
HaQT Fundamental Programming with Java
The high level programming languages are specially designed keeping in mind the ease
of programming. Most high level programming language keywords use common English
words.
However, the computer system cannot directly execute the high level program code. At the
hardware level, the computer processor can decode and execute only machine instructions
in binary.
And therefore, the high level program code written in any programming language must
be first converted into low level binary machine code. This conversion process is called as
program compilation.
C++ compilation
Java compilation
79