Professional Documents
Culture Documents
CC202 Module
CC202 Module
Java programming
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?
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
2
Acquire new knowledge
Lesson Proper
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.
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.
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.
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.
1. Make sure you have NetBeans installed in your computer along with your Java
Development Kit.
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!");
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.
2. Multiline Comment -
anything between the
symbols /* */ is ignored by
the compiler. As the name
suggest a multiline comment
may be several lines long.
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.
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.
end in a semicolon
Every statement MUST
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.
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.
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
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
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.
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.
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);
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.
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.
Examples:
+ and - operator
*, / and % operator
1
7
++ and -- operators
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.
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.
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.
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):
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.
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.
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
Java If Statements
2
5
In this example, the condition 10<5
is FALSE so nothing will be displayed on
the output window.
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
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
2
7
season before we print it.
if(condition){
Statement;
if(condition){
Statement 2;
}
}
else{
Statement;
}
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.
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.
2
9
executing the line System.out.println("You are one year old");
the output would be:
Sample Problem 1:
Using a switch statement, write a
program that determines the
season based on the month
given by the user.
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.
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
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);
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.
3
2
What is the output of the following code:
3. int val = 5;
while(val==5){
System.out.println(val);
val++;
}
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 ");
}
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
1. What is programming?
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
3
5
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
3. What is a variable?
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
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.
Creating Method
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.
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.
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);
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.
3
9
Sample 4: Example of some predefined methods.
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.
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.
4
3
4
4