0% found this document useful (0 votes)
7 views126 pages

CMPE 012 - Computer Programming

Uploaded by

Happy Haoru
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)
7 views126 pages

CMPE 012 - Computer Programming

Uploaded by

Happy Haoru
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

POLYTECHNIC UNIVERSITY

OF THE PHILLIPINES
Computer & Electronics Department
Institute of Technology
PUP Sta. Mesa

CMPE 012
Computer Programming

JOHN MICHAEL V. LEGASPI, MSIT


Computer
Programming
CMPE 012

JOHN MICHAEL V. LEGASPI, MSIT

ALL RIGHTS RESERVED. No part of this learning module may be


reproduced, used in any form, or by any means graphic, electronic, or
mechanical, including photocopying, recording, or information storage and
retrieval system without written permission from the authors and the
University.

Published and distributed by:

Polytechnic University of the Philippines

Address: Anonas Road, Sta. Mesa, Manila

Website: [Link]

Email: inquire@[Link]

Tel. No.: (+63 2) 5335-1PUP (5335-1787) or 5335-1777

2|Page
The VMPGO
VISION
PUP: The National Polytechnic University
MISSION
Ensuring inclusive and equitable quality education and promoting lifelong
learning opportunities through a re-engineered polytechnic university by committing to:
• provide democratized access to educational opportunities for the holistic
development of individuals with global perspective.
• offer industry-oriented curricula that produce highly skilled professionals with
managerial and technical capabilities and a strong sense of public service for
nation-building.
• embed a culture of research and innovation.
• continuously develop faculty and employees with the highest level of
professionalism.
• engage public and private institutions and other stakeholders for the attainment
of social development goal.
• establish a strong presence and impact in the international academic
community.
PHILOSOPHY
As a state university, the Polytechnic University of the Philippines believes that:
• Education is an instrument for the development of the citizenry and for the
enhancement of nation-building; and,
• That meaningful growth and transformation of the country are best achieved in
an atmosphere of brotherhood, peace, freedom, justice and nationalist-
oriented education imbued with the spirit of humanist internationalism.
SHARED VALUES AND PRINCIPLES
1. Integrity and Accountability
2. Nationalism
3. Sense of Service
4. Passion for Learning and Innovation
5. Inclusivity
6. Respect for Human Rights and the Environment
7. Excellence
8. Democracy

3|Page
GOALS OF THE COLLEGE/CAMPUS
Provide quality education through instruction, advance research, and extension
services.
Produce technology graduates for industry leaders and job providers.
Develop practical-based learning facilities aligned with the emerging technology
needs.
Obtain National Certificate (NC) in their chosen field for further studies and other
professional certifications.

PROGRAM DESCRIPTION
The Diploma in Computer Engineering Technology (DCpET) program is a confluence
of theoretical and application - oriented courses delivered in traditional and digital
modalities. The program aims to develop proficient, creative, technologically adaptive,
service-oriented, resilient, ethical, national and globally competitive Computer
Engineering Technologists and Technicians with effective communication and
organizational skills through a strong understanding of the fundamental theories and
principles of mathematics, physical sciences, and computer engineering and
technology courses.

The program intends to meet the rising demand for competent and highly skilled
individuals and professionals with technical and managerial capabilities that will serve
as prime movers in the globalized construction industry and who will continuously
provide major contributions, studies, and developments in the field of computer
engineering technology.

COURSE DESCRIPTION

The students will be guided by general principles underlying the practice of object-
oriented programming. They will explore the steps and critical attributes involved in the
paradigm, examine the benefits of using it to develop applications, and compare it to
approaches used in previous programming courses. This course also introduces the
student to the use of JAVA programming in building application align on the design, code
and test pattern in building software application using Object Oriented Programming
approach.

4|Page
INSTITUTIONAL LEARNING OUTCOMES (ILOS)
1. Creative and Critical Thinking. Graduates use their imaginative as well as a rational
thinking ability to life situations in order push boundaries, realize possibilities, and deepen
their interdisciplinary and general understanding of the world.
2. Effective Communication. Graduates are proficient in the four macro skills in
communication (reading, writing, listening, and speaking) and are able to use these
skills in solving problems. Making decisions, and articulating thoughts when engaging
with people in various circumstances.
3. Strong Service Orientation. Graduates exemplify the potentialities of an efficient,
well-rounded and responsible professional deeply committed to service excellence.
4. Community Engagement. Graduates take an active role in the promotion and
fulfillment of various advocacies (educational, social and environmental) for the
advancement of community welfare.
5. Adeptness in the Responsible Use of Technology. Graduates demonstrate
optimized use of digital learning abilities, including technical and numerical skills.
6. Passion to Lifelong Learning. Graduates are enabled to perform and function in the
society by taking responsibility in their quest to know more about the world through
lifelong learning.
7. High Level of Leadership and Organizational Skills. Graduates are developed to
become the best professionals in their respective disciplines by manifesting the
appropriate skills and leaderships qualities.
8. Sense of Personal and Professional Ethics. Graduates show desirable attitudes and
behavior either in their personal and professional circumstances.
9. Sense of National and Global Responsiveness. Graduates’ deep sense of national
compliments the need to live in a global village where one’s culture and other people
culture are respected.

2 | CMPE 012 – Computer Programming


PROGRAM LEARNING OUTCOMES (PLOS)
A. Apply knowledge of mathematics and natural science and engineering fundamentals to
critically and creatively identify and solve broadly and well – defined and practical
mechanical engineering technology problems using modern and state-of-the-art
technologies and application.
B. Conduct investigations of well-defined problems; locate and search relevant codes and
catalogues, conduct standard tests and measurements.
C. Build a project design or research study in accordance with legal, ethical, and
professional standards.
D. Function effectively as an individual, and as a member in diverse technical,
multidisciplinary and multi-cultural teams
E. Design solutions for well-defined technical problems and assist with the design of systems,
components or processes to meet specified needs with appropriate consideration for public
health and safety, cultural, societal, and environmental considerations.
F. Understand and commit to professional ethics and responsibilities and norms of
technologist/ technician practice.
G. Communicate effectively on well-defined engineering activities with the engineering
community and with society at large, by being able to comprehend the work of others,
document their own work, and give and receive clear instructions.
H. Demonstrate knowledge of the societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to engineering technician practice and solutions to
well-defined engineering problems
I. Recognize the need for and have the ability to engage in independent updating in the
context of specialized technical knowledge.
J. Identify contemporary issues within the computer engineering technology profession.
K. Apply appropriate techniques, resources, and modern engineering and IT tools to well-
defined engineering problems, with an awareness of the limitations.
L. Demonstrate knowledge and understanding of engineering management principles and
apply these to one’s own work, as a member or leader in a technical team and to manage
projects in multidisciplinary environments.
M. Demonstrate a significant level of technical competence and global competitiveness in the
field of mechanical engineering technology practice.

3 | CMPE 012 – Computer Programming


COURSE LEARNING OUTCOMES (CLOS).
At the end of this module, students will be able to perform the following:

1. Understand the concepts and principles of Computer Programming align in computer


engineering technology
2. Apply the Design of computer programming using system flowcharts design projects
3. Identify and describe syntax and semantics of basic programming in designing and
testing applications that inline in industry.
4. Perform and align built in functions libraries of programming languages using computer
programming approach and tools used.
5. Demonstrate practical approach of computer programming in computer engineering
technology that aligned in industry standards and ethical considerations.

4 | CMPE 012 – Computer Programming


Preface

This module Computer Programming is a fundamental skill for computer engineering


students, providing the foundation for building software applications and understanding how
computers work. This module is designed to introduce you to the world of programming,
equipping you with the knowledge and tools necessary to become a proficient programmer.
The goal of this course is to equip students with the ability to:
• Understand the basic concepts of programming, including variables, data types, control
structures, and functions.
• Write well-structured and efficient programs using a popular programming language.
• Debug and troubleshoot programming errors.
• Apply programming principles to solve real-world problems.
This module is structured to facilitate a smooth learning journey. It covers a wide range of
topics, including:
• Introduction to programming: Basic concepts, algorithms, and problem-solving
techniques.
• Programming languages: Practical examples using popular languages like Python, Java,
or C++.
• Data structures and algorithms: Fundamental data structures and algorithms for efficient
problem-solving.
• Object-oriented programming: Concepts of classes, objects, inheritance, and
polymorphism.
• Programming practices: best practices for writing clean, maintainable, and efficient code.
By the end of this course, you will have a strong foundation in programming and be well-
prepared to tackle more advanced topics in your computer engineering studies.

5 | CMPE 012 – Computer Programming


6 | CMPE 012 – Computer Programming
Table of Contents

Preliminaries 1
The VMPGO 1
MISSION 2
PHILOSOPY 2
SHARED VALUES AND PRINCIPLES 3
GOAL OF THE COLLEGES / CAMPUS 3
PROGRAM DESCRIPTION 4
COURSE DESCRIPTION 4
INSTITUTIONAL LEARNING OUTCOME (ILO’s) 5
PROGRAM LEARNING OUTCOME (PLO’s) 5
COURSE LEARNING OUTCOME (CLO’s) 7

Chapter I. Basic Concepts in Programming for Engineering 1


Introduction 1
What Computer Programs 2
Differences of Program to Programming Langauges 2
Types of Programming Langauges 3
Program Compiler 3
Computer Algorithms 4
System Flowcharts 4
Chapter 2. Introduction to JAVA 1
Introduction 1
What is JAVA 2
JAVA Platform 2
Use of JAVA 3
Feautures of JAVA 3
Types of JAVA 4
JVM | JAVA Virtual Environment 4
JRE | Java Runtime Environment 5
JDK | JAVA Development Kit 5
JAVA and JDK Installation 7
Assessment 1 9

Chapter 3. JAVA Variables and Data Types 10


Introduction 16
JAVA Variable 18
JAVA Data types 18
JAVA Program and Syntax 19
Assessment 2 20
Chapter 4 JAVA Operators 21
Arithmetic Operators 22
Unary Arithmetic Operator 22
Relational Operators 24
Logical Operators 25
Bitwise Operators 26
Assignment Operators 28
Conditional Operators 29
Assessment 3 29
Chapter 5. Control Structure : If and switch case 30
Introduction 30
JAVA if statement 31

7 | CMPE 012 – Computer Programming


JAVA if else statement 31
JAVA [Link] else statement 32
JAVA nested if Error! Bookmark not defined.
JAVA switch case 34
Assessment 4 35
Chapter V. Control Structure : Looping 30
Introduction 40
JAVA for loop 42
JAVA while loop 43
JAVA do..while loop 44
Assessment 5 45
Chapter VI. Basic Concepts in Object Oriented Programming 46
JAVA OOP Concepts 46
types of Programming Languages 46
Advantage and Disadvantage of OOP 46
OOP Feautures 47
Assessment 6 49
Chapter VII. Basic OOP – Class and Object 51
What is JAVA Class 51
How to create a JAVA Class 51
Types of JAVA Class 52
What is object in JAVA 52
How to create JAVA Objects 53
Assessment 7 53

Chapter 1

BASIC CONCEPTS IN PROGRAMMING FOR ENGINEERING

8 | CMPE 012 – Computer Programming


Overview:
By learning the basic foundations of programming, engineering students can
develop critical thinking, logical reasoning, and problem-solving abilities. These skills are
invaluable in various engineering fields, from designing and analyzing systems to
automating processes and developing innovative solutions. Moreover, programming
knowledge empowers engineers to collaborate effectively with software developers and
leverage technology to enhance their work.

Learning Outcomes:
✓ Understand the basic term in programming and programming languages and each type
of programming used.
✓ Understand the concept of computer algorithm and some logic formulation
✓ Explain the use and term of programming in design using flowchart
✓ Develop a system flowchart in different scenarios

Course Materials:

Programmers (developers) can communicate with computers by using a programming


language, which is a computer [Link] is a set of instructions written in a certain language
(such as C, C++, Java, or Python) to carry out a specific [Link], mobile applications,
and desktop applications can all be made using a programming language.

• Program: A program is a set of instructions that a computer can execute to perform a


specific task. It's essentially a sequence of commands that the computer follows to achieve
a desired outcome. Think of it as a recipe for the computer to follow.
• Computer Programmer: A computer programmer is a person who writes, designs,
develops, tests, and maintains computer programs. They are skilled in various
programming languages and use their problem-solving abilities to create software
applications.
• Computer Programming Languages: These are the languages used to write computer
programs. They provide a set of rules and syntax that computers can understand and
execute. There are many different programming languages, each with its own strengths
and weaknesses. Some popular examples include Python, Java, C++, JavaScript, and
C#.

Categories of Programming Languages


• Machine Language − This is the language designed specifically for computer hardware.
The central processing unit (CPU) of a computer system directly affects such language.
• Assembly Language − It is a language for simplifying and making readable machine
code.

9 | CMPE 012 – Computer Programming


• High Level Language − Algorithm to insert item in a data structure. The high level
language is straightforward, simple to understand, and close to [Link]-level
languages are important because they facilitate the creation of complicated software and
offer the following benefits:
1. Users do not need to master the high-level language in order to work with
it, unlike assembly language or machine language.
2. High-level languages are simple to learn and comprehend because they
resemble real languages.
3. High-level languages are created in a way that makes faults easy to see.
4. High-level language is simple to maintain and is simple to change.
5. A high-level language speeds up development.
6. High-level languages are more affordable to create.
• System Language − A system programming language is a programming language that
is used to create systems. These languages are made for creating systems, which
typically demand different development methodologies than application software.
• Scripting Language − Programming languages that use high-level constructs to
comprehend and carry out one command at a time are referred to as scripting
languages. Scripting languages, as opposed to more structured and compiled languages
like C and C++, tend to be faster to learn and to learn to code in.

Common Programming Languages


1. Python - Guido van Rossum developed the straightforward language Python in 1991.
Because it is an interpreted language, it does not require compilation before usage. Many
features are available in Python, such as support for various programming paradigms
(imperative, object-oriented, etc.), exception handling (try/except/finally), dynamic typing
(dynamic type checking), a very small runtime environment with fewer dependencies than
other languages, full Unicode support, and much more.
2. Java - James Gosling, Mike Sheridan, Chris Warth, Ed Frank, and Patrick Naughton
started it in June [Link], after going through several name changes, it was first
made available at Sun Microsystems in 1996. (Oak, Green, and Java from Java coffee).
Java is a platform for computers as well as a programming language. Java can be used
by programmers to create applications for mobile devices, laptops, tablets, and wearables.
Additionally, many of its instructions are identical due of the syntax's C/C++ foundation.
Java was created for high-level app development, in contrast to C/C++ which allows
programmers to write low-level code for systems programming.
3. TypeScript - Microsoft created and maintains TypeScript, an object-oriented language that
is open-source. With the addition of types, classes, and modules, this superset of
JavaScript enables programmers to create programs that run on any platform or browser
without the need for further compilation. Large-scale web apps and well-known libraries
like AngularJS use [Link], TypeScript is very compatible with the majority of
existing JavaScript codebases because it is built on ECMAScript 6th Edition (ES6).
4. C# - Microsoft created the object-oriented programming language C# (C Sharp) as part of
[Link] project. Strong typing, imperative, declarative, functional, generic, object-oriented
(class-based), and component-oriented programming paradigms are all covered by the
language, which is a cross between C and C++.
5. JavaScript - A simple programming language used in web browsers is called JavaScript.
It is a scripting language that may be used for client-side (web-based) and server-side
(web server-based) [Link] makes it possible for websites to store and use data,

10 | CMPE 012 – Computer Programming


access so-called "components" of pages, alter the information in those components,
perform functions whenever an event occurs on a website, make pages more interactive,
and so forth.
Additionally, it is supported by all major browsers, making it accessible to almost all users across
a variety of devices (Windows PCs, Macs, Linux computers).In the current era of online
development, JavaScript is without a doubt one of the most significant programming languages.

What is compiler?
A compiler is a program that converts a high-level language (such as C, C++, or Java) to a low-
level language (object program or machine program).The compiler also detects numerous
problems that occur during the compilation of a program. Various phases are used by the compiler
to transform high-level language to low-level language. A character stream entered by the
customer is compiled through several stages before providing the destination language.

The compiler's job is to translate a program written in one language into another without altering
its meaning. A program written in the HLL programming language is divided into two sections
when it is implemented. The source code is compiled and converted into object code in the first
component (low-level language).The second component uses the assembler to translate the
object program into the target code.

What is an Computer Algorithm?


An algorithm is a step-by-step procedure or a set of rules to be followed to achieve a
specific task or solve a problem. It's essentially a recipe for solving a problem, providing a clear
sequence of instructions.
• Algorithms are independent of programming languages. You can express the
same algorithm in different languages.
• Efficiency is a crucial aspect of algorithms. Some algorithms are more efficient
than others in terms of time or space complexity.
• There are many different types of algorithms, each designed for specific tasks,
such as searching, sorting, graph traversal, and more.

Algorithms are like menus or instruction materials because they provide a structured set
of steps to achieve a specific goal.

• Just as a menu outlines the available dishes and their ingredients, an algorithm
outlines the specific steps required to solve a problem or achieve a desired
outcome. Both menus and algorithms offer a clear and organized approach to
guiding individuals towards their objectives.
• Similarly, instruction materials, such as manuals or tutorials, provide step-by-step
instructions to accomplish a task. Algorithms serve a similar purpose in the realm
of computer science, providing detailed instructions for computers to follow.

11 | CMPE 012 – Computer Programming


• In essence, both menus and instruction materials, like algorithms, offer a
structured and sequential approach to guiding individuals or machines towards a
specific outcome.

Example:

Create an algorithm the user requires to input Two numbers, num1 and num2. And display
the results using sum. Output: The sum of num1 and num2.

Steps:
1. Initialize a variable sum to 0. This variable will store the final result.
2. Add num1 to sum. This updates the sum variable to include the value of num1.
3. Add num2 to sum. This further updates the sum variable to include the value of
num2.
4. Return sum. The final value of sum represents the sum of num1 and num2.
Example:
If num1 is 5 and num2 is 3:
1. sum is initialized to 0.
2. sum becomes 5 (0 + 5).
3. sum becomes 8 (5 + 3).
4. The function returns 8 as the sum of 5 and 3.

Why Algorithms Matter in Engineering


Algorithms are fundamental to computer science and engineering. They form the
backbone of software applications, from simple calculators to complex AI systems. Understanding
algorithms is essential for:
✓ Problem-solving: Algorithms provide a structured approach to breaking down complex
problems into smaller, manageable steps.
✓ Efficiency: Algorithms can be analyzed to determine their time and space complexity,
helping engineers optimize code for performance.
✓ Design and implementation: Algorithms serve as blueprints for designing and
implementing software solutions.

What is flowchart?
Flowcharts are written with program flow from top to bottom of a page. Each command is placed
in an appropriate-shaped box, and arrows are utilized to control program progress. Flowcharts
frequently employ the following shapes:

Basic Symbol used in flowcharting

12 | CMPE 012 – Computer Programming


Example #1: create a flowchart on the sample algorithm above
Enter Number 1
START
Enter Number 2

Display Results of
Sum = n1 + n2 ;
Sum
Chapter 2

INTRODUCTION TO JAVA
STOP

13 | CMPE 012 – Computer Programming


Overview:
Java is an object-oriented programming language with its runtime environment. It
is a combination of features of C and C++ with some essential additional concepts. Java
is well suited for both standalone and web application development and is designed to
provide solutions to most of the problems faced by users of the internet era.

Learning Outcomes:
After successful completion of this lesson, you should be able to:
● Learn what is Java programming languages
● Discover the features of Java
● Identify how to install java
● Modify the use of JDK, JRE and JVM
● Code the first java program

Course Materials:

What is JAVA?
Java is a programming language and a platform. Java is a high level, robust, object-
oriented and secure programming language.
Java is a general-purpose, class-based, object-oriented programming language designed
for having lesser implementation dependencies. It is a computing platform for application
development. Java is fast, secure and reliable therefore it is widely used for developing Java
applications in laptops, data centers, game consoles, scientific supercomputers, cell phones, etc.

What is Java Platform?


Java Platform is a collection of programs that helps programmers to efficiently develop
and run Java applications. It includes an execution engine, a compiler and a set of libraries in it.
It is a set of computer software and specifications. James Gosling developed the Java platform
at Sun Microsystems and it was later acquired by the Oracle Corporation.

Where is JAVA being used ?

Earlier Java was only used to design and program small computing devices, but it was
later adopted as one of the platform-independent programming languages, and now according to
Sun, 3 billion devices run Java.
Java is one of the most important programming languages in today's IT industries.

14 | CMPE 012 – Computer Programming


● JSP - In Java, JSP (Java Server Pages) is used to create dynamic web pages, such as
in PHP and ASP.
● Applets - Applets are another type of Java programs that are implemented on Internet
browsers and are always run as part of a web document.
● J2EE - Java 2 Enterprise Edition is a platform-independent environment that is a set of
different protocols and APIs and is used by various organizations to transfer data
between each other.
● JavaBeans - This is a set of reusable software components that can be easily used to
create new and advanced applications.
● Mobile - In addition to the above technology, Java is widely used in mobile devices
nowadays, many types of games and applications are being made in Java.

Types of JAVA Application


1. Web Application - Java is used to create server-side web applications.
Currently, Servlet, JSP, Struts, JSF, etc. technologies are used.
2. Standalone Application - It is also known as the desktop application or window-
based application. An application that we need to install on every machine or
server such as media player, antivirus, etc. AWT and Swing are used in java for
creating standalone applications.
3. Enterprise Application - An application that is distributed in nature, such as
banking applications, etc. It has the advantage of high-level security, load
balancing, and clustering. In Java, EJB is used for creating enterprise
applications.
4. Mobile Application - Java is used to create application software for mobile
devices. Currently, Java ME is used for building applications for small devices,
and also Java is a programming language for Google Android application
development.

Features of JAVA
● Object-Oriented - Java supports the features of object-oriented programming. Its object
model is simple and easy to expand.
● Platform independent - C and C++ are platform dependency languages hence the
application programs written in one Operating system cannot run in any other Operating
system, but in platform independence language like Java application programs written
in one Operating system can able to run on any Operating system.
● Simple - Java has included many features of C / C ++, which makes it easy to
understand.
● Secure - Java provides a wide range of protection from viruses and malicious
programs. It ensures that there will be no damage and no security will be broken.
● Portable - Java provides us with the concept of portability. Running the same program
with Java on different platforms is possible.
● Robust - During the development of the program, it helps us to find possible mistakes
as soon as possible.
● Multi-threaded - The multithreading programming feature in Java allows you to write a
program that performs several different tasks simultaneously.
● Distributed - Java is designed for distributed Internet environments as it manages
the TCP/IP protocol

15 | CMPE 012 – Computer Programming


JVM | JAVA VIRTUAL MACHINE

Java Virtual Machine (JVM) is a engine that provides runtime environment to drive the
Java Code or applications. It converts Java bytecode into machines language. JVM is a part of
Java Run Environment (JRE). In other programming languages, the compiler produces machine
code for a particular system. However, Java compiler produces code for a Virtual Machine known
as Java Virtual Machine.
Here is how JVM works
First, Java code is compiled into bytecode. This bytecode gets interpreted on different
machines
Between host system and Java source, Bytecode is an intermediary language.
JVM in Java is responsible for allocating memory space.

Working with Java Virtual Machine

JVM Architecture

1) ClassLoader
The class loader is a subsystem used for loading class files. It performs three major
functions viz. Loading, Linking, and Initialization.
2) Method Area
JVM Method Area stores class structures like metadata, the constant runtime pool, and
the code for methods.

3) Heap

16 | CMPE 012 – Computer Programming


All the Objects, their related instance variables, and arrays are stored in the heap. This
memory is common and shared across multiple threads.
4) JVM language Stacks
Java language Stacks store local variables, and it’s partial results. Each thread has its
own JVM stack, created simultaneously as the thread is created. A new frame is created
whenever a method is invoked, and it is deleted when method invocation process is complete.
5) PC Registers
PC register store the address of the Java virtual machine instruction which is currently
executing. In Java, each thread has its separate PC register.
6) Native Method Stacks
Native method stacks hold the instruction of native code depends on the native library. It
is written in another language instead of Java.
7) Execution Engine
It is a type of software used to test hardware, software, or complete systems. The test
execution engine never carries any information about the tested product.
8) Native Method interface
The Native Method Interface is a programming framework. It allows Java code which is
running in a JVM to call by libraries and native applications.
9) Native Method Libraries
Native Libraries is a collection of the Native Libraries(C, C++) which are needed by the
Execution Engine.

Software Code Compilation & Execution process

In order to write and execute a software program, you need the following
1) Editor – To type your program into, a notepad could be used for this
2) Compiler – To convert your high language program into native machine code
3) Linker – To combine different program files reference in your main program together.
4) Loader – To load the files from your secondary storage device like Hard Disk, Flash
Drive, CD into RAM for execution. The loading is automatically done when you execute your code.
5) Execution – Actual execution of the code which is handled by your OS & processor.

JRE | JAVA RUNTIME ENVIRONMENT


JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The
Java Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of JVM. It
physically exists. It contains a set of libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun
Micro Systems.

17 | CMPE 012 – Computer Programming


JDK | JAVA DEVELOPMENT KIT

JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It physically exists. It
contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:
o Standard Edition Java Platform
o Enterprise Edition Java Platform
o Micro Edition Java Platform

The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), etc. to
complete the development of a Java Application.

18 | CMPE 012 – Computer Programming


How to Install JDK and JAVA

Step1 : Download the application here. : [Link]


[Link]

Step 2 :

1. Accept License Agreement


2. Download latest Java JDK for your version(32 or 64 bit) of java for Windows.
Step 3) Once the download is complete, run the exe for install JDK. Click Next

Step 4) Select the PATH for Java installation and click next.

Step 5) Once installation is complete click Close

19 | CMPE 012 – Computer Programming


How to set Environment Variables in Java: Path and Classpath

The PATH variable gives the location of executables like javac, java etc. It is possible to
run a program without specifying the PATH but you will need to give full path of executable
like C:\Program Files\Java\jdk-13.0.1\bin\javac [Link] instead of simple javac [Link]
The CLASSPATH variable gives location of the Library Files.
Let's look into the steps to set the PATH and CLASSPATH
Step 1) Right Click on the My Computer and Select the properties

Step 2) Click on advanced system settings Step 3) Click on Environment Variables

Step 4) Click
on new Button
of User

variables Step 5) Type PATH in the


Variable name.

20 | CMPE 012 – Computer Programming


Step 6) Copy the path of bin folder which is installed in JDK folder.

Step 7) Paste Path of bin folder in Variable value and click on OK Button.

Assessment 1

True or false
______ 1. JRE is an acronym for Java Runtime Environment
______ 2. The PATH variable gives the location of executables like javac

21 | CMPE 012 – Computer Programming


______ 3. The JDK contains a private Java Virtual Machine (JVM) and a few other resources
such as an interpreter/loader (java), a compiler (javac), an archiver (jar)
______4. The class loader is a subsystem used for loading class files
______5. The implementation of JVM is also actively released by other companies besides Sun
Micro Systems.

ENUMERATION. :

A : JVM ARCHITECTURE

B : Software Code Compilation & Execution process

C : TYPES OF JAVA APPLICATION

22 | CMPE 012 – Computer Programming


D : USE OF JAVA

Unit II.

JAVA DATA TYPES AND VARIABLES

Overview:
Variables are the nouns of a programming language: they are the entities (values,
data) that act or are acted upon. A variable declaration always contains two components:
the type of the variable and its name. Also, the location of the variable declaration, that
is, where the declaration appears in relation to other code elements, determines the
scope of the variable. All variables in the Java language must have a data type. A
variable's data type determines the values that the variable can have and the operations
that can be performed on it.

Learning Outcomes:

After successful completion of this lesson, you should be able to:


● Understand the of the variable and data types in java programming
● Naming and arranging variable names
● Distinguished the use of data types in java coding
● Understand the java programming syntax

Course Materials:

23 | CMPE 012 – Computer Programming


What is a Variable in Java?

Variable in Java is a data container that stores the data values during Java program
execution. Every variable is assigned data type which designates the type and quantity of value
it can hold. Variable is a memory location name of the data. The Java variables have mainly three
types : Local, Instance and Static.
In order to use a variable in a program you to need to perform 2 steps
1. Variable Declaration
2. Variable Initialization
Examples of other Valid Declarations are
int a,b,c;
float pi;
double d;
char a;

Variable Initialization: To initialize a variable, you must assign it a valid value.

Example of other Valid Initializations are:

pi =3.14f;
do =20.22d;
a=’v’;
int a=2,b=4,c=6;
float pi=3.14f;
double do=20.22d;
char a=’v’;

Types of variables
In Java, there are three types of variables:
▪ Local Variables - local Variables are a variable that are declared inside the body of a
method.
▪ Instance Variables - Instance variables are defined without the STATIC keyword .They
are defined Outside a method declaration. They are Object specific and are known as
instance variables.
▪ Static Variables - Static variables are initialized only once, at the start of the program
execution. These variables should be initialized first, before the initialization of any
instance variables.

Example: Types of Variables in Java


class ooplesson {
static int a = 1; //static variable
int data = 99; //instance variable
void method() {
int b = 90; //local variable
}
}

24 | CMPE 012 – Computer Programming


What is Data Types in Java?
Data Types in Java are defined as
specifiers that allocate different sizes and
types of values that can be stored in the
variable or an identifier. Java has a rich set of
data types.

Data types in Java can be divided into two


parts :
▪ Primitive Data Types :- which
include integer, character, boolean,
and float
▪ Non-primitive Data Types :- which
include classes, arrays and
interfaces.

Why Data type is important:

▪ Every variable in Java has a data type which tells the compiler what type of
variable it as and what type of data it is going to store.
▪ Data type specifies the size and type of values.
▪ Information is stored in computer memory with different data types.
▪ Whenever a variable is declared, it becomes necessary to define a data type that
what will be the type of data that variable can hold.

Example :

public class SampleDataTypes{


public static void main(String args[]){
byte byteVar = 5;
short shortVar = 20;
int intVar = 30;
long longVar = 60;
float floatVar = 20;
double doubleVar = 20.123;
boolean booleanVar = true;
char charVar ='W';

[Link]("Value Of byte Variable is " + byteVar);


[Link]("Value Of short Variable is " + shortVar);
[Link]("Value Of int Variable is " + intVar);
[Link]("Value Of long Variable is " + longVar);
[Link]("Value Of float Variable is " + floatVar);
[Link]("Value Of double Variable is " + doubleVar);
[Link]("Value Of boolean Variable is " + booleanVar);
[Link]("Value Of char Variable is " + charVar);

25 | CMPE 012 – Computer Programming


}
}

Program Output :

Value Of byte Variable is 5


Value Of short Variable is 20
Value Of int Variable is 30
Value Of long Variable is 60
Value Of float Variable is 20.0
Value Of double Variable is 20.123
Value Of boolean Variable is true
Value Of char Variable is W

Our First JAVA Program :

In this lesson, we will learn how to write the simple program of java. We can write a simple hello
java program easily after installing the JDK.
To create a simple java program, you need to create a class that contains the main
method. Let's understand the requirement first.
Type the following java code in your text editor ( notepad , sublime, notepad ++ )

public class ooplesson{


public static void main(String args[]){
[Link](" Welcome to Object Oriented Programming Course");
}
}

save this file as [Link]

To compile: javac [Link]


To execute: java ooplesson

Parameters used in First Java Program


Let's see what is the meaning of class, public, static, void, main, String[], [Link]().
▪ class keyword is used to declare a class in java.
▪ public keyword is an access modifier which represents visibility. It means it is visible to
all.
▪ static is a keyword. If we declare any method as static, it is known as the static method.
The core advantage of the static method is that there is no need to create an object to
invoke the static method. The main method is executed by the JVM, so it doesn't require
to create an object to invoke the main method. So it saves memory.
▪ void is the return type of the method. It means it doesn't return any value.
▪ main represents the starting point of the program.
▪ String[] args is used for command line argument. We will learn it later.

26 | CMPE 012 – Computer Programming


▪ [Link]() is used to print statement. Here, System is a class, out is the
object of PrintStream class, println() is the method of PrintStream class. We will learn
about the internal working of [Link] statement later.

Assessment 2

PART 1 : Multiple Choice – Select the best answer from list of choices

[Link] type should you use to represent the average grade for a course?
A. int
B. double
C. boolean
D. String
[Link] type should you use to represent the number of people in a household?
A. int
B. double
C. boolean
D. String
[Link] type should you use to hold the first name of a person?
A. int
B. double
C. boolean
D. String
[Link] type should you use to record if it is raining or not?
A. int
B. double
C. boolean
D. String
[Link] type should you use to represent the amount of money you have?
A. int
B. double
C. boolean
D. String

PART 2: JAVA CODE -

1. underline all of the variable declarations in the following code


public class Test2

27 | CMPE 012 – Computer Programming


{
public static void main(String[] args)
{
int numLives;
numLives = 0;
[Link](numLives);
double health;
health = 8.5;
[Link](health);
boolean powerUp;
powerUp = true;
[Link](powerUp);
}
}
}

Unit III.

JAVA Operators

Overview:

Java operators are symbols that are used to perform mathematical or logical
manipulations. Java is rich with built-in operators. On this module we will elaborate each
types and transfer in to series of java code to let you understand each use.

Learning Outcomes:

After successful completion of this lesson, you should be able to:

● Understand the use of java operators


● Demonstrate each function when to use
● Apply the java operator into series of java code

Course Materials:

Arithmetic Operator

28 | CMPE 012 – Computer Programming


The way we calculate mathematical calculations, in the same way, Java
provides arithmetic operators for mathematical operations. It provides operators for all necessary
mathematical calculations.

Example of Arithmetic operations in java. Type this code in your text editor then save as
[Link] then compile and run.

public class arithop {


public static void main(String[] args) {
//Variables Definition and Initialization
int number1 = 12, number2 = 4;

//Addition Operation
int sum = number1 + number2;
[Link]("Sum is: " + sum);

//Subtraction Operation
int dif = number1 - number2;
[Link]("Difference is : " + dif);

//Multiplication Operation
int mul = number1 * number2;
[Link]("Multiplied value is : " + mul);

//Division Operation
int div = number1 / number2;
[Link]("Quotient is : " + div);

//Modulus Operation
int rem = number1 % number2;

29 | CMPE 012 – Computer Programming


[Link]("Remainder is : " + rem);

}
}

Program output :

Sum is: 16
Difference is : 8
Multiplied value is : 48
Quotient is : 3
Remainder is : 0

UNARY OPERATOR

In Java, unary arithmetic operators are used to increasing or decreasing the value of an
operand. Increment operator adds 1 to the value of a variable, whereas the decrement operator
decreases a value.

Syntax. :
val++;
val--;

Example of UNARY operations in java. Type this code in your text editor then save as
[Link] then compile and run.

public class unaryop {


public static void main(String[] args) {
int r = 6;
[Link]("r=: " + r++);
[Link]("r=: " + r);

int x = 6;

30 | CMPE 012 – Computer Programming


[Link]("x=: " + x--);
[Link]("x=: " + x);

int y = 6;
[Link]("y=: " + ++y);

int p = 6;
[Link]("p=: " + --p);
}
}

Program output

r=: 6
r=: 7
x=: 6
x=: 5
y=: 7
p=: 5

RELATIONAL OPERATORS
The Java Relational operators compare between operands and determine the relationship
between them.
There are six types of relational operators in Java, these are:

Example of Relational operations in java. Type this code in your text editor then save as
[Link] then compile and run.

public class relatiop {

public static void main(String[] args) {

31 | CMPE 012 – Computer Programming


//Variables Definition and Initialization
int num1 = 12, num2 = 4;

//is equal to
[Link]("num1 == num2 = " + (num1 == num2) );

//is not equal to


[Link]("num1 != num2 = " + (num1 != num2) );

//Greater than
[Link]("num1 > num2 = " + (num1 > num2) );

//Less than
[Link]("num1 < num2 = " + (num1 < num2) );

//Greater than or equal to


[Link]("num1 >= num2 = " + (num1 >= num2) );

//Less than or equal to


[Link]("num1 <= num2 = " + (num1 <= num2) );

}
}
LOGICAL OPERATORS
The Java Logical Operators work on the Boolean operand. It's also called Boolean logical
operators. It operates on two Boolean values, which return Boolean values as a result.

Example of logical operations in java. Type this code in your text editor then save as
[Link] then compile and run.

public class logicalop {


public static void main(String[] args) {
//Variables Definition and Initialization
boolean bool1 = true, bool2 = false;

//Logical AND
[Link]("bool1 && bool2 = " + (bool1 && bool2));

32 | CMPE 012 – Computer Programming


//Logical OR
[Link]("bool1 || bool2 = " + (bool1 | bool2) );

//Logical Not
[Link]("!(bool1 && bool2) = " + !(bool1 && bool2));

}
}

Program Output

bool1 && bool2 = false

bool1 || bool2 = true

!(bool1 && bool2) = true

JAVA BITWISE OPERATOR


The Java Bitwise Operators allow access and modification of a particular bit inside a
section of the data. It can be applied to integer types and bytes, and cannot be applied to float
and double.

33 | CMPE 012 – Computer Programming


Example of BITWISE operations in java. Type this code in your text editor then save as
[Link] then compile and run.

public class bitwiseop {


public static void main(String[] args) {
//Variables Definition and Initialization
int num1 = 30, num2 = 6, num3 =0;

//Bitwise AND
[Link]("num1 & num2 = " + (num1 & num2));

//Bitwise OR
[Link]("num1 | num2 = " + (num1 | num2) );

//Bitwise XOR
[Link]("num1 ^ num2 = " + (num1 ^ num2) );

//Binary Complement Operator


[Link]("~num1 = " + ~num1 );

//Binary Left Shift Operator


num3 = num1 << 2;
[Link]("num1 << 1 = " + num3 );

//Binary Right Shift Operator


num3 = num1 >> 2;
[Link]("num1 >> 1 = " + num3 );

//Shift right zero fill operator


num3 = num1 >>> 2;
[Link]("num1 >>> 1 = " + num3 );

}
}

Program Output

num1 & num2 = 6


num1 | num2 = 30
num1 ^ num2 = 24
~num1 = -31
num1 << 1 = 120
num1 >> 1 = 7
num1 >>> 1 = 7

JAVA ASSIGNMENT OPERATOR

34 | CMPE 012 – Computer Programming


The Java Assignment Operators are used when you want to assign a value to the
expression. The assignment operator denoted by the single equal sign =.

In a Java assignment statement, any expression can be on the right side and the left side
must be a variable name. For example, this does not mean that "a" is equal to "b", instead, it
means assigning the value of 'b' to 'a'. It is as follows:
syntax :
variable = expression;

EXAPLES :

int a = 6;
float b = 6.8F;

public class ChainAssign {


public static void main(String args[]) {
int a, b, c;
a = b = c = 100; // set a, b, and c to 100
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("c = " + c);
}
}

CONDITIONAL OPERATOR
The Java Conditional Operator selects one of two expressions for evaluation, which is
based on the value of the first operands. It is also called ternary operator because it
takes three arguments.

SYNTAX. : expression1 ? expression2:expression3;

The above syntax means that if the value given in Expression1 is true, then Expression2
will be evaluated; otherwise, expression3 will be evaluated.

Example :

public class condiop {


public static void main(String[] args) {
String out;
int a = 6, b = 12;
out = a==b ? "Yes":"No";
[Link]("Ans: "+out);
}
}

In the above example, the condition given in expression1 is false because the value of a
is not equal to the value of b.

35 | CMPE 012 – Computer Programming


Assessment 3

Multiple choice

[Link] is the value of b after the following code execute ?


int b = 5;
b = b * 2;
A. b = 5
B. b = 2
C. b = 7
D. b = 10

2. What are the values of x,y, and z, after the following code execute ?
int x = 0;
int y = 1;
int z = 2;
x = y;
y = y * 2;
z = 3;

A. x = 0, y = 1, z = 2
B. x = 1, y = 2, z = 3

36 | CMPE 012 – Computer Programming


C. x = 2, y = 2, z = 3
D. x = 1, y = 0, z = 3

What is the output of the following java code. :


public class OperatorExample
{
public static void main(String[] args)
{
[Link](2 + 3);
[Link](2 - 3);
[Link](2 * 3);
[Link](2 / 3);
[Link](2 == 3);
[Link](2 != 3);
}
}

Write your answer here :

Unit IV.

CONTROL STRUCTURE: if and switch


Overview:

Java decision-making statements allow you to make a decision, based upon the result of
a condition.
All the programs in Java have set of statements, which are executed sequentially in the
order in which they appear. It happens when jumping of statements or repetition of certain
calculations is not necessary. However, there may arise some situations where programmers
have to change the order of execution of statements based on certain conditions which involve
kind of decision-making statements.
On this chapter, we will create a source code with java decision process from sort of if
statement to switch statement .

Learning Outcomes:
After successful completion of this lesson, you should be able to:
● produce informative layouts using text with an appropriate color for a theme
● construct and design graphics with styles
● create a suitable font for a specific event

37 | CMPE 012 – Computer Programming


● play with the color combinations using gradients
● create and design your own logo

Course Materials:

Decision Making

Decision Making in programming is similar to decision making in real life. In programming


also we face some situations where we want a certain block of code to be executed when some
condition is fulfilled.

Java’s Selection statements:


▪ if

▪ if-else

▪ nested-if

▪ if-else-if

▪ switch-case

The if statement

if statement is the most simple decision making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e if a certain condition is true
then a block of statement is executed otherwise not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}

Examples

public class oopIfDemo


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

if (i > 15)

38 | CMPE 012 – Computer Programming


[Link]("10 is less than 15");

// This statement will be executed


// as if considers one statement by default
[Link]("I am Not in if");
}
}

if… Else statement:


We use if-else statements as well, to control the program flow based on some condition.
But it is has a difference
It executes some statement code block if the condition is true and if the condition is false,
it executes else statement code block.

Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}

Examples

class IfElseDemo
{
public static void main(String args[])
{
int i = 10;

if (i < 15)
[Link]("i is smaller than 15");
else
[Link]("i is greater than 15");
}
}

This example the user will input age and test the condition if eligible to vote…

import [Link].*;
public class Vote {
/** Enter the age of the person
* .it will show if the person is eligible to vote

39 | CMPE 012 – Computer Programming


*/
public static void main(String[] args) {
int age ;
[Link]("Enter the age : ") ;
// code to enter data from the keyboard.
Scanner sc = new Scanner([Link]);
age = [Link]();
if (age >= 18) {
[Link]("\n The person is eligible to vote.");
}
else {
[Link]("\n The person is not eligible to vote.");
}
}
}

If else if..else statement here, a user can decide among multiple [Link] if statements are
executed from the top down. As soon as one of the conditions controlling the if is true, the
statement associated with that if is executed, and the rest of the ladder is bypassed. If none of
the conditions is true, then the final else statement will be executed.
Syntax:
if (condition)
statement;
else if (condition)
statement;
.
else
statement;
Example :
public class oopifelseifDemo
{
public static void main(String args[])
{
int i = 20;

if (i == 10)
[Link]("i is 10");
else if (i == 15)
[Link]("i is 15");
else if (i == 20)
[Link]("i is 20");
else
[Link]("i is not present");
}
}

Example 2 :
import [Link];
public class AverageGrade {
/** Enter the marks of 3 subjects and find the average and the grade .

40 | CMPE 012 – Computer Programming


* .If avg>=80, grade A
* If avg>=60, grade B
* .If avg>=40, grade C
* .If avg<40, failed in the exam
*/
public static void main(String[] args) {
int s1, s2, s3 , sum , avg;
[Link]("Enter your marks for the 3 subjects");
Scanner sc = new Scanner([Link]);
s1 = [Link]();
s2 = [Link]();
s3 = [Link]();
sum = s1 + s2 + s3;
avg = sum/3;
[Link]("your avg is "+avg);
if (avg >= 80) {
[Link]("You got A grade");
}
else if ( avg >= 60) {
[Link]("You got B grade");
}
else if ( avg >= 40) {
[Link]("You got C grade");
}
else {
[Link]("You Failed in this exam");
}
}
}
NESTED IF
A nested if is an if statement that is the target of another if or else. Nested if statements
means an if statement inside an if statement. Yes, java allows us to nest if statements within if
statements. i.e, we can place an if statement inside another if statement.
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
Example :
class NestedIfDemo
{
public static void main(String args[])
{
int i = 10;

if (i == 10)
{
// First if statement

41 | CMPE 012 – Computer Programming


if (i < 15)
[Link]("i is smaller than 15");

// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
[Link]("i is smaller than 12 too");
else
[Link]("i is greater than 15");
}
}
}

Example 2 :
import [Link];
public class ScienceEligible {

public static void main(String[] args) {


int classname ;
float marks ;
// code to enter data from the keyboaard.
[Link]("Enter the classname and marks");
Scanner sc = new Scanner([Link]);
classname = [Link]();
marks = [Link]();
if (classname == 11) {
if ( marks >= 85) {
[Link]("You are eligible for Science stream !!");
}
else {
[Link]("Sorry ! You are not eligible for Science
stream1 !");
}
}
else {
[Link]("Sorry ! You are not eligible for Science stream !");
}
}
}

The switch case


It has 4 parts namely:
Switch:
It is the control keyword allowing us to make a choice out of multiple options.
Case:
This contains the options along with case labels out of which we have to choose our
relevant option.
The execution starts with the match case.
Break:

42 | CMPE 012 – Computer Programming


It is a jump statement which takes the control out of the loop.
It prevents the unnecessary flow of control to the subsequent cases after the match case.
Default:
The default code block gets executed when none of the cases matches with the case
values present in the switch. It is optional.
You can define any number of cases inside the switch statement depending upon the
requirement.
Duplicate cases are not allowed in switch statements.
When one option is chosen the statements inside that corresponding case are executed
and then control exits the switch statement.
This exit is ensured by adding break statements after the case blocks

Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;

default:
statementDefault;
}

Example :

class SwitchCaseDemo
{
public static void main(String args[])
{
int i = 9;
switch (i)
{
case 0:
[Link]("i is zero.");
break;
case 1:
[Link]("i is one.");
break;
case 2:
[Link]("i is two.");
break;
default:

43 | CMPE 012 – Computer Programming


[Link]("i is greater than 2.");
}
}
}

Example 2 :

import [Link];
public class MonthsName {
public static void main(String[] args) {
int month;
[Link]("Enter month number from 1 to 12 : ");
Scanner sc = new Scanner([Link]);
month = [Link]();
switch(month) {
case 1:
[Link]("January\n");
break;

case 2:
[Link]( "February\n");
break;

case 3:
[Link]("March\n");
break;
case 4:
[Link]("April\n");
break;

case 5:
[Link]("May\n");
break;

case 6:
[Link]("June\n");
break;

case 7:
[Link]("July\n");
break;

case 8:
[Link]("August\n");
break;

case 9:
[Link]("September\n");
break;

44 | CMPE 012 – Computer Programming


case 10:
[Link]("October\n");
break;

case 11:
[Link]("November\n");
break;

case 12:
[Link]("December\n");
break;

default:
[Link]("You have entered an invalid month number\n");
break;
}
}
}

Assessment 4

JAVA CODING : Open you java, answer the following problem and write your answer once
java code are already completed.

Problem No 1: create a java code name as [Link]. This program will ask the user to
enter Student ID and Student Name, after that program will ask to enter Midterm and Final
grade. Let’s use simple formula midterm + final / 2 and display result as final_grade. And check
if PASSED or FAILED. Use appropriate conditional if statement.

Problem No.2 : create a java code name as [Link]. This will program wil choose
from list of menus [ A - cake, B - fruits , C - drink , D- pasta ]. The user will enter choice from

45 | CMPE 012 – Computer Programming


list of choices . only letter A, B, C, and D can type. And after the user enter his/her choice. The
program will display what choice is selected. Use switch statement on this problem.

Unit V.
Control Structure: LOOPING

Overview:

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,
while loop and do..while loop ]

Learning Outcomes:
After successful completion of this lesson, you should be able to:
● learn how to code a java loop and ow its works
● provide a java solution using java looping
● design, code and test java loop

Course Materials:

46 | CMPE 012 – Computer Programming


47 | CMPE 012 – Computer Programming
Example of for loop

Write a program to print “Hello” 5 times using for loop.

public class HelloMultiple {


public static void main(String[] args) {
int no;
for (no = 1; no <= 5; no++) {
[Link]("Hello \n");
}
}
}

Program to display all the numbers from 1 to 10 using for loop.

public class Numbers {


public static void main(String[] args) {
int no;
[Link]("Numbers from 1 to 10 are");
for (no = 1; no <= 10; no++)
[Link](no);
}
}

48 | CMPE 012 – Computer Programming


Program to display the multiplication table of a number using for loop.

import [Link];
public class MultiplicationTable {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int number, term, i;
[Link]("Enter a number to print multiplication table");
number= [Link]();
[Link]("Enter number of terms in table");
term = [Link]();
// Prints multiplication table
[Link]("Multiplication table-------------------\n");
for (i = 1; i <= term; ++i) {
[Link](number + " X " + i + " = " + number*i);
}
}
}

Example of while loop


Program to display all the numbers from 1 to 10 using while loop

public class WhileExample {


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

Example 2:
public class WhileExample2 {
public static void main(String[] args) {
while(true){
[Link]("infinitive while loop");
}
}
}

Example of do.. while loop:


Write a program to print Hello, World 5 times using do while loop.

Example 1 :

public class HelloDo {


public static void main(String[] args) {

49 | CMPE 012 – Computer Programming


int i = 0;
do {
[Link]("Hello, World!\n");
i++;
} while ( i < 5 );
}
}

Example 2:

import [Link];

public class oopdowhile {


public static void main(String[] args) {

int sum = 0;
int number = 0;

// create an object of Scanner class


Scanner input = new Scanner([Link]);

// do...while loop continues


// until entered number is positive
do {
// add only positive numbers
sum += number;
[Link]("Enter a number");
number = [Link]();

} while(number >= 0);

[Link]("Sum = " + sum);


[Link]();
}
}

Assessment 5

JAVA CODING

50 | CMPE 012 – Computer Programming


1. create a java code name as [Link]. The user will require to type
StudentID, Name, Course and Section. After that the program will ask the user
if he/she want to continue the operation. If the user choose Yes the program will
loop and if user type No. the procedure will stop and display a message Thank
you.

Unit VI.

Introduction to Object Oriented Programming

Overview:

51 | CMPE 012 – Computer Programming


Object-oriented programming System(OOPs) is a programming paradigm based on the
concept of “objects” that contain data and methods. The primary purpose of object-oriented
programming is to increase the flexibility and maintainability of programs. Object oriented
programming brings together data and its behaviour(methods) in a single location(object) makes
it easier to understand how a program works.

Learning Outcomes:
After successful completion of this lesson, you should be able to:
1. Enabled the importance of Object Oriented Programming in modern application and
used.
2. Develop a working with class and objects in Java platform
3. Modify each function of Object Oriented Programming features in java platform and
technologies
4. Create executable Java Applications that created using OOP principles and source code
arrangements

Course Materials:

Object-oriented programming
System(OOPs) is a programming paradigm
based on the concept of “objects” that contain
data and methods. The primary purpose of
object-oriented programming is to increase the
flexibility and maintainability of programs.
Object oriented programming brings
together data and its behavior(methods) in a
single location(object) makes it easier to
understand how a program works
The OOP concept was basically
designed to overcome the drawback of the
above programming methodologies, which
were not so close to real-world applications.
The demand was increased, but still,
conventional methods were used. This new
approach brought a revolution in the
programming methodology field.

Object Oriented Programming popularly known as OOP, is used in a modern


programming language like Java

52 | CMPE 012 – Computer Programming


Programming languages can be classified into
3 primary types

Unstructured Programming Languages: The


most primitive of all programming languages having
sequentially flow of control. Code is repeated
through out the program

Structured Programming Languages: Has


non-sequentially flow of control. Use of functions
allows for re-use of code.

Object Oriented Programming: Combines


Data & Action Together.

Advantages of OOPs –
● It models the real world very well.
● With OOP, programs are easy to understand and maintain.
● OOP offers code reusability. Already created classes can be reused without having to write
them again.
● OOP facilitates the quick development of programs where parallel development of classes
is possible.
● With OOP, programs are easier to test, manage and debug.

Disadvantages of OOP –
● With OOP, classes sometimes tend be over-generalized.
● The relations among classes become superficial at times.
● The OOP design is tricky and requires appropriate knowledge. Also, one needs to do proper
planning and design for OOP programming.
● To program with OOP, the programmer needs proper skills such as that of
design, programming and thinking in terms of objects and classes etc.

OOP is a programming concept that works on the principles of abstraction, encapsulation,


inheritance, and polymorphism. It allows users to create the objects that they want and then,
create methods to handle those objects. The basic concept of OOPs is to create objects, re-use
them throughout the program, and manipulate these objects to get results.

Object Oriented programming is a programming style which is associated with the


concepts like class, object, Inheritance, Encapsulation, Abstraction, Polymorphism. Most popular
programming languages like Java, C++, C#, Ruby, etc.

53 | CMPE 012 – Computer Programming


OOP Features
Object

Any entity that has state and behavior is known as an


object. For example, a chair, pen, table, keyboard, bike, etc. It
can be physical or logical.
An Object can be defined as an instance of a class. An
object contains an address and takes up some space in
memory. Objects can communicate without knowing the details
of each other's data or code. The only necessary thing is the
type of message accepted and the type of response returned
by the objects.
Example: A dog is an object because it has states like color,
name, breed, etc. as well as behaviors like wagging the tail,
barking, eating, etc.

Class

Collection of objects is called class. It is a logical entity.


A class can also be defined as a blueprint from which you can create an individual object. Class
doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviors of a parent
object, it is known as inheritance. It provides code reusability. It is used to
achieve runtime polymorphism.

Polymorphism
If one task is performed in different ways, it is known
as polymorphism. For example: to convince the customer
differently, to draw something, for example, shape, triangle,
rectangle, etc.
In Java, we use method overloading and method
overriding to achieve polymorphism.
Another example can be to speak something; for
example, a cat speaks meow, dog barks woof, etc.

54 | CMPE 012 – Computer Programming


Abstraction
Hiding internal details and showing functionality is
known as abstraction. For example phone call, we don't
know the internal processing.
In Java, we use abstract class and interface to achieve
abstraction.

Encapsulation
Binding (or
wrapping)
code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with
different medicines.
A java class is the example of encapsulation. Java bean
is the fully encapsulated class because all the data
members are private here

Assessment 6

Multiple Choice : Encircle the correct answer

1. Which of the following is not a part of OOPS?


[Link] checking
B. Multitasking
C. Polymorphism
D. Information hiding

2. Which of the two features match each other?


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

3. The process by which one object can acquire the properties of another object:
A. Encapsulation

55 | CMPE 012 – Computer Programming


B. Inheritance
C. Polymorphism

4. An object that has more than one form is referred to as:


A. Inheritance
B. Interface
C. Abstract class
D. Polymorphism

5. What can Information Hiding also be termed as?


A. Data hiding
B. Encapsulation
C. Inheritance

6. Which of the following best defines a class?


a) Parent of an object
b) Instance of an object
c) Blueprint of an object
d) Scope of an object

Unit VII.

OOP – Class and Objects


Overview:
Objects and classes are considered to be the meat and potatoes of any OOPs based
language. Since Java is one of the most prominently used Object-oriented

56 | CMPE 012 – Computer Programming


programming languages it becomes very necessary to know these concepts by heart. This
chapter bring you will be giving you a complete overview of Java objects and classes

Learning Outcomes:

After successful completion of this lesson, you should be able to:


● learn about java class and object
● design, code and test java object and class
● identify other class in java

Course Materials:

Classes and Objects in Java are two such concepts which go hand in hand. You can’t
learn one without having the knowledge of the other. Together they form the building blocks of
Java
.

What is a Java Class?


A class in Java is a blueprint from which an object is created. It is a logical entity that helps in
defining the behavior and properties of an object. A class can only be accessed from outside via
its instance. Every class in Java must belong to some package. Packages in Java are nothing
but a group of similar types of classes, interfaces, and sub–packages.

The classes in Java are generally classified under two categories:

1. Built-in Classes
Built-in classes in Java are the classes which come bundled within predefined packages in
Java. Predefined packages are the packages which are developed by Sun MicroSystems and are
provided as a part of JDK (Java Development Kit) to help out a java programmer. A few of the
majorly used built-in classes are:

i. [Link]
ii. [Link]
iii. [Link]
iv. [Link]
v. [Link]
vi. [Link]
vii. [Link]
viii. [Link]
ix. [Link]
x. [Link]

2. User-Defined/ Custom Classes


As the name suggests, a custom or user-defined class is a class that is created by a user.
It will contain the class members as defined by the user.

57 | CMPE 012 – Computer Programming


How to Create a Class in Java?

A class is a user defined blueprint or prototype from which objects are created. It represents the
set of properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:
1. Modifiers: A class can be public or has default access
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Superclass (if any): The name of the class’s parent (superclass), if any, preceded by
the keyword extends. A class can only extend (subclass) one parent.
4. Interfaces (if any): A comma-separated list of interfaces implemented by the class, if
any, preceded by the keyword implements. A class can implement more than one
interface.
5. Body: The class body surrounded by braces, { }.

In order to create a full-fledged custom class, you need to know what are the various
elements a class is made up of. A Java class generally consists of the following:

1. Fields
Fields of a class are used to define the properties or state attributes of the class objects.
Thus they are declared within the body of the class. The general syntax to declare a class field is
given below:

2. Methods ( This topic will discuss on other chapter )


A method in Java is a collection of a statement which determines the behavior of a class
object. They are generally used to modify the state of a class field. By using methods you can
also delegate tasks in other objects.

3. Constructors ( This topic will discuss on other chapter )


A constructor in Java is used to initialize an object of a class immediately after the object
is created. A constructor must have its name same as its class. In Java, every class has a
constructor known as the default constructor but you can add more according to your requirement.

Rules to Create a Class

1. A Java class must have the class keyword followed by the class name, and class must be
followed by a legal identifier.
2. The class name must start with a capital letter and if you are using more than one word to
define a class name, every first letter of the latter words should be made capital.
3. There should not be any spaces or special characters used in a class name except the
dollar symbol($) and underscore(_).
4. A Java class can only have public or default access specifier.
5. It must have the class keyword, and class must be followed by a legal identifier.
6. It can extend only one parent class. By default, all the classes extend [Link]
directly or indirectly.
7. A class may optionally implement any number of interfaces separated by commas.
8. The class’s members must be always declared within a set of curly braces {}.
9. Each .java source file can contain any number of default classes but can only have one
public class.

58 | CMPE 012 – Computer Programming


10. Class containing the main() method is known as the Main class as it will act as the entry
point to your program.

Types of Classes in Java


There are basically three types of classes that are supported by Java:

1. Concrete Class
A normal class is technically a concrete class containing methods, class variables,
constructors, blocks and everything. Below is a basic example of a concrete class in Java:
class oopDemo{
//class body
}
2. Abstract Class
An abstract class is a class which is defined with the keyword abstract will have at
least one abstract method (i.e a method without body) within. Abstract classes without any
abstract method in it cannot be instantiated but can only be inherited.
abstract class oopDemo{
//abstract method
abstract void show();
}
3. Interfaces
Interfaces are similar to classes except a Java Interface can only contain method
signatures and fields. In order to use an interface, it must be implemented by a class.

public interface oopInterface{


public void show();
public void run();
}

public class oopDemo implements oopInterface{


public void show(){
//implementation
}
public void run(){
//implementation
}
}

What is an Object in Java?

59 | CMPE 012 – Computer Programming


An object in Java is the real-world entity which has its own property and behavior. These are
considered to be the fundamental concepts of Java and uses classes as their blueprints. A Java
program can have as many objects as required. An object in Java typically insists of the following:

1. State: This is represented by the attributes and properties of an object.


2. Behavior: This is defined by the methods of an object
3. Identity: This provides a unique name to an object and also enables the communication
between two or more objects.

Let’s understand the concept of an object using a real-world example.

Suppose we have an object called Mobile. It will have some identity like its model,
attributes such as color, RAM, price, and behavior such as text, on, off, etc. All the instances of
the class Mobile share the same set of attributes and the behavior. Here one thing you must
remember is that attribute values of each object will be unique. Moreover, a single Java class can
have any number of instances.

How to Create a Java Object?

There are three simple steps to create a Java object which are listed below:

● Declaration − This is the very first step of object creation. In this step, you need to declare
a variable with the class name as the data type.
● Instantiation − Next step is the instantiation where you need to use the ‘new’ keyword to
create the object.
● Initialization − Finally in the third step, you need to initialize the object by calling the class
constructor.

60 | CMPE 012 – Computer Programming


Below is an example of creating an object in Java.

public class oopDemo{


public oopDemo() {
// Default Constructor
[Link]("This is Default Constructor");
}
public oopDemo(String name) {
// This constructor has one parameter
[Link]("Hello" + name );
[Link]("WELCOME to OOP");
}

public static void main(String []args) {


//Creating an object using default constructor
oopDemo myObjs = new oopDemo();

//Creating an object using parameterized constructor


oopDemo myObj = new oopDemo(" CpE Students!!!1");
}
}

61 | CMPE 012 – Computer Programming


Unit IX.

OOP – JAVA CONSTRUCTOR

Overview:
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the object is
allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.

Learning Outcomes:
After successful completion of this lesson, you should be able to:
1. Enabled the importance of JAVA Constructor in particular java CLASS
2. Describe the elements and types of Java Constructor in coding arrangement
3. Develop a Java Constructor that connected in java class from design and execution

Course Materials:

What is JAVA Constructor ?

Constructors are used to initialize the object’s state. Like methods, a constructor also
contains collection of statements(i.e. instructions) that are executed at time of Object creation.
A constructor is a special method that has the same method name as the class name.
A Java constructor is special method that is called when an object is instantiated. In other
words, when you use the new keyword. The purpose of a Java constructor is to initializes the
newly created object before it is used.

Here is a simple example that creates an object, which results in the class constructor being
called: MyClass obj = new MyClass()
The new keyword here creates the object of class MyClass and
invokes the constructor to initialize this newly created object.

MyClass myClassObj = new MyClass();

A constructor method is different from an ordinary method in the following aspects:


● The name of the constructor method must be the same as the classname. By
classname's convention, it begins with an uppercase (instead of lowercase for
ordinary methods).

62 | CMPE 012 – Computer Programming


● Constructor has no return type in its method heading. It implicitly returns void.
No return statement is allowed inside the constructor's body.
● Constructor can only be invoked via the "new" operator. It can only be used once to
initialize the instance constructed. Once an instance is constructed, you cannot call
the constructor anymore.
● Constructors are not inherited. Every class shall define its own constructors.

Rules for writing Constructor:


● Constructor(s) of a class must has same name as the class name in which it resides.
● A constructor in Java can not be abstract, final, static and Synchronized.
● Access modifiers can be used in constructor declaration to control its access i.e
which other class can call the constructor.
Types of constructor
No-argument constructor: A constructor that has no parameter is known as
default constructor. If we don’t define a constructor in a class, then compiler
creates default constructor(with no arguments) for the class. And if we write a
constructor with arguments or no-arguments then the compiler does not create a
default constructor.
Default constructor provides the default values to the object like 0, null, etc.
depending on the type.
import [Link].*;

class NoArgCon
{ this would be invoked while an
object of that class is created.
int num;
String name;
NoArgCon()
{
[Link]("Constructor called");
}
}
public class SampleNoArgCon this would invoke default
{ constructor.
public static void main (String[] args)
{ Default constructor provides the
NoArgCon output = new NoArgCon(); default values to the object like 0, null
[Link]([Link]);
[Link]([Link]);
}}
No argument Constructors
As the name specifies the no argument constructors of Java does not accept
any parameters instead, using these constructors the instance variables of a method
will be initialized with fixed values for all objects.

63 | CMPE 012 – Computer Programming


Example
Public class MyClass {
Int num;
MyClass() {
num = 100;
}
}
You would call constructor to initialize objects as follows

public class ConsDemo {


public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
[Link]([Link] + " " + [Link]);
}
}
This would produce the following result

100 100

Parameterized Constructor: A constructor that has parameters is known as


parameterized constructor. If we want to initialize fields of the class with your
own values, then use a parameterized constructor.

import [Link].*;

class ConsPar
{
constructor would initialize data
// data members of the class. members
String name; with the values of passed arguments
int id; while object of that class created.

ConsPar(String name, int id)


{
[Link] = name;
[Link] = id;
}
}

64 | CMPE 012 – Computer Programming


class SampleParameterCons this would invoke the parameterized
{ constructor.
public static void main (String[] args)
{

ConsPar output = new ConsPar("adam", 1);


[Link]("Name :" + [Link] +
" and Id :" + [Link]);
}
}

How constructors are different from methods in Java?


● Constructor(s) must have the same name as the class within which it defined while it is not
necessary for the method in java.
● Constructor(s) do not return any type while method(s) have the return type or void if does
not return any value.
● Constructor is called only once at the time of Object creation while method(s) can be
called any numbers of time.

Why Constructors are not inherited in Java?

Constructor is a block of code that allows you to create an object of class and has same name as
class with no explicit return type.
Whenever a class (child class) extends another class (parent class), the sub class inherits state
and behavior in the form of variables and methods from its super class but it does not inherit
constructor of super class because of following reasons:
● Constructors are special and have same name as class name. So if constructors were
inherited in child class then child class would contain a parent class constructor which is
against the constraint that constructor should have same name as class name.

For example, see the below code:


class Parent {
public Parent()
{
}

public void print()


{
}
}

public class Child extends Parent {


public Parent()
{

65 | CMPE 012 – Computer Programming


}
public void print()
{
}

public static void main(String[] args)


{
Child c1 = new Child(); // allowed
Child c2 = new Parent(); // not allowed
}
}

If we define Parent class constructor inside Child class it will give compile time error for
return type and consider it a method. But for print method it does not give any compile
time error and consider it a overriding method.
● Now suppose if constructors can be inherited then it will be impossible to achieving
encapsulation. Because by using a super class’s constructor we can access/initialize private
members of a class.
● A constructor cannot be called as a method. It is called when object of the class is
created so it does not make sense of creating child class object using parent class
constructor notation. i.e. Child c = new Parent();
● A parent class constructor is not inherited in child class and this is why super() is
added automatically in child class constructor if there is no explicit call to super or this.
Source : [Link]

Take Home – Coding

No argument Constructors
As the name specifies the no argument constructors of Java does not accept any parameters
instead, using these constructors the instance variables of a method will be initialized with fixed
values for all objects.

Example
Public class MyClass {
Int num;
MyClass() {
num = 100;
}
}
You would call constructor to initialize objects as follows

public class ConsDemo {


public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
[Link]([Link] + " " + [Link]);
}
}
This would produce the following result

66 | CMPE 012 – Computer Programming


100 100

Parameterized Constructors
A constructor which has a specific number of parameters is called a parameterized
constructor.. Parameters are added to a constructor in the same way that they are added
to a method, just declare them inside the parentheses after the constructor's name.

Example
Here is a simple example that uses a constructor −

// A simple constructor.
class MyClass {
int x;

// Following is the constructor


MyClass(int i ) {
x = i;
}
}

public class ConsDemo {


public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
[Link](t1.x + " " + t2.x);
}
}
This would produce the following result −

10 20

67 | CMPE 012 – Computer Programming


Default Constructor - a constructor that is automatically created by the Java
compiler if it is not explicitly defined. The default constructor initializes any uninitialized
instance variables with default values.
Example
class DefaultConstructor {

int a;
boolean b;

public static void main(String[] args) {

// A default constructor is called


DefaultConstructor obj = new DefaultConstructor();

[Link]("a = " + obj.a);


[Link]("b = " + obj.b);
}
}
Output:

a=0
b = false

68 | CMPE 012 – Computer Programming


Which object will be created first?
class student
{ Answer: a
int marks;
Why? : The objects are created in the sequence of
};
how they are written. This happens because the
student s1, s2, s3;
constructors are called in the sequence of how the
a) s1 then s2 then s3 objects are mentioned. This is done in sequence.
b) s3 then s2 then s1
c) s2 then s3 then s1
d) all are created at same time

Which among the following is correct for the class defined below?

class student
{
int marks; Answer: c
public: student(){} Why ? : It is a special case of constructor with only 1
student(int x) argument. While calling a constructor with one
{
marks=x; argument, you are actually implicitly creating a
} conversion from the argument type to the type of
}; class. Hence you can directly specify the value of
main() that one argument with assignment operator.
{
student s1(100);
student s2();
student s3=100;
return 0;
}
a) Object s3, syntax error
b) Only object s1 and s2 will be created
c) Program runs and all objects are created
d) Program will give compile time error

69 | CMPE 012 – Computer Programming


Hands-On Exercises

class Subject {
String CourseName;

// public constructor
public Subject(){
CourseName = "CMPE 30023 – OOP ";
}
}

public class MainCon {

public static void main(String[] args) {

// object is created in another class


Subject showObj = new Subject();
[Link]("Subject name = "+ [Link]);
}
}

public class Students{


int id;
String name;
//creating a parameterized constructor
Students(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){[Link](id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Students s1 = new Students(111,"JUAN DELA CRUZ");
Students s2 = new Students(222,"NENA BATICOS");
//calling method to display the values of object
[Link]();
[Link]();
} }

70 | CMPE 012 – Computer Programming


Assessment 8

1. Which among the following is called first, automatically, whenever an object is created?
a) Class
b) Constructor
c) New
d) Trigger

2. Which among the following is not a necessary condition for constructors?


a) Its name must be same as that of class
b) It must not have any return type
c) It must contain a definition body
d) It can contains arguments

3. In which access should a constructor be defined, so that object of the class can be
created in any function?
a) Public
b) Protected
c) Private
d) Any access specifier will work

4. Default constructor must be defined, if parameterized constructor is defined and the


object is to be created without arguments.
a) True
b) False

5. Which among the following is true for copy constructor?


a) The argument object is passed by reference
b) It can be defined with zero arguments
c) Used when an object is passed by value to a function
d) Used when a function returns an object

6. How many types of constructors are available for use in general (with respect to
parameters)?
a) 2
b) 3
c) 4
d) 5

71 | CMPE 012 – Computer Programming


Unit XI.

OOP – JAVA METHODS

Overview:

In general, a method is a way to perform some task. Similarly, the method in


Java is a collection of instructions that performs a specific task. It provides the reusability
of code. We can also easily modify code using methods. In this section, we will
learn what is a method in Java, types of methods, method declaration, and how to
call a method in Java.

Learning Outcomes:
After successful completion of this lesson, you should be able to:
1. Demonstrate use of Methods in java programming
2. Demonstrate syntax arrangement of methods types in different settings
3. Modify the syntax and process of methods to constructors
4. Create executable Java Applications in using java methods in different java application
procedures

Course Materials:

A method is a collection of statements that perform some specific task and return the result
to the caller. A method can perform some specific task without returning anything. Methods allow
us to reuse the code without retyping the code. Methods are time savers and help us to reuse the
code without retyping the code.

72 | CMPE 012 – Computer Programming


Method Declaration
In general, method declarations has six components:
modifier static returnType nameOfMethod (parameters) {
// method body }

⮚ Modifier-: Defines access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 type of the access specifiers.
● public: accessible in all class in your application.
● protected: accessible within the class in which it is defined and in its
subclass(es)
● private: accessible only within the class in which it is defined.
● default (declared/defined without using any modifier) : accessible within
same class and package within which its class is defined.
⮚ The return type : The data type of the value returned by the method or void if does not
return a value.
⮚ Method Name : the rules for field names apply to method names as well, but the
convention is a little different.
⮚ Parameter list : Comma separated list of the input parameters are defined, preceded with
their data type, within the enclosed parenthesis. If there are no parameters, you must use
empty parentheses ().
⮚ Exception list : The exceptions you expect by the method can throw, you can specify
these exception(s).
⮚ Method body : it is enclosed between braces. The code you need to be executed to
perform your intended operations.

Calling a method

The method needs to be called for using its functionality. There can be three situations
when a method is called:
A method returns to the code that invoked it when:

✔ It completes all the statements in the method


✔ It reaches a return statement
✔ Throws an exception

73 | CMPE 012 – Computer Programming


User-defined Method
public static void myMethod() {
[Link]("My Function called");
}
public - access modifier. It means the method can be accessed from anywhere.
static - It means that the method can be accessed without any objects.
void - It means that the method does not return any value.

public class userMethod {

public static void main(String[] args) {


[Link]("About User-Defined Method.");

// method call
myMethod();

[Link]("Method was executed successfully!");


}
// method definition
private static void myMethod(){
[Link]("Hello ICT002 This is User Deined Method()!");
}
}

Method Arguments and Return Value

As discussed earlier, a Java method can have zero or more parameters. And, it may also
return some value.

public class SquareMain {


In this program, we have created a
public static void main(String[] args) {
int result; method named square(). This method
does not accept any arguments and
// call the method and store returned value returns value 10 *10.
result = square();
[Link]("Squared value of 10 is: " + result);
Here, we have mentioned the return
}
type of the method as int. Hence, the
public static int square() { method should always return an integer
// return statement value.
return 10 * 10;
}
}

74 | CMPE 012 – Computer Programming


public class MainArgs {
Here, the square() method accepts an
public static void main(String[] args) { argument i and returns the square of i.
int result, n; The returned value is stored in the
variable result.
n = 3; If we pass any other data type instead of
result = square(n);
[Link]("Square of 3 is: " + result); int, the compiler will throw an error. It is
because Java is a strongly typed
n = 4; language.
result = square(n); The argument n passed to the
[Link]("Square of 4 is: " + result);
getSquare() method during the method
}
call is called an actual argument.
// method
static int square(int i) {
return i * i;
}
}

Method parameters

Parameters are specified after the method name in a class, inside parentheses. You can
add as many parameters as you want but just separate them with a comma. Data can be passed
to functions as a parameter. Actually, parameters act as variables inside the method.

public class MyClass


{
static void myMethod(String fname)
{
[Link](fname + " TYPES OF OOP ");
}
public static void main(String[] args)
{
myMethod("Java");
myMethod("Kotlin");
myMethod("Selenium");
}
}

75 | CMPE 012 – Computer Programming


Another Example of non-return method

public class NonReturnMethod {

public static void main(String[] args) {


[Link]("FORMATIVE ASSESSMENT - ICT 002");
// method call
myMethod();
}
// method definition
private static void myMethod(){
[Link]("NAME: JUAN A. DELA CRUZ");
}
}

Hands-on Activity

Laboratory Exercises: 1 In this Program students is required to create a source code with return
value of parameters. On the main method, the program will ask the user to enter 2 whole numbers:
Enter Num1 and Enter Num 2 , after that the program will generate results by calling the formula
stored in a methods, name as addTwoInt() method, with parameter list of ( in a, int b) and formula
of sum = a + b and return the value of sum. And finally will display the results on the main
method. Student can use Scanner or JOptionPane. Or both libraries.
Answer :

import [Link].*;
import [Link].*;

class SampleMethodReturn {

int sum = 0;

public int addTwoInt(int a, int b){

sum = a + b;

return sum;
}

public static void main (String[] args) {


Scanner type = new Scanner ([Link]);

SampleMethodReturn add = new SampleMethodReturn();

[Link]("Enter 1st No:> ");


int no1 = [Link]();
[Link]("Enter 2nd No:> ");

76 | CMPE 012 – Computer Programming


int no2 = [Link]();

int s = [Link](no1, no2);


[Link]("Sum of two integer values :"+ s);
}

import [Link];
class SampleMethodReturnTwo {

float prod = 0;

public float addTwoFloat(float c, float d){


prod = c * d;
return prod;
}

public static void main (String[] args) {

SampleMethodReturnTwo add = new SampleMethodReturnTwo();

String n1 = [Link](null,"Enter 1t Number: > ");


float num1 = [Link](n1);

String n2 = [Link](null,"Enter 1t Number: > ");


float num2 = [Link](n2);

float p = [Link](num1,num2);
[Link](null,"Product of two Floating values :" + p);

Assessment 9

Underline the parts of methods on the following codes :

public static void swapFunction(int a, int b) {


[Link]("Before swapping(Inside), a = " + a + " b = " + b);

77 | CMPE 012 – Computer Programming


Unit X.

OOP – JAVA INHERITANCE

Overview:

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class.

Learning Outcomes:

After successful completion of this lesson, you should be able to:


1. Demonstrate use of INHERITANCE in java programming and development
2. Learn to declare, initialize and access inheritance principles in development
3. Identify the importance and use of inheritance in java application
4. Create executable Java Applications in using java inheritance

Course Materials:

JAVA INHERITANCE

78 | CMPE 012 – Computer Programming


Inheritance is an OOPS concept in which one object acquires the properties and
behaviors of the parent object. It’s creating a parent-child relationship between two classes. It
offers robust and natural mechanism for organizing and structure of any software

In OOP, computer programs are designed in such a way where everything is an object that
interacts with one another. Inheritance is an integral part of Java OOPs which lets the properties of
one class to be inherited by the other. It basically, helps in reusing the code and establish a
relationship between different classes.

As we know, a child inherits the properties from his parents. A similar concept is followed in
Java, where we have two classes:
REMINDER: A class which inherits the
properties is known as Child Class whereas a
1. Parent class (Super or Base class) class whose properties are inherited is known as
the class being inherited from Parent class.
2. Child class (Subclass or Derived class) To inherit from a class, use
the class that inherits from another class the extends keyword.

Example NOTES :
class Animal In Java, we use the extends keyword to inherit from
{ a class. Here, we have inherited the Dog class from the
// eat() method Animal class.
// sleep() method The Animal is the superclass (parent class or base
} class), and the Dog is a subclass (child class or derived
class Dog extends Animal class). The subclass inherits the fields and methods of the
{ superclass.
// bark() method
}

Inheritance is an is-a relationship. We use inheritance only if an is-a relationship is


present between the two classes. Here are some examples:
✔ A car is a vehicle.
✔ Orange is a fruit.

79 | CMPE 012 – Computer Programming


✔ A surgeon is a doctor.
✔ A dog is an animal.

Sample Inheritance
class Animal {
public void eat() {
[Link]("I can eat");
}
public void sleep() { Here, we have inherited a subclass Dog
[Link]("I can sleep"); from superclass Animal. The Dog class
} inherits the methods eat() and sleep() from
} the Animal class.
class Dog extends Animal { Hence, objects of the Dog class can access
public void bark() { the members of both the Dog class and the
[Link]("I can bark"); Animal class.
}
}
public class SampleInheritance {
public static void main(String[] args) {

Dog dog1 = new Dog();

[Link]();
[Link]();
[Link]();
}
}
NOTES : Remind the students that When a subclass extends a superclass in Java, all protected
and public fields and methods of the superclass are inherited by the subclass. By inherited is meant
that these fields and methods are part of of the subclass, as if the subclass had declared them itself.
protected and public fields can be called and referenced just like the methods declared directly in the
subclass

80 | CMPE 012 – Computer Programming


Example using Protected Keyword
protected Keyword
private members can be accessed only within the class
public members can be accessed from anywhere

You can also assign methods and fields protected. Protected members are accessible
● from within the class
● within its subclasses
● within the same package
Example of Protected Key word

class Animal {
protected String type;
private String color;

public void eat() {


[Link]("I can eat"); Here, the type field inside the Animal
} class is protected. We have accessed
public void sleep() { this field from the Main class using
[Link]("I can sleep");
} [Link] = "mammal";
public String getColor(){ It is possible because both the Animal
return color; and Main classes are in the same
} package (same file).
public void setColor(String col){
color = col;
}
}
class Dog extends Animal {
public void displayInfo(String c){
[Link]("I am a " + type);
[Link]("My color is " + c);
}
public void bark() {
[Link]("I can bark");
}
}
class InheritanceProtected {
public static void main(String[] args) {

Dog dog1 = new Dog();


[Link]();
[Link]();
[Link]();

[Link] = "mammal";
[Link]("black");
[Link]([Link]());
}}

81 | CMPE 012 – Computer Programming


Types of Inheritance

Single Inheritance
In single inheritance, one class inherits the properties of another. It enables a derived
class to inherit the properties and behavior from a single parent class. This will, in turn, enable
code reusability as well as add new features to the existing code.
CLASS A

CLASS B

Here, Class A is your parent class and


Class B is your child class which
inherits the properties and behavior of
the parent class.

class Animal{
void eat(){
[Link](“eating”);}
}
class Dog extends Animal{
void bark(){
[Link](“barking”);}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}
}

82 | CMPE 012 – Computer Programming


Multi-level Inheritance
When a class is derived from a class which is also derived from another class, i.e. a class
having more than one parent class but at different levels, such type of inheritance is called
Multilevel Inheritance.

CLASS A

CLASS B

CLASS
class C
B inherits the properties and
behavior of class A and class C
inherits the properties of class B.
Here Class A is the parent class for B
and class B is the parent class for C.
So in this case class C implicitly inherits
the properties and methods of class A
along with Class B. That’s what is
multilevel inheritance.

class Animal{
voideat(){
[Link](“eating…”);}
}
class Dog extends Animal{
void bark(){
[Link](“barking…”);}
}
class Puppy extends Dog{
void weep(){
[Link](“weeping…”);}
}
class TestInheritance2{
public static void main(String args[]){
Puppy d=new
Puppy();
[Link]();
[Link]();
[Link]();
}
}

83 | CMPE 012 – Computer Programming


Hierarchical Inheritance

When a class has more than one child classes (subclasses) or in other words, more than
one child classes have the same parent class, then such kind of inheritance is known as
hierarchical.

CLASS A

CLASS B CLASS C CLASS D

In the above flowchart, Class B


and C are the child classes which
are inheriting from the parent
class i.e Class A.

class Animal{
void eat(){
[Link](“eating…”);}
}
class Dog extends Animal{
void bark(){
[Link](“barking…”);}
}
class Cat extends Animal{
void meow(){
[Link](“meowing…”);}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();
}
}

84 | CMPE 012 – Computer Programming


Important facts about inheritance in Java

Default superclass: Except Object class, which has no superclass, every class has one
and only one direct superclass (single inheritance). In the absence of any other explicit
superclass, every class is implicitly a subclass of Object class.

Superclass can only be one: A superclass can have any number of subclasses. But a
subclass can have only one superclass. This is because Java does not support multiple
inheritance with classes. Although with interfaces, multiple inheritance is supported by java.

Inheriting Constructors: A subclass inherits all the members (fields, methods, and
nested classes) from its superclass. Constructors are not members, so they are not inherited by
subclasses, but the constructor of the superclass can be invoked from the subclass.

Private member inheritance: A subclass does not inherit the private members of its
parent class. However, if the superclass has public or protected methods(like getters and setters)
for accessing its private fields, these can also be used by the subclass.

What all can be done in a Subclass?

In sub-classes we can inherit members as is, replace them, hide them, or supplement them with
new members:
✔ The inherite fields can be used directly, just like any other fields.
✔ We can declare new fields in the subclass that are not in the superclass.
✔ The inherited methods can be used directly as they are.
✔ We can write a new instance method in the subclass that has the same signature
as the one in the superclass, thus overriding it (as in example above, toString()
method is overridden).
✔ We can write a new static method in the subclass that has the same signature as
the one in the superclass, thus hiding it.
✔ We can declare new methods in the subclass that are not in the superclass.
✔ We can write a subclass constructor that invokes the constructor of the superclass,
either implicitly or by using the keyword super.
Important terminology:
● Super Class: The class whose features are inherited is known as super class(or a
base class or a parent class).
● Sub Class: The class that inherits the other class is known as sub class(or a
derived class, extended class, or child class). The subclass can add its own fields
and methods in addition to the superclass fields and methods.
Types of Inheritance in Java
✔ Single Inheritance: In single inheritance, subclasses inherit the features of one
superclass.
✔ Multilevel Inheritance: In Multilevel Inheritance, a derived class will be
inheriting a base class and as well as the derived class also act as the base class
to other class.

85 | CMPE 012 – Computer Programming


✔ Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a
superclass (base class) for more than one sub class.
✔ Hybrid Inheritance (Through Interfaces) : It is a mix of two or more of the
above types of inheritance

Hand-On Exercises

Create a source code with base class Teacher and subclass ProgrammingTeacher. Since
class ProgrammingTeacher extends the properties from the base class, we need not declare
these properties and method in the subclass.
For base class Teacher, declare a String with variable teachers, designation and
collegeName. With method void() name as “does” with printed of “Class Adviser”;
On your main method, create an object name as “obj” that use to call all derived properties.

Answer:
class Teacher{
String teachers = "Juan A. Dela Cruz";
String designation = "Professor";
String collegeName = "School of Education";
void does(){
[Link]("Class Adviser");
}
}
public class ProgrammingTeacher extends Teacher{
String mainSubject = "ICT 002 Culminating Activity in ICT";

public static void main(String args[]){


ProgrammingTeacher obj = new ProgrammingTeacher();
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]();
}
}

Example 2 :

Student to expect type the given source code and test then provide personal analysis for
what type of inheritance. after that student required to add 2 solutions on given code for
subtraction and divisions

import [Link];
class Calculation {
int z;

public void addition(int x, int y) {


z = x + y;

86 | CMPE 012 – Computer Programming


[Link]("The sum of the given numbers:"+z);
}

public class Compute_Single extends Calculation {


public void multiplication(int x, int y) {
z = x * y;
[Link]("The product of the given numbers:"+z);
}

public static void main(String args[]) {


int a,b;
Scanner key = new Scanner ([Link]);

Compute_Single demo = new Compute_Single();


[Link]("Enter 1st Number:");
a =[Link]();
[Link]("Enter 2nd Number:");
b =[Link]();
[Link](a, b);
[Link](a,b);
}
}

Example 3 :

import [Link];
class ArithmeticOperation {
int z;

public void Subtraction(int x, int y) {


z = x - y;
[Link]("The difference between the given numbers:"+z);
}
public void multiplication(int x, int y) {
z = x * y;
[Link]("The product of the given numbers:"+z);

}
public void Division(int x, int y) {
z = x - y;
[Link]("The Qoutient between the given numbers:"+z);
}
}

public class Compute_Single extends ArithmeticOperation {

public void addition(int x, int y) {

87 | CMPE 012 – Computer Programming


z = x + y;
[Link]("The sum of the given numbers:"+z);
}

public static void main(String args[]) {


int a,b;
Scanner key = new Scanner ([Link]);

Compute_Single displays = new Compute_Single();

[Link]("Enter 1st Number:");


a =[Link]();
[Link]("Enter 2nd Number:");
b =[Link]();

[Link]("Results :");
[Link](a,b);
[Link](a, b);
[Link](a,b);
[Link](a,b);
}
}

Assessment 10 :

Multiple Choice: Encircle the correct answer in given set of question and situations. Avoid
any form of erasures and duplicate answer per number. Read carefully before you answer.

1. Which among the following best describes the Inheritance?


a) Copying the code already written
b) Using the code already written once
c) Using already defined functions in programming language
d) Using the data and functions into derived segment
2. How many basic types of inheritance are provided as OOP feature?
a) 4
b) 3
c) 2
d) 1
3. Which among the following best defines single level inheritance?
a) A class inheriting a derived class
b) A class inheriting a base class
c) A class inheriting a nested class
d) A class which gets inherited by 2 classes
4. Which among the following is correct for multiple inheritance?
a) class student{public: int marks;}s; class stream{int total;}; class topper:public student,
public stream{ };

88 | CMPE 012 – Computer Programming


b) class student{int marks;}; class stream{ }; class topper: public student{ };
c) class student{int marks;}; class stream:public student{ };
d) class student{ }; class stream{ }; class topper{ };
5. Which programming language doesn’t support multiple inheritance?
a) C++ and Java
b) C and C++
c) Java and SmallTalk
d) Java
6. Which among the following is correct for a hierarchical inheritance?
a) Two base classes can be used to be derived into one single class
b) Two or more classes can be derived into one class
c) One base class can be derived into other two derived classes or more
d) One base class can be derived into only 2 classes
7.
8. Which is the correct syntax of inheritance?
a) class derived_classname : base_classname{ /*define class body*/ };
b) class base_classname : derived_classname{ /*define class body*/ };
c) class derived_classname : access base_classname{ /*define class body*/ };
d) class base_classname :access derived_classname{ /*define class body*/ };

9. Which access type data gets derived as private member in derived class?
a) Private
b) Public
c) Protected
d) Protected and Private

10. If a base class is inherited in protected access mode then which among the following is
true?
a) Public and Protected members of base class becomes protected members of derived
class
b) Only protected members become protected members of derived class
c) Private, Protected and Public all members of base, become private of derived class
d) Only private members of base, become private of derived class

11. Members which are not intended to be inherited are declared as ________________
a) Public members
b) Protected members
c) Private members

89 | CMPE 012 – Computer Programming


Unit XI.

OOP – JAVA Polymorphism


Overview:
The word polymorphism means having multiple forms. The term Polymorphism gets
derived from the Greek word where poly + morphos where poly means many
and morphos means forms.

Polymorphism is another special feature of object-oriented programming (OOPs). The


approach which lies beneath this concept is "single interface with multiple implementations." It
offers a single interface for controlling access to a general class of actions.

Learning Outcomes:
After successful completion of this lesson, you should be able to:

1. Describe the importance of Polymorphism in java application


2. Demonstrate how polymorphism affect the entire creation of object and classes at the rest
o the java application
3. Create executable Java Applications that apply the principles of polymorphism in java
applications

Course Materials:

Create text Layers

90 | CMPE 012 – Computer Programming


What is Polymorphism

Real life example of polymorphism: A


person at the same time can have different
characteristic. Like a man at the same time is a
father, a husband, an employee. So the same
person possess different behavior in different
situations. This is called polymorphism.

On the right figure, you can see, Man


is only one, but he takes multiple roles like – he
is a dad to his child, he is an employee, a
salesperson and many more. This is known as
Polymorphism.

Polymorphism is the ability of an entity to take several forms. In object-oriented programming, it


refers to the ability of an object (or a reference to an object) to take different forms of objects. It allows
a common data-gathering message to be sent to each class. Polymorphism encourages called as
‘extendibility’ which means an object or a class can have it’s uses extended.
Consider a cell phone where you save your
Contacts. Suppose a person has two
contact numbers. For the ease of
accessibility, your cellphone provides you
the functionality where you can save two
numbers under the same name

Similarly, in Java, an object is only one but it


can take multiple forms depending on the
context of the program. Suppose you want to
write a function to save two contact numbers
of the same person, you can create it like –
void createContact(String name, int number1,
int number2).

Now, it’s not necessary that everyone in


As you can see in the above figure, your contact list will have two contact numbers.
createContact() method has two different Few of them might be having only a single
definitions. Here, which definition is to be contact number. In such situations, instead of
executed depends upon the number of creating another method with a different name
parameters being passed. If one parameter is to save one number for a contact, what you can
passed, then only a single contact number is do is, create another method with the same
saved under the contact. But, if two contact name i.e. createContact(). But, instead of
numbers are passed to this method at the same taking two contact numbers as parameters,
time, then both will be saved under the same take only one contact number as a parameter
contact. This is also known as Method i.e. void createContact(String name, int
Overloading. number1).

Types of Polymorphism in Java


Java supports two types of polymorphism and they are as follows:

91 | CMPE 012 – Computer Programming


✔ Static Polymorphism - Compile time Polymorphism
✔ Dynamic Polymorphism - Runtime polymorphism

Static Polymorphism
class Calculator A polymorphism that is resolved
{ during compile time is known as static
int add(int x, int y) polymorphism. Method overloading is an
{ example of compile time polymorphism.
return x+y;
} Example
int add(int x, int y, int z) Method Overloading is a feature
{ that allows a class to have two or more
return x+y+z; methods to have the same name, but
} with different parameter lists. In the
} below example, you have two definitions
public class TestOverload of the same method add(). So, which
{ add() method would be called is
public static void main(String args[]) determined by the parameter list at the
{ compile time. That is the reason this is
Calculator obj = new Calculator(); also known as compile time
[Link]([Link](100, 200)); polymorphism.
[Link]([Link](100, 200, 300));
}
}

Example 2 : Override
class MacBookOverride{
public void myMethod(){
[Link]("Example of Overridden Method");
}
}

92 | CMPE 012 – Computer Programming


public class iPadOverriding extends MacBookOverride{
public void myMethod(){
[Link]("Example of Overriding Method");
}
public static void main(String args[]){
MacBookOverride obj = new iPadOverriding();
[Link]();
[Link]("");

[Link]("This would call the myMethod() of parent class


MacBookOverride");
MacBookOverride objTwo = new MacBookOverride();
[Link]();
[Link]("");

[Link]("This would call the myMethod() of child class


iPadOverriding");
iPadOverriding objThree = new iPadOverriding();
[Link]();
[Link]("");
}}
Example
In the above example, you have two classes MacBook and iPad. MacBook is a parent class and iPad is
a child class. The child class is overriding the method myMethod() of the parent class. Here, we have
assigned child class object to the parent class reference to determine which method would be called
at run-time. It is the type of object that determines which version of the method would be called (not
the type of reference).

Dynamic Polymorphism
Dynamic polymorphism is a process in which a call to an overridden method is resolved
at runtime, that’s why it is called runtime polymorphism. Method Overriding is one of the ways to
achieve Dynamic Polymorphism. In any object-oriented programming language, Overriding is a
feature that allows a subclass or child class to provide a specific implementation of a method that
is already provided by one of its super-classes or parent classes.

What is the difference between Overloading and Overriding?

Overloading is about same function have different signatures. Overriding is about same function,
same signature but different classes connected through inheritance.
Overloading is an example of compiler time polymorphism and overriding is an example of run
time polymorphism.

Example 3 :
create a source code with base class Doctor and subclass Surgeon. The
property based on images at the right corner of the activity sheet.

93 | CMPE 012 – Computer Programming


On your main method, create an object
name as “DoctorObj” and “SurgeonObj” that use
to call all derived properties.

class Doctor{
public void treatPatient(){

}
}
class Surgeon extends Doctor{
public void treatPatient(){
[Link]("treatPatient method in class Surgeon will be executed");
}
}
class runOverriding{
public static void main (String args[]){
Doctor doctorObj = new Doctor();
[Link]();
[Link]("treatPatient method in class Doctor will be executed");

Surgeon surgeonObj = new Surgeon();


[Link]();
}}
Hands-on Activity
What is the output of the following?

class Test
{
public void prints()
{
[Link]("ICT 002");
}
}
public class Derived extends Test
{
Ans. (a)Explanation: A child class
public void prints()
reference variable cannot be used to {
store an instance of parent class. [Link]("Culiminating");
}
public static void main(String[] args)
{
Derived obj = new Test();
[Link]();
}
}
a) Compilation error

94 | CMPE 012 – Computer Programming


b) Runtime error
c) ICT
d) prints

What is the output of the following?

class Test
{
void myMethod()
{
[Link]("Culminating Activity");
}
}
public class Derived extends Test
Explanation: A child class cannot be used as a {
reference to an object of super class. void myMethod()
{
[Link]("ICT 002 ");
}

public static void main(String[] args)


{
Derived object = new Test();
[Link]();
}
}
a) Runtime error
b) void
c) Compilation error
d) prints

Create a source code that use the principles of Polymorphism. Create a base class Forest that
extend to leon and eagle. For each method create printed of their animal sound (leon and eagle).
Then on your main class create each object and call their object properties.

class Forest {
public void forestSound() {
[Link]("The animal makes a sound");
}
}

class leon extends Forest {


public void forestSound() {
[Link]("The Leon says: roar!!! ");
}
}

class eagle extends Forest {


public void forestSound() {
[Link]("The Eagle says: tweet tweet");

95 | CMPE 012 – Computer Programming


}
}

class MainClassPolymorphism {
public static void main(String[] args) {
Forest mySound = new Forest(); // Create aal object
Forest myleon = new leon(); // Create a Pig object
Forest myeagle = new eagle(); // Create a Dog object

[Link]();
[Link]();
[Link]();
}
}

Assessment 11:
Multiple Choice: Encircle the correct answer in given set of question and
situations. Avoid any form of erasures and duplicate answer per number. Read
carefully before you answer.

1. Which among the following best describes polymorphism?


a) It is the ability for a message/data to be processed in more than one form
b) It is the ability for a message/data to be processed in only 1 form
c) It is the ability for many messages/data to be processed in one way
d) It is the ability for undefined message/data to be processed in at least one way
2. What do you call the languages that support classes but not polymorphism?
a) Class based language
b) Procedure Oriented language
c) Object-based language
d) If classes are supported, polymorphism will always be supported
3. If same message is passed to objects of several different classes and all of those can
respond in a different way, what is this feature called?
a) Inheritance
b) Overloading
c) Polymorphism
d) Overriding

4. Which among the following can’t be used for polymorphism?


a) Static member functions
b) Member functions overloading
c) Predefined operator overloading
d) Constructor overloading

96 | CMPE 012 – Computer Programming


5. Which problem may arise if we use abstract class functions for polymorphism?
a) All classes are converted as abstract class
b) Derived class must be of abstract type
c) All the derived classes must implement the undefined functions
d) Derived classes can’t redefine the function

6. Which among the following is not true for polymorphism?


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

7. If 2 classes derive one base class and redefine a function of base class, also overload
some operators inside class body. Among these two things of function and operator
overloading, where is polymorphism used?
a) Function overloading only
b) Operator overloading only
c) Both of these are using polymorphism
d) Either function overloading or operator overloading because polymorphism can be
applied only once in a program

Unit XII.

OOP – JAVA Abstraction and Encapsulation

Overview:
On this chapter we will differentiate the use of java abstraction and encapsulation
Abstraction is the process or method of gaining the information. While encapsulation is the
process or method to contain the information. Abstraction is the method of hiding the unwanted
information. Whereas encapsulation is a method to hide the data in a single entity or unit along
with a method to protect information from outside.

97 | CMPE 012 – Computer Programming


Learning Outcomes:
After successful completion of this lesson, you should be able to:

1. Describe the importance of Encapsulation and Abstraction in java application


2. Demonstrate how the encapsulation and abstraction use their procedures in hiding and
overloading the procedures
3. Create executable Java Applications that apply the principles of Encapsulation and
Abstraction in java applications

Course Materials:

An abstraction is an act of representing essential features without including


background details. It is a technique of creating a new data type that is suited for a specific
application. For example, while driving a car, you do not have to be concerned with its
internal working. Here you just need to concern about parts like steering wheel, Gears,
accelerator, etc.

Encapsulation is an OOP technique of wrapping the data and code. In this OOPS
concept, the variables of a class are always hidden from other classes. It can only be
accessed using the methods of their current class. For example - in school, a student
cannot exist without a class.

98 | CMPE 012 – Computer Programming


Encapsulation refers to wrapping up
of data under a single unit. It is the
mechanism that binds code and the data it
manipulates. Another way to think about
encapsulation is, it is a protective shield
that prevents the data from being accessed
by the code outside this shield. In this, the
variables or data of a class is hidden from
any other class and can be accessed only
through any member function of own class
in which they are declared.
Note : You learned from the previous chapter
that private variables can only be accessed
within the same class (an outside class has no
access to it). However, it is possible to access
them if we provide
public get and set methods.
Encapsulation in Java can be achieved by:
✔ Declaring the variables of a class as private.
✔ Providing public setter and getter methods to modify and view the variables values.

Java Data Hiding


Data hiding is a way of restricting the access of our data members by hiding the
implementation details. Encapsulation also provides a way for data hiding. Data hiding can
be achieved with the help of access modifiers.
In Java, there are four access modifiers:

✔ public - visible from anywhere


✔ private - visible from only within the class
✔ protected - visible within the package, and among its subclasses
✔ default - visible within the package

class Student {
private String name;
public String getName() { Note : As you can see in the sample code, we
return name; have created a class Student which has
} a private variable name. Next, we have created a
public void setName(String name) { getter(get) and setter (set) to get and set the name of
[Link] = name; a student. With the help of these methods, any class
} which wishes to access the name variable has to do
} it using these getter and setter methods.
class TestEncap{
public static void main(String[] args) {
Student s=new Student();

99 | CMPE 012 – Computer Programming


[Link]("Harry Potter");
[Link]([Link]());
}}
Example of Data Hiding NOTES : In the example code, we have a
private field age. Since it is private, it cannot be
class Person { accessed from outside the class. In order to
private int age; access age, we have used public methods
getAge() and setAge(). These methods are called
public int getAge() { getter and setter methods.
return age; If we try to access the age field from the
} Main class, we will get an error.
[Link] = 24; // error: age has private
public void setAge(int age) { access in Person
[Link] = age; Making age private allowed us to restrict
} unauthorized access from outside the class. This
} is data hiding.
class MainEncap {
public static void main(String[] args) {
Person p1 = new Person();
[Link](24);
[Link]("My age is " + [Link]());
}
}

Example of Data Hiding with protected

class Person {
protected String profession;

protected void displayInfo() {


[Link]("I am a " + profession);
}
} NOTES : In the sample program, we have
created a class Person which includes a
class TeacherEncap extends Person { protected field profession and a protected
public static void main(String[] args) { method displayInfo().
TeacherEncap t1 = new TeacherEncap(); We have accessed these members from
[Link] = " SHS Teacher"; the TeacherEncap class (which is a subclass of
[Link](); Person).
}

Why Encapsulation?
✔ In Java, encapsulation helps us to keep related fields and methods together, which
makes our code cleaner and easy to read.
✔ It helps to control the modification of our data fields.

100 | CMPE 012 – Computer Programming


Abstraction in Java
Data Abstraction is the property by virtue of which only the essential details are displayed
to the user. The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed
as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object ignoring the irrelevant details. The properties and behaviors of an
object differentiate it from other objects of similar type and also help in classifying/grouping the
objects.

Illustration

Suppose you want to create a banking application and


you are asked to collect all the information about your
customer.
There are chances that you will come up with following
information about the customer
But, not all of the above information is required to
create a banking application.

Since we have
fetched/removed/selected the customer
information from a larger pool, the process
is referred as Abstraction.
However, the same information
once extracted can be used for a wide
range of applications. For instance, you
can use the same data for hospital
application, job portal application, a
Government database, etc. with little or no
modification. Hence, it becomes your
Master Data. This is an advantage of
Abstraction.
Source : [Link]

2 Ways of Abstraction

Abstract Class
Abstract class contains the ‘abstract’ keyword. But what exactly it means? If you make the
class abstract, it cannot be instantiated, i.e you cannot create an object of an abstract class. Also,
an abstract class can contain abstract as well as concrete methods.
Interface

101 | CMPE 012 – Computer Programming


An interface in Java is a collection of abstract methods and static constants. As you might
know in an interface, each method is public and abstract but it does not contain any constructor.
Along with abstraction, the interface also helps to achieve multiple inheritance in Java.

Advantages of Abstraction
✔ The main benefit of using an abstract class is that it allows you to group several related
classes as siblings.
✔ Abstraction helps to reduce the complexity of the design and implementation process of
software.

Example of Abstraction

Create source file name [Link] with the following content. After you create compile then
run.
public interface Shape{
public void draw();
public double getArea();
}
Create another source file name as [Link] After you create compile then run.
class Circle implements Shape{
private double radius;

public Circle(double r){


[Link] = r;
}
public void draw(){
[Link]("Drawing Circle");
}
public double getArea(){
return [Link]*[Link]*[Link];
}
public double getRadius(){
return [Link];
}

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

Shape c = new Circle(8);


[Link]();
[Link]("Area="+[Link]());
}
}

Result :
Drawing Circle
Area=201.06192982974676

102 | CMPE 012 – Computer Programming


Hands on Activity

Example of Encapsulation Example of Abstraction

abstract class Animal {


abstract void makeSound();

class Student { }
private String name; class Dog extends Animal {
public String getName() { public void makeSound() {
return name; [Link]("Bark bark.");
} }
public void setName(String name) { }
[Link] = name; class Cat extends Animal {
} public void makeSound() {
} [Link]("Meows ");
class TestEncap{ }
public static void main(String[] args) { }
Student s=new Student(); class Main {
[Link]("Harry Potter"); public static void main(String[] args) {
[Link]([Link]()); Dog d1 = new Dog();
} [Link]();
}
Cat c1 = new Cat();
[Link]();
}}

103 | CMPE 012 – Computer Programming


Identify the wrong syntax on the following source code, then type correct
source codes as your answer on the given box of your activity sheets
class Person {

private Int age;

class int getAge() {


return int;
}

public void setAge(int age) {


[Link] = ages;
}
}

class MainEncap {
public static void main(String[] args) {
person p1 = new Person[];
[Link](24);
[Link]("My age is " + [Link]());
}
}

Question : Student to expect type the given source code and test its functions.
The following source must be save in personal google drive with folder name
of Activity_Abstraction with 3 files [Link], [Link] and
[Link] and shared to your teacher
****** file name = [Link]

public abstract class Employee {


private String name;
private String address;
private int number;

public Employee(String name, String address, int number) {

104 | CMPE 012 – Computer Programming


[Link]("Constructing an Employee");
[Link] = name;
[Link] = address;
[Link] = number;
}

public double computePay() {


[Link]("Inside Employee computePay");
return 0.0;
}

public void mailCheck() {


[Link]("Mailing a check to " + [Link] + " " + [Link]);
}

public String toString() {


return name + " " + address + " " + number;
}

public String getName() {


return name;
}

public String getAddress() {


return address;
}

public void setAddress(String newAddress) {


address = newAddress;
}

public int getNumber() {


return number;
}
}

File name = [Link]

public class Salary extends Employee {


private double salary; // Annual salary

105 | CMPE 012 – Computer Programming


public Salary(String name, String address, int number, double salary) {
super(name, address, number);
setSalary(salary);
}

public void mailCheck() {


[Link]("Within mailCheck of Salary class ");
[Link]("Mailing check to " + getName() + " with salary " + salary);
}

public double getSalary() {


return salary;
}

public void setSalary(double newSalary) {


if(newSalary >= 0.0) {
salary = newSalary;
}
}

Assessment 12

Multiple Choice: Encircle the correct answer in given set of question and situations.
Avoid any form of erasures and duplicate answer per number. Read carefully before
you answer.
1. Which among the following best a) Create public member functions
describes encapsulation? to access those data members
a) It is a way of combining various b) Create private member functions
data members into a single unit to access those data members
b) It is a way of combining various c) Create protected member
member functions into a single unit functions to access those data
c) It is a way of combining various members
data members and member d) Private data members can never
functions into a single unit which can be accessed from outside the class
operate on any data 3. While using encapsulation, which
d) It is a way of combining various among the following is possible?
data members and member a) Code modification can be
functions that operate on those data additional overhead
members into a single unit b) Data member’s data type can be
2. If data members are private, what changed without changing any other
can we do to access them from the code
class object? c) Data member’s type can’t be

106 | CMPE 012 – Computer Programming


changed, or whole code have to be a) Make the programming easy
changed b) Make the programming complex
d) Member functions can be used to c) Provide more number of features
change the data type of data d) Provide better features
members 10. Class is _________ abstraction.
4. Which feature can be implemented a) Object
using encapsulation? b) Logical
a) Inheritance c) Real
b) Abstraction d) Hypothetical
c) Polymorphism 11. Object is ________ abstraction.
d) Overloading a) Object
5. Encapsulation helps in writing b) Logical
___________ classes in java. c) Real
a) Mutable d) Hypothetical
b) Abstract 12. Abstraction gives higher degree of
c) Wrapper ________
d) Immutable a) Class usage
6. Which among the following should b) Program complexity
be encapsulated? c) Idealized interface
a) The data which is prone to d) Unstable interface
change is near future 13. Abstraction can apply to
b) The data prone to change in long ____________
terms a) Control and data
c) The data which is intended to be b) Only data
changed c) Only control
d) The data which belongs to some d) Classes
other class 14. Which among the following can be
7. How can Encapsulation be viewed as combination of
achieved? abstraction of data and code.
a) Using Access Specifiers a) Class
b) Using only private members b) Object
c) Using inheritance c) Inheritance
d) Using Abstraction d) Interfaces
8. Which among the following best 15. Abstraction principle
defines abstraction? includes___________
a) Hiding the implementation a) Use abstraction at its minimum
b) Showing the important data b) Use abstraction to avoid longer
c) Hiding the important data codes
d) Hiding the implementation and c) Use abstraction whenever
showing only the features possible to avoid duplication
9. Hiding the implementation d) Use abstraction whenever
complexity can ____________ possible to achieve OOP

107 | CMPE 012 – Computer Programming


------ End of Instructional Material ------

108 | CMPE 012 – Computer Programming


Quiz no.1- Midterm

NAME : ________________________________

COURSE : _____________ SECTION : _______

Part 1: underline the wrong code in the given java program. ( Correct Answer )
imports [Link];
public class Input_Quiz
{
public statics void main(Strings args[])
{
int a:
float b;
String s;

Scanner ins = new Scanner([Link]);

[Link]("Enter an integer");
a = [Link]();
[Link]("You entered integer " + a);

[Link]("Enter a float");
bs = [Link]();
[Link]("You entered float " + ba);

[Link]("Enter a string");
s - [Link]();
[Link]("You entered string " + as);

109 | CMPE 012 – Computer Programming


}
}

Additional Question 1: what is name of the class ?


_____________________
Additional Question 2: how to compile your java ?
_____________________
Additional Question 3: how to call your java executable file?
_____________________

Midterm: major Exam

NAME : ________________________________

COURSE : _____________ SECTION : _______

Multiple Choice
1. ____________ are containers for storing data values.
a. Syntax b. data type c. variable
2. ____________ - includes byte, short, int, long, float, double, boolean and char
a. Numbers b. Primitive data types c. Strings
3. ____________ are used to determine the logic between variables or values
a. Assignment operator b. Arithmetic Operator c. Logical
Operator
4. ____________ are used to perform common mathematical operations.
a. Assignment operator b. Arithmetic Operator c. Logical
Operator
5. ____________ - such as String, Arrays and Classes
a. Numbers b. Primitive data types c. Non-primitive data type
6. ____________ - stores text, such as "Hello". String values are surrounded by
double quotes
a. Char b. String c. Integer
7. ____________ - stores integers (whole numbers), without decimals, such as 123 or
-123
a. integer b. float c. double

110 | CMPE 012 – Computer Programming


8. ____________ - stores floating point numbers, with decimals, such as 19.99 or -
19.99
a. long b. float c. short
9. ____________ - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
a. string b. array c. char
10. ____________ - stores values with two states: true or false
a. if/else b. Boolean c. switch
11. ____________ are used to perform operations on variables and values.
a. Operator b. Conditional c. Logical

12. A ____________ variable contains a collection of characters surrounded by double


quotes
a. Array b. Char c. String
13. Use ____________ to specify a block of code to be executed, if a specified
condition is true
a. For b. else c. if
14. Use ____________ to specify a block of code to be executed, if the same condition
is false
a. If/else b. else c. nestedif
15. Use ____________ to specify a new condition to test, if the first condition is false
a. Else/if b. nested if c. if
16. Use ____________ to specify many alternative blocks of code to be executed
a. While b. break c. switch
17. ____________ This loop will execute the code block once, before checking if the
condition is true, then it will repeat the loop as long as the condition is true.
a. For loop b. [Link] loop c. while loop
18. The ____________ statement allows you to define a block of code to be tested for
errors while it is being executed.
a. Finally b. catch c. throws d. try
19. The ____________ statement allows you to define a block of code to be executed,
if an error occurs in the try block.
a. Finally b. catch c. throws d. try

111 | CMPE 012 – Computer Programming


20. The ____________ statement lets you execute code, after try...catch, regardless of
the result
a. Finally b. catch c. throws d. try

Quiz no.1 - Finals

NAME : ________________________________

COURSE : _____________ SECTION : _______

Grading Criteria:
Assigning Variable / data type - 15 point
Proper Code Arrangement - 35 point
Program Execution - 35 point
Attitude / Knowledge - 15 point
-------------------------
100 points
Machine Problem (Laboratory)
Create a java program using do/while loop, that the user required to
input username and password, the program will ask the user to continue
[Y/N] if the user select N, the program process will terminate and display
message “System Close”

112 | CMPE 012 – Computer Programming


Multiple Choice :
1. Which among the following is not a level of abstraction?
a) Logical level
b) Physical level
c) View level
d) External level
2. If two classes combine some private data members and provides public member
functions to access and manipulate those data members. Where is abstraction used?
a) Using private access specifier for data members
b) Using class concept with both data members and member functions
c) Using public member functions to access and manipulate the data members
d) Data is not sufficient to decide what is being used
3. Encapsulation and abstraction differ as ____________
a) Binding and Hiding respectively
b) Hiding and Binding respectively
c) Can be used any way
d) Hiding and hiding respectively
4. Abstraction principle includes___________
a) Use abstraction at its minimum
b) Use abstraction to avoid longer codes
c) Use abstraction whenever possible to avoid duplication
d) Use abstraction whenever possible to achieve OOP
5. Which among the following can be viewed as combination of abstraction of data and
code.
a) Class
b) Object
c) Inheritance
d) Interfaces

113 | CMPE 012 – Computer Programming


6. Which definition best describes an object?
a) Instance of a class
b) Instance of itself
c) Child of a class
d) Overview of a class
7. Which among the following is false?
a) Object must be created before using members of a class
b) Memory for an object is allocated only after its constructor is called
c) Objects can’t be passed by reference
d) Objects size depends on its class data members
8. Which of the following is incorrect?
a) class student{ }s;
b) class student{ }; student s;
c) class student{ }s[];
d) class student{ }; student s[5];
9. The object can’t be __________
a) Passed by reference
b) Passed by value
c) Passed by copy
d) Passed as function
10. How members of an object are accessed?
a) Using dot operator/period symbol
b) Using scope resolution operator
c) Using member names directly
d) Using pointer only
11. Which of the following is not type of class?
a) Abstract Class
b) Final Class
c) Start Class
d) String Class.
12. Class is pass by _______
a) Value
b) Reference

114 | CMPE 012 – Computer Programming


c) Value or Reference, depending on program
d) Copy
13. Which of the following pairs are similar?
a) Class and object
b) Class and structure
c) Structure and object
d) Structure and functions
14. Which among the following is false for class features?
a) Classes may/may not have both data members and member functions
b) Class definition must be ended with a colon
c) Class can have only member functions with no data members
d) Class is similar to union and structures
15. Instance of which type of class can’t be created?
a) Anonymous class
b) Nested class
c) Parent class
d) Abstract class
16. Which among the following, for a pure OOP language, is true?
a) The language should follow 3 or more features of OOP
b) The language should follow at least 1 feature of OOP
c) The language must follow only 3 features of OOP
d) The language must follow all the rules of OOP
17. Which feature in OOP is used to allocate additional function to a predefined operator
in any language?
a) Operator Overloading
b) Function Overloading
c) Operator Overriding
d) Function Overriding
18. How many basic features of OOP are required for a programming language to be
purely OOP?
a) 7
b) 6
c) 5
d) 4

115 | CMPE 012 – Computer Programming


19. Which feature may be violated if we don’t use classes in a program?
a) Inheritance can’t be implemented
b) Object must be used is violated
c) Encapsulation only is violated
d) Basically all the features of OOP gets violated
20. Which among the following doesn’t come under OOP concept?
a) Platform independent
b) Data binding
c) Message passing
d) Data hiding

116 | CMPE 012 – Computer Programming


Finals : Major Exam :
NAME : ______________________________ COURSE : ____________ SECTION ____

Multiple Choice :

1. What is the extension of java code files?


a) .class
b) .java
c) .txt
d) .js
2. What is the extension of compiled java classes?
a) .class
b) .java
c) .txt
d) .js
3. Which of these selection statements test only for equality?
a) if
b) switch
c) if & switch
d) none of the mentioned
4. Which component is used to compile, debug and execute java program?
a) JVM
b) JDK
c) JIT
d) JRE
5. Which of these are selection statements in Java?
a) if()
b) for()
c) continue
d) break
6. How can we identify whether a compilation unit is class or interface from a .class file?
a) Java source file header
b) Extension of compilation unit
c) We cannot differentiate between class and interface
d) The class or interface name should be postfixed with unit type
7. Which of the following loops will execute the body of loop even when condition
controlling the loop is initially false?
a) do-while
b) while
c) for
d) none of the mentioned

117 | CMPE 012 – Computer Programming


8. What is use of interpreter?
a) They convert bytecode to machine language code
b) They read high level code and execute them
c) They are intermediated between JIT and JVM
d) It is a synonym for JIT
9. Which component is responsible for converting bytecode into machine specific code?
a) JVM
b) JDK
c) JIT
d) JRE
10. Which of these jump statements can skip processing the remainder of the code in its
body for a particular iteration?
a) break
b) return
c) exit
d) continue
11. Which component is responsible to run java program?
a) JVM
b) JDK
c) JIT
d) JRE
12. Which of this statement is incorrect?
a) switch statement is more efficient than a set of nested ifs
b) two case constants in the same switch can have identical values
c) switch statement can only test for equality, whereas if statement can evaluate any
type of boolean expression
d) it is possible to create a nested switch statements
13. Which one is a valid declaration of a boolean?
a) boolean b1 = 1;
b) boolean b2 = ‘false’;
c) boolean b3 = false;
d) boolean b4 = ‘true’
14. The while loop repeats a set of code while the condition is not met?
a) True
b) False
15. Which statement is true about java?
a) Platform independent programming language
b) Platform dependent programming language
c) Code dependent programming language
d) Sequence dependent programming language
16. What is true about a break?
a) Break stops the execution of entire program
b) Break halts the execution and forces the control out of the loop
c) Break forces the control out of the loop and starts the execution of next iteration
d) Break halts the execution of the loop for certain time frame
17. Which of the following can be operands of arithmetic operators?
a) Numeric
b) Boolean
c) Characters
d) Both Numeric & Characters

118 | CMPE 012 – Computer Programming


18. Which of the below is invalid identifier with the main method?
a) public
b) static
c) private
d) final

19. What is true about do statement?


a) do statement executes the code of a loop at least once
b) do statement does not get execute if condition is not matched in the first iteration
c) do statement checks the condition at the beginning of the loop
d) do statement executes the code more than once always
20. Modulus operator, %, can be applied to which of these? 7
a) Integers
b) Floating – point numbers
c) Both Integers and floating – point numbers
d) None of the mentioned
21. Which of the following is used with the switch statement?
a) Continue
b) Exit
c) break
d) do
22. Which of the following statements is correct?
a) Public method is accessible to all other classes in the hierarchy
b) Public method is accessible only to subclasses of its parent class
c) Public method can only be called by object of its class
d) Public method can be accessed by calling object of the public class
23. What is the return type of a method that does not return any value?
a) int
b) float
c) void
d) double
24. Which of these statement is incorrect?
a) Every class must contain a main() method
b) Applets do not require a main() method at all
c) There can be only one main() method in a program
d) main() method must be made public
25. What is the process of defining more than one method in a class differentiated by
method signature?
a) Function overriding
b) Function overloading
c) Function doubling
d) None of the mentioned
26. Which of the following is a valid declaration of an object of class Box?
a) Box obj = new Box();
b) Box obj = new Box;
c) obj = new Box();
d) new Box obj;
27. Which of the following is a method having same name as that of it’s class?
a) finalize
b) delete

119 | CMPE 012 – Computer Programming


c) class
d) constructor

28. Which of these keywords is used to make a class?


a) class
b) struct
c) int
d) none of the mentioned

29. Which method can be defined only once in a program? 8


a) main method
b) finalize method
c) static method
d) private method
30. Which of this statement is incorrect?
a) All object of a class are allotted memory for the all the variables defined in the
class
b) If a function is defined public it can be accessed by object of other class by
inheritation
c) main() method must be made public
d) All object of a class are allotted memory for the methods defined in the class
31. Which of these statements are incorrect?
a) Assignment operators are more efficiently implemented by Java run-time system
than their equivalent long forms
b) Assignment operators run faster than their equivalent long forms
c) Assignment operators can be used only with numeric and character data type
d) None of the mentioned
32. Which of the following is not OOPS concept in Java?
a) Inheritance
b) Encapsulation
c) Polymorphism
d) Compilation
33. Which of the following is a type of polymorphism in Java?
a) Compile time polymorphism
b) Execution time polymorphism
c) Multiple polymorphism
d) Multilevel polymorphism
34. Which concept of Java is a way of converting real world objects in terms of class?
a) Polymorphism
b) Encapsulation
c) Abstraction
d) Inheritance
35. Which concept of Java is achieved by combining methods and attribute into a class?
a) Encapsulation
b) Inheritance
c) Polymorphism
d) Abstraction

120 | CMPE 012 – Computer Programming


36. Method overriding is combination of inheritance and polymorphism?
a) True
b) false

37. Which of the following is not a decision making statement?


a) if
b) if-else
c) switch
d) do-while
38. What is the range of short data type in Java?
a) -128 to 127
b) -32768 to 32767
c) -2147483648 to 2147483647
d) None of the mentioned
39. What is the range of byte data type in Java? 9
a) -128 to 127
b) -32768 to 32767
c) -2147483648 to 2147483647
d) None of the mentioned
40. What is the output of relational operators?
a) Integer
b) Boolean
c) Characters
d) Double

--- end of exam. ----

Thank you

121 | CMPE 012 – Computer Programming


Grading System

1st Grading

Class Standing
● Assessment……………..40
● Quiz………………………60
100 x 70% ……….. 70%
Midterm Exam
● Drawing/Sketch…………………………….…..30%
Midterm Grade…………………………………………………..100%

2nd Grading

Class Standing
● Assessment……………..40
● Quiz………………………60
100 x 70% ……….. 70%
Final Exam
● Script……………………………..………….…..30%
Finals Grade……………………………………………………..100%

SIS Grade = (1st Grading + 2nd Grading)/2

References
Books :
Java for Absolute Beginners: Learn to Program the Fundamentals the Java 9+ Way
Iuliana Cosmina Edinburgh, UK
ISBN-13 (pbk): 978-1-4842-3777-9

Object-Oriented Programming and Java


Authors: Poo, Danny C.C., Kiong, Derek B.K.| Springer-Verlag Singapore

Object-Oriented Programming with Java: An Introduction 1st Edition


Author : David Barnes | ISBN-10 : 0130869007
Publisher : Prentice Hall; 1st edition (January 28, 2000)

Object-oriented Programming with Java: Essentials and Applications

122 | CMPE 012 – Computer Programming


Author : Rajkumar Buyya
ISBN :0070669082, 9780070669086
Publisher Tata McGraw-Hill Education, 2009

Installer :
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
:[Link]
[Link]

123 | CMPE 012 – Computer Programming

You might also like