0% found this document useful (0 votes)
60 views72 pages

CSC 313 - Object Oriented Ptogramming

Programming document

Uploaded by

dolanibojid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views72 pages

CSC 313 - Object Oriented Ptogramming

Programming document

Uploaded by

dolanibojid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

CSC 313-- Object Oriented Programming Language II

JOSEPH AYO BABALOLA UNIVERSITY

Course Module

for

CSC 313

OBJECT ORIENTED PROGRAMMING II

CSC 313
Centre for Distance Learning, JABU 1
CSC 313-- Object Oriented Programming Language II

OBJECT ORIENTED PROGRAMMING 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.

Centre for Distance Learning, JABU 2


CSC 313-- Object Oriented Programming Language II

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.

Background to the Course

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.

Centre for Distance Learning, JABU 3


CSC 313-- Object Oriented Programming Language II

Course Content

The course is broken down into study sessions. Each study session comprises:

 An introduction to the study session content.

 Learning outcomes.

 Content of study sessions.

 A study session summary.

 Assessments and/or assignment.

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.

Your feedback might include comments on:

 Course content and structure.

 Course reading materials and resources.

 Course assessments.

 Course assignments.

 Course duration.

 Course support (assigned tutors, technical help, etc.).

 Your general experience with the course provision as a distance learner.

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

Centre for Distance Learning, JABU 4


CSC 313-- Object Oriented Programming Language II

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.

Study Session 1. Software Development Tools


Study Session 2. Programming paradigms
Study Session 3. Basic Concepts of OOP
Study Session 4. Java Conditional Statement

Learning Support

1. General 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.

2. Module Delivery Schedules (Activities)

a. Working through the Module

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

Centre for Distance Learning, JABU 5


CSC 313-- Object Oriented Programming Language II

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

Centre for Distance Learning, JABU 6


CSC 313-- Object Oriented Programming Language II

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.

3. Final Assessment and Grading

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

Centre for Distance Learning, JABU 7


CSC 313-- Object Oriented Programming Language II

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.

4. Course Marking Scheme Assignment

Centre for Distance Learning, JABU 8


CSC 313-- Object-Oriented Programming Language II

Assignment Marks

Assignment 1 – 4 Four assignments, best three marks of the


four count at 10% each – 30% of course
marks.
End of course Assessment 70% of overall course marks.

Centre for Distance Learning, JABU


9
CSC 313-- Object-Oriented Programming Language II

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

Centre for Distance Learning, JABU


10
CSC 313-- Object-Oriented Programming Language II

IN-TEXT QUESTION .................................................................................................................. 52


IN-TEXT ANSWER ..................................................................................................................... 52
SUMMARY FOR STUDY SESSION 3 .................................................................................... 53
SELF-ASSESSMENT QUESTIONS (SAQs) FOR STUDY SESSION 3 ................................... 54
SAQ 3.1 (TESTING LEARNING OUTCOMES 3.1) .................................................................. 55
SAQ 3.2 (TESTING LEARNING OUTCOMES 3.2) .................................................................. 55
REFERENCES.............................................................................................................................. 55
STUDY SESSION 4 ..................................................................................................................... 56
Java Conditional Statement ........................................................................................................... 56
INTRODUCTION ........................................................................................................................ 56
LEARNING OUTCOMES FOR STUDY SESSION 4 ................................................................ 56
4.1 Java If-else Statement ............................................................................................................. 57
4.2 Using Ternary Operator ........................................................................................................ 58
4.3 Java if-else-if ladder Statement ............................................................................................ 58
4.4 Java Nested if statement ................................................................................................... 59
4.5 Java Switch Statement.......................................................................................................... 60
4.6 Loops in Java .......................................................................................................................... 61
4.7 Java while loop.........................................................................................................................65
4.8 Java do-while Loop .............................................................................................................. 66
IN-TEXT QUESTION .................................................................................................................. 67
IN-TEXT ANSWER ..................................................................................................................... 67
SUMMARY FOR STUDY SESSION 4 .................................................................................... 67
SELF-ASSESSMENT QUESTIONS (SAQs) FOR STUDY SESSION 4 ................................... 68
SAQ 4.1 (TESTING LEARNING OUTCOMES 4.1) .................................................................. 68
SAQ 4.2 (TESTING LEARNING OUTCOMES 4.2) .................................................................. 68
REFERENCES…………………………………………………………………………………..68
ANSWERS TO SELF ASSESSMENT QUESTIONS…………………………………………..69
GLOSSARY OF TERMS………………………………………………………………………..72

Centre for Distance Learning, JABU


11
CSC 313-- Object-Oriented Programming Language II

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.

LEARNING OUTCOMES FOR STUDY SESSION 1


When you have studied this session, you should be able to:
1) Understand the meaning of software development tools
2) Understand the concept of compiler and interpreter
3) Learn how to create a Java program
4) Know different types in Java
5) Know basic concept of OOP

1.1 Software Development tools


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

Centre for Distance Learning, JABU


12
CSC 313-- Object-Oriented Programming Language II

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

Centre for Distance Learning, JABU


13
CSC 313-- Object-Oriented Programming Language II

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

1.2 Compiler Vs Interpreter


Just understand the concept of the compiler and interpreter –
1) We give complete program as input to the Compiler. Our program is in the human readable
format.
2) Human readable format undergoes many passes and phases of Compiler and finally it is
converted into the machine readable format.
3) However Interpreter takes single line of code as input at a time and execute that line. It will
terminate the execution of the code as soon as it finds the error.
4) Memory requirement is less in case of Interpreter because no object code is created in case
of interpreter.
Main Differences between Interpreter and Compiler
The main difference between an Interpreter and a Compiler is that compilation requires analysis
and the generation of machine code only once, whereas an Interpreter may need to analyse and
interpret the same program statements each time it meets them e.g. instructions appearing within
a loop. For example, the following Visual Basic Code would be interpreted each time the loop is
entered:

For iCountvar = To 20
iSum = iSum + iCountvar
Pic.Display iSum
Next iCountvar

Centre for Distance Learning, JABU


14
CSC 313-- Object-Oriented Programming Language II

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) {

Centre for Distance Learning, JABU


15
CSC 313-- Object-Oriented Programming Language II

System.out.println("JabuUniversity!"); // Display the string.


}
}

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

public class Quadratic {

public static void main(String[] args) {


double b = Double.parseDouble(args[0]);
double c = Double.parseDouble(args[1]);

Centre for Distance Learning, JABU


16
CSC 313-- Object-Oriented Programming Language II

double discriminant = b*b - 4.0*c;


double sqroot = Math.sqrt(discriminant);

double root1 = (-b + sqroot) / 2.0;


double root2 = (-b - sqroot) / 2.0;

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.

Creating a Java program.


A program is nothing more than a sequence of characters, like a sentence, a paragraph, or a
poem. To create one, we need only define that sequence characters using a text editor in the same
way as we do for e-mail. HelloWorld.java is an example program. Type these character into your
text editor and save it into a file named HelloWorld.java.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}

Centre for Distance Learning, JABU


17
CSC 313-- Object-Oriented Programming Language II

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).

Centre for Distance Learning, JABU


18
CSC 313-- Object-Oriented Programming Language II

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.

1.3 Data Type

Data Types in Java

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.

Java Primitive Data Types

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

Centre for Distance Learning, JABU


19
CSC 313-- Object-Oriented Programming Language II

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;

Centre for Distance Learning, JABU


20
CSC 313-- Object-Oriented Programming Language II

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

Centre for Distance Learning, JABU


21
CSC 313-- Object-Oriented Programming Language II

false true false true


true false false true
true true true true
Comparisons. The comparison operators are mixed-type operations that take operands of one
type (e.g., int or double) and produce a result of typeboolean. These operations play a critical
role in the process of developing more sophisticated programs.

op meaning a op b true false


== equal to a is equal to b 2 == 2 3 == 2
!= not equal to a is not equal to b 3 != 2 2 != 2
< less than a is less than b 2 < 13 2 < 2
<= less than or equal to a is less than or equal to b 2 <= 2 3 <= 2
> greater than a is greater than b 13 > 2 2 > 13
>= greater than or equal to a is greater than or equal to b 3 >= 2 2 >= 3

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.

Centre for Distance Learning, JABU


22
CSC 313-- Object-Oriented Programming Language II

1.4 Java as a Object-oriented Programming Language


Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types of objects
that incorporates both data and behavior. Object-oriented programming (OOP) is a methodology
that simplifies software development and maintenance by providing some rules.
Basic concepts of OOP are:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation

1.5 Platform Independent


Java is platform independent because it is different from other languages like C, C++, etc. which
are compiled into platform specific machines while Java is a write once, run anywhere language.
A platform is the hardware or software environment in which a program runs. There are two
types of platforms software-based and hardware-based. Java provides a software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on the top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API (Application Programming Interface)
Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS,
etc. Java code is compiled by the compiler and converted into bytecode. This bytecode is a
platform-independent code because it can be run on multiple platforms, i.e., Write Once and Run
Anywhere(WORA)
Robust
Robust simply means strong. Java is robust because:
 It uses strong memory management.
 There is a lack of pointers that avoids security problems.

Centre for Distance Learning, JABU


23
CSC 313-- Object-Oriented Programming Language II

 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

Centre for Distance Learning, JABU


24
CSC 313-- Object-Oriented Programming Language II

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

SUMMARY FOR STUDY SESSION 1


In this study session, you have learnt that:
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.

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

Centre for Distance Learning, JABU


25
CSC 313-- Object-Oriented Programming Language II

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

SELF-ASSESSMENT QUESTIONS (SAQs) FOR STUDY SESSION 1


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.

SAQ 1.1 (TESTING LEARNING OUTCOMES )


What is programming tool or software development tool
Outline the processes involved in compiling java into executive form

SAQ 1.2 (TESTING LEARNING OUTCOMES )


Mention all the concept of OOP.
Why is it that Java is a Platform Independent programming language?

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/

Centre for Distance Learning, JABU


26
CSC 313-- Object-Oriented Programming Language II

STUDY SESSION 2
PROGRAMMING PARADIGMS

INTRODUCTION

Programming is a creative process carried out by programmers to instruct a computer on how to


do a task. A program is a set of instructions that tells a computer what to do in order to come up
with a solution to a particular problem. There are a number of alternative approaches to the
programming process, referred to as programming paradigms. Two of the most important
programming paradigms are the procedural paradigm and the object-oriented paradigm

LEARNING OUTCOMES FOR STUDY SESSION 1


When you have studied this session, you should be able to:
(1) Understand the concept of procedural programming language
(2) Understand the concept of object oriented programming language

2.1 Procedural Programming

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

Centre for Distance Learning, JABU


27
CSC 313-- Object-Oriented Programming Language II

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.

2.2 Object-Oriented Programming


Object-oriented programming, or OOP, is an approach to problem-solving where all
computations are carried out using objects. An object is a component of a program that 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.
Object-Oriented Programming (OOP) is a programming language that uses classes and objects to
create models based on the real world environment. An OBJECT-ORIENTED
PROGRAMMING application may use a collection of objects which will pass messages when
called upon to request a specific service or information. Objects are able to pass, receive
messages or process information in the form of data.
A simple example of an object would be a person. Logically, you would expect a person to have
a name. This would be considered a property of the person. You would also expect a person to be
able to do something, such as walking. This would be considered a method of the person. A
method in object-oriented programming is like a procedure in procedural programming. The key
difference here is that the method is part of an object. In Object-Oriented Programming, you
organize your code by creating objects, and then you can give those objects properties and you
can make them do certain things.
A key aspect of Object-Oriented Programming is the use of classes. A class is a blueprint of an
object. You can think of a class as a concept, and the object as the embodiment of that concept.
So let's say you want to use a person in your program. You want to be able to describe the person
and have the person do something. A class called 'person' would provide a blueprint for what a
person looks like and what a person can do. Examples of object-oriented languages include C#,
Java, Perl and Python.
In order to clearly understand the object orientation model, let’s take your “hand” as an example.
The “hand” is a -[class. Your body has two objects of the type "hand", named "left
hand" and "right hand". Their main functions are controlled or managed by a set of electrical

Centre for Distance Learning, JABU


28
CSC 313-- Object-Oriented Programming Language II

signals sent through your shoulders (through an interface). So the shoulder is an


interface that your body uses to interact with your hands. The hand is a well-architected class.
The hand is being reused to create the left hand and the right hand by slightly changing the
properties of it.

2.3 Key Differences

One of the most important characteristics of procedural programming is that it relies on


procedures that operate on data - these are two separate concepts. In Object-Oriented
Programming, these two concepts are bundled into objects. This makes it possible to create more
complicated behaviour with less code. The use of objects also makes it possible to reuse code.
Once you have created an object with more complex behaviour, you can use it anywhere in your
code. Procedural programming is dividing a task into procedures having steps to compute
something given an input in an imperative way.

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.

Centre for Distance Learning, JABU


29
CSC 313-- Object-Oriented Programming Language II

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

Object-Oriented programming, or OOP, is an approach to problem-solving where all


computations are carried out using what?.
A. Class
B. Object
C. Object-Oriented Programming
D. Procedural Programming

IN-TEXT ANSWER 1
B. Object

IN-TEXT QUESTION 2

Centre for Distance Learning, JABU


30
CSC 313-- Object-Oriented Programming Language II

A method in object-oriented programming is like a_ in procedural programming.


A Object
B Class
C Procedure
D OOP

IN-TEXT ANSWER 2

C. Procedure

SUMMARY FOR STUDY SESSION 2


In this study session, you have learnt that:

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.

Object-Oriented Programming, or OOP, is an approach to problem-solving where all


computations are carried out using objects. An object is a component of a program that 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 method in object-oriented programming is like a procedure in procedural programming. The


key difference here is that the method is part of an object. In object-oriented programming, you
organize your code by creating objects, and then you can give those objects properties and you
can make them do certain things.

Centre for Distance Learning, JABU


31
CSC 313-- Object-Oriented Programming Language II

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.

SELF-ASSESSMENT QUESTIONS (SAQs) FOR STUDY SESSION 2


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.

SAQ 2.1 (TESTING LEARNING OUTCOMES 2.1)


Describe Procedural Programming.
Describe OOP.
SAQ 2.2 (TESTING LEARNING OUTCOMES 2.2)
List two differences between OOP and Procedural Programming
Mention one of the problems of procedural programming language

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/

Centre for Distance Learning, JABU


32
CSC 313-- Object-Oriented Programming Language II

STUDY SESSION 3

BASIC CONCEPTS OF OOP


INTRODUCTION

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.

Centre for Distance Learning, JABU


33
CSC 313-- Object-Oriented Programming Language II

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

public class Dog{


String breed;
int age C
String color;

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.

Centre for Distance Learning, JABU


34
CSC 313-- Object-Oriented Programming Language II

public class Student


{
}

According to the sample given below we can say that the student object, named objectstudent,
has been created out of the student class

Student objectStudent = new Student();

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.

Centre for Distance Learning, JABU


35
CSC 313-- Object-Oriented Programming Language II

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(){
}

public Puppy(String name){


// This constructor has one parameter, name.
}}

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:

Declaration: A variable declaration with a variable name with an object type.


Instantiation: The 'new' key word is used to create the object.

Centre for Distance Learning, JABU


36
CSC 313-- Object-Oriented Programming Language II

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:

public class Puppy{

public Puppy(String name){


// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}

public static void main(String []args){


// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}}

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

Centre for Distance Learning, JABU


37
CSC 313-- Object-Oriented Programming Language II

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.

Centre for Distance Learning, JABU


38
CSC 313-- Object-Oriented Programming Language II

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;

public decimal CheckBalance() {


return accountBalance;
}
}

static void Main() {


Account myAccount = new Account();
decimal myBalance = myAccount.CheckBalance();

/* 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" */
}
}

Below is an example in Java:


public class Employee {
private BigDecimal salary = new BigDecimal(50000.00);

public BigDecimal getSalary() {


return salary;
}

public static void main() {


Employee e = new Employee();
BigDecimal sal = e.getSalary();
}

Centre for Distance Learning, JABU


39
CSC 313-- Object-Oriented Programming Language II

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

Centre for Distance Learning, JABU


40
CSC 313-- Object-Oriented Programming Language II

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.

Inheritance of Classes – Example


Let’s take a look at an example of class inheritance in .NET. This is how a base class looks like:

Felidae.cs

/// <summary>Felidae is latin for "cats"</summary>


public class Felidae
{
private bool male;

// This constructor calls another constructor


public Felidae() : this(true)
{}

// This is the constructor that is inherited


public Felidae(bool male)
{
this.male = male;
}

public bool Male


{
get { return male; }
set { this.male = value; }
}
}

This is how the inheriting class, Lion, looks like:

Lion.cs

Centre for Distance Learning, JABU


41
CSC 313-- Object-Oriented Programming Language II

public class Lion : Felidae


{
private int weight;

// Keyword "base" will be explained in the next paragraph


public Lion(bool male, int weight) : base(male)
{
this.weight = weight;
}

public int Weight


{
get { return weight; }
set { this.weight = value; }
}
}

public class Exception


{
}
public class IOException : Exception
{
}
According to the above example the new class (IOException), which is called the derived class
or subclass, inherits the members of an existing class (Exception), which is called the base class
or super-class. The classIOException can extend the functionality of the class Exception by
adding new types and methods and by overriding existing ones.

3.6 Base & Derived Classes:


A class can be derived from more than one classes, which means it can inherit data and functions
from multiple base classes. To define a derived class, we use a class derivation list to specify the
base class(es). A class derivation list names one or more base classes and has the form:

class derived-class: access-specifier base-class

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.

Centre for Distance Learning, JABU


42
CSC 313-- Object-Oriented Programming Language II

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

// Print the area of the object.


cout << "Total area: " << Rect.getArea() << endl;

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.

Centre for Distance Learning, JABU


43
CSC 313-- Object-Oriented Programming Language II

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.

Polymorphism describes a pattern in object oriented programming in which classes have


different functionality while sharing a common interface.

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 refers to a programming language's ability to process objects differently


depending on their data type or class. More specifically, it is the ability to redefine methods for
derived classes. For example, given a base class shape, polymorphism enables the programmer
to define different area methods for any number of derived classes, such as circles, rectangles
and triangles. No matter what shape an object is, applying the area method to it will return the
correct results. Polymorphism is considered to be a requirement of any true object-oriented
programming language (OOPL).

Centre for Distance Learning, JABU


44
CSC 313-- Object-Oriented Programming Language II

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.

 Polymorphism means to process objects differently based on their data type.


 In other words, it means, one method with multiple implementation, for a certain class of
action. And which implementation to be used is decided at runtime depending upon the
situation (i.e., data type of the object).
 This can be implemented by designing a generic interface, which provides generic methods
for a certain class of action and there can be multiple classes, which provide the
implementation of these generic methods.

There are 2 basic types of 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.

Centre for Distance Learning, JABU


45
CSC 313-- Object-Oriented Programming Language II

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

Here are some important facts about Overriding and 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.

Centre for Distance Learning, JABU


46
CSC 313-- Object-Oriented Programming Language II

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 void bark(){


System.out.println("bowl");

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

This is called Dynamic Polymorphism.


4. An Example of Overloading
class Dog{ public void bark(){ System.out.println("woof "); }
//overloading method public void bark(int num){ for(int i=0; i<num; i++)
System.out.println("woof "); }}

Centre for Distance Learning, JABU


47
CSC 313-- Object-Oriented Programming Language II

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).

3.8 What is polymorphism in Java

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.

How Polymorphism is supported in Java

Java has excellent support of polymorphism in terms of Inheritance, method


overloading and method overriding. Method overriding allows Java to invoke method based on a
particular object at run-time instead of declared type while coding. To get hold of the concept
let's see an example of polymorphism in Java:

public class TradingSystem{


public String getDescription(){
return "electronic trading system";
}
}

public class DirectMarketAccessSystem extends TradingSystem{


public String getDescription(){
return "direct market access system";
}
}

public class CommodityTradingSystem extends TradingSystem{


public String getDescription(){
return "Futures trading system";
}

Centre for Distance Learning, JABU


48
CSC 313-- Object-Oriented Programming Language II

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.

3.9 Method Overloading vs Method Overriding

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.

Centre for Distance Learning, JABU


49
CSC 313-- Object-Oriented Programming Language II

3.10 Abstraction

One of the most fundamental concept of OOP is Abstraction. Abstraction is a powerful


methodology to manage complex systems. Abstraction is managed by well-defined objects and
their hierarchical classification. For example a car in itself is a well-defined object, which is
composed of several other smaller objects like a gearing system, steering mechanism, engine,
which are again have their own subsystems. But for humans, car is one single object, which can
be managed by the help of its subsystems, even if its inner details are unknown.

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.

In Java Abstraction is achieved using Abstract classes, and Interfaces.


Abstraction means working with something we know how to use without knowing how it works
internally. A good example is a television set. We don’t need to know the inner workings of a
TV, in order to use it. All we need is a remote control with a small set of buttons (the interface of
the remote) and we will be able to watch the TV.

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.

Centre for Distance Learning, JABU


50
CSC 313-- Object-Oriented Programming Language II

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.

Example: So just take an example of Mobile Phone Design.


Relevant Features of a phone in which the user is interested are Camera, Music player, Calling
function, Voice recording and so on.
Irrelevant Features of a phone in which the user is not interested are circuit board design,
hardware used and so on.

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.

Abstraction and Encapsulation

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.

Centre for Distance Learning, JABU


51
CSC 313-- Object-Oriented Programming Language II

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.

Every method in OOP is encapsulation

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

Centre for Distance Learning, JABU


52
CSC 313-- Object-Oriented Programming Language II

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.

SUMMARY FOR STUDY SESSION 3


In this study session, you have learnt that:
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.

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.

Centre for Distance Learning, JABU


53
CSC 313-- Object-Oriented Programming Language II

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.

One of the most fundamental concept of OOP is Abstraction. Abstraction is a powerful


methodology to manage complex systems. Abstraction is managed by well-defined objects and
their hierarchical classification. For example, a car in itself is a well-defined object, which is
composed of several other smaller objects like a gearing system, steering mechanism, engine,
which are again have their own subsystems. But for humans car is one single object, which can
be managed by the help of its subsystems, even if its inner details are unknown.

SELF-ASSESSMENT QUESTIONS (SAQs) FOR STUDY SESSION 3


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.

SAQ 3.1 (TESTING LEARNING OUTCOMES 3.1)


Describe Abstraction.
Describe Inheritance.

Centre for Distance Learning, JABU


54
CSC 313-- Object-Oriented Programming Language II

SAQ 3.2 (TESTING LEARNING OUTCOMES 3.2)


What is a Object?
What is a Class?

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

Centre for Distance Learning, JABU


55
CSC 313-- Object-Oriented Programming Language II

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.

LEARNING OUTCOMES FOR STUDY SESSION 4


When you have studied this session, you should be able to:
(1) Understand the concept of Java Conditional Statement

4.1 Java If-else Statement


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
 nested if statement
 Java if Statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition){
//code to be executed
}

Example

//Java Program to demonstate the use of if statement.


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

Centre for Distance Learning, JABU


56
CSC 313-- Object-Oriented Programming Language II

//defining an 'age' variable


int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
}
}
}

Output: Age is greater than 18

Java if-else Statement

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
}

Example: odd number

Leap Year Example:

A year is leap, if it is divisible by 4 and 400. But, not by 100.


public class LeapYearExample {
public static void main(String[] args) {
int year=2020;
if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)){
System.out.println("LEAP YEAR");
}
else{
System.out.println("COMMON YEAR");
}

Centre for Distance Learning, JABU


57
CSC 313-- Object-Oriented Programming Language II

}
}

Output: LEAP YEAR

4.2 Using Ternary Operator

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:

public class IfElseTernaryExample {


public static void main(String[] args) {
int number=13;
//Using ternary operator
String output=(number%2==0)?"even number":"odd number";
System.out.println(output);
}
}

Output: odd number

4.3 Java if-else-if ladder Statement


The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true

Centre for Distance Learning, JABU


58
CSC 313-- Object-Oriented Programming Language II

}
...
else{
//code to be executed if all the conditions are false
}

4.4 Java Nested if statement


The nested if statement represents the if block within another if block. Here, the inner if block
condition executes only when outer if block condition is true.
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}

//Java Program to demonstrate the use of Nested If Statement.


public class JavaNestedIfExample {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
}
}}

Centre for Distance Learning, JABU


59
CSC 313-- Object-Oriented Programming Language II

Output: You are eligible to donate blood

4.5 Java Switch Statement

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

 There can be one or N number of case values for a switch expression.


 The case value must be of switch expression type only. The case value must be literal or
constant. It doesn't allow variables.
 The case values must be unique. In case of duplicate value, it renders compile-time error.
 The Java switch expression must be of byte, short, int, long (with its Wrapper
type), enums and string.
 Each case statement can have a break statement which is optional. When control reaches to
the break statement, it jumps the control after the switch expression. If a break statement is
not found, it executes the next case.
 The case value can have a default label which is optional.

Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional

Centre for Distance Learning, JABU


60
CSC 313-- Object-Oriented Programming Language II

......

default:
code to be executed if all cases are not matched;
}
Example

public class SwitchExample {


public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30");
}
}
}

Output: 20

4.6 Loops in Java


In 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

Centre for Distance Learning, JABU


61
CSC 313-- Object-Oriented Programming Language II

 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.

Comparison for loop while loop do while loop

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.

When to use If the number of iteration is If the number of If the number of


fixed, it is recommended to iteration is not fixed, it iteration is not fixed and
use for loop. is recommended to use you must have to
while loop. execute the loop at least
once, it is recommended
to use the do-while loop.

Syntax for(init;condition;incr/decr){ while(condition){ do{


// code to be executed //code to be executed //code to be executed
} } }while(condition);

Example //for loop //while loop //do-while loop


for(int i=1;i<=10;i++){ int i=1; int i=1;
System.out.println(i); while(i<=10){ do{
} System.out.println(i); System.out.println(i);
i++; i++;
} }while(i<=10);

Syntax for for(;;){ while(true){ do{

Centre for Distance Learning, JABU


62
CSC 313-- Object-Oriented Programming Language II

infinitive //code to be executed //code to be executed //code to be executed


loop } } }while(true);

Java For 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.
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

Centre for Distance Learning, JABU


63
CSC 313-- Object-Oriented Programming Language II

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:

public class NestedForExample {


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

Output
11
12
13
21
22
23
31
32
33

Pyramid Example 1:

public class PyramidExample {

Centre for Distance Learning, JABU


64
CSC 313-- Object-Oriented Programming Language II

public static void main(String[] args) {


for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();//new line
}
}
}

Output
*
**
***
****
*****

4.7 Java While 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.
Syntax:
while(condition){
//code to be executed
}

public class WhileExample {


public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}

Centre for Distance Learning, JABU


65
CSC 313-- Object-Oriented Programming Language II

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

4.8 Java do-while Loop

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

public class DoWhileExample {


public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);

Centre for Distance Learning, JABU


66
CSC 313-- Object-Oriented Programming Language II

}
}

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

SUMMARY FOR STUDY SESSION 4


In this study session, you have learnt that:

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.

Centre for Distance Learning, JABU


67
CSC 313-- Object-Oriented Programming Language II

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.

SELF-ASSESSMENT QUESTIONS (SAQs) FOR STUDY SESSION 4

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.

SAQ 4.1 (TESTING LEARNING OUTCOMES 4.1)


Mention three type of loop in java
What are the importance of loop in Java Programming language

SAQ 4.2 (TESTING LEARNING OUTCOMES 4.2)


List various type of “if statement in Java”
What are the usefulness of “Java do-while loop”

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

Centre for Distance Learning, JABU


68
CSC 313-- Object-Oriented Programming Language II

ANSWERS TO SELF- ASSESSMENT QUESTIONS

Answers to Self-Assessment Questions (SAQs) for study Session 1

SAQ 1.1 (TESTING LEARNING OUTCOMES )

What is programming tool or software development tool


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.
Outline the processes involved in compiling java into executive form
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.

SAQ 1.2 (TESTING LEARNING OUTCOMES )

Mention all the concept of OOP.


1. Class
2. Object
3. Polymorphism
4. Encapsulation
5. Inheritance
6. Abstraction
Why is it that Java is a Platform Independent programming language?
Java is platform independent because it is different from other languages like C, C++, etc. which
are compiled into platform specific machines while Java is a write once, run anywhere language.

Answers to Self- Assessment Question (SAQs) for study Session 2

Centre for Distance Learning, JABU


69
CSC 313-- Object-Oriented Programming Language II

SAQ 2.1 (TESTING LEARNING OUTCOMES 2.1)


Describe Procedural Programming?
Procedural Programming language relies on procedures for mode of operation.One of the most
important characteristics of procedural programming is that it relies on procedures that operate
on data
Describe OOP?
Object-Oriented Programming, or OOP, is an approach to problem-solving where all
computations are carried out using objects. An object is a component of a program that 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.
SAQ 2.2 (TESTING LEARNING OUTCOMES 2.2)
List two differences between OOP and Procedural Programming
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.

Mention one of the problems of procedural programming language


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.

SAQ 3.1 (TESTING LEARNING OUTCOMES 3.1)


Describe Abstraction?
One of the most fundamental concept of OOP is Abstraction. Abstraction is a powerful
methodology to manage complex systems. Abstraction is managed by well-defined objects and
their hierarchical classification. For example, a car in itself is a well-defined object, which is
composed of several other smaller objects like a gearing system, steering mechanism, engine,
which are again have their own subsystems. But for humans car is one single object, which can
be managed by the help of its subsystems, even if its inner details are unknown.

Centre for Distance Learning, JABU


70
CSC 313-- Object-Oriented Programming Language II

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.

SAQ 3.2 (TESTING LEARNING OUTCOMES 3.2)


What is a 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.

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.

ANSWER TO SELF-ASSESSMENT QUESTIONS (SAQs) FOR STUDY FOUR

SAQ 4.1 (TESTING LEARNING OUTCOMES 4.1)


Mention three type of loop in java?
There are various types of if statement in Java; if statement, if-else statement, if-else-if ladder
and nested if statement.
What are the importance of loop in Java Programming language?
In Java programming languages, loops are used to execute a set of instructions/functions
repeatedly when some conditions become true.

SAQ 4.2 (TESTING LEARNING OUTCOMES 4.2)


List various type of “if statement in Java”

Centre for Distance Learning, JABU


71
CSC 313-- Object-Oriented Programming Language II

 if statement
 if-else statement
 if-else-if ladder
 nested if statement
 Java if Statement

What are the usefulness of “Java do-while loop”


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. The Java do-while loop is
executed at least once because condition is checked after loop body.

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

Centre for Distance Learning, JABU


72

You might also like