CSC 313 - Object Oriented Ptogramming
CSC 313 - Object Oriented Ptogramming
Course Module
for
CSC 313
CSC 313
Centre for Distance Learning, JABU 1
CSC 313-- Object Oriented Programming Language II
Copyright
Copyright © 2020 by Centre for Distance Learning, Joseph Ayo Babalola University, Osun
State, Nigeria.
All rights reserved. No part of this publication may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, electronic, mechanical, photocopying,
recording or otherwise, without the prior permission of the copyright owner.
STUDY GUIDE
About this Study Guide
The Study Guide has been produced by the Centre for Distance Learning, Joseph Ayo
Babalola University. This Study Guide is designed to help you plan your studies and to
provide a more detailed interpretation of the course contents for CSC 313. It contains both
the Syllabus and the Study Sessions for the paper, which you can follow when preparing
for the examination. The Syllabus outlines the content of the paper and how that content is
examined. The Study Sessions take the syllabus and expand it into teaching or study
sessions of similar length. These sessions indicate what I expect of you for each part of the
syllabus, and therefore give you guidance in the skills you are expected to demonstrate in
the examination. The time to complete each session will vary according to your capabilities
and the time you have available to study. Repeated coverage of the material is vital to
ensure your understanding and recall of the subject. Be sure to practice the
Self-Assessment Questions to consolidate your knowledge.
Course Overview
This course assists the student to have broad knowledge of programming languages, survey
of programming languages, history of all programming languages, syntax of programming
language and its type checking.
This module is designed to support you in developing new academic skills. You will
continue to develop many of these skills during the duration of your programme. Hopefully,
this study guide will be one to which you return as you continue to develop your skills. It
takes time and practice to develop the key study skills and you should make use of the
supports that are provided by the Centre for Distance Learning. An important way of
continually developing and improving your academic skills is to make use of the feedback
provided by tutors on assignments submitted. The points of feedback provided by your
tutors can be used to improve future assignments. Should you need additional feedback at
any stage, please do not hesitate to contact me.
Course Content
The course is broken down into study sessions. Each study session comprises:
Learning outcomes.
Module Evaluation
At the end of each session, we would appreciate it if you would take a few moments to
give us your feedback on any aspect of this course. The gathering of such feedback is an
important part of our quality assurance and accreditation processes.
Course assessments.
Course assignments.
Course duration.
Your constructive feedback will help us to improve and enhance this course
Study Skills
As a learner, you will be taking control of your learning environment. You will need to
consider performance issues related to time management, goal setting, stress management,
etc. You will also need to reacquaint yourself with areas such as essay planning, coping
with exams and using the web as a learning resource. Your most significant considerations
will be time and space, i.e. the time you dedicate to your learning and the environment in
which you engage in that learning. We recommend that you take time now—before
starting your self-study—to familiarize yourself with these issues. There are a number of
excellent web links and resources on the Course Module for your use.
Study Sessions
This study guide should be read in conjunction with the Module textbook in print by the
same authors, which will be provided to you. In addition to this, you are encouraged to
consult additional recommended reading materials on the subject matter. The following
topics are covered in the module.
Learning Support
This study guide and the module text are the key material for studying the relevant chapters.
Each topic provides you with a 'road map' to guide you through the module. Lecture notes
will supplement the textbook readings. You are also expected to attempt the online
activities on the Learning Management System, as they will deepen your understanding of
the individual topics. Online discussions and collaborations are additional vital parts of the
learning support tools. They give you the opportunity to express your understanding and
application of the topics under discussion in practice. Furthermore, you benefit from the
experiences and insights of your peers challenging their perspectives and actions.
To benefit maximally from this course, you are required to read each study session very
well, read the textbooks and other materials, as recommended at the end of each study
session. Each study session contains self-assessment questions and at certain points in the
course, you would be required to submit assignments for assessment purposes. At the end
of the course, there is final examination. This course entails that you spend a lot of time
reading. I would advise that you avail yourself the opportunity of attending the tutorial
sessions where you will have the opportunity of comparing your knowledge with that of
other learners.
b. Session Arrangement
You are to study and prepare for all sessions. The study sessions are divided into weekly
formats as displayed on the LMS.
c. Students Activities
The module has various activities. You will be provided with answers to every activity
question. Therefore, your emphasis when working the activities should be on
understanding your answers. It is more important that you understand why every answer is
correct. There are different forms of activities in this module, ranging from reading
activities, case studies, and discussion forum. The use of activities is particularly based on
the learning outcomes and the nature of content. Some Study Sessions come with
discussion topics. You may discuss the Study Sessions at respective discussion boards on
the LMS. You may see dates for active discussion with tutor on course schedule. This
course schedule is available on the LMS.
d. Assignments
This module comes with Tutor Marked Assignments (TMA). Assignments are expected to
be turned-in on LMS. You may also receive TMAs as part of online class activities. Your
tutor will provide feedbacks to TMAs in not more than 2-week expected duration.
Schedule dates for submitting assignments and engaging in course / class activities are
available on the LMS. Kindly visit the LMS often for updates.
e. Assessment
There are three aspects to the assessment of the course. The first is made up of the
self-assessment exercises; the second consists of the Tutor-Marked Assignments and third
is the written examination/end of course examination. You are advised to do the exercises.
In attempting the assignments, you are expected to apply the information, knowledge and
techniques that you gathered during the course. The assignments must be submitted to your
facilitator for formal assessment in accordance with the deadlines stated in the presentation
schedule and the assignment file. The work you submit to your tutor for assessment will
count for 30% of your total course work. At the end of the course, you will need to sit for a
final or end-of-course examination of about three hour duration. This examination will
count for 70% of your total course mark.
f. Tutor-Marked Assignment
The TMA is a continuous assessment component of your course. It accounts for 30% of the
total score. You will be given four (4) TMAs to answer. Three of these must be answered
before you are allowed to sit for the end-of-course examination. The TMAs would be given
to you by your facilitator and returned after you have done the assignment. Assignment
questions for the units in this course are contained in the assignment file. You will be able
to complete your reading, references and study sessions. However, it is desirable in all
degree levels of education to demonstrate that you have read and researched more into
your references, which will give you a wider viewpoint and may provide you with a deeper
understanding of the subject.
Make sure that each assignment reaches your facilitator on or before the deadline given in
the presentation schedule and assignment file. If for any reason you cannot complete your
work on time, contact your facilitator before the assignment is due to discuss the possibility
of an extension. An extension will not be granted after the due date unless there are
exceptional circumstances.
Information: kindly go through and adapt and make necessary amendments to suit your
course.
The end-of-course examination will be for about 3 hours and it has a value of 70% of the
total course work. The examination will consist of questions, which will reflect the type of
self-testing, practice exercise, Self-Assessment Questions (SAQs), In-Text Questions
(ITAs) and Tutor-Marked Assignment (TMA) problems you have previously
encountered. All areas of the course will be assessed.
Use the time between finishing the last study session and sitting for the examination to
revise the whole course. You might find it useful to review your Self-Assessment
Questions (SAQs), In-Text Questions (ITAs), Tutor Marked Assignment (TMAs) and
comments on them before the examination. The end-of-course examination covers
information from all parts of the course.
Assignment Marks
Table of Contents
STUDY GUIDE .............................................................................Error! Bookmark not defined.
STUDY SESSION 1: .................................................................................................................... 12
Software Development Tools .......................................................................................................12
INTRODUCTION ........................................................................................................................ 12
LEARNING OUTCOMES FOR STUDY SESSION 1 ................................................................ 12
1.1 Software development tools ............................................................................................... 12
1.2 Compiler Vs Interpreter ..................................................................................................... 14
1.3 Data Type ......................................................................................................................... 19
1.4 Java as a Object-oriented Programming Language ................................................................. 23
1.5 Platform Independent ........................................................................................................... 23
1.6 Architecture-Neutral ............................................................................................................ 24
IN-TEXT QUESTION .................................................................................................................. 26
IN-TEXT ANSWER ..................................................................................................................... 26
SELF-ASSESSMENT QUESTIONS (SAQs) FOR STUDY SESSION 1 ................................... 26
SAQ 1.1 (TESTING LEARNING OUTCOMES 1.1) .................................................................. 26
SAQ 1.2 (TESTING LEARNING OUTCOMES 1.2) .................................................................. 26
REFERENCES.............................................................................................................................. 26
STUDY SESSION 2 ..................................................................................................................... 27
Programming Paradigms ............................................................................................................... 27
INTRODUCTION ........................................................................................................................ 27
LEARNING OUTCOMES FOR STUDY SESSION 1 ................................................................ 27
2.1 Procedural Programming ................................................................................................... 27
2.2 Object-Oriented Programming ........................................................................................... 28
2.3 Key Differences ............................................................................................................... 29
IN-TEXT QUESTION .................................................................................................................. 30
IN-TEXT ANSWER ..................................................................................................................... 30
SUMMARY FOR STUDY SESSION 2 .................................................................................... 30
SAQ 2.1 (TESTING LEARNING OUTCOMES 2.1) .................................................................. 31
SAQ 2.2 (TESTING LEARNING OUTCOMES 2.2) .................................................................. 31
REFERENCES.............................................................................................................................. 32
STUDY SESSION 3 ..................................................................................................................... 32
Basic Concepts of OOP ................................................................................................................. 33
INTRODUCTION ........................................................................................................................ 33
LEARNING OUTCOMES FOR STUDY SESSION 3 ................................................................ 33
3.1. Object ................................................................................................................................. 34
3.2 Class ................................................................................................................................... 34
3.3 Constructors: .................................................................................................................... 36
3.4. Encapsulation ..................................................................................................................... 37
3.5 Inheritance ........................................................................................................................ 40
3.6 Base & Derived Classes: .................................................................................................. 42
3.7 Polymorphism .................................................................................................................. 43
3.8 What is polymorphism in Java ......................................................................................... 47
3.9 Method Overloading vs Method Overriding ...................................................................... 48
3.10 Abstraction ....................................................................................................................... 49
STUDY SESSION 1
SOFTWARE DEVELOPMENT TOOLS
INTRODUCTION
A programming tool or software development tool is a computer program that software
developers use to create, debug, maintain, or otherwise support other programs and applications.
The term usually refers to relatively simple programs, that can be combined together to
accomplish a task, much as one might use multiple hand tools to fix a physical object. The ability
to use a variety of tools productively is one hallmark of a skilled software engineer.
The most basic tools are a source code editor and a compiler or interpreter, which are used
ubiquitously and continuously. Other tools are used more or less depending on the language,
development methodology, and individual engineer, and are often used for a discrete task, like
a debugger or profiler. Tools may be discrete programs, executed separately – often from
the command line – or may be parts of a single large program, called an integrated development
environment (IDE). In many cases, particularly for simpler use, simple ad hoc techniques are
used instead of a tool, such as print debugging instead of using a debugger, manual timing (of
overall program or section of code) instead of a profiler, or tracking bugs in a text file or
spreadsheet instead of a bug tracking system.
Integrated Development Environments combine the features of many tools into one package.
They for example, make it easier to do specific tasks, such as searching for content only in files
in a particular project. IDEs may for example be used for development of enterprise-level
applications.
There are software development tools web sites that list commercial and open source software
tools relating to all areas of software development: programming editors and frameworks (Java,
.NET, PHP, C#, JavaScript, Ruby, Ajax, etc.), project management, Agile, Scrum, Kanban,
UML, software testing, databases, configuration management.
In Java, programs are not compiled into executable files; they are compiled into bytecode , which
the JVM (Java Virtual Machine) then executes at runtime. Java source code is compiled into
bytecode when we use the java compiler. The bytecode gets saved on the disk with the file
extension .class. When the program is to be run, the bytecode is converted, using the
Just-In-Time (JIT) compiler. The result is machine code which is then fed to the memory and is
executed.
Java code needs to be compiled twice in order to be executed:
1. Java programs need to be compiled to bytecode.
2. When the bytecode is run, it needs to be converted to machine code.
The Java classes/bytecode are compiled to machine code and loaded into memory by the JVM
when needed the first time. This is different from other languages like C/C++ where programs
are to be compiled to machine code and linked to create an executable file before it can be
executed.
Compiler is a computer program (or a set of programs) that transfers source code written in
programming language( the source language) into another computer language (the target
language), with the latter often known as object code. It can also be seen as a special program
that processes statements written in a particular programming language and turns them into
machine language or “code” that a computer’s processor uses.
Interpreter is a computer program that directly executes , that is, performs, instruction written in
a programming or scripting language, without previously compiling them into a machine
language program
For iCountvar = To 20
iSum = iSum + iCountvar
Pic.Display iSum
Next iCountvar
This has implications for error reporting, eg: when an Interpreter encounters an error, it reports it
to the user immediately and halts further execution of the program. Such instant feedback,
pinpointing the exact location of the error, helps the programmer to find and remove errors.
Compiler, on the other hand, analyse the entire program, taking note of where errors have
occurred, and places these in an error/diagnostic file. If errors have occurred then the program
cannot run. Programmers must then use the error messages to identify and remove the errors in
the source code. Some compilers assist by adding line numbers to the source listing to help
pinpoint errors and all compilers will describe the nature of the error e.g. missing semi-colon,
expected keyword, etc. - although interpreting some compiler diagnostics is a skill in itself.
Error correction can be very time-consuming and frustrating, particularly in the case where
spurious errors occur, e.g. many errors are highlighted in the source but the cause of the error is a
single, simple mistake. An example of this would be errors that are generated by, say, a compiler,
if a programmer simply misses out a semi-colon.
Another important difference is that interpreters can be 2 to 10 times slower than Compilers. One
reason for this is that they translate the same statements within a loop over and over again.
Compilers can produce much more efficient object code than Interpreters thus making the
compiled programs to run faster.
Interpreters however are easier to use, particularly for beginners, since errors are immediately
displayed, corrected by the user, until the program is able to be executed. On the whole
compilers tend to be more difficult to use.
Writing your program
To write your first program, you'll need:
(i) The Java SE Development Kit 8 (JDK 8)
(ii) A text editor
Creating Your First Application
/**
* The JabuUniversity class implements an application that
* simply prints "JabuUniversity d!" to standard output.
*/
class JabuUniversity App {
public static void main(String[] args) {
Your first application, JabuUniversity App, will simply display the greeting "JabuUniversity !".
To create this program.
Create a source file
A source file contains code, written in the Java programming language, that you and other
programmers can understand. You can use any text editor to create and edit source files.
Compile the source file into a .class file
The Java programming language compiler (javac) takes your source file and translates its text
into instructions that the Java virtual machine can understand. The instructions contained within
this file are known as bytecodes.
Run the program
The Java application launcher tool (java) uses the Java virtual machine to run your application.
/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
System.out.println(root1);
System.out.println(root2);
}
}
Programming in Java.
We break the process of programming in Java into three steps:
Create the program by typing it into a text editor and saving it to a file named, say,
MyProgram.java.
Compile it by typing "javac MyProgram.java" in the terminal window.
Run (or execute) it by typing "java MyProgram" in the terminal window.
The first step creates the program; the second translates it into a language more suitable for
machine execution (and puts the result in a file named MyProgram.class); the third actually runs
the program.
Compiling a Java program. At first, it might seem to you as though the Java programming
language is designed to be best understood by the computer. Actually, to the contrary, the
language is designed to be best understood by the programmer (that's you). A compiler is an
application that translates programs from the Java language to a language more suitable for
executing on the computer. It takes a text file with the .java extension as input (your program)
and produces a file with a .class extension (the computer-language version). To compile
HelloWorld.java type the boldfaced text below at the terminal. (We use the % symbol to denote
the command prompt, but it may appear different depending on your system.)
% javac HelloWorld.java
If you typed in the program correctly, you should see no error messages. Otherwise, go back and
make sure you typed in the program exactly as it appears above.
Executing a Java program. Once you compile your program, you can run it. This is the exciting
part, where the computer follows your instructions. To run the HelloWorld program, type the
following at the terminal:
% java HelloWorld
If all goes well, you should see the following response
Hello, World
Understanding a Java program. The key line with System.out.println() send the text "Hello,
World". When we begin to write more complicated programs, we will discuss the meaning of
public, class, main, String[], args, System.out, and so on.
Creating your own Java program.
For the time being, all of our programs will be just like HelloWorld.java, except with a different
sequence of statements in main(). The easiest way to write such a program is to:
Copy HelloWorld.java into a new file whose name is the program name followed by .java.
Replace HelloWorld with the program name everywhere.
Replace the print statement by a sequence of statements.
Errors. Most errors are easily fixed by carefully examining the program as we create it, in just the
same way as we fix spelling and grammatical errors when we type an e-mail message.
Compile-time errors. These errors are caught by the system when we compile the program,
because they prevent the compiler from doing the translation (so it issues an error message that
tries to explain why).
Run-time errors. These errors are caught by the system when we execute the program, because
the program tries to perform an invalid operation (e.g., division by zero).
Logical errors. These errors are (hopefully) caught by the programmer when we execute the
program and it produces the wrong answer. Bugs are the bane of a programmer's existence. They
can be subtle and very hard to find.
Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float
and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
In Java language, primitive data types are the building blocks of data manipulation. These are the
most basic data types available in Java language. Java is a statically-typed programming
language. It means, all variables must be declared before its use. That is why we need to declare
variable's type and name.
There are 8 types of primitive data types:
boolean data type
byte data type
char data type
short data type
int data type
long data type
float data type
double data type
A data type is a set of values and a set of operations defined on them. For example, we are
familiar with numbers and with operations defined on them such as addition and multiplication
(in mathematics, we are accustomed to thinking of the set of numbers as being infinite; in
computer programs we have to work with a finite number of possibilities).
There are eight different built-in types of data in Java, mostly different kinds of numbers. Other
types are available in system libraries, and programming in Java is actually centered around
building our own data types, as we shall see later. We use the system type for strings of
characters so frequently that we also consider it here.
Basic definitions. We use the following four statement Java program fragment to introduce some
terminology that we'll be using:
int a, b,
c; a =
1234; b
= 99; c
= a + b;
The first statement declares three variables with the identifiers a, b, and c to be of type int. The
next two assignment statements change the values of the variables, using the literals 1234 and
99. The final statement assigns c to have the value 1333 by evaluating the expression a + b.
Characters and Strings. A char is an alphanumeric character or symbol, like the ones that you
type. We usually do not perform any operations on characters other than assigning values to
variables. A String is a sequence of characters. The most common operation that we perform on
strings is known as concatenation: given two strings, chain them together to make a new string.
For example, consider the following Java program fragment:
String a, b,
c; a =
"Hello,"; b
= " Bob"; c
= a + b;
The first statement declares three variables to be of type String. The next three statements assign
values to them, with the end result that c has the value"Hello, Bob". Using string concatenation,
Program Ruler.java prints the relative lengths of the subdivisions on a ruler.
Integers. An int is an integer (whole number) between -231 and 231 - 1 (-2,147,483,648 to
2,147,483,647). We use ints frequently not just because they occur frequently in the real world,
but also they naturally arise when expressing algorithms. Standard arithmetic operators for
addition, multiplication, and division, for ints are built in to Java, as illustrated in IntOps.java.
The type long is similar to int except it can represent integers in a much larger ranger, between
-263 an 263 - 1. We occasionally use long when we need to work with huge integers.
Real numbers. The double type is for representing floating-point numbers, e.g., for use in
scientific applications. The internal representation is like scientific notation, so that we can
compute with real numbers in a huge range. We can specify a floating point number using either
a string of digits with a decimal point, e.g., 3.14159 for a 6 six digit approximation to the
mathematical constant pi, or with a notation like scientific notation, e.g., 6.022E23 for
Avogadro's constant 6.022 × 1023. Standard arithmetic operators for addition, multiplication, and
division, for doubles are built in to Java, as illustrated in DoubleOps.java.
ProgramQuadratic.java shows the use of doubles in computing the two roots of a quadratic
equation using the quadratic formula. The Java Math library defines trigonometric functions,
logarithm/exponential, and other common functions for doubles. Trig.java illustrates a number of
trigonometric functions includingMath.sin(), Math.cos(), and Math.toRadians().
Booleans: The boolean type has just two values: true or false. The apparent simplicity is
deceiving - booleans lie at the foundation of computer science. The most important operators
defined for booleans are for and, or, and not.
and: a && b is true if both a and b are true, and false otherwise.
or: a || b is true if either a or b is true (or both are true), and false otherwise
not: !a is true if a is false, and false otherwise.
Although these definitions are intuitive and easy to understand, it is worthwhile to fully specify
each possibility for each operation in a truth table.
a b a && b a || b
false false false false
LeapYear.java tests whether an integer corresponds to a leap year in the Gregorian calendar.
Here's is Stanley Rabinowitz's entertaining response to a question as to why OpenVMS assumes
that 2000 is a leap year.
Type conversion.
We often find ourselves converting data from one type to another using one of the following
approaches.
Explicit type conversion. Call methods such as Math.round(), Integer.parseInt(),
and Double.parseDouble().
Automatic type conversion. For primitive numeric types, the system automatically performs type
conversion when we use a value whose type has a larger range of values than expected.
Explicit casts. Java also has some built-in type conversion methods for primitive types that you
can use when you are aware that you might lose information, but you have to make your
intention using something called a cast. Program RandomInt.java reads in a command-line
argument N and prints out a "random" integer between 0 and N-1.
Automatic conversions for strings. The built-in type String obeys special rules. One of these
special rules is that you can easily convert any type of data to a String by using the + operator.
There is automatic garbage collection in java which runs on the Java Virtual Machine to get
rid of objects which are not being used by a Java application anymore.
There are exception handling and the type checking mechanism in Java. All these points
make Java robust.
1.6 Architecture-Neutral
Java is architecture neutral because there are no implementation dependent features, for example,
the size of primitive types is fixed. In C programming, int data type occupies 2 bytes of memory
for 32-bit architecture and 4 bytes of memory for 64-bit architecture. However, it occupies 4
bytes of memory for both 32 and 64-bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is
"close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is
an interpreted language, that is why it is slower than compiled languages, e.g., C, C++, etc.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a common memory
area. Threads are important for multi-media, Web applications, etc.
Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded
on demand. It also supports functions from its native languages, i.e., C and C++. Java supports
dynamic compilation and automatic memory management (garbage collection).
IN-TEXT QUESTION 1
Java supports the following except
a. Dynamic Compilation
b. Dynamic language
c. Automatic memory management
d. Interpreter
IN-TEXT ANSWER
D. Interpreter
IN-TEXT QUESTION 2
Which of these is not part of the concepts of OOP
A. Class
B. Encapsulation
C. Inheritance
D. Program
IN-TEXT ANSWER 2
D Program
Integrated development environments combine the features of many tools into one package.
They for example make it easier to do specific tasks, such as searching for content only in files in
a particular project. IDEs may for example be used for development of enterprise-level
applications. There are software development tools web sites that list commercial and open
source software tools related to all areas of software development: programming editors and
frameworks (Java, .NET, PHP, C#, JavaScript, Ruby, Ajax, etc.), project management, Agile,
Scrum, Kanban, UML, software testing, databases, configuration management. In Java, programs
are not compiled into executable files; they are compiled into bytecode , which the JVM (Java
Virtual Machine) then executes at runtime. Java source code is compiled into bytecode when we
use the java compiler. The bytecode gets saved on the disk with the file extension .class. When
the program is to be run, the bytecode is converted, using the just-in-time (JIT) compiler. The
result is machine code which is then fed to the memory and is executed.
Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java: primitive data type and Non-primitive data type. Basic concepts of
OOPs are Object, Class, Inheritance, Polymorphism, Abstraction and Encapsulation
REFERENCES
https://beginnersbook.com/2017/08/data-types-in-java/#:~:text=In%20Java%2C%20we%20have
%20eight,one%20operating%20system%20to%20another.
https://www.edureka.co/blog/object-oriented-programming/#:~:text=Object%20Oriented%20pro
gramming%20is%20a,an%20object%2Doriented%20programming%20paradigm.
https://www.goodfirms.co/glossary/software-tools/
https://www.kidscodecs.com/resources/software-programming-tools/
STUDY SESSION 2
PROGRAMMING PARADIGMS
INTRODUCTION
Procedural Programming uses a list of instructions to tell the computer what to do step-by-step.
Procedural Programming relies on - you guessed it - procedures, also known as routines or
subroutines. A procedure contains a series of computational steps to be carried out. Procedural
programming is also referred to as imperative programming. Procedural programming languages
are also known as top-down languages. Procedural Programming takes on applications by
solving problems from the top of the code down to the bottom.
If you want a computer to do something, you should provide step-by-step instructions on how to
do it. It is, therefore, no surprise that most of the early programming languages are all
procedural. Examples of procedural languages include Fortran, COBOL and C, which have been
around since the 1960s and 70s.
This happens when a program starts with a problem and then breaks that problem down into
smaller sub-problems or sub-procedures. These sub-procedures are continually broken down in
the process called functional decomposition until the sub-procedure is simple enough to be
solved.
The issue that is obvious in Procedural Programming is that if a edit is needed to the program,
the developer must edit every line of code that corresponds to the original change in the code.
Object Oriented Programming is dividing a task into objects which have behaviours (methods)
specified which act upon their data (members).
In Procedural Programming, program is divided into small parts called functions. In OOP,
program is divided into parts called objects.
In Procedural Programming, Importance is not given to data but to functions as well as sequence
of actions to be done. In OOP, Importance is given to the data rather than procedures
or functions because it works as a real world.
Procedural Programming follows Top Down approach. OOP follows Bottom Up approach.
Procedural Programming does not have any access specifier. OOP has access specifiers named
Public, Private, Protected, etc.
In Procedural programming, data can move freely from function to function in the system. In
OOP, objects can move and communicate with each other through member functions. To add
new data and function in POP is not so easy. OOP provides an easy way to add new data and
function.
In POP, Most function uses Global data for sharing that can be accessed freely from function to
function in the system. In OOP, data can not move easily from function to function,it can
be kept public or private so we can control the access of data.
POP does not have any proper way for hiding data so it is less secure. OOP provides Data Hiding
so provides more security.
The problem with procedural programming is that code reusability is hard and limited – only
procedures can be reused and it is hard to make them generic and flexible.
In POP, overloading is not possible. In OOP, overloading is possible in the form of Function
examples of real-world objects: your dog, your desk, your television set, your bicycle.
Real-world objects share two characteristics: They all have state and behavior. Dogs have state
(name, color, breed, hungry) and behavior (barking, fetching, wagging tail).
The main advantages and goals of OOP are to make complex software faster to develop and
easier to maintain. OOP enables the easy reuse of code by applying simple and widely accepted
rules (principles
IN-TEXT QUESTION 1
IN-TEXT ANSWER 1
B. Object
IN-TEXT QUESTION 2
IN-TEXT ANSWER 2
C. Procedure
Procedural Programming uses a list of instructions to tell the computer what to do step-by-step.
Procedural Programming relies on - you guessed it - procedures, also known as routines or
subroutines. A procedure contains a series of computational steps to be carried out. Procedural
Programming is also referred to as imperative programming. Procedural Programming languages
are also known as top-down languages. Procedural Programming takes on applications by
solving problems from the top of the code down to the bottom.
In Procedural Programming, Most function uses global data for sharing that can be accessed
freely from function to function in the system. In OOP, data can not move easily from function to
function,it can be kept public or private so we can control the access of data.
REFERENCES
http://www.exceptionbound.com/programming-tut/introduction-to-java-object-oriented-program
ming-paradigm
https://subscription.packtpub.com/book/application_development/9781786463593/1/ch01lvl1sec
11/java-programming-paradigms
https://www.geeksforgeeks.org/introduction-of-programming-paradigms/
STUDY SESSION 3
An object is a software bundle of related state and behavior. Software objects are often used to
model the real-world objects that you find in everyday life. Objects are the basic unit of OOP.
They are instances of class, which have data members and uses various member functions to
perform tasks.
LEARNING OUTCOMES FOR STUDY SESSION 3
When you have studied this session, you should be able to:
(1) Understand the concept of an object
(2) Understand the concept of a Class
(3) Understand the concept of Polymorphism
(4) Understand the concept of Inheritance
(5) Understand the concepts of Abstraction
3.1. Object
An object is a software bundle of related state and behaviour. Software objects are often used to
model the real-world objects that you find in everyday life.
Objects are the basic unit of OOP. They are instances of class, which have data members and
uses various member functions to perform tasks.
An object can be considered a "thing" that can perform a set of related activities. The set of
activities that the object performs defines the object's behavior. For example,
the Hand (object) can grip something, or student (object) can give their names or addresses.
Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as
well as behaviours -wagging, barking, eating. An object is an instance of a class.
Objects in Java:
Let us now look deep into what are objects. If we consider the real-world we can find many
objects around us, cars, dogs, humans, etc. All these objects have a state and behavior.
If we consider a dog, then its state is - name, breed, color, and the behaviour is - barking,
wagging, running. If you compare the software object with a real world object, they have very
similar characteristics.
Software objects also have a state and behaviour. A software object's state is stored in fields and
behaviour is shown via methods. So in software development, methods operate on the internal
state of an object and the object-to-object communication is done via methods
void barking(){
}
void hungry(){
}
void sleeping(){
}}
3.2 Class
A class is simply a representation of a type of object. It is the blueprint, or plan, or template, that
describes the details of an object. A class is the blueprint from which the individual objects are
created. Class is composed of three things: a name, attributes, and operations.
Class - A class can be defined as a template/blue print that describes the behaviors/states that
object of its type support.
According to the sample given below we can say that the student object, named objectstudent,
has been created out of the student class
In real world, you'll often find many individual objects all of the same kind. As an example, there
may be thousands of other bicycles in existence, all of the same make and model. Each bicycle
has built from the same blueprint. In object-oriented terms, we say that the bicycle is an instance
of the class of objects known as bicycles.
Also, It is similar to structures in C language. Class can also be defined as user defined data type
but it also contains functions in it. It declare & defines what data variables the object will have
and what operations can be performed on the class's object.
A class is a blue print from which individual objects are created. A sample of a class is given in
object above
A class can contain any of the following variable types.
Local variables: Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable will be
destroyed when the method has completed.
Instance variables: Instance variables are variables within a class but outside any method. These
variables are initialized when the class is instantiated. Instance variables can be accessed from
inside any method, constructor or blocks of that particular class.
Class variables: Class variables are variables declared with in a class, outside any method, with
the static keyword.
A class can have any number of methods to access the value of various kinds of methods. In the
above example, barking(), hungry() and sleeping() are methods.
Below mentioned are some of the important topics that need to be discussed when looking into
classes of the Java Language.
3.3 Constructors
When discussing about classes, one of the most important sub topic would be constructors. Every
class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler
builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class. A class can have more than one
constructor.
Example of a constructor is given below:
public class Puppy{
public Puppy(){
}
Creating an Object:
As mentioned previously, a class provides the blueprints for objects. So basically an object is
created from a class. In Java, the new key word is used to create new objects.
There are three steps when creating an object from a class:
Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the
new object.
Example of creating an object is given below:
If we compile and run the above program, then it would produce the following result:
Passed Name is :tommy
3.4. Encapsulation
Encapsulation is placing the data and the functions that work on that data in the same place.
Encapsulation is:
Binding the data with the code that manipulates it.
It keeps the data and the code safe from external interference
The idea of encapsulation is to keep classes separated and prevent them from having tightly
coupled with each other.
Encapsulation cab has been viewed as hiding irrelevant data from the user. A class may contain
much information that is not useful for an outside class or interface. The idea behind this concept
is “Don’t tell me how you do it. Just do it.”. So classes use encapsulation to hide its members
that are not relevant for an outside class or interface. Encapsulation can be done using access
specifiers
The encapsulation is the inclusion-within a program object-of all the resources needed for the
object to function, basically, the methods and the data. In OOP, the encapsulation is mainly
achieved by creating classes, the classes expose public methods and properties. A class is a
kind of a container or capsule or a cell, which encapsulates a set of methods, attribute and
properties to provide its indented functionalities to other classes. In that sense, encapsulation also
allows a class to change its internal implementation without hurting the overall functioning of the
system. That idea of encapsulation is to hide how a class does its business, while allowing other
classes to make request of it.
Encapsulation is about placing the data and the functions that work on that data in the same
place.
While working with procedural languages, it is not always clear which functions work on which
variables but object-oriented programming provides you framework to place the data and the
relevant functions together in the same object.
Encapsulation is the packing of data and functions into a single component. The features of
encapsulation are supported using classes in most object-oriented programming languages,
although other alternatives also exist. It allows selective hiding of properties and methods in an
object by building an impenetrable wall to protect the code from accidental corruption.
Encapsulation can be used to hide data member and member function. Under this definition,
encapsulation means that the internal representation of an object is generally hidden from view
outside of the object's definition
Hiding the internals of the object protects its integrity by preventing users from setting the
internal data of the component into an invalid or inconsistent state. A supposed benefit of
encapsulation is that it can reduce system complexity, and thus increase robustness, by allowing
the developer to limit the inter-dependencies between software components
It is the principle of information hiding. That is, the implementation (the internal workings) of an
object is hidden from the rest of the program.
A popular example you’ll hear for encapsulation is driving a car. Do you need to know exactly
how every aspect of a car works (engine, carburettor, alternator, and so on)? No. You need to
know how to use the steering wheel, brakes, accelerator, and so on.
Encapsulation helps to create code that is loosely coupled. Because the details are hidden, it
reduces the ability of other objects to directly modify an object's state and behaviour.
Encapsulation can help to create more maintainable code by helping to prevent the ripple effect
of code changes. It also helps with creating loosely coupled code by reducing direct access to an
object's state and behavior.
Below is an example in C# that shows how access to a data field can be restricted through the use
of a private keyword:
class Program {
public class Account {
private decimal accountBalance = 500.00m;
/* This Main method can check the balance via the public
* "CheckBalance" method provided by the "Account" class
* but it cannot manipulate the value of "accountBalance" */
}
}
3.5 Inheritance
Inheritance is a way to reuse once written code again and again. The class which is inherited is
called base calls & the class which inherits is called derived class. So when, a derived class
inherits a base class, the derived class can use all the functions which are defined in the base
class, hence making a code reusable.
One of the most useful aspects of Object-Oriented Programming is code reusability. As the name
suggests, Inheritance is the process of forming a new class from an existing class that is from the
existing class called the base class, a new class is known as derived class.
This is a very important concept of Object-Oriented Programming since this feature helps to
reduce the code size.
In Object-Oriented Programming, inheritance enables new objects to take on the properties of
existing objects. A class that is used as the basis for inheritance is called a superclass or base
class. A class that inherits from a superclass is called a subclass or derived class. The
terms parent class and child class are also acceptable terms to use respectively. A child inherits
visible properties and methods from its parent, while adding additional properties and methods of
its own.
Using two concepts of Inheritance, Subclassing (making a new class based on a previous one)
and overriding (changing how a previous class works), you can organize your objects into a
hierarchy. Using Inheritance to make this hierarchy often creates easier to understand code, but
most importantly, it allows you to reuse and organize code more effectively
It allows a class to "inherit" (behavior or characteristics) of another, more general class. For
example, a lion belongs to the biological family of cats (Felidae). All cats that have
four paws, are predators and hunt their prey. This functionality can be coded once in
the Felidae class and all its predators can reuse it – Tiger, Puma, Bobcat, etc. Inheritance is
described as ”is-kind-of relationship”, e.g. Tiger is kind of Animal.
Felidae.cs
Lion.cs
Where access-specifier is one of public, protected, or private, and base-class is the name of a
previously defined class. If the access-specifier is not used, then it is private by default.
Consider a base class Shape and its derived class Rectangle as follows:
#include <iostream>
using namespace std;
// Base classclass Shape {
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;};
// Derived classclass Rectangle: public Shape{
public:
int getArea()
{
return (width * height);
}};
int main(void){
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
return 0;}
When the above code is compiled and executed, it produces the following result:
3.7 Polymorphism
This is an object-oriented programming concept that refers to the ability of a variable, function or
object to take on multiple forms. In a programming language that exhibits polymorphism, objects
of classes belonging to the same hierarchical tree (i.e. inherited from a common base class) may
possess functions bearing the same name, but each having different behaviors.
As an example, let us assume that there is a base class named Animals from which the subclasses
Horse, Fish and Bird are derived. Let us also assume that the Animals class has a function named
Move, which is inherited by all subclasses mentioned. With polymorphism, each subclass may
have its own way of implementing the function. So, for example, when the Move function is
called in an object of the Horse class, the function might respond by displaying trotting on the
screen. On the other hand, when the same function is called in an object of the Fish class,
swimming might be displayed on the screen. In the case of a Bird object, it may be flying.
Polymorphism means one name, many forms. Polymorphism manifests itself by having multiple
methods all with the same name, but slightly different functionality.
The beauty of polymorphism is that the code working with the different classes does not need to
know which class it is using since they’re all used the same way. A real world analogy for
polymorphism is a button. Everyone knows how to use a button. You simply apply pressure to it.
What a button “does,” however, depends on what it is connected to and the context in which it is
used — but the result does not affect how it is used. If your boss tells you to press a button, you
already have all the information needed to perform the task.
Polymorphism means one name, many forms. Polymorphism manifests itself by having multiple
methods all with the same name, but slightly different functionality.
In summary, Polymorphism The ability to use an operator or function in different ways. In other
words giving different meaning or functions to the operators or functions is called
polymorphism. Poly refers to many. That is, a single function or an operator functioning in many
different ways upon the usage it is called polymorphism.
Overloading in simple words means two methods having same method name but takes different
input parameters. This is called static because, which method to be invoked will be decided at the
time of compilation
Overriding means a derived class is implementing a method of its super class.
Overridding, also called run-time polymorphism. For method overloading, the compiler
determines which method will be executed, and this decision is made when the code gets
compiled.
Overloading, which is referred to as compile-time polymorphism. Method will be used for
method overriding is determined at runtime based on the dynamic type of an object.
Lets us look at the same example of a car. A car have a gear transmission system. It has four
front gears and one backward gear. When the engine is accelerated then depending upon which
gear is engaged, different amount of power and movement is delivered to the car. Polymorphism
could be static and dynamic both. Overloading is static polymorphism while, overriding is
dynamic polymorphism.
Overriding and Overloading are two very important concepts in Java. They are confusing for
Java novice programmers. This post illustrates their differences by using two simple examples.
1. Definitions
Overloading occurs when two or more methods in one class have the same method name but
different parameters.
Overriding means having two methods with the same method name and parameters (i.e.,method
signature). One of the methods is in the parent class and the other is in the child class. Overriding
allows a child class to provide a specific implementation of a method that is already provided its
parent class.
2. Overriding vs. Overloading
1. Real object type, not the reference variable's type, determines which overridden method is
used at runtime. In contrast, reference type determines which overloaded method will be used a t
compile time.
2. Polymorphism applies to overriding, not to overloading.
3. Overriding is a run-time concept while overloading is a compile-time concept.
3. An Example of Overriding
Here is an example of overriding. After reading the code, guess the output.
class Dog
{public void bark()
{
System.out.println("woof ");
}}
class Hound extends
Dog{public void sniff()
{System.out.println("sniff");
}
}}
public class OverridingTest
{
public static void main(String [] args)
{
Dog dog = new Hound();
dog.bark();
}}
Output:
bowl
In the example above, the dog variable is declared to be a Dog. During compile time, the
compiler checks if the Dog class has the bark() method. As long as the Dog class has
thebark() method, the code compilers. At run-time, a Hound is created and assigned to dog. The
JVM knows that dog is referring to the object of Hound, so it calls the bark() method of Hound.
In this overloading example, the two bark method can be invoked by using different parameters.
Compiler know they are different because they have different method signature (method name
and method parameter list).
Polymorphism is an OOP concept which advice use of common interface instead of concrete
implementation while writing code. When we program for interface our code is capable of
handling any new requirement or enhancement arising in near future due to new implementation
of our common interface. If we don't use common interface and rely on concrete implementation,
we always need to change and duplicate most of our code to support new implementation. Its not
only Java but other object oriented language like C++ also supports polymorphism and it comes
as fundamental along with other OOP concepts like Encapsulation.
Here we have a super class called Trading System and there two
Implementation Direct Market Access System and Commodity Trading System and here we will
write code which is flexible enough to work with any future implementation of Trading
System we can achieve this by using Polymorphism in Java which we will see in further
example.
Though name of method remains same in case of both method overloading and overriding, main
difference comes from the fact that method overloading is resolved during compile time, while
method overriding is resolved at runtime. Also, rules of overriding or overloading a method is
different in Java. For example, private, static and final method cannot be overriding in Java but
you can still overload them. For overriding both name and signature of method must remain
same, but in for overloading method signature must be different. Last but not the least difference
between them is that call to overloading methods are resolved using static binding while call to
overridding method is resolved using dynamic binding in Java. By the way, Method overloading
and method overriding in Java are two important concept in Java which allow Java programmer
to declare method with same name but different behaviour. Method overloading and method
overriding is based on Polymorphism in Java. In case of method overloading, method with same
name co-exists in same class but they must have different method signature, while in case of
method overriding, method with same name is declared in derived class or sub class. Method
overloading is resolved using static binding in Java at compile time while method overriding is
resolved using dynamic binding in Java at runtime. In short When you overload a method in Java
its method signature got changed while in case of overriding method signature remains same but
a method can only be overridden in sub class. Since Java supports Polymorphism and resolve
object at run-time, it is capable to call overridding method in Java. By the way, difference
between method overloading and overriding is also one of the popular Java design question and
appear in almost all levels of Java interviews.
3.10 Abstraction
As per dictionary, Abstraction is the quality of dealing with ideas rather than events. for example
when you consider the case of e-mail, complex details such as what happens the moment you
send an e-mail, the protocol your email server uses are hidden from the user, therefore to send an
e-mail you just need to like wise in Object oriented programming Abstraction is a process
process of hiding the implementation details from the user, only the functionality will be
provided to the user. In other words user will have the information on what the object does
instead of how it does it.
The same goes for objects in OOP. If we have an object Laptop and it needs a processor, we use
the object Processor. We do not know (or rather it is of no concern to us) how it calculates. In
order to use it, it’s sufficient to call the method Calculate() with appropriate
parameters.Abstraction is one of the most important concepts in programming and OOP. It
allows us to write code, which works with abstract data structures (like dictionaries, lists, arrays
and others). We can work with an abstract data type by using its interface without concerning
ourselves with its implementation.
Data abstraction refers to, providing only essential information to the outside world and hiding
their background details, i.e., to represent the needed information in program without presenting
the details.For example, a database system hides certain details of how data is stored and created
and maintained.
Abstraction is defined as showing only the relevant data to the user. Generally, abstraction and
encapsulation are explained in confusing manners.
So in designing the Mobile Phone Model, both relevant and irrelevant features are required. But
we need to show only relevant features. So we design a Mobile Phone in such a way that only
relevant features are shown and irrelevant features are hidden. And remember one thing, that
deciding relevant and irrelevant features is totally a user’s choice
Abstraction is applied everywhere in software and OOP.
When a class is conceptualized, what are the properties we can have in it given the context. If we
are designing a class Animal in the context of a zoo, it is important that we have an attribute as
animal type to describe domestic or wild. This attribute may not make sense when we design the
class in a different context.
Similarly, what are the behaviours we are going to have in the class? Abstraction is also applied
here. What is necessary to have here and what will be an overdose? Then we cut off some
information from the class. This process is applying abstraction.
When we ask for the difference between Encapsulation and Abstraction, I would
say, encapsulation uses abstraction as a concept. So then, is it only encapsulation. No, abstraction
is even a concept applied as part of inheritance and Polymorphism.
We got to look at Abstraction at a level higher among the other OOP concepts Encapsulation,
Inheritance and Polymorphism.
Point x = { 1, 8 } ;
Point y = {34, 87 }
Int d = distance(x, y) ; Here, distance encapsulates the calculation between two points in a
plane; it hides implementation details. Abstraction is the process of generalization, that is, taking
a concrete implementation and making it applicable to different related data type. A classical ex
of abstraction is qsort funtion which sorts data in C’s. One thing about qsort is that it doesn't care
about the data its sorting. In fact, it doesn't know which data its sorts
Abstraction is when we hide the implementation level details from the users and give access to
only necessary values only like sum (1,56), we have abstracted the process of sum from the user
Abstraction let you focus on what the object does instead of how it does it
Encapsulation means hiding the internal details or mechanics of how an object does something.
Like when you drive, you know what the gas pedal does but you may not know the process
behind it because it is encapsulated.
In summary, Encapsulation is the packing of data and functions operating on that data into a
single component and restricting access to some of object’s component. It means that the internal
representation of an object is generally hidden from view outside of the object’s definition
Abstraction is a mechanism which represent the essential features without including
implementation details
Another school of thought believe that we do abstraction when deciding what to implement. We
do encapsulation when hiding something that you have implemented. Abstraction is
implemented in Java using interface and abstract class, while encapsulation is implemented using
private, package-private and protected access modifier.
IN-TEXT QUESTION
In Java Abstraction is achieved using Abstract classes, and Interfaces.
A. Object and Class
B. Class and Object
C. Method Overloading vs Method Overriding
D. Abstract classes, and Interfaces.
IN-TEXT ANSWER
D.Abstract classes, and Interfaces.
Software objects also have a state and behaviour. A software object's state is stored in fields and
behavior is shown via methods. So in software development, methods operate on the internal
state of an object and the object-to-object communication is done via methods. A class is simply
a representation of a type of object. It is the blueprint, or plan, or template, that describes the
details of an object. A class is the blueprint from which the individual objects are created.
The idea of encapsulation is to keep classes separated and prevent them from having tightly
coupled with each other. Encapsulation can be viewed as hiding irrelevant data from the user. A
class may contain much information that is not useful for an outside class or interface.
Inheritance is a way to reuse once written code again and again. The class which is inherited is
called base calls & the class which inherits is called derived class. So when, a derived class
inherits a base class, the derived class can use all the functions which are defined in base class,
hence making code reusable.
One of the most useful aspects of object-oriented programming is code reusability. As the name
suggests Inheritance is the process of forming a new class from an existing class that is from the
existing class called as base class, new class is formed called derived class.
This is an object-oriented programming concept that refers to the ability of a variable, function or
object to take on multiple forms. In a programming language that exhibits polymorphism, objects
of classes belonging to the same hierarchical tree (i.e. inherited from a common base class) may
possess functions bearing the same name, but each having different behaviours.
REFERENCES
https://beginnersbook.com/2013/04/oops-concepts/
https://www.geeksforgeeks.org/object-oriented-programming-oops-concept-in-java
https://www.javatpoint.com/java-oops-concepts
https://www.journaldev.com/12496/oops-concepts-java-example
STUDY SESSION 4
Java Conditional Statement
INTRODUCTION
Java has the following conditional statements: Use if to specify a block of code to be executed, if
a specified condition is true. Use else to specify a block of code to be executed, if the same
condition is false. Use else if to specify a new condition to test, if the first condition is false.
Example
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
}
}
We can also use ternary operator (? :) to perform the task of if...else statement. It is a shorthand
way to check the condition. If the condition is true, the result of ? is returned. But, if the
condition is false, the result of : is returned.
Example:
}
...
else{
//code to be executed if all the conditions are false
}
The Java switch statement executes one statement from multiple conditions. It is
like if-else-if ladder statement. The switch statement works with byte, short, int, long, enum
types, String and some wrapper types like Byte, Short, Int, and Long. Since Java 7, you can
use strings in the switch statement.
In other words, the switch statement tests the equality of a variable against multiple values.
Points to Remember
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Example
Output: 20
while loop
do-while loop
The Java for loop is used to iterate a part of the program several times. If the number of iteration
is fixed, it is recommended to use for loop.
The java while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop.
The java do-while loop is used to iterate a part of the program several times. Use it if the number
of iterate is not fixed and must have to execute the loop at least once.
Introduction The Java for loop is a The Java while loop is The Java do while loop
control flow statement that a control flow is a control flow
iterates a part of statement that executes statement that executes a
the programs multiple times. a part of the programs part of the programs at
repeatedly on the basis least once and the
of given boolean further execution
condition. depends upon the given
boolean condition.
The Java for loop is used to iterate a part of the program several times. If the number of iteration
is fixed, it is recommended to use for loop.
There are three types of for loops in java.
1. Simple For Loop
2. For-each or Enhanced For Loop
3. Labeled For Loop
4.
Example in a simple loop
/Java Program to demonstrate the example of for loop
//which prints table of 1
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
Output
1
2
3
4
5
6
7
8
9
10
Java Nested For Loop
If we have a for loop inside the another loop, it is known as nested for loop. The inner loop
executes completely whenever outer loop executes.
Example:
Output
11
12
13
21
22
23
31
32
33
Pyramid Example 1:
Output
*
**
***
****
*****
The Java while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop.
Syntax:
while(condition){
//code to be executed
}
Output:
1
2
3
4
5
6
7
8
9
10
The Java do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended to
use do-while loop.
The Java do-while loop is executed at least once because condition is checked after loop body.
Syntax:
do{
//code to be executed
}while(condition);
}
}
Output:
1
2
3
4
5
6
7
8
9
10
IN-TEXT QUESTION
The loop inside the another loop in Java is known as?
A. nested for loop
B. Else if Statement
C. Do while loop
D.While loop
IN-TEXT ANSWER
A.nested for loop
Java has the following conditional statements: Use if to specify a block of code to be executed, if
a specified condition is true. Use else to specify a block of code to be executed, if the same
condition is false. Use else if to specify a new condition to test, if the first condition is false.
The Java if statement is used to test the condition. It checks boolean condition: true or false.
There are various types of if statement in Java; if statement, if-else statement, if-else-if ladder
and nested if statement. In Java programming languages, loops are used to execute a set of
instructions/functions repeatedly when some conditions become true. There are three types of
loops in Java; for loop, while loop and do-while loop.
Now that you have completed this study session, you can assess how well you have achieved its
Learning outcomes by answering the following questions. Write your answers in your study
notebook; discuss them with course-mates and your Facilitator at the next contact session. You
can check your answers with the notes on the Self-Assessment Questions at the end of this
module.
REFERENCES
(1) https://www.javatpoint.com/java-oops-concepts
(2) Thinking in Java – Bruce Eckel
(3) Beginning Java 2- Ivbor horton
(4) Just Java 1.2- Peter van der linder
Describe Inheritance?
Inheritance is a way to reuse once written code again and again. The class which is inherited is
called base calls & the class which inherits is called derived class. So when, a derived class
inherits a base class, the derived class can use all the functions which are defined in base class,
hence making code reusable.
What is a Class?
A class is simply a representation of a type of object. It is the blueprint, or plan, or template, that
describes the details of an object. A class is the blueprint from which the individual objects are
created. Class is composed of three things: a name, attributes, and operations. Class - A class can
be defined as a template/blue print that describes the behaviors/states that object of its type
support.
if statement
if-else statement
if-else-if ladder
nested if statement
Java if Statement
GLOSSARY OF TERMS
Java: Java is an object-oriented programming language that produces software for multiple
platforms
IDE: Integrated Development Environment
OOP: Object-Oriented Programming
POP: Procedural Programming Language
WORA: Write Once and Run Anywhere
JIT: Just-in-time