IM CMPE 20022 Computer Programming
IM CMPE 20022 Computer Programming
COURSE GUIDE
I. Course Code: CMPE 20022
II. Course Title: Computer Programming
III. Course Overview
A. Course Description
C. Course Topics
To ensure the accomplishment of the learning outcomes, this course will cover
the following topics:
This material was prepared for students to be equipped with theoretical and technical
know-how for the subject CMPE 20022: Computer Programming.
2
It is a self-paced material; hence, please be guided to -
1. Manage time well. Schedule properly reading the material and doing the activities
set. It is targeted that at the end of the semester, all activities set will be sent back
to the Electronics Engineering Department.
2. Focus. Make sure that you do things one at a time. Read the material over and
over until you are able to get the point of the lesson. If some areas are not clear
enough, you can refer to related books, the suggested readings, and videos as it may
deem necessary.
3. Give your best. In doing the assessment task whether formative or summative,
target the highest standards because you are a better student. You have the
knowledge and skills that you need to finish with the quality of work.
4. Submit on time. Once you are finished with the instructional material, it is
expected for you to send back your answers to activities and assessment.
5. Answer Assessment. Copy the question in a separate sheet and show solutions
and answers neatly complete, legibly, and concise. Also, Box in Final Answers
6. Work independently. It is expected that you work on the material on your own.
You can ask help from others but do your best to do it first.
7. Motivate yourself. Whatever knowledge or skill you are gaining from the course will
definitely help you take a step closer to be an Electronics Engineer. Enjoy what
you are doing and everything else will follow.
8. Reach Out. If you need help or guidance in any part of the lesson, please reach
out to your professor or to the ECE Department.
V. Grading System
VI. References
3
Prepared By:
4
COURSE TOPIC I: Introduction to Object-Oriented Programming and UML
Overview
Object-oriented programming is the latest approach to software engineering supporting
more functionality compared to the older programming paradigm which uses the top-down
approach. Object oriented programming adds more security and ease of use by adding
encapsulations and information hiding capabilities. In addition to this, polymorphism and
abstraction also provides lots of advantages for your programming which makes it the
most popular programming paradigm nowadays.
Learning Objectives
After successful completion of the lesson, you should be able to:
⚫ Discuss and differentiate the concepts of object-oriented programming
⚫ Construct different UML diagrams such as Class Diagrams, Sequence Diagrams,
etc from simple Use Case Scenario or system requirement
Course Material
Before going to the main topic of object-oriented programming, one needs to know first
the earlier known form of programming which is known as the structural or procedural
programming.
Procedural Programming
Procedural programming is a programming paradigm, derived from structured
programming, based on the concept of procedure call. Procedures, also known as
routines, subroutines, or functions, simply contain a series of computational steps to be
carried out. Any given procedure might be called at any point during a program’s
execution.
5
2. Data Types
In Java or any other programming languages, a variable has a type that indicates
what sort of data it can hold.
a) Integers - can hold whole numbers (e.g. 3, -7, 0)
b) Float - can hold numbers with decimal values (e.g. 3.14, -2.7, 17.5)
c) Characters - can hold individual characters (e.g. ‘A’, ‘;’, ‘x’)
d) Strings - can hold combinations of characters (e.g. “Hello”, “car”)
3. Commands
Commands are instructions for getting data in and out of variables for doing
computations with data
Example:
interest = principal * 0.07;
The code above commands the CPU to get the value of the principal variable,
multiply it to 0.07 and send the resulting product to another variable named interest.
Program
A program is basically a sequence of instructions which executes these instructions one
by one as they occur in the source code. But as the program executes instructions from
start to finish, it would soon run out of instructions to execute, one way or another. So
modern programming languages use control structures and subroutines to handle this
programming limitation.
Control Structures
Control structures are special instructions that can change the flow of control in a
program.
6
Example:
if ( principal > 10000 )
else
The code above simply means that if the value in the principal variable is
greater than 10000, it will multiply it to 0.05 before storing the product to the
interest variable. If it is not greater than 10000, then it will multiply it to 0.04
instead.
Subroutine
Subroutines consist of the instructions for performing tasks, grouped together as a unit
and a given name. This helps into organizing your program flow and design.
As we remember, data types and variables in the traditional structured programming are
separate from the instructions. In object-oriented programming, the data structure
becomes an object that includes both data and functions that can manipulate the data
inside that object. This way, the programmer doesn’t need to know the exact code of
instructions inside the object as long as it performs its desired task. Additionally, the user
only has a predetermined number of procedures that he can execute to the data
preventing unintentional or intentional changes to the data inside the object.
7
Basic Object-Oriented Programming Concepts
1. Classes. A class is a category of objects
Example: There might be a class called shape which contains objects which
are circles, rectangles and triangles. The class defines all common properties of
the different objects that belong to it.
2. Objects. An object is a self-contained entity that consists of both data and
procedures (methods) to manipulate the data.
3. Methods. A method is a procedure that is executed when an object receives a
message. It is the same as procedure, function or routines in other procedural
programming languages. The only difference is that in object-oriented
programming, a method is always associated with a class.
4. Inheritance. Inheritance in object-oriented programming is a feature that
represents the relationship between classes. It allows a class to have the same
behavior to provide special action for specific needs.
5. Encapsulation. This is the process of combining elements to create a new entity.
For example, programmers use encapsulation to combine data types and
procedures or methods. Encapsulation is used in object-oriented programming to
create high-level objects. It is closely related to abstraction and information hiding.
6. Abstraction. Abstraction is a process of picking out (abstracting) common
features of objects and procedures. A programmer would use abstraction, for
example, to note that two functions perform almost the same task and can be
combined into a single function.
7. Polymorphism. In object-oriented programming, it refers to the programming
language’s ability to process objects differently depending on their data type or
class. For example, given a base class shape, polymorphism enables the
programmer to define different area methods for any numbers of derived classes,
such as circles, rectangles and triangles. No matter what shape the object is,
applying the area method will return the correct results.
8. Information Hiding. In programming, it is the process of hiding details of an
object or function. Information hiding increases security and reduces complexity.
The programmer then can focus on the new object without worrying about the
hidden details or data inside that object. Encapsulation is often used to achieve
information hiding. It can also prevent other programmers from intentionally or
unintentionally changing parts of the program.
8
Advantages of Object-Oriented Programming
One of the principal advantages of object-oriented programming techniques over
procedural programming techniques is that they enable programmers to create
modules that do not need to be changed when a new type of object is added. A
programmer can easily create a new object that inherits many of its features from
existing objects.
The unified modeling language become the standard modeling language for object-
oriented modeling. It has many diagrams, however, the most diagrams that are
commonly used are:
1. Use case diagram: It shows the interaction between a system and its
environment (users or systems) within a particular situation.
9
2. Class diagram: It shows the different objects, their relationship, their behaviors,
and attributes.
3. Sequence diagram: It shows the interactions between the different objects in the
system, and between actors and the objects in a system.
4. State machine diagram: It shows how the system respond to external and
internal events.
5. Activity diagram: It shows the flow of the data between the processes in the
system.
Types of Relationships
1. Inheritance
Inheritance provides a generic super class that has the common attributes and
methods between all subclasses. This way, we avoid duplicates, as we don’t have
to write them as we don’t have to write the common attributes or methods. You
only need to write them one in the superclass and the subclasses will all have the
attributes and methods from their superclass.
Inheritance also refers to the “IS-A” relationship. For example, “a nurse IS-A
person”, “a square IS-A shape”, etc.
10
2. Association, Aggregation and Composition
⚫ Association - relationship between classes that interacts with other. It is
usually denoted by a line in the conceptual framework.
Example: the Customer object uses the Shopping Cart to get the number
of Items in the Cart.
⚫ Aggregation (HAS-A relationship) - relationship which describes that an
object can be made of, or built from some other objects.
Example: “a car HAS-A engine”, “a classroom HAS-A student”, etc.
⚫ Composition - same as aggregation, but it implies the concept of ownership
In the example, the page class can only exist if the document class is
instantiated. Logically, the page class will be destroyed too if the document
class is destroyed since the composition relationship is being used.
On the other hand, a student can exist with or without the classroom class
since an aggregation relationship is used.
Use aggregation when the objects can exist independently, and use
composition when these objects can’t logically exist without that object that’s
made of them.
3. Multiplicity
Multiplicity is the active logical association when the cardinality of a class in
relation to another is being depicted. For example, one battalion may include
multiple soldiers. The notation 1…* means “one to many”.
11
UML Diagrams and Models
1. Conceptual Model
One of the first step on designing a software is to have a conceptual model
of the project. Once the use cases or user stories have been laid out, the next
thing to do is to create a conceptual model of the system. In this model, important
objects must be identified without thinking yet if they will be translated to actual
classes and software objects in the design phase.
2. Refining Objects
After identifying your candidate objects, you can start refining them and
choose the actual objects that will be in the system. So to do that,…
Example:
Customer Order
12
Item Order Number (can be attribute of order)
Shopping Cart Order Status (can be attribute of order)
Payment Order Details (can be attribute of order)
Address Email
Sale System (the program itself)
3. Drawing Objects
Using a pen and paper, draw each objects in a bounding box.
13
5. Identifying Object Behaviors
Behaviors are the things (verbs) the object can do, or, in other words, the
responsibilities of an object, that will become methods in our object class. So,
check back the use cases or user stories, and look for verbs and phrases to
pick responsibilities.
Example:
Use Case Scenario: Customer verifies items in shopping cart.
Customer provides payment and address to process sale. System
validates payment and responds by confirming order, and provides
order number that Customer can use to check on order status. System
will send Customer a copy of the order details by email.
Things like verifies items, provides payment and address, process sale,
provide order number, check order status, and send order details by email.
Now, not all of these will become behaviors, some will be combined, some
will need to be split apart, and some will not be needed or be replaced by
something else, but they are a good starting point.
14
Additional Pointers in assigning responsibilities;
⚫ Change the generic verb “provide” to “set’ or “get” instead to make it
clear what we are trying to do
⚫ If you see some phrases like “System validates payment” or “System
sends email”, this means that a part of the system validates payment
or sends email and it is the programmer’s job to determine which
object should be responsible for it.
⚫ If you have an object with a lot of responsibilities, chances are, you
are doing it wrong. Think of ways to distribute the responsibilities
among objects. Remember that an object should be responsible of
itself as much as possible.
15
2. Structural Model
Structural models of software display the organization of a system in terms of
components that make up that system and their relationships.
Class Diagram - used for modeling the structure of the classes in a software
system
1. Naming Convention
You start by using a way of naming your classes. Usually, the class
name is in singular, and uppercase first letter, like “UserName”. For
attributes, and methods, they are in camelcase; lowercase first letter, and
all other words begins with uppercase letter, like “getProductDetails” or
“getOrderNumber”
2. Attributes
Next step is to write the attributes, their data types and their default
value if they exist.
16
3. Methods
Write the methods, their parameter if exist inside a parentheses, and
their return type.
4. Access Modifiers
Every attribute or method should be either Public, Private or
Protected. This is called access modifiers which control how they can be
accessed. A good practice is to keep every members (attributes and
methods) private unless it needs to be exposed. Using signs (positive or
negative) can denote the access modifier in each member of the class.
⚫ Public (‘+’): It says that it can be seen and triggered at any part of the
application
⚫ Private (‘-’): It says that it can only be triggered inside its class only
⚫ Protected (‘#’): It says that it can only be triggered inside its class and
also inside the child classes
17
5. Constructor and Deconstructor
Whenever an object is created, there are methods that are
automatically called which assign the correct attributes to that object upon
creation. These are called Constructors.
On the other hand, when an object is destroyed or went out of scope,
another method is automatically called to immediately destroy the
attributes associated with that object. It is called Deconstructors which
are prevalent in C++ than in Java.
3. Interaction Model
Interaction Models show the interaction between the components of a
system, or between the system being developed and other systems (or users).
18
Sequence Diagram - used to model the interactions between the users and
the objects in the objects in the system, and between the objects themselves. It
is used to give an overview of specific parts of the system, a specific use case,
actually the important ones, or the unclear parts of the system. So you don’t need
to sketch out every single interaction in the system.
⚫ Generic Form - shows all possible sequence of interactions to all
scenarios (conditions) of a use case.
⚫ Specific Form - shows the sequence of interactions of one scenario
Here is an example of a Sequence Diagram.
19
4. Rectangular Box on the life-line - represents an activation of an object.
It’s the time period during which the object performs an operation. The
life-line denotes the object existence, while activation denotes the object
is performing operation as well.
You can add a condition on the arrow says that this message won’t
be sent unless the condition is true.
2. Returned Value
When you are expecting a response, dashed arrow (stickhead)
represents the returned value. Only show the returned value if it is
important.
20
3. Self Delegation
An operation or method within the same object’s class.
Types of Messages
1. Synchronous Message
It’s a message where the caller object has to wait for the receiving
object to finish execution.
It always has an associated return values or acknowledgement of
being successfully completed. So, object will still in activation until it
receives a respond.
2. Simple Message
A message that transfer control from the sender to the recipient
object.
It’s one way message. An example of that is a return from
synchronous message. The return message transfers the control to the
sender object.
21
3. Asynchronous Message
The caller object doesn’t have to wait for the receiving object to finish
execution. The arrow in this case is shown as an open arrowhead.
Asynchronous messages are common in concurrent, real time
systems, in which several objects operate in parallel.
22
Conditional and Looping Interaction
1. Alt
If there are different actions to take based on different conditions, you
can surround these action with what’s called “alt” frame. So you will show
the interactions in case of both conditions.
2. Loop
If there are messages that need to happen multiple times, you can
surround this with what’s called a “loop” frame.
23
4. Behavioral Model
Behavioral Models show the dynamic behavior of the system as it’s
executing. They show what happens or what’s supposed to happen when a
system response to an alarm.
You can think of an alarm as being of two types:
⚫ Data - some data that has to be processed by the system
⚫ Events - Some event happens that triggers system processing. Events
may have associated data, but this is not always the case.
Many business systems are data processing systems that are primarily driven
by data. For example, a phone billing system will accept information about calls
made by customer, calculate the costs and these calls, and generate a bill.
By contrast, real-time systems are often driven with minimal data-processing.
For example, a landline phone switching system responds to events such as
pressing on keys on a handset by capturing the phone number.
Supplemental Information
Watch
Object Oriented Programming https://www.youtube.com/watch?v=pTB0EiLXUC8
Read
24
⚫ Booch, et.al. (2007) The Unified Modeling Language User Guide. Pearson
⚫ https://medium.com/omarelgabrys-blog/object-oriented-analysis-and-design-
introduction-part-1-a93b0ca69d36
Assessment
1. Draw a UML class diagram that models the relationships between the following
classes: Mall, Store, Sales Person, Department, Manager, Merchandise, Store Catalog,
Store Website, and Customer.
25
COURSE TOPIC II: Object-Oriented Analysis and Design
Overview
Object-oriented analysis and design is a structured method for analyzing and designing
a system by applying the object-oriented concepts, and developing a set of graphical
system models during the development life cycle of a software.
Learning Objectives
After successful completion of the lesson, you should be able to:
⚫ Analyze and differentiate a well-written code from a poorly-designed program
⚫ Discuss the different object-oriented design principles
Course Material
26
Types of Coupling in Object-Oriented Programming
1. Subclass Coupling
Describes the relationship between a child and its parent. The child is
connected to its parent but the parent is not connected to the child.
2. Temporal Coupling
It is when two methods are bundled together into one just because they
happen to occur at the same time.
Disadvantage of Coupling
Tightly coupled systems tend to exhibit the following developmental
characteristics, which are often seen as disadvantages:
1. A change in one class usually forces a ripple effect of changes in other
parts of the system.
2. Coding might require more effort and/or time due to increased inter-class
dependency.
3. A particular class might be harder to reuse and/or test because
independent modules must be included.
Cohesion
Cohesion is referred to as the degree to which the elements inside a module belong
together. In one sense, it is a measure of the strength of relationship between the
methods and data of a class and some unifying purpose or concept served by that
class. In another sense, it is the measure of the strength of relationship between the
class’s methods and data themselves.
Cohesion is an ordinal type of measurement and is usually described as “high
cohesion” or “low cohesion”. Modules with high cohesion are tend to be preferable,
because high cohesion is associated with several desirable traits of software
including robustness, reliability, reusability, and understandability. In contrast, low
cohesion is associated with undesirable traits such as being difficult to maintain, test,
reuse, or even understand.
Cohesion is increased if:
⚫ The functionality embedded in a class, accessed through its methods,
have much in common
27
⚫ Methods carry out a small number of related activities, by avoiding
coarsely grained or unrelated sets of data
⚫ Related methods are in the same source file or otherwise grouped
together; for example, in separate files but in the same sub-
directory/folder
Types of Cohesion
1. Coincidental Coupling (worst)
Coincidental cohesion is when parts of a module are grouped
arbitrarily and the only relationship between the parts is that they have
been grouped together.
2. Logical Cohesion
Logical cohesion is when parts of a module are grouped because
they are logically categorized to do the same thing even though they are
different by nature (e.g., grouping all mouse and keyboard input handling
routines)
3. Temporal Cohesion
Temporal cohesion is when parts of a module are grouped by when
they are processed - the parts are processed at a particular time in
program execution (e.g., functions which are called after catching an
exception which closes open files, creates an error log, and notifies the
user)
4. Procedural Cohesion
Procedural cohesion is when parts of a module are grouped because
they always follow a certain sequence of execution (e.g., functions which
checks file permissions and then opens the file)
28
5. Communicational/Informational Cohesion
Communicational cohesion is when parts of a module are grouped
because they operate on the same data (e.g., modules which operates
on the same record of information)
6. Sequential Cohesion
Sequential cohesion is when parts of module are grouped because
the output from one part is the input to another part like an assembly line
(e.g., functions which reads data from a file and processes the data)
7. Functional Cohesion (best)
Functional cohesion is when parts of a module are grouped because
they all contribute to a single well-defined task of a module (e.g.,
arithmetic operations inside one module)
Coupling is usually contrasted with cohesion. Low coupling often correlates with high
cohesion, and vice versa. Low coupling is often a sign of a well-constructed system,
and when combined with high cohesion, supports the general goals of high readability
and maintainability.
Coupling and cohesion are terms which occur together very frequently. Coupling
refers to the inter-dependencies between objects while cohesion describes how
related the functions within a single class are. Low cohesion implies that a given
module performs tasks which are not very related to each other and hence can create
problems as the module becomes large.
29
way in which the requests are carried out, by instead only specifying the intent of a
certain request.
For example, let’s say we have a Person class. In a data-driven design, we will need set
the attributes first like the gender, birthdate, etc., then we will set the methods that we can
do with that class using the data that it holds. Structure is the primary concern which is
straightforward and easy to understand especially for those who has a background on
procedural programming.
On the other hand, in a responsibility-driven design, we will need to think first of the
responsibility of a class before thinking about the structure or attributes that we will be
needing to do the task. Like we say this Person class will be having a responsibility of
calculating a person’s age. To do this, the Person object needs the person’s birthdate. As
you can see, the primary concern in a responsibility-driven design are behaviors of the
class first then the structure or data in it.
Certain roles are laid out to describe different types of responsible implementations to
help you define software elements. A “role” is some collection of related tasks that can
be bundled to a single responsibility. Some of these roles are the following:
⚫ Service Providers - designed to do things
⚫ Interfaces - translate requests and convert from one level of abstraction to
another
⚫ Information holders - designed to know things
⚫ Controllers - designed to direct activities
⚫ Coordinators - designed to delegate work
⚫ Structurers - manage objects relations and/or organize large numbers of similar
objects
Data-driven design talks about a centralized control system in its approach to have
application logic in one place. This is simple and easy to implement for the most part.
Responsible-driven design is all about delegated control to assign responsibilities to
elements and therefore each element can be reused very quickly because it only fulfills
its own responsibilities and not ones from some other elements in the design.
When assigning responsibilities, here are a few principles or patterns that can help with
the design:
⚫ Keep information in one place
“Single Point of truth Principle” - states that each piece of information is stored
exactly once.
30
⚫ Keep Responsibility Small
“Law of Demeter - Principle of the Least Knowledge” - each element should have
a limited piece of knowledge stored in itself and have about other elements
(Information Hiding / Information Expert)
⚫ Wrap Related Operations
“Whole Value Object” - wrap related operations/information in an object on its own
and give it a descriptive name
⚫ Only use what you need
“Interface Segregation Principle” - each interface should only implement method
which it needs
⚫ Aligned Responsibility
“Single Responsibility Principle” - each class in your software should have a
single responsibility and this responsibility should entirely be wrapped in this part.
31
Object-Oriented Analysis
In the object-oriented analysis, we…
1. Elicit requirements: Define what does the software need to do, and what’s
the problem the software is trying to solve
2. Specify requirements: Describe requirements, usually, using use cases
(and scenarios) or user stories.
3. Conceptual model: Identify the important objects, refine them, and define
their relationships and behavior and draw them in a simple diagram.
Object-Oriented Design
The analysis phase identifies the objects, their relationship, and behavior using the
conceptual model while in design phase, objects were described using their
attributes, behavior and interactions. A class diagram is mapped from the conceptual
diagram which gives a visual representation of the classes you need, And here is
where you get to be specific about object-oriented principles like inheritance and
polymorphism. The input for object-oriented design is provided by the output of object-
oriented analysis. But, analysis and design may occur in parallel, and the results of
one activity can be used by the other.
In object-oriented design, we…
1. Describe the classes and their relationships using class diagram.
2. Describe the interaction between the objects using sequence diagram.
3. Apply software design principles and design patterns.
System Modeling
System Modeling is the process of developing models of the system, with each model
representing a different perspectives of that system. The most important aspect about a
system model is that it leaves out detail; it’s an abstract representation of the system.
Models are used in the analysis process to help elicit the requirements, during the design
process to describe the system to engineers, and after implementation to document the
system structure and operation.
32
We may develop a model to represent the system from different perspectives.
1. External, where you model the context or the environment of the system.
2. Interaction, where you model the interaction between components of a system,
or between a system and other systems.
3. Structural, where you model the organization of the system, or the structure of
the data being processed by the system.
4. Behavioral, where you model the dynamic behavior of the system and how it
respond to events.
33
Object Oriented Design Principles
1. KISS
It stands for “Keep It Simple, Stupid”. What this principles states that “most
systems work best if they are kept simple rather than making them complex;
therefore simplicity should be a key goal in design and unnecessary complexity
should be avoided”.
If a code is simple, it will be easier to maintain and debug, easier to test, easier
to be documented, and negotiate if there is a problem.
2. DRY
“Don’t Repeat Yourself”. Try to avoid duplicates, instead, you put them into single
part of the system, or a method.
Imagine that you have copied and pasted blocks of code in different parts of your
system. In case you change one of them, you will need to change and check
every part that has the same block of code.
3. YAGNI
“You Ain’t Gonna Need It”. Implement only what is needed at the moment, under
the current requirements. Adding extra features, demands adding more code to
write, to maintain, to test and to debug. Leave the additional features that are not
yet needed for future revisions or versions of your program.
4. SOLID
S:Single Responsibility Principle
An object should have one and only one responsibility. You don’t need to
have an object that does different or many tasks. An object can have many
behaviors and methods, but all of them are relevant to it’s single
responsibility. So, whenever there is a change that needs to happen, there
will be only one class to be modified, this class has one primary responsibility.
O: Open/Closed Principle
Software entities (classes, modules, functions, etc.) should be open for
extension, but closed for modification. Whenever there’s a need to add
additional behaviors, or methods, you don’t have to modify existing ones,
instead, you start writing new methods.
34
L: Liskov Substitution Principle
A super class can be replaced by any of its inheriting sub classes at any
parts of the system without any change in the code. It means that the
subclasses should extend the functionality of the super class without
overriding it.
5. GRASP
General Responsibility Assignment Software Patterns (GRASP) is another set of
design principles. GRASP tends to take a responsibility focus, like ‘who creates
this object’, ‘who is in charge of how these objects talk to each other’, ‘who takes
care of passing all messages received from a user interface?’, etc.
a) Information Expert
When you assign a responsibility in a form of a method, or fields, you
assign it to the object that has the most information about it.
Imagine you have a class called Customer and Order. The customer tries
to know all the orders placed by him. A common mistake is to assign this
responsibility to the Customer class, since the customer who will trigger
this method. But, this is not the responsibility of the customer, the Order
class is the one which has all the information about the orders.
35
b) Creator
It tries to determine who is taking the responsibility of creating objects.
You answer these questions:
⚫ Who is responsible for creating the objects?, or, how those
objects are created in the first place?
⚫ Does one object contain another (composition relationship)?
⚫ Does one object very closely use another, or, will one object know
enough to make another object?
And if so, it would seem to make sense to nominate those objects as
taking that ‘creator’ role and making it obvious which objects are
responsible for creating objects.
c) Low Coupling
It means you try to reduce the dependency between your objects. If one
object needs to connect tightly to five other objects and call 20 different
methods just to work, you have a high coupling.
Lots of dependencies meaning lots of potential for breaking things if you
make a change to any of these objects.
Now low coupling does not mean no coupling. Objects do need to know
about each other, but as much as possible they should do what they can
with the minimum dependencies.
d) High Cohesion
The more you have a class that has a relevant and focused
responsibilities, the higher cohesion you will have. You try to make the
responsibilities of your classes relevant, related as much as you can. You
many need to break a class into some classes and distribute the
responsibilities, instead of having a single class that does everything.
e) Controller
If, for example, we have a user interface and also some business related
classes. We don’t want to have high coupling between them to actually
tie them directly together, where the user interface object has to know
about the business objects and vice versa. It is very common to create a
36
controller class just for the purpose of handling the connection between
the user interface and the business related objects.
f) Pure Fabrication
If there is something that needs to exist in the application that isn’t really
related to any of the existing classes, or if there is a behavior that doesn’t
naturally fit in existing classes, we need to invent or fabricate a new class
than to force those behaviors into an existing class where it doesn’t
belong. That newly fabricated class might not have existed in our
conceptual model, but it needs to exist now. And there’s nothing wrong
with creating a class that represents pure functionality as long as you
know why you’re doing it.
g) Indirection
This is the idea that we decrease coupling between objects. If you have
multiple objects that need to talk to each other, it’s very easy to have a
high coupling between them, where there is a lot of dependencies. What
we can do instead is to reduce those direct connections by putting an
indirection object between them to simplify the amount of connections
that each object has to make.
h) Polymorphism
Having an object that can take the shape of several different objects. This
allows us to trigger the correct behavior.
i) Protected Variations
How to design a system so that changes and variations have the
minimum impact on what already exists.
Identify the parts of the system that are more likely to change, separate
them from what stays the same, and then, encapsulate every part that
vary in the system. Most of the concepts of object-oriented programming
are simply ways of doing this, things like encapsulation and data-hiding,
making your attributes private.
The open/closed principle that we can add, but we try not to change code
that already works is yet another way of protecting your application from
variations.
37
6. Other DON’Ts in Coding Design
Here are just some of the violations of design principles which will have a negative
impact on your code’s overall design quality
a) Long Methods
When you open up a method to read it and it has many lines of codes. This
is the kind of thing that really needs to be split up into smaller methods.
b) Working with very short and very long Identifiers
Aside from using letters like ‘i’ for indexes and iteration, we shouldn’t be
expecting to see variables called A, B and C in a real code.
c) Pointless comments
Another thing to be aware of would be writing so many pointless comments.
Yes, code should be commented and code should be well-written so that it’s
readable and the code code comments itself. We do want comments, but we
don’t want comments where the comment is actually longer than the code
that it’s describing.
d) God Object
This is where you have one master object that tries to do everything in the
program, or at least one object that seems to be doing very different
responsibilities that have nothing to do with each other. It is a clue that this
needs to be revisited and broken into the right kind of objects.
e) Feature Envy
If the class seems to do very little except it uses all the methods of one other
class, it’s another sign that you need to rethink the roles of one or the other.
Supplemental Information
Watch
https://www.youtube.com/watch?v=IzN9Vuoivrg&list=PL6XklZATqYx9dj72MKG6wL
YjljeB2odra
Read
⚫ Booch, G (2007). Object-oriented analysis and Design with Applications, 3rd Ed.
Addison-Wesley
⚫ https://medium.com/omarelgabrys-blog/object-oriented-analysis-and-design-
introduction-part-1-a93b0ca69d36
38
COURSE TOPIC III: Programming Language Fundamentals
Overview
Programming which is sometimes called coding makes up the details of the overall design
of a program. The details are the explicit, step-by-step instructions for performing fairly
small-scale task.
This module will examine the facilities for coding in the java programming language.
Learning Outcomes
After successful completion of the lesson, you should be able to:
⚫ Differentiate the different types of data for programming
⚫ Enumerate the different operators being used in coding
⚫ Analyze simple expressions and statements
⚫ Construct working programs as required
Course Material
A program is a sequence of instructions can a computer can execute to perform some
task. These instructions are written in a form that the computer can understand which are
called computer languages.
Programming languages are different in human language in being completely
unambiguous and and very strict about what is allowed and not allowed in the program.
High level computer languages are used to write codes for the programs which are
somewhat closer to what human can understand. Then compilers or interpreters are used
to convert those high-level languages to machine language which the computer can
execute. In case of Java, the code is interpreted to bytecode which runs on a Java Virtual
Machine in a target computer.
Details about this concept will be discussed on other parts of the course.
39
But syntax is only a apart of the story. You can have a program that runs but gives
incorrect output. The program logic should be right and here is where semantics comes
in. The semantics of a programming language is a set of rules that determine the
meaning of the program written in that program. A semantically correct program is one
that does what you want it to.
Furthermore, a program can be syntactically and semantically correct but still a bad
program. A program should be written in a way that will make it easier for people to read
and understand. It follows different conventions and styles that are familiar to other
programmers. This aspect of programming is sometimes referred to as pragmatics.
Writing Comments
Comments are line or lines of codes that the computer will ignore and is often intended
for human readers. There are two ways to write comments in Java.
1. Single Line Comment - begins with a // and extends to the end of the line. The
computer ignores the // and everything that follows it on the same line
Example:
//This is a single line comment
2. Multi line Comment - starts with /* and ends with */ and can extend over more
than one line
Example:
/*
*/
Classes
All programming in Java is done inside “classes”. A class should be started by declaring
the name of the class with this syntax:
}
Example:
public class HelloWorld {
40
In the example, “Hello World”, the name of the class, also serves as the name of the
program. But not every class is a program. In order to define a program, a class should
include a routine named main, with the definition in this form:
public static void main(Strings[] args) {
<statements>
Subroutines
Large programs are complex and in order to simplify them, they can be grouped into
subroutines. Subroutines consists of the instructions for performing some task, grouped
together as a unit and given a name. In Java, subroutines can come in different forms
and are called by their name. Here’s an example:
System.out.println();
This command is an example of subroutine call statement with the primary task to
displaying text in a standard output.
<statements>
<optional subroutines>
41
Class Name: HelloWorld
Objective: Display the text “Hello World” in the output
System.out.println(“Hello World”);
Naming Conventions
According to syntax in Java, every class, variables, and subroutines should be named
using identifiers. An identifier is a sequence of one or more characters.
⚫ Identifiers must begin with a letter or underscore (‘_’)
⚫ Can only be consists of letters, digits or underscores (Java uses the Unicode
character set)
⚫ No spaces are allowed
⚫ Case-sensitive
Compound Names
A compound name is a kind of path to an item through one or more levels
of containment. It consists of several simple names separated by periods.
Example is “System.out.println()” which indicates that something called
“System” contains something called “out” which in turn contains something called
“println()”
Naming Pragmatics
⚫ Classes are usually named with identifiers that begin in upper case letters
while
42
⚫ Variables and subroutines are usually named with identifiers that begin in
lowercase letters
⚫ When an identifier is made up of several words, it is customary to
capitalize the first letter of each word except the first (e.g., interestRate,
shoppingCart) This is called camel case.
Variables
Computers store data in a specific memory location with a numerical address. In high-
level programming, we use variables to refer to those memory locations instead of
remembering all the numerical addresses. Think of the variable as a container box where
you can store data
Assignment Statement
Assignment statement is used to store data into a variable or into a memory location. It
takes the form:
<variable> = <expression>
where <expression> represents anything that refers to or computes a data value. The
computer first evaluates the <expression> and stores the data inside the memory location
that the <variable>
Example:
rate = 0.07;
43
2. short - occupies two bytes of memory that can represent integers that ranges
from -32768 to 32767
3. int - occupies three bytes of memory that can represent integers that ranges
from -2147483648 to 2147483647
4. long - occupies four bytes of memory that can represent integers that ranges
from -9223372036854775808 to 9223372036854775807
5. float - occupies four bytes of memory that can represent numbers with
decimal digits. It can range up to about 10 raised to the power of 38 and has
about 7 significant digits
6. double - occupies eight bytes of memory that can represent numbers with
decimal digits. It can range up to about 10 raised to the power of 308 and has
about 15 significant digits
7. char - occupies two bytes in the memory that can hold a single character from
the Unicode character set
8. boolean - holds two logical values either true or false
Strings
A value of type String is a sequence of characters. Double quotes are used to represent
a string in the code but not part of the string itself
Example:
“Hello World!”
Declaration of Variables
A variable can only be used in a program declared. A variable declaration statement is
used is used to declare variables which takes the form:
<Type name> <variable name or names>
Example:
int numberOfStudents;
double x, y;
boolean isFinished;
char middleInitial;
44
Writing your Second Program
This example code will compute and display in the output the interest and interest rate of
a value invested. The following code will demonstrate the use of declaration statements,
assignment statements and different data types including the primary data types and
strings.
/*Do computations*/
principal = 17000;
rate = 0.027;
45
System.out.print(“The interest earned is Php”);
System.out.println(interest);
System.out.println(principal);
Displaying Output
The most basic function is System.out.print(x), where x can be a value or expression of
any type. If the parameter, x, is not a string. It is converted to a value of type String, and
the string is the output to the standard display.
System.out.println(x) outputs the same text as System.out.println(x), but it follows that
text with a line feed, which means that any subsequent output will be on the next line.
Example 1:
System.out.print(“Hello”);
System.out.print(“World”);
Displayed Output:
HelloWorld
Example 2:
System.out.println(“Hello”);
System.out.println(“World”);
Displayed Output:
Hello
World
46
Reading Input
Reading in Java is a little difficult compared to displaying output because of the
assortment of format and data types to read from. You may be able to read an input but
processing it correctly might be a challenge.
There are alot of ways to read from the user’s input but what we will discuss here is the
use of the Scanner class. One advantage of using Scanner is that it’s a standard part of
Java and so is always there when you want it.
First, since Scanner is defined in the package java.util, you should add the following
import directive to your program at the beginning of the source code file, before the public
class:
import java.util.Scanner;
Then include the following statement at the beginning of your main() routine:
Scanner stdin = new Scanner( System.in );
This creates a variable named stdin of type Scanner. You can now use a variety of
subroutines such as nextDouble(), nextInt(), nextLong and nextBoolean() for reading user
input. For full lists of Scanner subroutines, please refer to the official Java Scanner class
routines resource.
Read and analyze this example code below for your reference.
import java.util.Scanner;
double principal;
double rate;
double interest;
Principal = stdin.nextDouble();
47
System.out.print(“Enter the annual interest rate (as a decimal); “);
Rate = stdin.nextDouble();
} //end of main()
Operators
Arithmetic Operators
Arithmetic operators include addition, subtraction, multiplication, and division. These
operators can be used on values of any numeric type like byte, short, int, long, float, or
double. A special operator “%” is used to get the remainder in a division operation.
Operation Operator Example
Addition + 7+2=9
Subtraction - 7-2=5
Multiplication * 7 * 2 = 14
Division / 7/2=3 Note: the quotient
will always be a
whole number
Modulus % 7%2=1
Increment / Decrement
Adding or subtracting one to the value inside a variable is very common in programming.
These are called incrementing or decrementing. Normally, adding or subtracting a value
of one to a variable can written as:
48
counter = counter + 1;
timer = timer - 1;
Using the increment and decrement operators, the above statements can also be written
counter++;
timer--;
In the examples above,the statement “y = x++;” has the effect of adding the old value of
the variable x to the variable y before incrementing the value of x. On the other hand, the
statement “z = ++x;” increments first the value of x before assigning the new value to the
variable z. Same concept applies to decrementing variables. The decrement operator
works in a similar way.
Important note in particular is the statement “x = x++;” does not change the value of x.
because the value that is assigned to x is also the old value of x making the increment
useless. You can avoid this error by using a new variable to assign the value into, just
like the statement “y=x++;”.
Relational Operators
Relational operators are used to test whether two values are equal, whether one value is
greater than another, and so forth. Such statements will output a boolean value indicating
whether the relation is true or false. These expressions will be used more in control
statements and loops in the next sections of this module.
Relations Meaning
A == B Is A “equal to” B?
A != B Is A “not equal to” B?
A<B Is A “less than” B?
A>B Is A “greater than” B?
49
A <= B Is A “less than or equal to” B?
A >=B Is A “greater than or equal to” B?
Boolean Operators
Boolean operators combine two or more boolean values which results to another boolean
value. “And” operator will result in a true value only if both the combined value is true. The
expression “A && B” is true if both A and B are true.
The expression “A || B” using the “Or” operator will result to a “true” value if either of the
expression A or B is true.
The boolean operator “not” is unary operator which is indicated by ! and is written in front
of its single operand. This operator’s main function is to reverse the value of its single
operand from true to false, or false to true.
Boolean Operation Operator
And && (two ampersand)
Or || (two pipe or vertical line)
Not ! (exclamation symbol)
Assignment Operators
Java has several variations on assignment operator, which exist to save typing. Every
operator in Java that applies to two operands, except for relational operators, gives rise
to a similar assignment operator. For example:
Expression Meaning
x += y; Same as x = x + y;
x -= y; Same as x = x - y;
x *= y; Same as x = x * y;
x /= y; Same as x = x / y;
x %= y; Same as x = x % y;
q &&= p; Same as q = q && p; (for booleans q and
p
Precedence Values
50
If several operators were used in a single expression, precedence rules determine the
order of evaluations. It is like the PEMDAS in basic arithmetic. Using parentheses
responsibly while coding is a good practice to simplify the evaluation of expressions.
Here are the operators used in Java listed in order from highest precedence (evaluated
first) to lowest precedence (evaluated last):
Unary Operators ++, --, !,
Multiplication and Division *, /, %
Addition and Subtraction +, -
Relational Operators <, >, <=, >=
Equality and Inequalities ==, !=
Boolean AND &&
Boolean OR ||
Assignment Operators =, +=, -=, *=, /=, %=
Supplemental Information
Watch
Youtube Tutorials about Basic Java Programming of your choosing
Read
Chapter 6 - Eck, D. J. (2020). Introduction to Programming using Java.
http://math.hws.edu/javanotes/
Assessment
Give the values resulting values of x and y after executing the following statements.
Assume initial values of x = 2 and y = 0.
1. y = x++; x = ______ y = ______
2. y = ++x; x = ______ y = ______
3. y= x--; x = ______ y = ______
4. y = --x; x = ______ y = ______
5. x = x++ x = ______ y = ______
51
Determine the resulting boolean output of the following expressions. Assume values A =
2, B = 5, C = 3, and D = 15.
6. result = ( A == B ); result = ______
7. result = ( B <= C ); result = ______
8. result = ( D > A ); result = ______
9. result = ( ( A + C ) != ( B ) ); result = ______
10. result = ( ( ( C * B ) + A ) < ( D + C ) ) result = ______
Writing Basic Programs. Choose one problem from the items below and write a java
program that will execute the required task.
A. Write a program that will print your initials to standard output in letters that are nine
lines tall. Each big letter should be made up of a bunch of *’s. For example, if your initial
were “MTG”, then the output should look like:
** ** *************** *******
** ** ** ** ** ***
** **** ** ** ***
** ** ** ** *** ********
** ** ** *** ***
** ** ** **** ****
** ** ** *******
B. Write a program that asks for the user’s name and greets the user by name. Before
outputting the user’s name, convert it to uppercase letters. For example, if the user’s
name is Fred, then the program should respond “Hello, FRED, nice to meet you!”.
52
C. Write a program that asks the user how many eggs she has and then tells the user
how many dozen eggs she has and how many extra eggs are left over. For example, if
the user says that she has 52 eggs, then your program would respond with:
53
COURSE TOPIC IV: Advanced Programming Language Fundamentals
Overview
Control Structures are special structures that can change the flow of control of a program.
There are two basic types of control structure: loops, which allow a sequence of
instructions to be repeated over and over, and branches, which allow the computer to
decide between two or more different courses of action by testing conditions that occur
as the program is running.
Learning Outcomes
After successful completion of this lesson, you should be able to:
⚫ Implement different control structures such as loops and branching statements
⚫ Explain the concept of Arrays in Java programming
Course Material
Control Structures
Two types of control structures, loops and branches , can be used to repeat a sequence
of statements over and over or to choose among two or more possible courses of action.
There are six control structures in Java which are blocks, while loop, the do…while
loop, the for loop, the if statement and the switch statement.
Blocks
The block is the simplest type of structured statement. Its purpose is simply to group a
sequence of statements into a single statement. The format of block is:
{
}
That is, it consists of a sequence of statements enclosed between a pair of braces.
54
The While Loop
The while loop is used to repeat a given statement over and over but only as long as a
specified condition remains true. A while loop has the form:
while ( <boolean expression> ) {
}
The semantics of a while statement go like this: When the computer comes to a while
statement, it evaluates the < boolean expression >, which yields either true or false as its
value. If the value is false, the computer skips over the rest of the while loop and proceeds
to the next command in the program. If the value of the expression is true, the computer,
executes the < statement > or blocks of < statements > inside the loop. Then it returns to
the beginning of the while loop and repeats the process. That is, it re-evaluates the <
boolean expression >, ends the loop if the value is false and continues if the value is true.
This is an example that prints out the numbers 1, 2, 3, 4, 5;
int number;
number = 1;
System.out.println(number);
number = number + 1;
System.out.println(“Done!”);
55
The do…while Statement
Sometimes, it is more convenient to test the continuation condition at the end of the
statement, instead of at the beginning, as is done in the while loop. The do…while
statement is very similar to the while statement except that the word “while,” along witt
the condition that it tests, has been moved to the end. The word “do” is added to mark
the beginning to the loop. A do…while statement has the form
do {
import java.util.Scanner;
boolean wantsToContinue;
do {
Checkers.playGame();
wantsToContinue = stdin.nextBoolean();
In this example, let’s just say we have a class named playGame() that plays one game of
checkers against the user. So the subroutine Checkers.playGame(); can be used to
represent one game. Then after the game, the program will ask the user if he wanted to
play another game. The user’s response will be processed and will be stored in the
boolean variable wantsToContinue. If the user’s answer is true, then the game will start
again and if the user’s response is false, then the loop will end.
56
Break and Continue Statements
Sometimes, you need to test several conditions while at the middle of the loop instead of
at the beginning or end. Java provides a general method for breaking out of the middle of
any loop. It is called a break statement, which takes the form
break;
When the computer executes a break statement in a loop, it will immediately jumps out
of the loop. It then continues on whatever follows the loop in the program.
A continue statement is related to break, but less commonly used. A continue statement
tells a computer to skip the rest of the current iterations of the loop. However, instead of
jumping out of the loop altogether, it jumps back to the beginning of the loop and continues
with the next iteration (including evaluating the loops continuation condition to see
whether any further iterations are required.)
For Loops
The for statement makes a some while statements easier to write. They basically do the
same thing but the syntax is different. The formal syntax of the for statement is as follows:
<statements>
}
The initialization, continuation condition and updating have all been combined in
the first line of the for loop. This makes everything involved in the “control” of the loop in
the first place, which helps the loop easier to read and understand.
The < continuation-condition > must be a boolean-valued expression. The <initialization>
is usually a declaration or an assignment statement, but it can be any expression that
would be allowed as a statement in a program. The <update> can be any simple
statement, but is usually an increment, a decrement, or an assignment statement. Here’s
a flow control diagram for a for statement:
57
As an example, lets say that we want to use a for loop that prints out just the even
numbers between 2 and 20, that is: 2, 4, 6, 8, 10, 12, 14, 16, 18, 20. there are several
ways to do this.
System.out.prinln( 2*N );
// 2,4, …, 20 directly
// the loop
58
for ( N = 2; N <=20; N = N + 2 ) {
System.out.println( N );
If ( N%2 == 0 ) // is N even?
System.out.println( N );
The If Statement
An if statement tells the computer to take one of the two alternative courses of action,
depending on whether the value of a given boolean-valued expression is true or false. An
if statement has the form:
if ( < boolean expression > )
else
59
In other cases, the else statements can be omitted if you only want the computer to
execute one statement if the boolean expression is true and continue the program without
doing anything is the boolean expression is false.
if ( <Boolean expression> )
<statement>
Additionally, either both the <statements> in an if statement can be a block, so adding the
braces are preferred by most programmers as convention.
if ( <Boolean expression> ) {
else {
60
A switch statement, as it is most often used, has the form:
switch ( <expression> ) {
case <constant-1>:
<statement-1>
break;
case <constant-2>:
<statement-2>
break;
//more cases
case <constant-N>:
<statement-N>
break;
<default-statement>
Data Structure
A data structure consists of a number of data items chunked together so that they can be
treated as a single unit.
61
Arrays
An array is a a data structure in which the items are arranged as a numbered sequence,
so that each individual item can be referred to by its position number. The number of
items in an array is called the length of the array. The type of the individual items in an
array is called the base type of the array. And the position number of an item in an array
is called the index of that item.
The base type of an array can be any java type like a String or any of the eighth primitive
types. An array with base type String is referred to as “array of Strings” while an array
with base type int is referred to as “array of int”.
Keep in mind that an array is basically a collection of variables (memory locations) and
not collection of values so we can refer to those values by calling the variables that the
array holds. The array itself needs to be named and given a variable. Basically an array
is a variable whose value is a collection of variables. But before you can use a variable
to refer to an array, that variable must be declared, and it must have a type. Array types
can be used to declare variables; for example,
String[] namelist;
int[] numbers;
double[] prices;
However, declaring a variable does not make the actual array. Arrays are created using
a special syntax in Java. Here are the examples:
62
int i;
System.Out.println( list[i] );
}
In the example, the first time through the loop, i = 0, and list[i] refers to list[0]. So it is the
value stored in the variable list[0] that is printed. The second time through the loop, i = 1,
and the value stored in list[1] is printed. If the length of the list is 5, then the loop ends
after printing the value of list[4], when i = 5 and the continuation condition “i < list.length”
is no longer true. This is a typical example of using loop to process an array.
Supplemental Information
Watch
Youtube Tutorials about Basic Java Programming
Read
Chapter 3-7 - Eck, D. J. (2020). Introduction to Programming using Java.
http://math.hws.edu/javanotes/
63
COURSE TOPIC V: Exception Handling
Overview
In addition to control structures that determine the normal flow control in a program, Java
has a way to deal with “exceptional” cases that throw the flow of control off its normal
track. When an error occurs during the execution of a program, the default behavior is to
terminate the program and to print an error message. However, Java makes it possible
to “catch” such errors and program a response different from simply letting the program
crash. This is done with the try.. catch statement.
Learning Objectives
After successful completion of this lesson, you should be able to:
⚫ Discuss how exceptions are handled in Java programming
⚫ Apply the principle of try..catch statements
Course Material
Exceptions
The term exception is used to refer to the type of event that one might want to handle with
try…catch. An exception is an exception to the normal flow of control in the program. The
term is used in preference to “error” because in some cases, an exception might not be
considered to be an error at all. You can sometimes think of an exception as just another
way to organize a program.
Exceptions in Java are represented as objects of type Exception. Actual exceptions are
usually defined by subclasses of Exception. Different subclassses represent different
types of exceptions.
64
value. In this case, an exception of type NumberFormatException occurs. If nothing
is done to handle the exception, the program will crash.
IllegalArgumentException
An IllegalArgumentException can occur when an illegal value is passed as a
parameter to a subroutine. For example, if a subroutine requires that parameter be
greater than or equal to zero, an IllegalArgumentException might occur when a
negative value is passed to the subroutine. How the subroutine will respond to the
illegal value should be handled in the subroutine itself but a common response is an
IllegalArgumentException.
Try..Catch
When an exception occurs, we say that the exception is “thrown.” For example we say
that Interger.parse(str) throws an exception of type NumberFormatException when the
value of str is illegal. When an exception is thrown, it is possible to “catch” the exception
and prevent it from crashing the program. This is done with a try..catch statement. In
simplified form, the syntax for a try..catch statement can be:
try {
<statements-1>
<statements-2>
65
As an example, suppose that str is a variable of type String whose value might or might
not represent a legal real number. Then we could say:
double x;
try {
s = Double.parseDouble(str);
catch ( NumberFormatException e ){
x = Double.NaN;
Supplemental Information
Assessment
66
COURSE TOPIC VI: Introduction to GUI Programming
Overview
Computer users today expect to interact with their computers using a graphical user
interface (GUI), and Java can be used to write sophisticated GUI programs. When you
run a GUI program, it opens one or more windows on your computer screen. As a
programmer, you can have complete control over what appears in the window and how
the user can interact with it.
Learning Outcomes
After successful completion of this lesson, you should be able to:
⚫ Discuss and differentiate the methods used in making shapes and other GUI
elements
⚫ Construct working GUI programs that draw simple shapes with no user interaction
Course Material
67
Assuming that the drawing area is 800-by-500 pixels, the rectangle in the upper left of the
picture would have, approximately, width of 200 and height of 150, and upper left corner
at coordinates ( 50, 50 ).
Drawing Shapes
Drawing in Java is done using graphics context. A graphics context is an object. As an
object, it can include subroutines and data. Among the subroutines in a graphics context
are routines for drawing basic shapes such as lines, rectangles, ovals, and text. Among
the data in a graphics context are the color and font that are currently selected for drawing.
One other piece of data in a graphics context is the “drawing surface” on which the
drawing is done. Different graphics context objects can draw to different drawing surfaces.
For us, the drawing surface will be the content area of a window, not including its border
or title bar.
1. g.setFill( c ) - called to set the color to be used for filling shapes. The parameter c
is an object belonging to a class named Color.
68
Example: g.setFill( Color.BLUE )
g.setFill( Color.WHITE)
2. g.setStroke( c ) - called to set the color to be used for stroking shapes. The
parameter c is an object belonging to a class named Color.
g.setStroke( Color.BLACK )
3. g.setLineWidth( w ) - sets the size of the pen that will be used for subsequent
stroke operations, where w is measured in pixels.
4. g.strokeLine( x1, y1, x2, y2 ) - draws a line from the point with coordinates ( x1,
y1 ) to the point with coordinates ( x2, y2 ). The width of the line is 1, unless a
different line width has been set by calling g.setLineWidth(), and the color is black
unless a different color has been set by calling g.setStroke()
Example: g.setFill(Color.BLUE)
g.setFill(Color.WHITE)
Sample Problem:
69
Write a code that will draw a set of ten horizontal lines that are parallel with each
other. Each line should be 200 pixels long and the distance from each line to the next
is 10 pixels. Start the first line at the coordinates ( 100, 50 ).
Solution:
int y; // y-coordinate for the line
// because y coordinate is 50
Drawing in a Program
Java codes must be inside a subroutine definition that is itself inside a class definition.
Here is an example of a subroutine which draws random circles on the screen which each
varying in colors between the colors that was set on the switch statement:
public void drawPicture (GraphicsContext g, int width, int height) {
g.setFill(Color.WHITE);
70
int colorChoice; // used to select a random color
centerX = (int)(width*Math.random());
centerY = (int)(height*Math.random());
colorChoice = (int)(4*Math.random());
switch ( colorChoice ) {
case 0:
g.setFill(Color.RED);
break;
case 1:
g.setFill(Color.GREEN);
break;
case 2:
g.setFill(Color.BLUE);
break;
case 3:
g.setFill(Color.YELLOW);
break;
71
g.setStroke(color.BLACK);
} //end of drawPicture()
Note: Please make sure that you properly configured your IDE and JavaFX plugin before
running this code.
Supplemental Information
Read
Chapter 6 - Eck, D. J. (2020). Introduction to Programming using Java.
http://math.hws.edu/javanotes/
Assessment
1. Write a GUI program that draws a checkerboard. Edit the sample code above and
replace the content of the subroutine with your answer.
a) The checkerboard should be 400-by-400 pixels.
b) The checkerboard contains 8 rows and 8 columns of squares
c) The squares are red and black (or whatever colors you choose)
72