1ST Grading Java
1ST Grading Java
NAME OF
STUDENT
YEAR & SECTION
NOTE
No part of this compilation may be reproduced in any form or by any means without prior
written consent of the institution.
VISION:
“Expanding the Right Choice for Real Life Education in Southern Luzon”
MISSION:
Cognizant to the vital role of real-life education, LC is committed to:
1. Provide holistic higher education and technical-vocational programs which are valued by the stakeholders.
(Academics)
2. Transform the youth into world-class professionals who creatively respond to ever changing world of work.
(Graduates)
3. Advance research production to improve human life and address societal needs. (Research)
4. Engage in various projects that aim to build strong community relation and involvement. (Community)
5. Promote compliance with quality assurance in both service delivery and program development. (Quality Assurance)
CORE VALUES:
Lesson 1
TOPIC: THE HISTORY, EVOLUTION AND OVERVIEW OF JAVA
DURATION: 1 WEEK
PREFERRED DELIVERY: Virtual Classroom, Electronic, Printed Module
LEARNING OBJECTIVES
By the end of this module, students will have completed the following objectives:
1. Define Java programming language.
2. Trace the lineage of Java programming.
3. Enumerate and discuss the features of Java programming.
4. Describe the four concepts of Object-oriented (Java) programming.
TO DO LIST
Reading
o Course Content and Lecture in Module 1 (page 2- 5)
Take Quiz
COURSE CONTENT
Regardless of whether one thinks that Java is now growing, or dying, one has to admit that Java
had truly revolutionized and had defined the programming language. Java had combined and brought to
the tons of useful programming languages features that were previously available only separately or in
various languages. Java is a programming language and platform released by Sun Microsystems in 1995.
Java is a secure, fast, and reliable programming language. Java is everywhere in PCs to Mobile phone,
satellites, other electronic devices. There are many applications and websites that will not run without java
installation in your machine.
In this chapter, we begin to trace the history of Java. We then discuss the definition of Java. Next,
we will discuss the feature of Java. Finally, we examine the four concepts of object-oriented programming
which defines the Java.
Java’s Lineage
Java is related to C++, which is a direct descendant of C. Much of the character of Java is inherited from these two
languages.
C is a powerful general-purpose programming language. It can be used to develop a software like operating
systems, databases, compilers, and so on. C programming is an excellent language to learn to program for
beginners.
C++ is a powerful general-purpose programming language. It can be used to develop operating systems,
browsers, games and so on. C++ supports different ways of programming like procedural, object-oriented,
functional and so on. This makes the C++ powerful as well as flexible.
Java is a powerful general-purpose programming language. It is used to develop desktop and mobile applications, big
data processing, embedded systems and so on. According to Oracle, the company that owns Java, Java runs on 3 billion
devices worldwide, which makes Java one of the most popular programming languages.
Because of the similarities between Java and C++, it is tempting to think of Java as simply the “Internet version of
C++.” However, to do so would be a large mistake. Java has significant practical and philosophical differences. While it is
true that Java was influenced by C++, it is not an enhanced version of C++. For example, Java is neither upwardly nor
downwardly compatible with C++. Of course, the similarities with C++ are significant, and if you are a C++ programmer,
then you will feel right at home with Java. One other point: Java was not designed to replace C++. Java was designed to
solve a certain set of problems. C++ was designed to solve a different set of problems. Both will coexist for many years to
come.
As mentioned at the start of this chapter, computer languages evolve for two reasons: to adapt to changes in
environment and to implement advances in the art of programming. The environmental change that prompted Java was the
need for platform-independent programs destined for distribution on the Internet. However, Java also embodies changes in
the way that people approach the writing of programs. For example, Java enhanced and refined the object-oriented
paradigm used by C++, added integrated support for multithreading, and provided a library that simplified Internet access. In
the final analysis, though, it was not the individual features of Java that made it so remarkable. Rather, it was the language
as a whole. Java was the perfect response to the demands of the then newly emerging, highly distributed computing
universe. Java was to Internet programming what C was to system programming: a revolutionary force that changed the
world.
compilation is a specialized feature, and it does not replace Java’s traditional approach just described. Because of the
highly specialized nature of ahead-of-time compilation, it is not discussed further in this book.
4. User For the execution of the applet, a No such interface is required for the execution or
user interface is required such as servlet
Interface
Abstract Window Toolkit (AWT)
or swing.
5. Required The applet requires user on the other hand, servlets are executed on the
interface on the client machine servers and hence require less bandwidth.
Bandwidth
for execution so it requires more
bandwidth
6. Secure Applets are more prone to risk as Servlets are more secure as execution is under
execution is on the client server security.
machine.
Interpreted – Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The
development process is more rapid and analytical since the linking is an incremental and lightweight process.
High Performance – with the use of Just-in-Time compilers, Java enables high performance.
Distributed – Java is designed for the distributed environment of the internet.
Dynamic – Java programs can carry an extensive amount of run-time information that can be used to verify and resolve
accesses to objects and run-time.
EVALUATING OF LEARNING
Identification
1. It is powerful general-purpose programming language. It is used to develop desktop and mobile
applications, big data processing, embedded systems and so on.
2. It is a powerful general-purpose programming language. It can be used to develop operating systems,
browsers, games and so on.
3. It is a powerful general-purpose programming language. It can be used to develop a software like
operating systems, databases, compilers, and so on.
4. It is the company that owns Java.
5. It is a programming paradigm based on the concept of “object”, which can contain data, in the form of
fields, and code in the form of procedures.
6. It is the extension of encapsulation because it hides certain properties and methods from the outside
code to make the interface of the object simpler.
7. It works in a digital way to form a protective barrier around the information that separates it from the rest
of the code.
8. It is also called overriding and overloading.
9. It is the ability of creating a new class from an existing class.
10. It was initially called “Oak”.
Enumeration
1-10. Java Buzz Words/Features of Java.
Lesson 2
TOPIC: LANGUAGE FUNDAMENTALS OR GRAMMAR OF JAVA
DURATION: 1 WEEK
PREFERRED DELIVERY: Virtual Classroom, Electronic, Printed Module
LEARNING OBJECTIVES
By the end of this module, students will have completed the following objectives:
5. Define Object-oriented programming.
6. Describe the four-basic concept of object-oriented programming.
7. Creating simple programs.
8. Discuss the two control statements.
9. Discuss the Bocks of Codes.
TO DO LIST
Create a Simple program that will display your Name, Address, Section, Age and Motto.
Reading
o Course Content and Lecture in Module 2 (page 2- 6)
Take Quiz
COURSE CONTENT
Regardless of whether one thinks that Java is now growing, or dying, one has to admit that Java
had truly revolutionized and had defined the programming language. Java had combined and brought to
the tons of useful programming languages features that were previously available only separately or in
various languages. Java is a programming language and platform released by Sun Microsystems in 1995.
Java is a secure, fast, and reliable programming language. Java is everywhere in PCs to Mobile phone,
satellites, other electronic devices. There are many applications and websites that will not run without java
installation in your machine.
In this chapter, we begin to discuss the object-oriented programing and its four-basic concept.
Then we will create two simple programs that performs java programming language. Next is the discuss
the two control statements in addition of looping statements. Lastly, we will initiate a program using the
blocks of code.
Object-Oriented Programming
Object-oriented programming (OOP) is at the core of Java. OOP is so integral to Java that it is best to understand
its basic principles before you begin writing even simple Java programs. OOP is a programming paradigm based on the
concept of “object”, which can contain data, in the form of fields, and code in the form of procedures.
Encapsulation
Just like a pill “encapsulates” or contains the medication inside of its coating, the principle of encapsulation works in
a digital way to form a protective barrier around the information that separates it from the rest of the code.
Abstraction
Abstraction is like the extension of encapsulation because it hides certain properties and methods from the outside
code to make the interface of the object simpler. It helps isolate the impact of changes made to the code so that if
something goes wrong, the change will only affect the variables shown and not the outside code.
Inheritance
Using this concept, programmers can extend the functionality of the code’s existing classes to eliminate repetitive
code. For instance, elements of HTML code that include a text box, select field and check box have certain properties in
common with specific methods. In short it is the ability of creating a new class from an existing class. Inheritance is when an
object acquires the property of another object.
Polymorphism
This concept allows programmers to redefine the way something works by changing how it is done or by changing
the parts in which it is done. It is also the ability for multiple objects of the same base class, but different subclasses override
a method of the base class and perform different operations on that same method. Terms of Polymorphism are called
overriding or overloading.
class HelloWorld {
// Your program begins with a call to main().
public static void main (String args[]){
System.out.println(“Hello World.”);
}
}
Explanation:
/*
This is a simple Java program
Call this file “HelloWorld.java”.
*/
The one shown at the top of the program is called a multiline comment. This type of comment must begin with /*
and end with */.
class Example {
This line uses the keyword class to declare that a new class is being defined.
Example is an identifier that is the name of the class.
{ open curly brace and close curly brace } this is where you will input the codes of the program you wanted to
create.
System.out.println(“Hello World.”);
System is a predefined class that provides access to the system
out is the output stream that is connected to the console.
println( ) displays the string which is passed to it.
When you run this program, you will see the following output:
This is num: 100
The value of num * 2 is 200
Explanation:
In this statement, the plus sign causes the value of num to be appended to the string that precedes it, and then the
resulting string is output.
Several new things are occurring here. First, the built-in method print( ) is used to display the string "The value of
num * 2 is ". This string is not followed by a newline.
The if statement determines the flow of execution based on whether some condition is true or false.
if(condition) statement;
Condition or Boolean Expression is one that evaluates to either true or false. If condition is true, then the statement
is executed. If condition is false, then the statement is bypassed.
The for loop statements are important part of nearly any programming language because they provide a way to
repeatedly execute some tasks.
initialization is the portion of the loop sets a loop control variable to an initial value.
iteration is an expression determines how the loop control variable is changed each time the loop iterates.
Explanation:
In this example, x is the loop control variable. It is initialized to zero in the initialization portion of the for. At the start
of each iteration (including the first one), the conditional test x < 10 is performed. If the outcome of this test is true, the
println( ) statement is executed, and then the iteration portion of the loop is executed, which increases x by 1 (x = x + 1).
This process continues until the conditional test is false.
This is done by enclosing the statements between opening and closing curly braces. Once a block of code has
been created, it becomes a logical unit that can be used any place that a single statement can.
In this case, the target of the for loop is a block of code and not just a single statement. Thus, each time the loop
iterates, the three statements inside the block will be executed. This fact is, of course, evidenced by the output generated by
the program.
ACTIVITY
Output:
Name:
Strand & Section:
Age:
Address:
Gender:
Contact Number:
COVID-19 Status:
Lesson 3
TOPIC: RESERVED/KEYWORDS PRESENT IN JAVA
PREFERRED DELIVERY: Virtual Classroom, Electronic, Printed Module
LEARNING OBJECTIVES
By the end of this module, students will have completed the following objectives:
10. Define the lexical issues.
11. Enumerate the different symbols used in java programming.
12. Define the java keywords.
TO DO LIST
Reading
o Course Content and Lecture in Module 3 (page 2- 3)
Take Quiz
COURSE CONTENT
Regardless of whether one thinks that Java is now growing, or dying, one has to admit that Java
had truly revolutionized and had defined the programming language. Java had combined and brought to
the tons of useful programming languages features that were previously available only separately or in
various languages. Java is a programming language and platform released by Sun Microsystems in 1995.
Java is a secure, fast, and reliable programming language. Java is everywhere in PCs to Mobile phone,
satellites, other electronic devices. There are many applications and websites that will not run without java
installation in your machine.
In this chapter, we will discuss the lexical issues the, common symbols used in programming, and
the java keywords
Lexical Issues
Whitespace. Java is a free-form language. This means that you do not need to follow any special indentation rules.
In Java, whitespace includes a space, tab, newline, or form feed.
Identifiers. Identifiers are used to name things, such as classes, variables, and methods. An identifier may be any
descriptive sequence of uppercase and lowercase letters, numbers, or the underscore and dollar-sign characters.
Literals. A constant value in Java is created by using a literal representation of it. A literal can be used anywhere a
value of its type is allowed.
Comments. As mentioned, there are three types of comments defined by Java. You have already seen two: single-
line and multiline. The third type is called a documentation comment. This type of comment is used to produce an HTML file
that documents your program.
Separator. there are a few characters that are used as separators. The most commonly used separator in Java is
the semicolon. As you have seen, it is often used to terminate statements.
Java Keywords
Java keywords are also known as reserved words. Keywords are particular words which acts as a key to a code.
These are predefined words by Java so it cannot be used as a variable or object name
1. abstract: Java abstract keyword is used to declare abstract class. Abstract class can provide the implementation of
interface. It can have abstract and non-abstract methods.
2. boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold True and False values
only.
3. break: Java break keyword is used to break loop or switch statement. It breaks the current flow of the program at
specified condition.
4. byte: Java byte keyword is used to declare a variable that can hold an 8-bit data values.
5. case: Java case keyword is used to with the switch statements to mark blocks of text.
6. catch: Java catch keyword is used to catch the exceptions generated by try statements. It must be used after the try
block only.
7. char: Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode characters.
8. class: Java class keyword is used to declare a class.
9. continue: Java continue keyword is used to continue the loop. It continues the current flow of the program and skips
the remaining code at the specified condition.
10. default: Java default keyword is used to specify the default block of code in a switch statement.
11. do: Java do keyword is used in control statement to declare a loop. It can iterate a part of the program several
times.
12. double: Java double keyword is used to declare a variable that can hold a 64-bit floating-point numbers.
13. else: Java else keyword is used to indicate the alternative branches in an if statement.
14. enum: Java enum keyword is used to define a fixed set of constants. Enum constructors are always private or
default.
15. extends: Java extends keyword is used to indicate that a class is derived from another class or interface.
16. final: Java final keyword is used to indicate that a variable holds a constant value. It is applied with a variable. It is
used to restrict the user.
17. finally: Java finally keyword indicates a block of code in a try-catch structure. This block is always executed whether
exception is handled or not.
18. float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point number.
19. for: Java for keyword is used to start a for loop. It is used to execute a set of instructions/functions repeatedly when
some conditions become true. If the number of iteration is fixed, it is recommended to use for loop.
20. if: Java if keyword tests the condition. It executes the if block if condition is true.
21. implements: Java implements keyword is used to implement an interface.
22. import: Java import keyword makes classes and interfaces available and accessible to the current source code.
23. instanceof: Java instanceof keyword is used to test whether the object is an instance of the specified class or
implements an interface.
24. int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
25. interface: Java interface keyword is used to declare an interface. It can have only abstract methods.
26. long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
27. native: Java native keyword is used to specify that a method is implemented in native code using JNI (Java Native
Interface).
28. new: Java new keyword is used to create new objects.
29. null: Java null keyword is used to indicate that a reference does not refer to anything. It removes the garbage value.
30. package: Java package keyword is used to declare a Java package that includes the classes.
31. private: Java private keyword is an access modifier. It is used to indicate that a method or variable may be
accessed only in the class in which it is declared.
32. protected: Java protected keyword is an access modifier. It can be accessible within package and outside the
package but through inheritance only. It can't be applied on the class.
33. public: Java public keyword is an access modifier. It is used to indicate that an item is accessible anywhere. It has
the widest scope among all other modifiers.
34. return: Java return keyword is used to return from a method when its execution is complete.
35. short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
36. static: Java static keyword is used to indicate that a variable or method is a class method. The static keyword in
Java is used for memory management mainly.
37. strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.
38. super: Java super keyword is a reference variable that is used to refer parent class object. It can be used to invoke
immediate parent class method.
39. switch: The Java switch keyword contains a switch statement that executes code based on test value. The switch
statement tests the equality of a variable against multiple values.
40. synchronized: Java synchronized keyword is used to specify the critical sections or methods in multithreaded code.
41. this: Java this keyword can be used to refer the current object in a method or constructor.
42. throw: The Java throw keyword is used to explicitly throw an exception. The throw keyword is mainly used to throw
custom exception. It is followed by an instance.
43. throws: The Java throws keyword is used to declare an exception. Checked exception can be propagated with
throws.
44. transient: Java transient keyword is used in serialization. If you define any data member as transient, it will not be
serialized.
45. try: Java try keyword is used to start a block of code that will be tested for exceptions. The try block must be
followed by either catch or finally block.
46. void: Java void keyword is used to specify that a method does not have a return value.
47. volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.
48. while: Java while keyword is used to start a while loop. This loop iterates a part of the program several times. If the
number of iterations is not fixed, it is recommended to use while loop.
Lesson 4
TOPIC: DATA TYPES, VACRIABLES AND ARRAYS
DURATION: 1 WEEK
PREFERRED DELIVERY: Virtual Classroom, Electronic, Printed Module
LEARNING OBJECTIVES
By the end of this module, students will have completed the following objectives:
13. Discuss the primitive types.
14. Discuss and explain oh how you can input a variable by making a program in Java.
TO DO LIST
Reading
o Course Content and Lecture in Module 4 (page 2- 3)
Take Quiz
COURSE CONTENT
Regardless of whether one thinks that Java is now growing, or dying, one has to admit that Java
had truly revolutionized and had defined the programming language. Java had combined and brought to
the tons of useful programming languages features that were previously available only separately or in
various languages. Java is a programming language and platform released by Sun Microsystems in 1995.
Java is a secure, fast, and reliable programming language. Java is everywhere in PCs to Mobile phone,
satellites, other electronic devices. There are many applications and websites that will not run without java
installation in your machine.
In this chapter, we will discus and create a program that will use the primitive types.
Integers
byte - The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to 127.
short - is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least-used Java type.
int - The most commonly used integer type is int. It is a signed 32-bit type that has a range from –2,147,483,648 to
2,147,483,647.
long - is a signed 64-bit type that has a range from -9,223,372,036,854,775,808 to 9,223,372,036,854,755,807 and
is useful for those occasions where an int type is not large enough to hold the desired value. The range of a long is
quite large.
Float - the type float specifies a single-precision value that uses 32 bits of storage (e.g 32.4).
Double - Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually
faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations
(e.g 32.3456734).
char - the data type used to store characters. A key point to understand is that Java uses Unicode to represent characters.
Booleans - is also the type required by the conditional expressions that govern the control statements such as if and for.
Variables
The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier,
a type, and an optional initializer. In addition, all variables have a scope, which defines their visibility, and a lifetime.
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a variable declaration is
shown here: type identifier [ = value ][, identifier [= value ] …];
Ex: Int a, b, c;
Java Input
Java provides different ways to get input from the user. To get input from user using the object of Scanner class. In
order to use the object of Scanner, we need to import java.util.Scanner package.
import java.util.Scanner;
Then, we need to create an object of the Scanner class. We can use the object to take input from the user.
//create an object of Scanner
Scanner input = new Scanner (Sytem.in);
Example Code:
import java.util.Scanner;
class InputInteger{
public static void main(String[]args){
Scanner input = new Scanner (Sytem.in);
Sytem.out.print(“Enter an integer:”);
int number = input.nextInt();
system.out,println(“You entered:” + number);
input.close();
}
}
When you run this program, you will see the following output:
Enter an Integer:14 //this is where you are going to input the number you desired
You Entered:14 //inputted number
Activity 4.1
1. Create a program that will input and output a double variable.
Output:
Enter double:
Double entered:
Activity 4.2
1. Create a program that will input and output a float variable.
Output:
Enter float:
Float entered:
Activity 4.3
1. Create a program that will input and output a string variable:
Output:
Enter text:
Text entered:
Lesson 5
TOPIC: JAVA OPERATORS
DURATION: 1 WEEK
PREFERRED DELIVERY: Virtual Classroom, Electronic, Printed Module
LEARNING OBJECTIVES
By the end of this module, students will have completed the following objectives:
15. Enumerate and discuss the java operators.
16. Give and demonstrate example programs using java operators
TO DO LIST
Reading
o Course Content and Lecture in Module 1 (page 2- 7)
Take Quiz
COURSE CONTENT
Regardless of whether one thinks that Java is now growing, or dying, one has to admit that Java
had truly revolutionized and had defined the programming language. Java had combined and brought to
the tons of useful programming languages features that were previously available only separately or in
various languages. Java is a programming language and platform released by Sun Microsystems in 1995.
Java is a secure, fast, and reliable programming language. Java is everywhere in PCs to Mobile phone,
satellites, other electronic devices. There are many applications and websites that will not run without java
installation in your machine.
In this chapter, we will discuss the java operators and perform example programs using them.
Java Operators
Java provides a rich operator environment. Most of its operators can be divided into the following four groups:
arithmetic, bitwise, relational, and logical. Java also defines some additional operators that handle certain special situations.
Assignment Operators
The assignment operators assign the value on its right to the variable on its left.
Example Activity 5.1: Assignment Operator
class AssignmentOperator {
public static void main(String[] args) {
// Assigning 5 to number1
number1 = 5;
System.out.println(number1);
Output:
5
5
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc.
Operator Meaning
- Subtraction Operator
* Multiplication Operator
/ Division Operator
% Remainder Operator
class ArithmeticOperator {
public static void main(String[] args) {
Output:
Equality and relational operators are used in decision making and loops (which will be discussed later). For now, check this
simple example.
class RelationalOperator {
public static void main(String[] args) {
Output:
Logical Operators
The logical operators || (conditional-OR) and && (conditional-AND) operate on boolean expressions. Here's how
they work.
Operato
Description Example
r
class LogicalOperator {
public static void main(String[] args) {
System.out.println(result);
Output:
true
false
Unary Operators
Operato
Meaning
r
Unary plus (not necessary to use since numbers are positive without
+
using it)
class UnaryOperator {
public static void main(String[] args) {
Output:
+number = 5.2
-number = -5.2
number = 6.2
number = 5.2
!flag = true
instanceof Operator
In addition to relational operators, there is also a type comparison operator instanceof which compares an object to a
specified type. For example,
class instanceofOperator {
public static void main(String[] args) {
Output:
Ternary Operator
The conditional operator or ternary operator ?: is shorthand for the if-then-else statement. The syntax of the
conditional operator is:
class ConditionalOperator {
public static void main(String[] args) {
}
}
Output:
Leap year
To perform bitwise and bit shift operators in Java, these operators are used. These operators are not commonly
used.
Operator Description
~ Bitwise Complement
^ Bitwise exclusive OR
| Bitwise inclusive OR
Activity
Write a program that will show the following outputs of two numbers using arithmetic operations. (Arithmetic.java)
Given value of two numbers:
x = 45
y = 135
Output:
The sum of x and y is:
The difference of x and y:
The product of x and y is:
The quotient of x and y is:
Lesson 6
TOPIC: DECISION MAKING AND BRANCHING PROGRAMING IN JAVA
DURATION: 1 WEEK
PREFERRED DELIVERY: Virtual Classroom, Electronic, Printed Module
LEARNING OBJECTIVES
By the end of this module, students will have completed the following objectives:
17. Enumerate and discuss the java decision making ang branching programming in Java.
18. Give and demonstrate example programs using decision making ang branching programing in Java.
TO DO LIST
Reading
o Course Content and Lecture in Module 1 (page 2- 10)
Take Quiz
COURSE CONTENT
Regardless of whether one thinks that Java is now growing, or dying, one has to admit that Java
had truly revolutionized and had defined the programming language. Java had combined and brought to
the tons of useful programming languages features that were previously available only separately or in
various languages. Java is a programming language and platform released by Sun Microsystems in 1995.
Java is a secure, fast, and reliable programming language. Java is everywhere in PCs to Mobile phone,
satellites, other electronic devices. There are many applications and websites that will not run without java
installation in your machine.
In this chapter, we will discuss the if, if else, if else if, and switch decision making and branching
programming and perform example programs using them.
In computer programming, it's often desirable to execute a certain section of code based upon whether the
specified condition is true or false (which is known only during the run time). For such cases, control flow statements are
used.
if (expression) {
// statements
}
Here expression is a boolean expression. A boolean expression returns either true or false.
if the expression is evaluated to true, statement(s) inside the body of if (statements inside parenthesis) are
executed
if the expression is evaluated to false, statement(s) inside the body of if are skipped from execution
class IfStatement {
public static void main(String[] args) {
Output:
Explanation:
In the above example, we have a variable named number. Here, the test expression checks if the number is
greater than 0 (number > 0).
Since the number is greater than 0. So the test expression evaluates to true. Hence code inside the body of if is executed.
Now, change the value of the number to a negative integer. Let's say -5.
If we run the above program with the new value of the number, the output will be:
Here, the value of number is less than 0. So, the test expression number > 0 evaluates to false. Hence, the body
of if is executed.
The if statement executes a certain section of code if the test expression is evaluated to true . However, if the test
expression is evaluated to false , it does nothing.
In this case, we can use an optional else block. Statements inside the body of else block are executed if the test expression
is evaluated to false . This is known as the if-then-else statement in Java.
The syntax of the if-then-else statement is:
if (expression) {
// codes
}
else {
// some other code
}
Here, our program will do one task (task inside if block) if the test expression is true and another task (task inside
else block) if the test expression is false .
How if...else statement works?
class IfElse {
public static void main(String[] args) {
int number = 10;
Output:
Explanation:
In the above example, we have a variable named number. Here, the test expression checks if the number is
greater than 0 (number > 0).
Since the value of the number is 10, the test expression evaluates to true. Hence code inside the body of if is
executed.
Now, change the value of the number to a negative integer. Let's say -5.
If we run the program with the new value of the number, the output will be:
Here, the value of number is -5. So the test expression evaluates to false. Hence code inside the body of else is
executed.
In Java, we have an if...else...if ladder, that can be used to execute one block of code among multiple other blocks.
if (expression1) {
// codes
}
else if(expression2) {
// codes
}
else if (expression3) {
// codes
}
.
.
else {
// codes
}
Explanation:
Here, if statements are executed from the top towards the bottom. As soon as the test expression is true , codes
inside the body of that the if statement is executed. Then, the control of the program jumps outside the if-else-if ladder.
If all test expressions are false , codes inside the body of else is executed.
Example Avtivity 6.3: Java if..else..if Statement
class Ladder {
public static void main(String[] args) {
int number = 0;
Output:
The number is 0.
Explanation
In the above example, we are checking whether the number is positive, negative or zero. Here, we have two test
expressions:
number > 0 - checks if the number is greater than 0
number < 0 - checks if the number is less than 0
Here, the value of number is 0 . So both the test expression evaluates to false . Hence the statement inside the body
of else is executed.
In Java, it is also possible to if..else statements inside a if..else statement. It's called nested if...else statement.
Here's a program to find largest of 3 numbers:
class Number {
public static void main(String[] args) {
else {
largestNumber = n3;
}
}
else {
else {
largestNumber = n3;
}
Output:
In Java, we have used the if..else..if ladder to execute a block of code among multiple blocks. However, the syntax
of if...else...if ladders are too long.
Hence, we can use the switch statement as a substitute for long if...else...if ladders. The use of switch statements
makes our code more readable.
The syntax of the switch statement is:
switch (variable/expression) {
case value1:
// statements of case1
break;
case value2:
// statements of case2
break;
.. .. ...
.. .. ...
default:
// default statements
}
Explanation
The switch statement evaluates the expression (mostly variable) and compares it with values (can be expressions)
of each case label.
Now, if the value matches a certain case label, then all the statements of the matching case label are executed.
For example, if the variable/expression is equal to value2. In this case, all statements of that
matching case (statements of case2) are executed.
Notice, the use of break statements in each case. The break statement is used to terminate the execution of
the switch statement.
It is important because if break is not used all the statements after the matching case are executed in sequence
until the end of the switch statement.
class Main {
public static void main(String[] args) {
int week = 4;
String day;
Output:
Explanation:
In the above example, we have used the switch statement to find out the day of a week. Here, we have a
variable week that holds an integer value. The value is compared to each case inside the switch block.
Here the value of week is 4. Hence it matches the case 4. So the statement inside case 4 is executed.
The program below takes three inputs from the user: one operator and 2 numbers. Based on the operator provided
by the user, it performs the calculation on the numbers. Then the result is displayed on the screen.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
char operator;
Double number1, number2, result;
number1 = scanner.nextDouble();
number2 = scanner.nextDouble();
switch (operator) {
default:
System.out.println("Invalid operator!");
break;
}
}
}
Output:
In the above example, we have used the switch statement to create a calculator. It performs the calculation based
on the operator provided by the user.
ACTIVITY
Create a program using if else if and condition statement that will enter 6 numbers (Quiz) and get the average
grade of the student and its remark.
Output:
Q1
Q2
Q3
Q4
Q5
Q6
Average:
Remarks:
Lesson 7
TOPIC: DECISION MAKING AND LOOPING
DURATION: 1 WEEK
PREFERRED DELIVERY: Virtual Classroom, Electronic, Printed Module
LEARNING OBJECTIVES
By the end of this module, students will have completed the following objectives:
19. Enumerate and discuss the java decision making and looping in Java.
20. Give and demonstrate example programs using decision making and looping in Java.
TO DO LIST
Reading
o Course Content and Lecture in Module 1 (page 2- 23)
Take Quiz
COURSE CONTENT
Regardless of whether one thinks that Java is now growing, or dying, one has to admit that Java
had truly revolutionized and had defined the programming language. Java had combined and brought to
the tons of useful programming languages features that were previously available only separately or in
various languages. Java is a programming language and platform released by Sun Microsystems in 1995.
Java is a secure, fast, and reliable programming language. Java is everywhere in PCs to Mobile phone,
satellites, other electronic devices. There are many applications and websites that will not run without java
installation in your machine.
Looping Statements
In computer programming, loops are used to repeat a specific block of code until a certain condition is met (test
expression is false). For example,
Imagine we need to print a sentence 50 times on your screen. Well, we can do it by using the print statement 50
times (without using loops). How about you need to print a sentence one million times? You need to use loops. With loops,
we can simply write the print statement one time and run it for any number of times.
It's just a simple example showing the importance of loop in computer programming.
class Loop {
public static void main(String[] args) {
Output:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
Explanation
In the above example, we have
class Number {
public static void main(String[] args) {
int sum = 0;
Output:
Sum = 500500
Explanation
Here, we have a variable named sum. Its initial value is 0. Inside for loop, we have initialized a variable
named i with value 1.
class Infinite {
public static void main(String[] args) {
int sum = 0;
Here, the test expression ( i <= 10 ) is never false and hello is printed infinite number to times (at least in theory).
Note: The initialization, update and test expression used in for statement is optional. Here's another example of the
infinite for loop.
for ( ; ; ) {
In Java, while working with arrays and collections, we can use the enhanced form of for loop. It is also known as a
for-each loop. It is because the loop iterates through each element of arrays or collections.
To know why the for-each loop is preferred over for loop while working with arrays, let's see the following example.
Here the example shows how we can iterate through elements of an array using the standard for loop.
class ForLoop {
public static void main(String[] args) {
Output:
a
e
i
o
u
Now we will perform the same task using the for-each loop.
class AssignmentOperator {
public static void main(String[] args) {
Output:
a
e
i
o
u
Here, we can see that the output of both the program is the same.
When we carefully analyze both the program, we can notice that the for-each loop is easier to write and makes our
code more readable. This is the reason it is called enhanced for loop.
Hence, it is recommended to use the enhanced for loop over the standard for loop whenever possible.
Here,
Here's how the for-each loop works in Java. For each iteration, the for-each loop
iterates through each item in given collections or arrays ( collections ),
stores each item in a variable ( item )
and executes the body of the loop.
Let's make it clear through an example.
The program below calculates the sum of all elements of an integer array.
class EnhancedForLoop {
public static void main(String[] args) {
Output:
Sum = 19
Explanation
In the above program, the execution of the for-each loop looks as:
Iteration Value
while (testExpression) {
// codes inside the body of while loop
}
class Loop {
public static void main(String[] args) {
int i = 1;
Output:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
Explanation
In the above example, we have a test expression ( i <= 10 ). It checks whether the value of i is less than or equal to
10.
Here initially, the value of i is 1. So the test expression evaluates to true for the first time. Hence, the print statement
inside while loop is executed.
Inside while loop notice the statement
++i;
This statement increases the value of i by 1 in each iteration. After 10 iterations, the value of i will be 11. Then, the
test expression ( i <= 10 ) evaluates to false and while loop terminates.
class AssignmentOperator {
public static void main(String[] args) {
while (i != 0) {
sum += i; // sum = sum + i;
--i;
}
Output:
Sum = 5050
Here, we have two variables named sum and i whose initial values are 0 and 100 respectively.
In each iteration of the while loop,
the sum variable is assigned value: sum + i
the value of i is decreased by 1
The loop continues until the value of i is equal to 0. For better visualization,
do {
// codes inside body of do while loop
} while (testExpression);
The program below calculates the sum of numbers entered by the user until user enters 0.
import java.util.Scanner;
class Sum {
public static void main(String[] args) {
do {
sum += number;
} while (number != 0.0); // test expression
Output:
If a loop exists inside the body of another loop, it's called a nested loop. Here's an example of the nested for loop.
class NestedForLoop {
public static void main(String[] args) {
Output:
Here, the outer loop iterates 5 times. In each iteration of outer loop, the inner loop iterates 2 times.
class NestedLoop {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
++i;
}
}
}
Output:
Here you can see that the output of this program and above program is same.
1 2
1 2 3
1 2 3 4
1 2 3 4 5
class Pattern {
public static void main(String[] args) {
int rows = 5;
System.out.println("");
}
}
}
While working with loops, it is sometimes desirable to skip some statements inside the loop or terminate the loop
immediately without checking the test expression.
In such cases, break and continue statements are used. You will learn about the d in the next chapter.
The break statement in Java terminates the loop immediately, and the control of the program moves to the next
statement following the loop.
Here is the syntax of the break statement in Java:
break;
class Test {
public static void main(String[] args) {
// for loop
for (int i = 1; i <= 10; ++i) {
Output:
1
2
3
4
In the above program, we are using the for loop to print the value of i in each iteration.
if (i == 5) {
break;
}
This means when the value of i is equal to 5, the loop terminates. Hence we get the output with values less than 5
only.
import java.util.Scanner;
class UserInputSum {
public static void main(String[] args) {
while (true) {
System.out.print("Enter a number: ");
sum += number;
}
System.out.println("Sum = " + sum);
}
}
Output:
Enter a number: 0
Enter a number: -4.5
Sum = 10.5
In the above program, the test expression of the while loop is always true . Here, notice the line,
This means when the user input negative numbers, the while loop is terminated.
Here, the break statement terminates the innermost while loop, and control jumps to the outer loop.
We can use the labeled break statement to terminate the outermost loop as well.
As you can see in the above image, we have used the label identifier to specify the outer loop. Now, notice how
the break statement is used ( break label; ).
Here, the break statement is terminating the labeled statement (i.e. outer loop). Then, the control of the program
jumps to the statement after the labeled statement.
Here's another example:
while (testExpression) {
// codes
second:
while (testExpression) {
// codes
while(testExpression) {
// codes
break second;
}
}
// control jumps here
}
In the above example, when the statement break second; is executed, the while loop labeled as second is terminated.
And, the control of the program moves to the statement after the second while loop.
class LabeledBreak {
public static void main(String[] args) {
Output:
i = 1; j = 1
i = 1; j = 2
i = 2; j = 1
In the above example, the labeled break statement is used to terminate the loop labeled as first. That is,
first:
for(int i = 1; i < 5; i++) {...}
Here, if we change the statement break first; to break second; the program will behave differently. In this case, for loop
labeled as second will be terminated. For example,
class LabeledBreak {
public static void main(String[] args) {
Output:
i = 1; j = 1
i = 1; j = 2
i = 2; j = 1
i = 3; j = 1
i = 3; j = 2
i = 4; j = 1
i = 4; j = 2
While working with loops, it is sometimes desirable to skip some statements inside the loop or terminate the loop
immediately without checking the test expression.
In such cases, break and continue statements are used. To learn about the break statement, visit Java break.
The continue statement in Java skips the current iteration of a loop ( for , while , do...while , etc) and the control of the
program moves to the end of the loop. And, the test expression of a loop is evaluated.
In the case of for loop, the update statement is executed before the test expression.
The continue statement is almost always used in decision-making statements (if...else Statement). It's syntax is:
continue;
class Test {
public static void main(String[] args) {
// for loop
for (int i = 1; i <= 10; ++i) {
Output:
2
3
4
9
10
In the above program, we are using for loop to print the value of i in each iteration.
This means when the value of i becomes more than 4 and less then 9, the print statement inside the loop is
skipped. Hence we get the output with values 5, 6, 7, and 8 skipped.
To take input from the user, we have used the Scanner object. To learn more about Scanner , visit Java Scanner.
import java.util.Scanner;
class AssignmentOperator {
public static void main(String[] args) {
sum += number;
}
System.out.println("Sum = " + sum);
}
}
Output:
Sum = 7.8
This means when the user input negative numbers, the current iteration of the loop is skipped. And the next
iteration is started.
class Test {
public static void main(String[] args) {
// for loop
for (int i = 1; i <= 10; ++i) {
Output:
1
2
3
4
9
10
In the above program, we are using for loop to print the value of i in each iteration. To know how for loop works,
visit Java for loop. Here, notice the statement,
This means when the value of i becomes more than 4 and less then 9, the print statement inside the loop is
skipped. Hence we get the output with values 5, 6, 7, and 8 skipped.
Example/Activity 7.15: Java continue statement
The program below calculates the sum of 5 positive numbers entered by the user. If the user enters negative
number or zero, it is skipped from the calculation.
To take input from the user, we have used the Scanner object.
import java.util.Scanner;
class AssignmentOperator {
public static void main(String[] args) {
sum += number;
}
System.out.println("Sum = " + sum);
}
}
Output:
This means when the user input negative numbers, the current iteration of the loop is skipped. And the next
iteration is started.
ACTIVITY
(10 points)
1. Create a program using looping statements that will show the given output.
* *****
** ****
*** ***
**** **
***** *
(10 points)
2. create a program using looping statements that will show the given output.
1
12
123
1234
12345
123456
(10 ponts)
3. Create a program using looping statements that will show the given output.
*
* *
* * *
* * * *
* * *
* *
*