0% found this document useful (0 votes)
12 views

Im Programming Logic and Design

Programing
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)
12 views

Im Programming Logic and Design

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

POLYTECHNIC UNIVERSITY OF THE PHILIPPINES

SANTA MARIA, BULACAN CAMPUS


Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

INSTRUCTIONAL MATERIALS FOR


PROGRAMMING LOGIC AND DESIGN

Bachelor of Science in Computer Engineering

Asst. Prof. JENNILYN S. AVANCEÑA, MIT

FIRST TERM
ACADEMIC YEAR 2024 – 2025
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

CHAPTER 1: BASICS OF PROGRAMMING

OVERVIEW

Introduces programming, covering essential concepts such as the types of


programming languages, the programming cycle, algorithms, and programming
methodologies. It explains the differences between low-level and high-level programming
languages, highlighting the role of machine and assembly languages as well as compilers
and interpreters. The material introduces the key steps in problem-solving using algorithms
and presents tools like pseudocode and flowcharts for representing algorithms.
Additionally, it contrasts two popular programming methodologies: procedural
programming and object-oriented programming, emphasizing their application in solving
complex problems.

DESIRE LEARNING OUTCOMES


1. Define and differentiate between low-level and high-level programming languages.
2. Illustrate the steps of the programming cycle and explain their significance in
solving programming problems.
3. Design and represent algorithms using pseudocode and flowcharts for simple
computational tasks.
4. Identify and correct syntax and logical errors in a program using debugging
techniques.
5. Compare procedural programming and object-oriented programming and explain
their applications in software development.
--------------------------------------------------------------------------------------------------

TYPES OF PROGRAMMING

Computer program – It is a sequence of statements intended to accomplish a certain task.


It is a set of instructions for a computer to follow.

Programming – It is a process of planning and creating a program

Low-level Languages – These are the languages that deal with a computer’s hardware
components. There are two (2) common low-level languages: machine language and
assembly language.

• Machine Language – It is the language that the computer can directly understand. It
is the most basic set of instructions that the computer can execute. Machine
language programs are written in binary codes (0, 1).
• Assembly Language – It is a symbolic form of machine language that is easier for
people to read, such as ADD AX DX. This makes use of instructions in mnemonic
form.
• Assembler – a program that translates assembly language instructions
into machine language.

High-level Languages – These are the programming languages that use natural languages,
such as the English language. A high-level language has its own syntax.

2|Page
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

• Syntax – rules of the language, for example, print or write is used to produce an
output.
• Commands – these are program statements that carry out tasks that the program
has to perform, for example, print this word or add these two (2) numbers.
• Compiler – it is a program that translates a program written in a high-level language
into a low-level language before executing the program statements.
• Interpreter – this acts as a compiler, but it translates one (1) program statement at a
time, this executes the statement as soon as it is translated.
• Syntax errors – these are errors that might be encountered during the process of
translation. An example is a misspelled command.
• Logical errors – errors that occur when the syntax of the program is correct, but the
expected output is not.
• Debugging – the process of locating and correcting the errors of a program.

PROGRAMING CYCLE

Algorithm – It is a step-by-step problem-solving process or a set of rules to be followed in


calculations or other problem-solving operations, especially by a computer. It ensures that
a solution is reached in a finite amount of time, which makes it essential for solving
programming problems.

Remember: There is no specific algorithm for a specific problem

Variable – are the names you give to a computer


memory location which are used to store values in a
computer program.

Input – Things that you will ask from the user

Output – Things that you display to the user

The problem-solving process in the programming environment involves the following steps:

1. Problem Analysis: Analyze the problem and outline the problem and its solution
requirements.
2. Algorithm Design: Design an algorithm to solve the problem.
3. Coding: Implement the algorithm in a programming language.
4. Execution: Verify that the algorithm works.

3|Page
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

To develop a program that solves a problem, start first by analyzing the problem, then
outlining the problem and the options for a solution. Then design the algorithm, write the
program instructions, and enter the program into a computer system.

ALGORITHM

An algorithm must be expressed completely in a natural language that anyone can follow,
such as directions that can be written in the English language. The computer programmer
lists down all the steps required to resolve a problem before writing the actual code.

Example 1:

Design an algorithm that finds and displays the volume of a rectangle. It is required to know
the rectangle’s length, width, and height, and the formula to know the rectangle’s volume.
The formula is volume = length × width × height.

The algorithm to find and display the volume of the rectangle is:

1. Define the variables needed


Let length be the length of the rectangle
Let width be the width of the rectangle
Let height be the height of the rectangle
Let volume be the volume of the rectangle
2. Initialize the value of each variable
length = 0, width = 0, height = 0
3. Input the value of the define variable
4. Find the volume using the formula: volume = length × width × height.
5. Display the computed volume.

Example 2:

Write an algorithm to read two numbers and find their sum.

1. Define the variables needed


Let firstnum be the first number
Let secondnum be the the second number
Let sum be the sum of the two numbers
2. Initialize the value of each variable
firstnum=0, secondnum=0, sum=0
3. Input the value of each variable
4. Find the sum; sum = firstnum+secondnum
5. Display the computed sum

Example 3:

Write an algorithm to temperature conversion, given Fahrenheit to Celsius

1. Define the variable needed


Let fah be the Fahrenheit
Let cel be the Celsius

4|Page
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

2. Initialize the variable


fah=0, cel=0
3. Input the value in fah variable
4. Convert the Fahrenheit to Celsius using the formula
cel = 5/9 * (fah-32)
5. Display the computed cel

There are two (2) commonly used tools in representing an algorithm:

• Pseudocode
• Flowchart

PSEUDOCODE

Pseudocode – is a method of describing computer algorithms using a combination of


natural language and programming language. It is a technique to show the programming
steps.

The following are some rules that are frequently followed when writing pseudocode:

• Symbols are used for the following common operations:


o Arithmetic operations (+, -, *, /)
o Assignment ( = or <- )
o Comparison (=, ≠, <, >, ≤, ≥)
o Logical (and, or)
• Certain keywords can be used as a command, such as PRINT, WRITE, READ, INPUT,
SET, GO TO, etc.
• Indentation is used to indicate branches and loops of instructions.

Example 1:

Using the example problem in the algorithm.

The pseudocode to find and display the volume of the rectangle is:

START
INITIALIZE length =0; width =0; height = 0; volume = 0;
READ length / INPUT length
READ width / INPUT width
READ height / INPUT height
VOLUME = length*width*height or volume <- length*width*height
PRINT volume / DISPLAY volume
END

Example 2:

Write the pseudocode to read two numbers and find their sum.

5|Page
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

START
INITIALIZE firstnum=0; secondnum=0; sum=0;
READ firstnum
READ secondnum
sum = firstnum + secondnum or sum <- fistnum + secondnum
DISPLAY sum
END

Example 3:

Write the pseudocode of temperature conversion, given Fahrenheit to Celsius

START
INITIALIZE fah=0; cel=0
READ fah
cel = 5/9 * (fah-32) or cel <- 5/9 * (fah-32)
DISPLAY cel
END

Example 4:

Write the pseudocode to find the greater number between two numbers

START
INITIALIZE num1=0, num2=0, ans = 0
INPUT num1
INPUT num2
If (num1 > num2) then ans= num1
If (num2 > num1) then ans = num2
DISPLAY ans
END

FLOWCHART

Flowchart – is a visual representation of an algorithm. It contains shapes describing how an


algorithm or program operates. Each command is placed in an appropriate shape, and
arrows are used to direct program flow.

Flowchart shapes represent various operations. These shapes are connected by directed
lines to indicate the flow of data or control from one (1) point to another. Table 1 shows the
often-used shapes in a flowchart.

Flowchart Shape Function


Flow lines: Used to indicate the direction of the process flow
by connecting other shapes. Arrows should not cross each
other.
Terminal block: Used to represent the beginning or end of a
program.

6|Page
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

Preparation: Used for initialization of variables.


Differentiates between steps that prepare for work and steps
that do work. It helps introduce the setup to another step
within the same process.
Process: Used to represent a process step or activity or
operations, such as computation, initialization, etc.
Data: This represents the data used as inputs or outputs,
such as user input and display text.
Decision block: This indicates a decision operation in the
process or use to ask question, where there are two (2)
alternatives: true and false.
Connector: Used as a connector to combine flow lines by
indicating an identifier, such as letters. This is used for
complex algorithms and also to avoid flowlines intersection.
Predefined Process: Indicates the use of an algorithm
specified outside the program, such as methods or functions.

Example 1:

Using the example problem in the algorithm


Show the flowchart to find and display the volume of the rectangle is:

7|Page
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

Example 2:

Show the flowchart to find the greater number between two numbers

PROGRAMMING METHODOLOGIES
Programming methodology – is the approach to analyzing such complex problems by
planning software development and controlling the development process. There are two
(2) popular approaches to writing computer programs:
Procedural Programming – in this approach, the problem is broken down into functions
that perform one (1) task each. This approach is suitable only for small programs that have
a low level of complexity.
Object-Oriented Programming – in this approach, programs are organized around
objects rather than actions, and data rather than logic. The solution revolves around
entities or objects that are part of the problem. It deals with how to store data related to
the entities, how the entities behave, and how they interact with each other to give the
desired result.

8|Page
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

Figure 2. Representation of Procedural and Object-Oriented programming


--------------------------------------------------------------------------------------------------
References

Baesens, B., Backiel, A., & Broucke, S. (2015). Beginning java programming: The object-
oriented approach. Indiana: John Wiley & Sons, Inc.

Farrell, J. (2014). Java programming, 7th edition. Boston: Course Technology, Cengage
Learning.

Savitch, W. (2014). Java: An introduction to problem solving and programming, 7th edition.
California: Pearson Education, Inc.

9|Page
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

CHAPTER 2: ELEMENTS OF JAVA


OVERVIEW

Java is an object-oriented programming language built on classes and objects,


emphasizing reusability and modularity. Core elements include data types (primitive and
non-primitive) for storing values, methods for defining behavior, and classes for creating
objects. Inheritance allows classes to reuse and extend functionality, while interfaces and
abstract classes define common behaviors that classes can implement. Java organizes
code through packages, promoting structure and preventing naming conflicts. Exception
handling mechanisms manage runtime errors, ensuring stable program execution. The
language also relies on the Java Virtual Machine (JVM) for platform independence, making
Java applications portable across different systems.

DESIRE LEARNING OUTCOMES


1. Students will be able to explain the basic components of Java, including classes,
methods, data types, and the Java Virtual Machine (JVM).
2. Students will be able to write, compile, and run simple Java programs, utilizing
console and windowed applications.
3. Students will demonstrate the correct usage of Java syntax, reserved words,
comments, and import statements in their code.
4. Students will be able to implement Java’s input and output methods (e.g., Scanner
for input and System.out.print/System.out.println for output) in their programs to
interact with users.
--------------------------------------------------------------------------------------------------
JAVA

A high-level programming language that was developed by Sun Microsystems for


general-purpose business applications and interactive, web-based Internet applications.
Java can be used to write programs that run on any operating system or device.

JAVA ENVIRONMENT MACHINE (JVM)

An environment that translates Java bytecode (compiled format for Java programs)
into machine language and executes it.

SOURCE CODE

Programming statements written in a high-level language. This is created using a text


editor or a development environment.

DEVELOPMENT ENVIRONMENT

A set of tools that help write programs easily, such as NetBeans. The statements are
saved in a file. Then, the Java compiler converts the source code into a binary program of
bytecode. The Java interpreter then checks the bytecode and communicates with the
operating system, executing the bytecode instructions line by line within the Java Virtual
Machine.

10 | P a g e
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

TWO (2) TYPES OF JAVA PROGRAM

Application – this is a stand-alone program. It can either be a:

• Console application – supports character output to a computer screen in a DOS


window.
• Windowed application – creates a GUI with elements such as menus, buttons,
dialog boxes, etc.

Applet – it is a program embedded in a Web page. It runs in a browser.

EXAMPLE OF A SIMPLE JAVA PROGRAM

public class FirstJavaProgram {

public static void main(String[] args) {

System.out.println(“First Java Application”);

The FirstJavaProgram is a class name. A class is the basic unit of a Java program. All
Java codes are grouped into a class. The definition of the class starts with an access modifier

11 | P a g e
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

(such as public), which specifies the accessibility of classes, followed by the keyword class.
Every class definition is enclosed within pair of curly brackets or braces ( { and } ). These
braces mark the beginning and the end of the class.

The main method is a special method and is the entry point of the program execution.
A Java class can only have one (1) main method. In the example Java program, it contains
only one (1) programming statement or command: System.out.println(“First Java
Application”);. A statement is an action that the program must perform.

A literal string is a series of characters that appear exactly as entered. Any literal
string in Java appears between double quotation marks. Arguments are information passed
to a method so it can perform its task.

RESERVED WORDS

Reserved words or keywords have special predefined meaning and cannot be used
in naming variables, classes, methods, or identifiers. The Java language designates certain
keywords that the compiler recognizes as reserved words. The following table lists all the
reserved words in Java.

abstract continue for new switch

assert default goto package synchronized

boolean do if private this

break double implements protected throw

byte else import public throws

case enum instance of return transient

catch extends int short try

char final interface static void

class finally long strictfp volatile

const float native super while

12 | P a g e
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

THE main() METHOD

The main method is a special method in every Java application. When executing a
Java program, execution always begins with the method main. All Java applications must
include a class containing one (1) main method.

Defining the main method in any class:

public static void main(String[] args) { }

The basic parts of the main method are the heading and the body:

• The public static void main(String[] args) is the heading.


• The statements enclosed between the braces form the body of the main method. It
contains the declaration and execution of the program.

Here are descriptions of the meaning and purpose of the terms used in the method heading:

• The public keyword is an access modifier. The method heading should be public for
the Java interpreter to call it and to run the class.
• Static keywords mean that a method is accessible and usable.
• The void keyword indicates that the main method does not return any value when it
is called.
• The name of the method is the main. When executing a Java application, the JVM
always executes the main method first.
• The contents between the parentheses of the main method, which is String[] args,
represent the type of argument that can be passed to the main method.

COMMENTS

Comments are used to explain the details in a program. These are notes that a
programmer writes to a program to help another person to understand the program.
Comments are ignored by the compiler, meaning they are not executed when the Java
programs run.

Java has two (2) common types of comments:

• Single-line comments – these are comments that begin with // and can be placed
anywhere in the line.
• Example:
System.out.println(“Welcome to Java.”); //prints Welcome to Java.

• Multiple-line comments – these are enclosed between /* and */.


• Example:

/*
Program that converts Kilogram to Gram
*/
public class KiloToGram

13 | P a g e
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

THE import STATEMENT

Packages – these are collections of related classes that have been grouped together
into a folder. The name of the folder is the name of the package and begins with lowercase
letters. The classes in the package are each placed in a separate file, and the file name
begins with the name of the class.

import – this is a reserved keyword in Java used to access the classes in a package.
There are two (2) common ways on how to use the import statement:

• Importing a package member: To import a specific class into the current file, follow
the following syntax:

import package_name.Class_name;

Example:

import java.util.Date;

• Importing an entire package: To import all the classes contained in a particular


package, use the import statement with the asterisk (*) wildcard character:

import package_name.*;

Example:

import java.util.*;

When importing packages, all the import statements must appear before the class
declaration.

INPUT

Scanner – a class in the java.util package. The methods of this class are used to read
data from the standard input device and store data into variables.

To use the methods of Scanner in a computer program, first, import the class using
the following statements:

import java.util.Scanner; or import java.util.*;

Then create an object of the Scanner class and associate it with the standard input
device. Below is a sample statement.

Scanner input = new Scanner(System.in);

• The Scanner input part declares an object of Scanner type named input. The object
name can be any declared name by a programmer.

• The new Scanner(System.in) part creates a Scanner object connected to the


System.in property. The System.in is an InputStream which is connected to the
standard input device (the keyboard).

14 | P a g e
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

The Scanner class contains methods that retrieve values from an input device. Each
retrieved value is a token, which is a set of characters separated from the next set of
whitespaces.

Shown below lists the commonly used methods of the Scanner class that read different
data types from the standard input device. Each retrieves a value from the keyboard and
returns it if the next token is a correct data type; otherwise, the method will throw an
exception.

OUTPUT

Java provides some simple output statements to send output to the standard
output device, the display screen. Examples of these output statements are the following:

System.out.print(“This is a text.”);

and

System.out.println(“This is a text.”);

• The print() method displays an output, and the insertion point stays in the
current line.
• The println() method moves the insertion point to the following line after
the output is displayed.

When displaying a string with variables, simply concatenate them using the plus (+)
sign. For example:

String name = “Jess Diaz”;

System.out.println(“Hello! My name is ” + name + “.”);

and

int kilo = 2;

System.out.println(kilo + “ kilos of sugar.”);

The output of print and println methods are in the format of strings.

15 | P a g e
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

CHAPTER 3: DATA TYPES


OVERVIEW

Java provides a variety of primitive data types such as byte, short, int, long, float,
double, boolean, and char, which are the fundamental building blocks for storing and
managing values in programs. Variables in Java are memory locations that store values and
can be modified during program execution, while constants have fixed values that cannot
change. Java also supports type casting, which allows converting values between data
types. Widening conversion (implicit) safely increases data type precision, while narrowing
conversion (explicit) may cause data loss and requires explicit instructions from the
programmer using the cast operator. Understanding how to manage data types, variables,
constants, and type casting is crucial for efficient Java programming.

DESIRE LEARNING OUTCOMES


1. Students will be able to identify Java’s primitive data types and use them correctly
in their programs.
2. Students will understand how to declare, initialize, and manipulate variables and
constants effectively in Java.
3. Students will apply both widening and narrowing conversions in their code,
demonstrating proper usage of implicit and explicit type casting.
4. Students will evaluate scenarios that require type casting and explain the potential
impact of narrowing conversions on data precision.
--------------------------------------------------------------------------------------------------
PRIMITIVE DATA TYPES

Data type – used to specify the set of values and their operations. The values have
data types because they are stored in memory in the same format and have the same
operations defined for them.

Primitive data types – the fundamental data types in Java. These are predefined data
types by the language and named by a keyword.

Java supports eight (8) built-in primitive data types shown below. The hierarchy of
integer data type and floating-point numbers of data type are from the lowest precision to
highest precision.

16 | P a g e
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

• byte – The byte data type can be useful for saving memory space in large arrays.
Example variable declaration: byte b = 100;
• short – The short data type is also useful for saving memory space in large arrays.
Example variable declaration: short s = 1400;
• int – This data type is generally used as the default data type for integral values unless
there is a concern about memory space. Example variable declaration: int a = 12400;
• long – This data type is used when a wider range than int is needed. Example
declaration: long a = 124000L;
• float – The float data type is also used to save memory in large arrays of floating-point
numbers. Example variable declaration: float f1 = 234.5f;
• double – For decimal values, this data type is generally the default data type.
Example variable declaration: double d1 = 234.5d; or double d1 = 234.5;
• boolean – The Boolean data type has only two (2) possible values: true or false. This
is used for simple flags that track true/false conditions. Example variable
declaration: Boolean is Correct = true;
• char – The char data type is used to store a single character. In Java, the character is
enclosed in single quotes. Example variable declaration: char letter = ‘A’;

Java programming language also provides special support for character strings using
the java.lang.String class. The String class is not technically a primitive data type.

CONSTANTS AND VARIABLES

Variable is a name for a memory location that stores a specific value, such as
numbers and letters. A variable is an identifier. It can hold only one (1) value at a time, but
its value may change during program execution. For example, a created variable named
score holds a value of 0 when the program starts and was altered during program execution
to hold the value of 350. To use a variable, it must be declared first. The basic form of a
variable declaration is:

data_type variable_name [= value];

The data_type is one (1) of Java’s data types and variable_name is the name of the variable.
To declare more than one (1) variable of the specified type, use a comma-separated list. The
following are some valid examples of variable declaration and initialization in Java:

int a, b, c; double grade = 2.75;

int a = 10, b = 5 + 3; char letter = ‘A’;

int x = a + 5; byte b;

float f = 2.75f; int size; size = 30;

17 | P a g e
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

Java variables are implemented as memory locations. Each variable is assigned one
(1) memory location. When the variable is given a value, the value is enclosed as a string of
0s and 1s and is placed in the variable’s memory location.

Constant – it is a memory location whose value cannot be changed during program


execution.

When a created variable is stored in the memory, Java uses a named constant to instruct a
program to mark the memory location as constant throughout program execution. To
allocate memory, use Java’s declaration statements. The syntax to declare a named
constant is:

final data_type variable_name = value;

The final is a Java reserved word. This keyword is used to specify that the value stored in the
variable_name is fixed and cannot be changed. The following are some valid examples of
named constant declaration and initialization in Java:

final double PI = 3.14159;

final int SQUARE_SIDES = 4;

final char BLANK_SPACE = ‘ ’;

final int HOURS_PER_DAY; HOURS_PER_DAY = 24;

TYPE CASTING

Type casting – this refers to converting a value from a specific type to a variable of another
type (note: booleans cannot be converted to numeric types).

There are two (2) types of conversion:

• Widening conversion (implicit casting) – the conversion of the lower precision data
type to a value of a higher precision data type. This causes no loss of information, and
the casting will be performed by the Java Virtual Machine (JVM) implicitly or
automatically.

For example, an int variable x with value 4 to a higher-order double data type without
loss of information

int x = 4;

double a = x; //the value of variable a is 4.0

In Java, the following widening conversions are possible:

18 | P a g e
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

o From byte to short, int, long, float, or double


o From short to int, long, float, or double
o From char to int, long, float, or double
o From int to long, float, or double
o From long to float or double
o From float to double

• Narrowing conversion (explicit casting) – the conversion of a higher precision data


type into a value of a lower precision data type. This will typically involve loss of
information.

The following is an example of Java’s strict type checking. The code will not compile,
and an error will be generated:

float x = 6.82f;

int a = x; //cannot be converted or assignment is illegal

The casting is not done by JVM and should be made explicit by the programmer
through a cast operator. The cast operator takes the following form:

(data_type_name) expression.

First, the expression is evaluated. Its value is then treated as a value of the type
specified by data_type_name. The following is the example of explicit casting:

float x = 6.82f;

int a = (int) x; //the value of variable a is 6

The conversion is done from higher-order data type to lower-order data type as
follows:

In Java, the following narrowing conversions are possible:

From byte to char

o From short to byte, or char


o From char to byte or short
o From int to byte, short, or char
o Form long to byte, short, char, or int
o From float to byte, short, char, int, or long
o From double to byte, short, char, int, long, or float

When using the cast operator to treat a floating-point number as an integer, the
decimal part of the floating-point number is dropped. The following examples show
how cast operators work:

int a = (int) 7.9; //the return value is 7

19 | P a g e
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

int b = (int) 3.3; //3

double c = (double) 25; //25.0

double d = (double) (5 + 3) //8.0

--------------------------------------------------------------------------------------------------
REFERENCE:

Baesens, B., Backiel, A., & Broucke, S. (2015). Beginning java programming: The object-
oriented approach. Indiana: John Wiley & Sons, Inc.

Farrell, J. (2014). Java programming, 7th edition. Boston: Course Technology, Cengage
Learning.

Savitch, W. (2014). Java: An introduction to problem solving and programming, 7th edition.
California: Pearson Education, Inc.

20 | P a g e
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

CHAPTER 4: OPERATORS
OVERVIEW

Operators in Java are symbols that direct the compiler or interpreter to execute
specific mathematical, relational, logical, or assignment operations. These operators
manipulate data values (operands) to produce results, such as performing arithmetic
calculations, evaluating relationships between values, making logical decisions, or
assigning values to variables. Java also includes operator precedence rules, determining the
order in which operations are performed, which can be overridden using parentheses.

DESIRE LEARNING OUTCOMES


1. Explain the different types of operators in Java, including arithmetic, relational,
logical, and assignment operators.
2. Perform basic arithmetic operations using Java's arithmetic operators and interpret
the results.
3. Evaluate relational expressions to return Boolean values for decision-making in Java
programs.
4. Apply logical operators to combine or invert Boolean expressions in conditional
statements.
5. Demonstrate the use of operator precedence and parentheses to correctly structure
complex expressions.
--------------------------------------------------------------------------------------------------

OPERATORS

These are specific symbols in a programming language. These symbols tell the compiler or
interpreter of the program to perform a specific mathematical, relational, or logical
operation and produce the result.

ARITHMETIC OPERATORS

Are used to perform basic mathematical operations on numerical values. A value used on
either side of an operator is an operand.

For example, in the expression 45 + 2, the numbers 45 and 2 are operands.

Table 1 shows the list of arithmetic operators.

Assume the following variable declarations: int x = 11, y = 3;

Operator Description Example Return value


+ Addition x+y 14
- Subtraction x–y 8
* Multiplication x*y 33
/ Division x/y 3 (not 3.66)
% Modulus x%y 2

21 | P a g e
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

The operators (/) and (%) have special considerations. Java supports two (2) types of
division:

• Floating-point division occurs when either or both of the operands are floating-point
values and the result is a floating-point value. For example: int x = 11; double y = 3;
System.out.println( x / y ); //the output is 3.66
• Integer division occurs when both operands are integers. The result is an integer,
and any factorial part of the result is lost. For example: int x = 11; int y = 3;
System.out.println( x / y ); //the output is 3

RELATIONAL OPERATORS

Used to evaluate the relation between the operands and generate a decision on that base.
These typically return a Boolean value.

For example, a relational operator is used to compare the scores of two (2) students
(score1> score2) or (score1 < score2).

Table 2 illustrates the relational operators used in Java.

Assume the following variable declarations: int x = 11, y = 3;

Operator Description Example Return value


> Greater than x>y true
>= Greater than or equal x >= y true
< Lesser than x<y false
<= Lesser than or equal x <= y false
== Equal x == y false
!= Not equal x != y true

The relational expressions can also be used to assign value in variables.

For example: boolean b = 10 > 2; //the expression 10 > 2 is evaluated and the result is true
and assigned to the variable b.

LOGICAL OPERATORS

Return a Boolean value based on the Boolean result of the given expressions. Logical
operators are always evaluated from left to right.

For example, the expression (3 > 2) && (2 < 3) has a return value of true. The relational
expressions were evaluated first, and then its Boolean results are used to evaluate the
logical expression with logical AND (&&) operator.

Table 3 illustrates the evaluation of logical operators used in Java.

Assume the following variable declarations: boolean A = 3 > 2; boolean B = 2 < 1;. The value
of Boolean variable A as the expression is evaluated is true and variable B is false.

22 | P a g e
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

Operator Description Example Return value


Logical AND operator: If both operands are true,
&& A && B false
then the condition becomes true
Logical OR operator: If at least one (1) operand is
|| A || B true
true, then the condition becomes true
Bitwise and Logical XOR operator: If only one (1)
^ A^B true
operand is true, then the condition becomes true
!A false
Unary NOT operator: Use to reverse the logical
! state of its operand. If the condition is true, then !(A && B) true
the Logical NOT operator will make it false A && !B
true

ASSIGNMENT OPERATORS

These are used to assign values to a variable. The left operand gets the value of the
expression on the right.

For example, int x = 20;, the variable x gets 20.

Table 4 lists some of the assignment operators used in Java.

Assume the following variable declarations: int score;

Operator Description Example Return


value
Assigns values from right side operands to the
== score = 32 32
left side operands
Adds right operand to the left operand and score+=2
+= 34
assigns the result to the left operand score = score + 2
Subtracts right operand from left operand and score-=3
-= 31
assigns the result to the left operand score = score - 3
Multiplies right operand with the left operand and score*=2
*= 62
assigns the result to the left operand score = score * 2
Divides left operand with the right operand and score /=2
/+ 31
assigns the result to the left operand score = score / 2
It takes modulus using two (2) operands and score%=2
%= 1
assigns the result to the left operand score = score % 2
Adds 1 to the left operand and assigns the result score++
++ 2
to the left operand (Increment) score = score + 1
Subtracts 1 from the left operand and assign the score--
-- 1
result to the left operand (Decrement) score = score - 1

Increment/Decrement in java is performed in two ways:

23 | P a g e
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

1) Post-Increment/Post-Decrement (score++): we use score++ in our statement if we want


to use the current value, and then we want to increment/decrement the value of score by 1.

2) Pre-Increment/Pre-Decrement (++score): We use ++score in our statement if we want to


increment/decrement the value of score by 1 and then use it in our statement.

ORDER OF PRECEDENCE

It is a collection of rules that specifies which operations need to be performed in an


expression. For a given expression containing more than two (2) operators, it determines
which operations should be calculated first.

Certain operators have higher precedence than others. For example, the multiplication
operator has higher precedence than the addition operator: int x = 10 + 3 * 8. In this
expression, variable x is assigned 34 because the operator (*) has higher precedence than
operator (+), so 3 gets multiplied by 8 first, and then 10 is added to the product. Table 5 lists
the operators used in Java from highest to lowest precedence.

Precedence Operators Symbol


Assigns values from right side operands to
Highest !
the left side operands
Multiplication, division, modulus *, /, %
Addition, subtraction +, -
Intermediate Relational >, <, >=, <=
Equality ==, !=
Logical AND &&
Logical OR ||
Lowest Assignment =

When operators of equal precedence appear in the same expression, a rule must govern,
which is evaluated first. In the expression, all binary operators, except assignment
operators, are evaluated from left to right. To avoid confusion, programmers used
parentheses to group expressions.

Precedence rules can be overridden by explicit parentheses (). These can be used to group
items in an expression. Parentheses are used to tell the computer which operations to
perform first. For example, consider the first and second statements with different
positioning of their parentheses:

int a = 10, b = 3, c = 8, ex1, ex2;

ex1 = (a + b) * c; //example 1, result is 104

ex2 = a + (b * c); //example 2, result is 34

To evaluate the expression in the second statement, the computer first adds variables a and
b and then multiplies the result by variable c. To evaluate the expression in the third

24 | P a g e
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

statement, it multiplies variables b and c and then adds the result to variable a. When these
two (2) expressions are evaluated, they produce different results.

--------------------------------------------------------------------------------------------------

REFERENCES:

Baesens, B., Backiel, A., & Broucke, S. (2015). Beginning java programming: The object-
oriented approach. Indiana: John Wiley & Sons, Inc.

Farrell, J. (2014). Java programming, 7th edition. Boston: Course Technology, Cengage
Learning.

Savitch, W. (2014). Java: An introduction to problem solving and programming, 7th edition.
California: Pearson Education, Inc.

25 | P a g e
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

CHAPTER 5: EXPRESSIONS
OVERVIEW

Expressions in Java are constructs made up of variables and operators that evaluate
to a single value, which can be numeric, Boolean, or a String. Java supports different types
of expressions, including arithmetic expressions that return numeric values (integral and
floating-point), mixed expressions that involve both integers and floating-point values, and
logical expressions that evaluate to Boolean values. These expressions follow specific rules
for operator precedence, especially when dealing with mixed data types or logical
operations, and parentheses can be used to group expressions and control the order of
evaluation.

DESIRE LEARNING OUTCOMES


1. Differentiate between integral, floating-point, and mixed expressions in Java and
explain how they are evaluated.
2. Apply the rules for evaluating mixed expressions in Java, where integers are
temporarily treated as floating-point numbers.
3. Construct logical expressions using relational and logical operators and evaluate
them to return Boolean values.
--------------------------------------------------------------------------------------------------
EXPRESSIONS

A construct made up of variables and operators that evaluate to a single value. For example,
11 + 13 and x = 12 are expressions. An expression can also return to other types of values,
such as Boolean or String.

ARITHMETIC EXPRESSIONS

An expression that returns to a numeric value. These expressions consist of arithmetic


operators, operands, and assignment operators. There are two (2) types of arithmetic
expressions:

• Integral expression – If all operands in an expression are integers and the expression
returns an integer type value, the expression is an integral expression. For example:

x = 11 + 3 * 24 – 5 / 4 //the result is an integer type and value is 82

• Floating-point expression – if all operands in an expression are floating-point


numbers, and the expression returns a floating-point type value, the expression is a
floating-point expression. For example:

y = 2.8 * 17.5 – 1.40 //the result is a floating-point and the value is 47.6

MIXED EXPRESSION

An expression that has operands of different data types. These contain both integers and

26 | P a g e
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
SANTA MARIA, BULACAN CAMPUS
Km. 38, Sitio Gulod, Pulong Buhangin, Santa Maria, Bulacan

floating-point numbers and return a floating-point number. For example, 11.5 + 3 * 2.25
and 6 / 4 + 3.9 have an integer type operand and a floating-point operand.
There are two (2) rules to apply when evaluating mixed expressions:

Rule 1. If the operator has the same types of operands, the operator is evaluated according
to the type of operand.

For example:

25 / 2 * 2.0 //evaluation: 12 * 2.0 = 24.0

25.0 / 2.0 * 2 //evaluation: 12.5 * 2 = 25.0

Rule 2. If the operator has both types of operands, during calculation, the integer is treated
temporarily as a floating-point number, and the final result is a floating-point number.

For example:

25.0 / 2 * 2 //evaluation: 12.5 * 2 = 25.0

LOGICAL EXPRESSIONS

An expression that returns a Boolean value when evaluated. These expressions can consist
of logical operators and relational expressions. Logical operators have low precedence and
are evaluated after other operations have been evaluated.

For example, the expression 14 >= 5 && 12 != 3 evaluates to true.

If two (2) or more logical operators appear in an expression, the expression is evaluated from
left to right.

For example, the expression 3 > 3 || 4 < 2 && 12 > 3 || 4 < 5 evaluates to true.

Parentheses are used to group expressions and to control the operators in the expression.

For example, (3 > 3 || 4 < 2) && (12 > 3 || 4 < 5) evaluates to false.

--------------------------------------------------------------------------------------------------
REFERENCES:

Baesens, B., Backiel, A., & Broucke, S. (2015). Beginning java programming: The object-
oriented approach. Indiana: John Wiley & Sons, Inc.

Farrell, J. (2014). Java programming, 7th edition. Boston: Course Technology, Cengage
Learning.

Savitch, W. (2014). Java: An introduction to problem solving and programming, 7th edition.
California: Pearson Education, Inc.

27 | P a g e

You might also like