Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 44

Unit 1: Introduction to Computer and

Java programming

1. Software and Code Documentation


2. Programming and Problem Solving
3. Introduction to Java
4. Testing and Debugging

Objectives:
At the end of the unit, you must have:
a. Identified the basic syntax of Java programming language,
b. Performed the basic syntax written in Java,
c. Familiarized the different type of system errors for testing and
debugging.

1
How much do you know?

2. What is a software?

_____________________________________________________________________

_____________________________________________________________________

3. Give at least 2 examples of a software.

_____________________________________________________________________

_____________________________________________________________________

4. Give at least 2 examples of a Programming Language.

_____________________________________________________________________

_____________________________________________________________________

5. Give example of an Operating System.

_____________________________________________________________________

_____________________________________________________________________

6. In your own understanding, what is problem solving?

_____________________________________________________________________

_____________________________________________________________________

_____________________________________________________________________

2
Acquire new knowledge
Lesson Proper

Software and Code Documentation


Software is a set of instructions or programs instructing a computer to do a
specific tasks. It is a generic term used to describe computer programs that run on
PCs, mobile phones, tablets or other similar devices. Software is often use to
describe all the functional aspects of a computer that do not refer to is physical
components (hardware). So basically, everything that runs on a computer, from an
operating system, to a diagnostic tool, video game, or app can be defined as
software.
Software are developed by people normally called as programmers. By
technical definition, programmer is an individual that writes/creates computer
software or applications by giving the computer specific programming instructions.
Most programmers have a broad computing and coding background across multiple
programming languages and platforms. Some of these language are C, C++, Java,
Python, PHP, HMTL, JavaScript, etc.
A programmer may also specialize in one or more computing fields, like
database, security, software developments, Web or Mobile development, Game
Development, etc. You will learn more about these terminologies and different areas
of programming as you go along on this course.

Programming and Problem Solving


We already defined what a programmer is so
now, what is programming? As mentioned in hackr.io
“Programming is a way to ‘instruct the
computer to perform various tasks’”. It is the
task of the programmers to write the ‘instructions’
that a computer would follow.
Programming and problem solving comes hand-
in-hand since in order to write codes or instructions
to the computer you have to identify what the
“problem” is or what is your reason for writing those
specific instructions. What are you trying to solve or
create?
In order to do problem solving it is the task of Source: pexels.com
the programmer to break big problems into smaller
step-by-step procedure, this is also known as algorithm. Algorithm is defined as a
procedure or a formula for solving a problem, based on conducting a sequence of
specified actions.
Part of learning programming is learning its own language. In order to write
those ‘instructions’ you have to learn the proper syntax for the programming
language that you’re using. There are a lot of different programming languages now,
but for this lesson we will only focus on Java. In order to become a programmer, it
is advisable to focus or master ONE language first so it will be easier for you to learn
you second language.

3
Introduction to Java
History of Java
Java was developed by James Gosling and his colleague at Sun Microsystems in
the early 1990’s but it was publicly implemented on 1995. If we will trace back more
into history there are other languages prior to the Java language, so most of Javas
syntax was also borrowed from another popular language before its time, which is C
and C++, but Java has a greater uniformity and simplicity. It made the promise of
“Write Once, Run Anywhere”, which means it could run to any platforms or operating
system.

Get Started with Java. The tools you need.

What’s already on your computer.


1. Java Compiler - this translates your code into computer-friendly instructions.
The computer can only understand machine language, which is composed only
of 1s and 0s. It could not understand human language (like letters or symbols).
It is the compilers job to translate human language to machine language and
machine language to human language.

Hello 01001000 01100101


01101100 01101111
00100001

COMPILE
R

2. Java Virtual Machine - this programs allows Java programs to run on any
device or operating system and to manage and optimize program memory.
Before Java was released in 1995, all computer programs were written for a
specific operating system, a program created for Mac or Apple devices would not
“run” on Windows or Linux Operating System.

3. Java API or Application Programming Interface - in the context of Java,


this is a collection of prewritten codes that are already included on your IDE
(Integrated Development Environment). As you learn how to code in Java you
will notice different APIs or ‘packages’ being included or imported into your
code.

What you need to install:

1. Java Development Kit - the JDK is required to install NetBeans IDE. You
can download the latest version of is on
http://www.oracle.com/technetwork/java/javase/downloads.

2. IDE (Integrated Development Environment) - an IDE is


an “environment” where we typically write our code. There are a

4
lot of available IDEs out there but you also need to use the appropriate one
based on the language you’re using. For this subject, we will be using NetBeans
IDE. It’s a popular IDE intended for Java programming. So make sure you have
it installed in your computer. You can visit the netbeans.org website to download
the installer. You can also follow instructions on this page:
https://netbeans.org/community/releases/82/install.html.

Writing you first Java Program.

Get started with NetBeans.

1. Make sure you have NetBeans installed in your computer along with your Java
Development Kit.

2. Once you open up your NetBeans IDE,


on the left-top part choose File > New Project.

3. A new window will appear. Choose Java to


expand its categories. Then select Java
Application and click Next.

4. The Project Name would be the file


name of your project. The Project
Location and Project Folder is where
your project would be saved. You can
change this details if you want. Leave the
other details as it is. Then click Finish.

5
Because you left the Create main class checkbox selected in the New Project
Window, the IDE has created a skeleton Main Class for you.

To write your first Java Program you can replace the line:
// TODO code application logic here

With:
System.out.println("Hello World!");

Make sure that you


manually type in the
code, don’t just rely on
copy and paste
method.

Save the changes by


choosing File > Save
or by pressing ctrl + s
on your keyboard.
Your code should look
like this:

Compiling and Running


After writing your code, you usually have to compile and run it to see if it’s working.
There are different ways to do this.
7. Choose Run then Run Project.
8. Click this button, usually located at the upper part of the scree.
9. Press F6 on you keyboard.

After running the program,


you should see the output
in the output window.

Congratulations! You just tried your first Java Program.

Code Explanation and Syntax:

The line numbers on the left side are displayed for reference purposes but are
not part of the program.
The code package myfirstjavaapplication; in line 6 indicates the name
of your package or folder.
The codes enclosed in
/* */ are called comments.

6
The contents of the comments are ignored by the compiler. All programming
languages have a comment feature. Comments are usually used by programmers to
enter a remark that describes or explains some operations in the program.

Java support 3 styles of comment.


1. Single-line comment -
which begins in // and ends at the
end of the line (no special
character necessary. As shown in
the example, the code in line 18 is
a comment and will be ignored by the compiler.

2. Multiline Comment -
anything between the
symbols /* */ is ignored by
the compiler. As the name
suggest a multiline comment
may be several lines long.

3. Documentation Comment - this are sometimes called as Javadoc


comment, this works like a multiline comment but it begins with a /** (instead of /*)
and ends with */. A javadoc comment appears immediately before a class, interface,
method or field definition. You will see a lot of javadoc comments in NetBeans IDE.

The code public class MyFirstJavaApplication in line 12 uses the


keywords public class. Public indicates that anyone can access your class other
option is to make it private. Class can be considered as the ‘blueprint’ of your
program. Most buildings need a blueprint before they can start to actually build it,
same with Java programming, you can’t start your code without declaring at least
one class, these serves as the foundation of everything.

MyFirstJavaApplication is
an identifier that serves as the name
of your class. The class name always
starts with an UPPERCASE letter. The
entire class definition or content are
enclosed in an opening and closing
curly braces { }.

main is the name of the method. Method is a block of code which only runs
when it is called. You can pass data, known as parameters, into a method.

Statements - one line of code ending in a semi-colon. As shown in line 18 of.


Block - consist of one or more statements enclosed in curly braces. Code from
line 12 to 15 are called “block of codes”.

7
The code System.out.println(); would print or display anything inside the
parenthesis (). The phrase Hello World is enclosed in a double quotation to indicate
that it’s a String (will be discussed more later) and it should be printed as it is. You
can also do simple arithmetic functions in it.
For example:
System.out.println(8+5);
The code would display the sum of the two numbers (13). Notice that in
performing arithmetic functions you don’t need to put it in a double quotation.

Access specifier, public Opening curly brace


means anyone can access it Name of the class of the class

Parameter, this method declares the


parameter args, which is an array of
Return type; void means instances of the class Strings. This
Name of the method
there’s not return value. will be discussed further later on

Opening curly brace


of the method

end in a semicolon
Every statement MUST

The string you want


This says print to to print.
Closing curly Closing curly
standard output.
brace of the class brace of the
method

Don’t worry if you can’t understand most of these terminologies and functions
since all of these will be discussed later on in the modules. For now, I’m just trying
to give you a general idea of what we’ll discuss.

Testing and Debugging

Bug - a mistake in a program


Debugging - eliminating mistakes in a program.

In developing a system, you would usually encounter different types of error. It


is important to know the different types of errors for you to know how to fix them.
1. Syntax Error -
violation of the grammar
rules of the language.
This one is easy to
correct since the compiler
gives indications as to
where the errors came from. Hover your mouse in this symbol
to display the error message

8
2. Run-time Error - this are detected during the execution of the program.
Sometimes this are discovered when the user enters an invalid data which is not
relevant. This are not usually difficult to find since the error are also displayed in the
console or Output Window.

3. Logic Error - this is when your program compiles and executes successfully
but does the wrong thing or returns an incorrect result. This are usually harder to
find since it does not display a clear error message. Most of the time you have to
really review or analyze your code to find out what’s wrong since most of the time
the error is in your algorithm itself.

9
Apply your knowledge. In this part, you will practice what you have
learned.

1. Give some examples of an Operating System


_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
2. Why is it important for a programmer to develop their problem solving skills?
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________

Pen and Paper Coding (Just write your answer no need to use NetBeans yet)
10. Write a Java Program that would display your full name.
_____________________________________________________________________
_____________________________________________________________________

1
0
Assess your knowledge. You will be tested here and you will be able
to know the gaps in your understanding in this lesson. If you are not
satisfied with the feedback, you may then go back to some point that
you may have missed.

1. What are the 3 types of Java comments?


_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
2. _________________ A term used that refers to a line of code that ends with a
semi-colon.
3. _________________ Refers to one or more lines of code, usually enclosed in a
curly braces.
4. _________________ a type of error is caused by an error in the algorithm.
5. Which of the following code shows a Syntax Error.
a) System.out.println(“Hello World!”);
b) System.out.println(abc);
c) system.out.println(“Hello World!”);
6. What does IDE stands for?
_____________________________________________________________________
7. This translates the human language to machine language.
_____________________________________________________________________
8. ___________________ Machine language are composed of which numbers?
9. What does API stands for?
_____________________________________________________________________
10. ____________________ this is the process of eliminating errors in your
program.

1
1
Unit 2: Variables, Data Type and I/O
(Input/Output)
1. Variables and Assignment
2. Data Types and Expressions
3. Input and Output

Objectives:
At the end of the unit, you must have:
a. Identified the different data types used in Java.
b. Described the use of input and output of information
c. Performed the use of data types and expressions

1
2
How much do you know?

1. What is a variable?
_____________________________________________________________________
_____________________________________________________________________
2. Give a few example of data types.
_____________________________________________________________________
_____________________________________________________________________
3. What are the computer peripherals we used to input something into the software?
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
4. What are the computer peripherals we used to display or provide output to the
users?
_____________________________________________________________________
_____________________________________________________________________

1
3
Acquire new knowledge
Lesson Proper

Variables and Assignment


Variable designates a location in the memory for storing data and computational
results in the program. A variable has a name that can be used to access the
memory location. Think of a variable as a labeled basket. One basket is labeled
“Apple”, another basket is labeled “Orange” and a basket labeled banana. By
standards you should put apples, oranges and bananas to there respective baskets.
You can’t put banana in a basket labeled Apple.

APPLE BANANA ORANGE

With that example in mind, the label on the basket is the variable name, the
type of fruit is the data type, and the amount of fruits inside is the value. The
number of fruits in each basket can changed but you can’t change the type of fruit
that you should put in each basket.
In context, variable is a name which can be associated with a value that
can be changed.

How to declare and initialize a variable?


Before using a variable, all variable have to be declared first. Declaring a
variable means defining its data type (we will discuss data types in the next topic),
and optionally, setting an initial value.
Initializing a value means assigning a value to your variable. Variable do not
have to be initialized when they are declared, but it is often useful.

Syntax to:
declare a variable: dataType variableName;
Initialize a variable: variableName = value;
Declare and Initialize a variable: dataType variableName = value;

Example:
declare a variable: int age;
Initialize a variable: age = 35;
Declare and Initialize a variable: int age = 35;

1
4
As an example we will create a program that could compute the area of a
circle. To write a program it is also important to design an algorithm and translate
the algorithm to code. The algorithm for this program can be described as follow:
1. Read the radius of the circle.
2. Compute the area using the formula A = πr² or Area = pi * (radius * radius).
3. Display the area.

To translate everything into a code, first we need to


declare a variable. Since area and radius could contain
decimal values, we will use double as our data type and
radius as our variable name and 50 as our sample value.
double radius = 50;

After declaring a variable for radius we also need a variable for the area. We can
declare: double area;
Notice that it doesn’t have any value yet since we will assign a value once we
compute the value of the area. We can do that by:
area = 3.1416 * (radius * radius);

The complete code


would look like this:

Remember to put your code inside the main method.


The code in line 16 assigns the value or answer of the equation to variable area.
The code System.out.println(area); display the value of the area in the
Output Window.
Click this or press F6 in you keyboard to display the output.

Things to remember in naming a variable:


11. Variables should ALWAYS starts with a letter, underscore or dollar sign. BUT
NOT A NUMBER. Number can only used after a character. (by java
standards it should start with a lowercase letter but if it’s composed of 2
words you can capitalize the second word)
√ num1 or firstNumber × 1num or 1stNum
12. Spaces are NOT ALLOWED.
√ total area × total_area or totalArea
13. Java is very case-sensitive; the variable name radius is different from
RADIUS or Radius.
14. You cannot use keywords or reserved words as variable names
Ex. public, private, class, method, main, package (usually anything that’s in
color blue or green in your NetBeans IDE).

1
5
Data type and Expressions
Java has 8 primitive data types: byte, short, int, long, char, float, double and
boolean. A data type should start with a LOWERCASE letter.

byte - smallest integer value. Value ranges from -128 to 128.


Ex. byte age = 23;

short - range from -32,768 to 32,767


Ex. short no_of_students = 8500;

int - commonly used integer type, range from -


2,147,483,648 to 2,147,483,647 The example gives an error message :
Uncompilable source code -
Ex. int incompatible types: possible
lossy conversion from int to
long - this is useful for occasion where an int type is short.
not large enough to hold the desired value. Range from - Since you cannot assign a value larger than
32,767 to short data type.
9,223,372,036,854,775,8080 to
9,223,372,036,854,775,8080.
Ex. long lightSpeed = 16070400000000;

float - this are usually useful when you need a fractional component, but don’t
require a large degree of precision. For example, float can be useful when
representing monetary values (dollar, peso, cents).
Ex. float weekly_wage = 458.38;

double - when you need to maintain accuracy over many calculations, or if you
are manipulating large-valued numbers, double is the best choice.
Ex. double pi = 3.1416;

char - data type that stores single characters. Value should be enclosed in single
quotation.
Ex. char choice = ‘a’;
Char can also handle Unicode values. Unicode defines a fully international
character set that can represent all of the characters found in human languages.
Ex. char value = 88;
88 is the code for X so this would display X. When assigning a Unicode value to
char, you don’t have to enclose it in a single quote.

bool - used for logical values. It can only have true or false as its value.
Ex. bool completed = true;
This will be discussed further in unit 3.

String - this is not included in the 8 primitive data type since string is a CLASS.
But it usually acts as a data type and is often used as such. It stores one or more
characters unlike data type char which can only store one character.
Ex. String name = “Grace Lhyn”;
When declaring a String, make sure you use a capital letter S and the value
should be enclosed in double quotations.

1
6
Operators
Most of Javas operators can be divided into the following groups: arithmetic,
relational and logical.

Arithmetic Operators - they are used to perform simple arithmetic operations


on primitive data types.
 + : Addition
 - : Subtraction
 * : Multiplication
 / : Division
 % : Modulo - divided left-hand operator to right-hand operator and returns
remainder
 ++ : Increment - increases the value by 1.
 -- : Decrement - decreases the value by 1.

Examples:
+ and - operator

+ can perform basic


addition for integers. But
as shown in line 21, we
add the value of x (thank)
to y (you), this value are
Strings, and if + operator
is used with Strings it
‘concatenate’ the given
Strings.

*, / and % operator

The code in line 16 shows


another example of
concatenation. We
concatenate the “a * b” to
the arithmetic operation a
* b by using the +
operator.

The next image shows the


output of the code.

1
7
++ and -- operators

The increment (++)


operator increases the value
of its operand by one. The
decrement (--) decreases the
value by 1.

Assignment Operators: “=” - assignment operator is used to assign value to any


variable. General format or syntax is: variable = value;
In many cases assignment operator can be combined with other operators to
build a shorter version of statement called Compound Statement. For example,
instead of a=a+5, you can write a+=5.
You can also do this for other arithmetic operators, -=, *=, /= and %=.

Relational Operators - these operators are used to check for relations like
equality, greater than, less than. They return boolean result (true or false) after the
comparison and are extensively used in looping statements as well as conditional if
else statements (looping and conditional statements will be discussed on the next
topic).
Syntax: variable relation_operator value;
15. Equal to, ==
16. Not Equal to, !=
17. Less than, <
18. Less than or equal to, <=
19. Greater than, >
20. Greater than or equal to, >=

1
8
Logical Operators - these are used to perform “logical AND” and “logical OR”
operation.
21. &&, Logical AND - returns true when both or all conditions are true.
22. ||, Logical OR - returns true if at least one condition is true.

Since the expression a!=b is TRUE , b==10 is TRUE the output of line 15 is
TRUE. But line 17 is FALSE since the expression a<20 is FALSE even though
b==10 is TRUE.

In logical OR, only ONE expression needs to be TRUE for the output to be TRUE.
So line 19 is TRUE since the expression b>a is FALSE and a>10 is TRUE and line 21
is FALSE since both of the expressions are FALSE.

Ternary Operator - this is a shorthand version of if-else statement (which will be


discussed in the next unit). it has 3 operands, hence the name ternary.
Syntax: condition ? if true : if false
The above statement means that if the condition evaluates to true, then execute
the statements after the ‘?’ else executes the statements after the ‘:’.

In the sample code, if the expression a > b is TRUE then the value of variable
result will be “A is greater than B” but if the expression is FALSE then the value of
variable result will be “A is less than B”.

1
9
Input and Output
In the previous example we assigned a value to our variables, but in order to
assign a different value we need to modify the source code and recompile it which is
not ideal for our users since the user usually don’t have any idea how the source
code works.
In developing a system, you should allow the user to input a value. Like how a
calculator allows you to input a value before performing any mathematical equations.

Reading input from the keyboard


Java uses System.out to refer to standard output device (monitor) and
System.in to the standard input device (keyboard). We learned earlier that we can
display an output to the user by using the println method without adding any
package on our IDE. But unlike output, input is not directly supported in Java, so we
can use the Scanner class to create an object to read input from System.in, as
follows:
Scanner input = new Scanner (System.in);
‘input’ is a variable name whose type is Scanner. The new
Scanner(System.in) creates an object of the Scanner type.

As shown in the
example, we used
the nextDouble()
method to allow the
user to input values
with decimals.
There are other
methods that you
can use depending
on the type of value
you want the user
to input.

Other methods you can use for System.in.

METHOD DESCRIPTION
nextByte() Reads an integer of the byte type
nextShort() Reads an integer of the short type
nextInt() Reads an integer of the int type
nextLong() Reads an integer of the long type
nextFloat() Reads an integer of the float type
nextDouble() Reads an integer of the double type
next() Reads a string that ends before a white space character
nextLine() Reads a line of text (i.e. a string ending with the Enter key
pressed)

2
0
Apply your knowledge. In this part, you will practice what you have
learned.

Declare and initialize a variable with the following value (observe proper syntax):

I love Programming. ________________________________________________


32.54 ________________________________________________
A ________________________________________________
546.23 ________________________________________________
125 ________________________________________________
-12 ________________________________________________
C ________________________________________________
Hello ________________________________________________
12345678911 ________________________________________________
D ________________________________________________

Write a code that could print out the following:

Sum of two integers.

Compute the current age of a person if his/her birthday is on the year 1994.

2
1
Assess your knowledge. You will be tested here and you will be able
to know the gaps in your understanding in this lesson. If you are not
satisfied with the feedback, you may then go back to some point that
you may have missed.

Determine if the value is TRUE or FALSE based on the LOGICAL Operators.

(4 > 5) && (5 == 5) ______________ (4 > 5) || (5 == 5) _____________


(100 != 50) && (70 != 50) _________ (100 != 50) || (70 != 50) _________
(45 == 45) && (45 > 40) && (50 < 45) ______________
(45 == 45) || (45 > 40) || (50 < 45) ________________
( (“Java” != “Python”) && (“Python” != “HTML”) ) || (1991>2000)
_______________

Using a TERNARY OPERATOR display the word “PASSED’ if the Student Grade is 75
or above and “FAILED” if the Student Grade is 74 or below.

2
2
Unit 3:Basic Flow of Control
a) Simple flow of control
b) Using boolean expressions
c) Multiway branches
d) More about Java Loop Statements

Objectives
At the end of the unit, the student must have:
23. Identified the use and functions of conditional statements in java.
24. Described the use of Boolean Expressions
25. Designed programs using the different conditional and loop statements.

2
3
How much do you know?

LOGICAL CONNECTIVITY

1. If Sunny studies, she will pass her exam else if she do not study she will fail the
exam. After the term, Sunny failed the exam. Which one of the following can be
concluded from the above statement?
a) Sunny DID NOT study for the exam.
b) Sunny studied for the exam.
c) None of the above.

2. Yedam will either buy a car OR a house. Which one of the following can be
concluded from this?
a) Yedam will buy both a car AND a house.
b) Yedam did not buy a car or a house.
c) If Yedam buy a car, he will not buy a house and vice versa.
d) None of the above.

In each of the following sentences, the main statement is followed by other 4


sentences. Select a pair of sentences that relate logically to the given statement.

3. The teacher gives a break, only if the students are exhausted.


i. The teacher gives a break.
ii. The teacher did not give a break
iii. Students are not exhausted
iv. Students are exhausted.

4. If you don’t save money you will not get any reward.
i. You saved money
ii. You didn’t save any money
iii. You got a reward
iv. You didn’t get any reward

2
4
Acquire new knowledge
Lesson Proper

Simple Flow of Control


Generally the statements inside your java code are executed from top to bottom,
in the order that they appear. Control flow statements, change or break the flow of
execution by implementing decision making, looping, and branching your program to
execute particular blocks of code based on the conditions.
There are 3 types of control flow statements supported by the Java
Programming Language.
26. Decision making statements: if-then, if-then-else, switch
27. Looping Statements: for, while, do-while
28. Branching Statements: break, continue, return

DECISION MAKING STATEMENTS

Java If Statements

The If-Then statement


The if-then statement is the most basic of all the control flow statements. It
enables your program to execute a certain section of code depending on the state of
variables, or values returned from methods.
Syntax:
The statement could be a single line of code or a
if(condition){
block of codes enclosed in curly braces. The
Statement;
} condition is any expression that returns a boolean
values (true/false).
The ‘if statement’ works like this: if the condition is
TRUE then the statement will be executed. But if
the condition is false, the statement will NOT be
executed.

In the example, the condition


10>5 is TRUE so the line “10 is
greater than 5” will be displayed
in the output window.

2
5
In this example, the condition 10<5
is FALSE so nothing will be displayed on
the output window.

The If-Then-Else statement


The if-then-else statement provides an alternate path when an ‘if’ clause
evaluates false.
Syntax:
if(condition){ The ‘if-then-else statement’ works like this: if the
Statement1;
condition is TRUE then the statement1 will be executed
}
but if the condition is false the statement2 will be
else{
Statement2; executed.
}

In this example, the


condition
a>b is FALSE so it
would skip the first
statement
and would
execute the statement in the else block.

Chaining If statements
You can ‘chain’ if-else statements, and create a decision tree sort of thing.
Syntax:

if(condition){
Statement1;
} You can have as many else if
else if(condition{ conditions as necessary.
Statement2;
}
else{
Statement3;
}

2
6
Using Boolean Expressions
Using Logical Operators in If-else Condition

Sample Problem 1:
Write a program that would
display the students Grades (A-F)
based on their average. Use the data
below as your basis.

95-100 = A
90-94 = B
85-89 = C
80-84 = D
75-79 = E
below 75 = F

In the sample code we used the


LOGICAL AND (&&) Operator to
compare the values of the variable
average.

By using Logical && the result would be TRUE if BOTH of the condition is TRUE.
The block else if(average>=90 && average<=94){
is TRUE since the value System.out.println("Your grade is B");
of average (90) is }
equal to 90 AND less
than 94

Sample Problem 2:
Write a program that determines the
season based on the month given
by the user.
Dec, Jan, Feb = Winter
March, April, May = Spring
June, July, Aug = Summer
Sept, Oct, Nov = Autumn

In this example we use the LOGICAL


OR (||) since a specific season can
be on different months. And we put
the statement
System.out.println(season);
After the if-else code since we want
to determine first the value of

2
7
season before we print it.

In the output the user input the number 5 (May),


and based on our condition the statement
month==3 || month==4 || month==5 is
TRUE since month==5 condition is TRUE.
Multiway Branches
Nested If Statement
Nested-If works similar to normal if-else condition. The only difference is that
there will be an if condition inside another if condition.
Syntax:

if(condition){
Statement;
if(condition){
Statement 2;
}
}
else{
Statement;
}

As shown in the example, you can also have an if-


else statement inside the if-statement.
The code would display the output:

Since the condition a==30 is TRUE so it would print the line: A is equals to
30 and proceed to the next if-statement.

In this example, the


statement a==30 is
FALSE so it
proceeds to the
else statement and
display the output:

switch(expression){
case value1:
statement 1;
break; Switch Statement
case value2: Another way to control the flow of
statement 2;
break;
default: 2
default statement; 8
}
your programs with decision-making statements is by a switch statement. A switch
statement gives you the option to test for range of values for your variables. If you
think your if-else-if statements is long and complex, you can use switch statement
instead.
Syntax:
You usually need to declare and initialize a variable before using a switch statement,
as shown in the example below.
In switch statement, the value of the expression is compared with each of the
values in the case statement. If a match is found, the code sequence following that
case statement is executed. There might be more than one case being matched but
switch will choose the first immediate matching case ignoring the others.

In this example, we
declare and initialize a variable
name age with the value 1.
The line switch(age) would
evaluate the value of age and
compare it to the case values.
Since the line case 1
matches the value of the
variable age, the code following
that case statement would be
executed and it would ignore
the rest of the codes. So the
output of the following code is,
You are one year old.

Let’s take a look at another example, this


is the switch statement version of the if-then-
else statement earlier.
The value of the variable vehicle is “Car”.
The line switch(vehicle) evaluates the
value of the variable and compare it to the
case statements. Since the value matches the
2nd case which is the code case “Car”: it
would execute the code after it and ignore the
rest of the code.
So the output of the following code is,
I’m a CAR

Note: When trying this code, you can


change the value of the variables to see what would happen.
String values are very case-sensitive so the value Car is different from CAR or
car.

Break statement is also necessary in switch statement. Because without it


your switch statement would fall through. Let’s take a look at this example.`
The sample switch statement
does not have a break
statement so instead of just

2
9
executing the line System.out.println("You are one year old");
the output would be:

The default statement is optional. If no case


matches and no default is present, then no
further action is taken.

Sample Problem 1:
Using a switch statement, write a
program that determines the
season based on the month
given by the user.

Dec, Jan, Feb = Winter


March, April, May = Spring
June, July, Aug = Summer
Sept, Oct, Nov = Autumn

More Java Loop Statements


for loop
The java for loop repeats the execution of a set of Java statements. A for loop
executes a block of code as long as some condition is true.
Syntax:
for(initialization; condition; increment/decrement){
Loop body or java statements;
}

3
0
The initialization expression initializes the loop and is executed ONLY ONCE at
the beginning of the loop. The condition is evaluated every loop and if it evaluates
to false, the loop is terminated. And lastly the increment/decrement expression is
executed after each
iteration through the
loop.

The output of the


example would be:

In the sample code, the line int i=0; will be executed first.
The condition i<5; will be evaluated next if the code is true
then the loop body will be executed but if the condition is false the
code will be terminated. Since the condition i<5 is TRUE it will
proceed to the loop body and will display the output Number: 0.
After executing the loop body it will proceed to the increment i++ and will add a
value of 1 to the i variable. After adding a value, it would go back to the condition
i<5 and compare the new value of i (which is 2 after the i++) to 5, if it is still true
then it will proceed to the loop body. And the same process with loop until the
condition became false.

while loop
The while statement or loop continually executes a block of statements while a
particular condition is true. The while statement continues testing the expression and
executing its block until the expression evaluates to false.
Syntax:
The condition can be any Boolean expression. The
while(condition){ loop body will be executed as long as the condition
loop body is TRUE. When the condition becomes false, the
}
control passes to the next line of code after the loop.

Example:
output

The statement System.out.println(n); will execute as long as the


condition n>0 is TRUE. The statement n-- decrease the value of n by 1 during each
loop.

While Loop Sample Problem

Sample Program 1:
Write a Java Program that prints the
number 1-10.

Sample Program 2:

3
1
Write a Java Program that print the number 5, 10, 15, 20, 25, 30.

The while loop evaluates its conditional expression at the top of the loop, the
body of the loop will not execute even once if the condition is false to begin with.

do-while Loop
The difference between do-while and while is that do-while evaluates it
expression at the bottom of the loop instead of the top. Therefore, the statements
within the do block are always executed at least once.
Syntax:
do{
loop body
}
while (condition);

The first sample code would display the


number from 1-10.
The second sample would only display the
number 10 since the condition n<0 is FALSE.

Nested loop
If a loop exists inside the body of another loop, it’s called a nested loop. You can
do this on a while loop or for loop.

Apply your
knowledge. In
this part, you will practice what you have
learned.

1. Write a program that allows the user to input his/her


age. Then the program will show if the person is eligible
to vote. A person who is eligible to vote must be 18
years old and above.

3
2
What is the output of the following code:

2. for(int num = 0; num < 10; num+=2){


System.out.println(num);
}

3. int val = 5;
while(val==5){
System.out.println(val);
val++;
}

4. for (int a = 3; a < 5; a++){


System.out.println(“Value of a: “ + a);
}

Assess your knowledge. You will be tested here and you will be able
to know the gaps in your understanding in this lesson. If you are not
satisfied with the feedback, you may then go back to some point that
you may have missed.

1. Write a Java program that ask the user to input three number and print the
greatest number.

3
3
What is the output of the following code:

1. int num=50;
if(num==50){
System.out.println(“TRUE”);
}
System.out.println(num);

2. int count_down = 3;
while (count_down > 0){
System.out.println(“Hello”);
count_down = count_down – 1;
}

2. int i=2;
switch(i+2){
case 1:
System.out.println("Case1");
break;
case 2:
System.out.println("Case2");
break;
case 3:
System.out.println("Case3");
break;
case 4:
System.out.println("Case4");
break;
default:
System.out.println("Default ");
}

Unit 4: Java Methods and Program


Design

a) Top-down and Bottom-up Approach


b) Predefined Methods and Programmer Defined Methods
c) Local Variables
d) Overloading Function Methods

Objectives:

3
4
At the end of the unit, you must have:
a. Identified the use of methods,
b. Designed and developed a program using methods

How much do you know?

1. What is programming?
_____________________________________________________________________

_____________________________________________________________________

_____________________________________________________________________

2. What is the task of a programmer?

3
5
_____________________________________________________________________

_____________________________________________________________________

_____________________________________________________________________

3. What is a variable?

_____________________________________________________________________

_____________________________________________________________________

_____________________________________________________________________

Acquire new knowledge


Lesson Proper

Top-Down and Bottom-up Approach


When talking in terms of computer science and programming, the algorithms we
use to solve complex problems in a systematic and controlled way are designed on
the basis of two approaches that is Top-down and Bottom-up Approach.

Top-Down Approach
Top-down programming starts at the top and then works its way down. This is
essentially the breaking down of a system to gain insight into the sub-systems that
make it up. In a top-down approach, an overview of the system is formulated,

3
6
specifying but not detailing any first-level subsystems.
So you start at the most abstract level, by defining the problem, and from there
add more details. It’s a bit like starting with an outline and then filling things in as
you go until you have a story.

Bottom-Up Approach
In this design, individual parts of the system are specified in details. The parts
are the linked to form a larger components, which are in turn linked until a complete
system is formed.
This design is commonly used in Object Oriented Programming Language like
Java.

Predefined Methods and Programmer Defined


Methods
Predefined method or built-in methods are the methods or statements that
are included in the compiler and performs certain tasks. Some examples of this are
print(), println(), nextInt(), max() and a lot more. We will learn about other
predefined methods as we go along in this programming subject.
Programmer defined methods are methods created by the programmer
themselves which can also be used or called multiple times.

A Java method is a collection of statements that are grouped together to


perform an operation. It is a block of code which only runs when it is called. When
you call the System.out.println() method, the system actually executes several
statements in order to display a
message on the console.
println() is an example of a
predefined method. Another example is
the main() method.
All Java program must have an
entry point, which is always the main()
method. The main() method is the key
to making a Java program executable.

Creating Method

 public static - modifier


public static int methodName(int a, int
 Int - return type
b){
 methodName - name of
//body
the method
 a,b - formal parameters
 Int a, int b - list of modifier returnType methodName(parameter)
parameter {
//method body
The syntax shown includes:
29. Modifier - it defines the access type of the method and it is optional to use.
30. returnType - method may return a value.
31. methodName - this is the name of your method.
32. Parameter List - it is consists of the type, order, and number of parameters

3
7
of a method. These are optional, method may contain zero parameters.
33. Method body - the method body defines what the method does with the
statements.

The sample code returns


the minimum between two
numbers.

Method Calling
The example above shows how to create a method but for using a method, it
should be called. There are two ways in which a method is called i.e., method return
a value or returns nothing (no return value).
When a program invokes a method, the program control gets transferred to the
called method. This called method then returns control to the caller in two
conditions, when the return
statement is executed or it
reaches the method ending
closing brace.

The following example demonstrates


how to define a method and how to
call it.

Sample 1: With return value


using a programmer defined n1 is equal to the value of a, and n2 is equal to the value of
method.
The sample code will produce the
following result:

In line 18 we called the method


named minFunction with
parameters a and b so the program
control would jump to the minFunction method on line 22.

minFunction method has a return value specified in line 31: return min.

After executing the whole method body the program control returns to line 19 to
execute the code:
System.out.println("Minimum Value = " + c);

Sample 2: NO return value (void) using a programmer defined method.

The void keyword allows us to

3
8
create methods which do not return a value. In the following example we’re
considering a void method methodRank. This method is a void method, which does
not return any value. Call to a void method must be a statement i.e.
methodRank(255.7); it is a Java statement which ends with a semicolon.

Sample 3: Changing void method to value-returning method using a


programmer defined method.

The printGrade method


is another example of void
method. Again a call to a void
method must be a statement
as in line 17.
To see the difference
between a void and value-
returning method, let’s
redesign the printGrade
method to value-returning
method. We’ll name this one
as getGrade.

As shown in the example


the getGrade method has a
return value of type char and
we declare a return statement
in line 37. We also assigned a
variable for the value of
getGrade method in line 16.

3
9
Sample 4: Example of some predefined methods.

The example shows


some predefined
methods like max and
sqrt by using the Math
Class.

(Class will be discussed


later on this course.)

Passing parameters by values


The power of a method is its ability to work with parameters. You can use
println to print any string and max to find the maximum between any two int
values. When calling a method, you need to provide arguments, which must be given
in the same order as their respective parameters in the method signature. This is
known as parameter order association.

In the sample code, you can call the method printSample to print any message
for a specific number of times.
On line 17 we have a statement printSample("Hello", 3); that passes
the actual string value “Hello” to the parameter message; passes 3 to parameter n.
based on the method body this would print the word “Hello” 3 times.

4
0
In this other example, you can see that you can call the same method multiple
times and you can also change there value. But make sure that you provide the
correct value based on the data type of the parameter.

Local Variables
A local variable in Java is a variable that’s declared within the body of a method.
Then you can use the variable within that method. Other methods in the class aren’t
even aware that the variable exists.
This could also means that you
can use the same variable name in a
different method without it overlapping
each other.

You can also declare local variables within blocks of code marked by curly braces
as shown in the code below.

Overloading Methods
The max method that was used earlier only works with the int data type. But
what if you need to determine which of two-floating point numbers or double
numbers has the maximum value? The solution is to create another method with the
same name but different parameters, as shown in the example code:

4
1
If you call max with int parameters, the max method that expects int
parameters will be invoked; if you call max with double paramters, the max method
that expects double parameters will be invoked. This is referred to as method
overloading; that is, two methods have the same name but different parameter
lists within one class. The java compiler determines which method is used on the
method signature.

Apply your knowledge. In this part, you will practice what you have
learned.

34. Give at least 2 examples of predefined method.

35. How can you determine if the method is a value-returning method or a void
method?
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________

4
2
36. What is the output of the following code?

Assess your knowledge. You will be tested here and you will be able
to know the gaps in your understanding in this lesson. If you are not
satisfied with the feedback, you may then go back to some point that
you may have missed.

What is the output of the following code:

4
3
4
4

You might also like