[go: up one dir, main page]

0% found this document useful (0 votes)
12 views66 pages

1ST Grading Java

1. The document discusses the history and evolution of the Java programming language. It traces Java's lineage back to C and C++ and describes how Java was created at Sun Microsystems in the 1990s to be a platform-independent language for programming consumer electronics. 2. With the rise of the World Wide Web in the mid-1990s, Java's focus shifted to becoming a language for internet programming due to the Web's need for portable programs across different systems. 3. The document provides an overview of Java, describing its syntax which is derived from C and C++, and how it combines object-oriented features to be an appealing language for programmers familiar with C/C++.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views66 pages

1ST Grading Java

1. The document discusses the history and evolution of the Java programming language. It traces Java's lineage back to C and C++ and describes how Java was created at Sun Microsystems in the 1990s to be a platform-independent language for programming consumer electronics. 2. With the rise of the World Wide Web in the mid-1990s, Java's focus shifted to becoming a language for internet programming due to the Web's need for portable programs across different systems. 3. The document provides an overview of Java, describing its syntax which is derived from C and C++, and how it combines object-oriented features to be an appealing language for programmers familiar with C/C++.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 66

Lemery Colleges, Inc.

A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

SCHOOL OF BUSINESS AND MANAGEMENT


ACCOUNTING, BUSINESS AND MANAGEMENT
Academic Year 2020-2021
FIRST SEMESTER

NCIII: Computer Programming


Java

NAME OF
STUDENT
YEAR & SECTION

Course Code : NCIII


Course Description : COMPUTER PROGRAMMING JAVA
Credit Unit : 3 Units
Instructor : William M. Yuzon

NOTE
No part of this compilation may be reproduced in any form or by any means without prior
written consent of the institution.

JAVA PROGRAMMING ▪ PAGE 1


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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:

L- Love of God and Country


C- C’s (Competent, Committed and Compassionate) in service
I- Innovative Minds
A- Aspiring People
N- Noble Dreams

JAVA PROGRAMMING ▪ PAGE 2


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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 PROGRAMMING ▪ PAGE 3


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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.

The Creation of Java


Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun
Microsystems, Inc. in 1991. It took 18 months to develop the first working version. This language was initially called “Oak,”
but was renamed “Java” in 1995. Between the initial implementation of Oak in the fall of 1992 and the public announcement
of Java in the spring of 1995, many more people contributed to the design and evolution of the language. Bill Joy, Arthur
van Hoff, Jonathan Payne, Frank Yellin, and Tim Lindholm were key contributors to the maturing of the original prototype.
Somewhat surprisingly, the original impetus for Java was not the Internet! Instead, the primary motivation was the
need for a platform-independent (that is, architecture-neutral) language that could be used to create software to be
embedded in various consumer electronic devices, such as microwave ovens and remote controls. As you can probably
guess, many different types of CPUs are used as controllers. The trouble with C and C++ (and most other languages) is that
they are designed to be compiled for a specific target. Although it is possible to compile a C++ program for just about any
type of CPU, to do so requires a full C++ compiler targeted for that CPU. The problem is that compilers are expensive and
time-consuming to create. An easier—and more cost-efficient—solution was needed. In an attempt to find such a solution,
Gosling and others began work on a portable, platform-independent language that could be used to produce code that
would run on a variety of CPUs under differing environments. This effort ultimately led to the creation of Java.
About the time that the details of Java were being worked out, a second, and ultimately more important, factor was
emerging that would play a crucial role in the future of Java. This second force was, of course, the World Wide Web. Had
the Web not taken shape at about the same time that Java was being implemented, Java might have remained a useful but
obscure language for programming consumer electronics. However, with the emergence of the World Wide Web, Java was
propelled to the forefront of computer language design, because the Web, too, demanded portable programs.
Most programmers learn early in their careers that portable programs are as elusive as they are desirable. While
the quest for a way to create efficient, portable (platform-independent) programs is nearly as old as the discipline of
programming itself, it had taken a back seat to other, more pressing problems. Further, because (at that time) much of the
computer world had divided itself into the three competing camps of Intel, Macintosh, and UNIX, most programmers stayed
within their fortified boundaries, and the urgent need for portable code was reduced. However, with the advent of the
Internet and the Web, the old problem of portability returned with a vengeance. After all, the Internet consists of a diverse,
distributed universe populated with various types of computers, operating systems, and CPUs. Even though many kinds of
platforms are attached to the Internet, users would like them all to be able to run the same program. What was once an
irritating but low-priority problem had become a high-profile necessity.
By 1993, it became obvious to members of the Java design team that the problems of portability frequently
encountered when creating code for embedded controllers are also found when attempting to create code for the Internet.
In fact, the same problem that Java was initially designed to solve on a small scale could also be applied to the Internet on a
large scale. This realization caused the focus of Java to switch from consumer electronics to Internet programming. So,
while the desire for an architecture-neutral programming language provided the initial spark, the Internet ultimately led to
Java’s large-scale success.
As mentioned earlier, Java derives much of its character from C and C++. This is by intent. The Java designers
knew that using the familiar syntax of C and echoing the object-oriented features of C++ would make their language
appealing to the legions of experienced C/C++ programmers. In addition to the surface similarities, Java shares some of the
other attributes that helped make C and C++ successful. First, Java was designed, tested, and refined by real, working
programmers. It is a language grounded in the needs and experiences of the people who devised it. Thus, Java is a
programmer’s language. Second, Java is cohesive and logically consistent. Third, except for those constraints imposed by
the Internet environment, Java gives you, the programmer, full control. If you program well, your programs reflect it. If you
program poorly, your programs reflect that, too. Put differently, Java is not a language with training wheels. It is a language
for professional programmers.

JAVA PROGRAMMING ▪ PAGE 4


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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.

How Java Impacted the Internet


The Internet helped catapult Java to the forefront of programming, and Java, in turn, had a profound effect on the
Internet. In addition to simplifying web programming in general, Java innovated a new type of networked program called the
applet that changed the way the online world thought about content. Java also addressed some of the thorniest issues
associated with the Internet: portability and security. Let’s look more closely at each of these.

Java’s Magic: The Bytecode


The key that allowed Java to solve both the security and the portability problems just described is that the output of
a Java compiler is not executable code. Rather, it is bytecode. Bytecode is a highly optimized set of instructions designed to
be executed by what is called the Java Virtual Machine (JVM), which is part of the Java Runtime Environment (JRE). In
essence, the original JVM was designed as an interpreter for bytecode. This may come as a bit of a surprise since many
modern languages are designed to be compiled into executable code because of performance concerns. However, the fact
that a Java program is executed by the JVM helps solve the major problems associated with web-based programs. Here is
why.
Translating a Java program into bytecode makes it much easier to run a program in a wide variety of environments
because only the JVM needs to be implemented for each platform. Once a JRE exists for a given system, any Java
program can run on it. Remember, although the details of the JVM will differ from platform to platform, all understand the
same Java bytecode. If a Java program were compiled to native code, then different versions of the same program would
have to exist for each type of CPU connected to the Internet. This is, of course, not a feasible solution. Thus, the execution
of bytecode by the JVM is the easiest way to create truly portable programs.
The fact that a Java program is executed by the JVM also helps to make it secure. Because the JVM is in control, it
manages program execution. Thus, it is possible for the JVM to create a restricted execution environment, called the
sandbox, that contains the program, preventing unrestricted access to the machine. Safety is also enhanced by certain
restrictions that exist in the Java language.
In general, when a program is compiled to an intermediate form and then interpreted by a virtual machine, it runs
slower than it would run if compiled to executable code. However, with Java, the differential between the two is not so great.
Because bytecode has been highly optimized, the use of bytecode enables the JVM to execute programs much faster than
you might expect.
Although Java was designed as an interpreted language, there is nothing about Java that prevents on-the-fly
compilation of bytecode into native code in order to boost performance. For this reason, the HotSpot technology was
introduced not long after Java’s initial release. HotSpot provides a Just-In-Time (JIT) compiler for bytecode. When a JIT
compiler is part of the JVM, selected portions of bytecode are compiled into executable code in real time, on a piece-by-
piece, demand basis. It is important to understand that an entire Java program is not compiled into executable code all at
once. Instead, a JIT compiler compiles code as it is needed, during execution. Furthermore, not all sequences of bytecode
are compiled—only those that will benefit from compilation. The remaining code is simply interpreted. However, the just-
intime approach still yields a significant performance boost. Even when dynamic compilation is applied to bytecode, the
portability and safety features still apply, because the JVM is still in charge of the execution environment.
One other point: Beginning with JDK 9, some Java environments will also support an ahead-of-time compiler that
can be used to compile bytecode into native code prior to execution by the JVM, rather than on-the-fly. Ahead-oftime

JAVA PROGRAMMING ▪ PAGE 5


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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.

Moving Beyond Applets and Servlets


In Java, both Applets and Servlets are the programs and applications that run in a java environment.

Key Applets Servlets


1. Execution Applets are executed on client- Servlets on the other hand executed on the server
side side.
2. Parent Applet includes Servlets includes
Packages java.applet.* and java.awt.* javax.servlet.* and java.servlet.http.*

3. Methods Important methods of Applet Lifecycle methods of servlet are:


include: init(), stop(), paint(),
init(), service(), and destroy()
start(), destroy()

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.

The Java Buzz Words / Features of Java


Object Oriented - object model in Java is simple and easy to extend, while primitive types, such as integers, are kept as
high-performance nonobjects.
Platform Independent – unlike many other programming languages including C and C++, when Java is compiled, it is
not compiled into platform specific machine, rather into platform-independent byte code. This byte code is distributed
over the web and interpreted by the Virtual Machine (JVM) on whichever platform is being run on.
Simple – Java is designed to be easy to learn and use effectively.
Secure – with Javas secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques
are based on the public-key encryption.
Architecture-neutral – Java compiler generates and architecture-neutral object file format, which makes the compiled
code executable on many processors, with the presence of Java runtime system.
Portable – being architecture-neutral and having no implementation dependent aspects of the specification make Java
portable.
Robust – Java makes an effort to eliminate error-prone situations by emphasizing mainly on compile time error
checking and runtime checking.
Multithreaded – with Java’s multithreaded feature it is possible to write the programs that can perform many tasks
simultaneously.

JAVA PROGRAMMING ▪ PAGE 6


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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.

JAVA PROGRAMMING ▪ PAGE 7


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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.

11-14. Main concepts of Object-Oriented Programming.

15-20. Give at least 6 features of Java.

JAVA PROGRAMMING ▪ PAGE 8


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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.

JAVA PROGRAMMING ▪ PAGE 9


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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.

Four Basic Concepts of OOP

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.

A First Simple Program


For creating a new Project click on the menu bar File > Project then name it “Example” it will automatically add .java
file extension.
For creating a new Class click on the menu bar File > Class then name it “HelloWorld” it will automatically compiled
on your project Example.java.
/*
This is a simple Java program
Call this file “HelloWorld.java”.
*/

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 */.

JAVA PROGRAMMING ▪ PAGE 10


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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.

// Your program begins with a call to main().


This is the second type of comment supported by Java. A single-line comment begins with a // and ends at the end
of the line.

public static void main (String args[]){


public keyword is an access modifier, which allows the programmer to control the visibility of class members.
The keyword static allows main( ) to be called without having to instantiate a particular instance of the class.
The keyword void simply tells the compiler that main( ) does not return a value.
main( ) is the method called when a Java application begins.
String args[ ] declares a parameter named args, which is an array of instances of the class String.

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.

Second Short Program

When you run this program, you will see the following output:
This is num: 100
The value of num * 2 is 200

Explanation:

int num; // this declares a variable called num


This line declares an integer variable called num.

num = 100; // this assigns num the value 100


assigns to num the value 100. In Java, the assignment operator is a single equal sign.

System.out.println("This is num: " + num);

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.

JAVA PROGRAMMING ▪ PAGE 11


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

System.out.print ("The value of num * 2 is ");


System.out.println (num);

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.

Two Control Statements

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.

Operations used in Conditional/Boolean Expression

The output generated by this program is shown here:


x is less than y
x now equal to y
x now greater than y

Notice one other thing in this program. The line


int x, y;
declares two variables, x and y, by use of a comma-separated list.

The for loop statements are important part of nearly any programming language because they provide a way to
repeatedly execute some tasks.

JAVA PROGRAMMING ▪ PAGE 12


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

for(initialization; condition; iteration) statement;

initialization is the portion of the loop sets a loop control variable to an initial value.

condition is a Boolean expression that tests the loop control variable.

iteration is an expression determines how the loop control variable is changed each time the loop iterates.

This program generates the following output:


This is x: 0
This is x: 1
This is x: 2
This is x: 3
This is x: 4
This is x: 5
This is x: 6
This is x: 7
This is x: 8
This is x: 9

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.

Blocks of Code or the Code Blocks

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.

JAVA PROGRAMMING ▪ PAGE 13


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

The output generated by this program is shown here:


This is x: 0
This is y: 20
This is x: 1
This is y: 18
This is x: 2
This is y: 16
This is x: 3
This is y: 14
This is x: 4
This is y: 12
This is x: 5
This is y: 10
This is x: 6
This is y: 8
This is x: 7
This is y: 6
This is x: 8
This is y: 4
This is x: 9
This is y: 2

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.

JAVA PROGRAMMING ▪ PAGE 14


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

ACTIVITY

Create a program that will display the following output (YourInformation.java).

Output:
Name:
Strand & Section:
Age:
Address:
Gender:
Contact Number:
COVID-19 Status:

JAVA PROGRAMMING ▪ PAGE 15


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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

JAVA PROGRAMMING ▪ PAGE 16


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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.

JAVA PROGRAMMING ▪ PAGE 17


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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.

JAVA PROGRAMMING ▪ PAGE 18


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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

 Create a program that will input and output a double variable.


 Create a program that will input and output a float variable.
 Create a program that will input and output a string variable:

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.

JAVA PROGRAMMING ▪ PAGE 19


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

The Primitive Types


Eight primitive types of data: byte, short, int, long, char, float, double, and boolean. The primitive types are also
commonly referred to as simple types. These can be put in four groups:
 Integers This group includes byte, short, int, and long, which are for whole-valued signed numbers.
 Floating-point numbers This group includes float and double, which represent numbers with fractional precision.
 Characters This group includes char, which represents symbols in a character set, like letters and numbers. There
is a type that uses sequence of char (form of text) called strings.
 Boolean This group includes boolean, which is a special type for

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);

JAVA PROGRAMMING ▪ PAGE 20


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

//take input from the user


int number = input.nextInt();

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

JAVA PROGRAMMING ▪ PAGE 21


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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:

JAVA PROGRAMMING ▪ PAGE 22


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

Enter float:
Float entered:

Activity 4.3
1. Create a program that will input and output a string variable:
Output:
Enter text:
Text entered:

JAVA PROGRAMMING ▪ PAGE 23


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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

 Create the example activity using assignment operators.


 Create the example activity using arithmetic operators.
 Create the example activity using Relational Operator
 Create the example activity using Logical Operator
 Create the example activity using Unary Operator
 Create the example activity using instaceof Operator.

JAVA PROGRAMMING ▪ PAGE 24


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

 Create the example activity using Ternary Operator

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) {

int number1, number2;

// Assigning 5 to number1
number1 = 5;
System.out.println(number1);

JAVA PROGRAMMING ▪ PAGE 25


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

// Assigning value of variable number2 to number1


number2 = number1;
System.out.println(number2);
}
}

Output:

5
5

Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc.

Operator Meaning

+ Addition (also used for string concatenation)

- Subtraction Operator

* Multiplication Operator

/ Division Operator

% Remainder Operator

Example Activity 5.2: Arithmetic Operator

class ArithmeticOperator {
public static void main(String[] args) {

double number1 = 12.5, number2 = 3.5, result;

// Using addition operator


result = number1 + number2;
System.out.println("number1 + number2 = " + result);

// Using subtraction operator


result = number1 - number2;
System.out.println("number1 - number2 = " + result);

// Using multiplication operator


result = number1 * number2;
System.out.println("number1 * number2 = " + result);

JAVA PROGRAMMING ▪ PAGE 26


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

// Using division operator


result = number1 / number2;
System.out.println("number1 / number2 = " + result);

// Using remainder operator


result = number1 % number2;
System.out.println("number1 % number2 = " + result);
}
}

Output:

number1 + number2 = 16.0


number1 - number2 = 9.0
number1 * number2 = 43.75
number1 / number2 = 3.5714285714285716
number1 % number2 = 2.0

Equality and Relational Operators


The equality and relational operators determine the relationship between the two operands. It checks if an operand
is greater than, less than, equal to, not equal to and so on. Depending on the relationship, it is evaluated to
either true or false.

Operator Description Example

== equal to 5 == 3 is evaluated to false

!= not equal to 5 != 3 is evaluated to true

> greater than 5 > 3 is evaluated to true

< less than 5 < 3 is evaluated to false

>= greater than or equal to 5 >= 5 is evaluated to true

<= less than or equal to 5 <= 5 is evaluated to true

Equality and relational operators are used in decision making and loops (which will be discussed later). For now, check this
simple example.

Example Activity 5.3: Equality and Relational Operator

class RelationalOperator {
public static void main(String[] args) {

int number1 = 5, number2 = 6;

if (number1 > number2) {


System.out.println("number1 is greater than number2.");
}
else {

JAVA PROGRAMMING ▪ PAGE 27


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

System.out.println("number2 is greater than number1.");


}
}
}

Output:

number2 is greater than number1.

Logical Operators

The logical operators || (conditional-OR) and && (conditional-AND) operate on boolean expressions. Here's how
they work.
Operato
Description Example
r

conditional-OR: true if either of the false || true is


||
boolean expression is true evaluated to true

conditional-AND: true if all boolean


&&
expressions are true

Example Activity 5.4: Logical Operator

class LogicalOperator {
public static void main(String[] args) {

int number1 = 1, number2 = 2, number3 = 9;


boolean result;

// At least one expression needs to be true for the result to be true


result = (number1 > number2) || (number3 > number1);

// result will be true because (number1 > number2) is true

System.out.println(result);

// All expression must be true from result to be true


result = (number1 > number2) && (number3 > number1);

// result will be false because (number3 > number1) is false


System.out.println(result);
}
}

Output:

true
false

JAVA PROGRAMMING ▪ PAGE 28


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

Unary Operators

The unary operator performs operations on only one operand.

Operato
Meaning
r

Unary plus (not necessary to use since numbers are positive without
+
using it)

- Unary minus: inverts the sign of an expression

++ Increment operator: increments value by 1

-- decrement operator: decrements value by 1

! Logical complement operator: inverts the value of a boolean

Example Activity 5.5: Unary Operator

class UnaryOperator {
public static void main(String[] args) {

double number = 5.2, resultNumber;


boolean flag = false;

System.out.println("+number = " + +number);


// number is equal to 5.2 here.

System.out.println("-number = " + -number);


// number is equal to 5.2 here.

// ++number is equivalent to number = number + 1


System.out.println("number = " + ++number);
// number is equal to 6.2 here.

// -- number is equivalent to number = number - 1

System.out.println("number = " + --number);


// number is equal to 5.2 here.

System.out.println("!flag = " + !flag);


// flag is still false.
}

Output:

+number = 5.2
-number = -5.2
number = 6.2
number = 5.2
!flag = true

JAVA PROGRAMMING ▪ PAGE 29


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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,

Example Activity 5.6: instaceof Operator

class instanceofOperator {
public static void main(String[] args) {

String test = "asdf";


boolean result;

result = test instanceof String;


System.out.println("Is test an object of String? " + result);
}
}

Output:

Is test an object of String? true

Ternary Operator

The conditional operator or ternary operator ?: is shorthand for the if-then-else statement. The syntax of the
conditional operator is:

variable = Expression ? expression1 : expression2

Here's how it works.

 If the Expression is true, expression1 is assigned to the variable.


 If the Expression is false, expression2 is assigned to the variable.
Example Activity 5.7: Ternary Operator

class ConditionalOperator {
public static void main(String[] args) {

int februaryDays = 29;


String result;

result = (februaryDays == 28) ? "Not a leap year" : "Leap year";


System.out.println(result);

JAVA PROGRAMMING ▪ PAGE 30


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

}
}

Output:

Leap year

Bitwise and Bit Shift Operators

To perform bitwise and bit shift operators in Java, these operators are used. These operators are not commonly
used.

Operator Description

~ Bitwise Complement

<< Left Shift

>> Right Shift

>>> Unsigned Right Shift

& Bitwise AND

^ 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:

JAVA PROGRAMMING ▪ PAGE 31


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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

 Create the example activity using “if” statement.

JAVA PROGRAMMING ▪ PAGE 32


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

 Create the example activity using “if else” statement.


 Create the example activity using “if else if” statement
 Create the example activity using Java “switch” statement

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.

JAVA PROGRAMMING ▪ PAGE 33


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

Java if, if...else Statement

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.

Java if (if-then) Statement

In Java, the syntax of the if-then statement is:

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

How if statement works?

Example Activity 6.1: if Stratement

class IfStatement {
public static void main(String[] args) {

int number = 10;

// checks if number is greater than 0


if (number > 0) {
System.out.println("The number is positive.");
}
System.out.println("This statement is always executed.");
}
}

Output:

The number is positive.

JAVA PROGRAMMING ▪ PAGE 34


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

This statement is always executed.

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.

int number = -5;

If we run the above program with the new value of the number, the output will be:

This statement is always executed.

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.

Java if...else (if-then-else) Statement

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?

JAVA PROGRAMMING ▪ PAGE 35


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

Example Activity 6.2: Java if else Statement

class IfElse {
public static void main(String[] args) {
int number = 10;

// checks if number is greater than 0


if (number > 0) {
System.out.println("The number is positive.");
}
else {
System.out.println("The number is not positive.");
}

System.out.println("This statement is always executed.");


}
}

Output:

The number is positive.


This statement is always executed.

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.

int number = -5;

If we run the program with the new value of the number, the output will be:

The number is not positive.


This statement is always executed.

JAVA PROGRAMMING ▪ PAGE 36


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

Here, the value of number is -5. So the test expression evaluates to false. Hence code inside the body of else is
executed.

Java if..else..if Statement

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;

// checks if number is greater than 0


if (number > 0) {
System.out.println("The number is positive.");
}

// checks if number is less than 0


else if (number < 0) {
System.out.println("The number is negative.");
}
else {
System.out.println("The number is 0.");
}
}
}

Output:

JAVA PROGRAMMING ▪ PAGE 37


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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.

Java Nested if..else Statement

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:

Example Activity 6.4: Nested if...else Statement

class Number {
public static void main(String[] args) {

// declaring double type variables


Double n1 = -1.0, n2 = 4.5, n3 = -5.3, largestNumber;

// checks if n1 is greater than or equal to n2


if (n1 >= n2) {

// if...else statement inside the if block


// checks if n1 is greater than or equal to n3
if (n1 >= n3) {
largestNumber = n1;
}

else {
largestNumber = n3;
}
}
else {

// if..else statement inside else block


// checks if n2 is greater than or equal to n3
if (n2 >= n3) {
largestNumber = n2;
}

else {
largestNumber = n3;
}

JAVA PROGRAMMING ▪ PAGE 38


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

System.out.println("The largest number is " + largestNumber);


}
}

Output:

The largest number is 4.5

Java switch Statement

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.

JAVA PROGRAMMING ▪ PAGE 39


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

Flowchart of switch Statement

Example Activity 6.5: Java switch statement

class Main {
public static void main(String[] args) {

int week = 4;
String day;

// switch statement to check day


switch (week) {
case 1:
day = "Sunday";
break;
case 2:
day = "Monday";
break;
case 3:
day = "Tuesday";
break;

JAVA PROGRAMMING ▪ PAGE 40


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

// match the value of week


case 4:
day = "Wednesday";
break;
case 5:
day = "Thursday";
break;
case 6:
day = "Friday";
break;
case 7:
day = "Saturday";
break;
default:
day = "Invalid day";
break;
}
System.out.println("The day is " + day);
}
}

Output:

The day is Wednesday

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.

Example 6.6: Making Calculator using the switch statement

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;

// create an object of Scanner class


Scanner scanner = new Scanner(System.in);
System.out.print("Enter operator (either +, -, * or /): ");

// ask user to enter operator


operator = scanner.next().charAt(0);
System.out.print("Enter number1 and number2 respectively: ");

// ask user to enter numbers

JAVA PROGRAMMING ▪ PAGE 41


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

number1 = scanner.nextDouble();

number2 = scanner.nextDouble();

switch (operator) {

// performs addition between numbers


case '+':
result = number1 + number2;
System.out.print(number1 + "+" + number2 + " = " + result);
break;

// performs subtraction between numbers


case '-':
result = number1 - number2;
System.out.print(number1 + "-" + number2 + " = " + result);
break;

// performs multiplication between numbers


case '*':
result = number1 * number2;
System.out.print(number1 + "*" + number2 + " = " + result);
break;

// performs division between numbers


case '/':
result = number1 / number2;
System.out.print(number1 + "/" + number2 + " = " + result);
break;

default:
System.out.println("Invalid operator!");
break;
}
}
}

Output:

Enter operator (either +, -, * or /): *


Enter number1 and number2 respectively: 1.4
-5.3
1.4*-5.3 = -7.419999999999999

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.

JAVA PROGRAMMING ▪ PAGE 42


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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:

JAVA PROGRAMMING ▪ PAGE 43


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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

 Create all the example activities.

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.

In this chapter, we will discuss the different looping statements.

JAVA PROGRAMMING ▪ PAGE 44


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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.

Java for Loop


The syntax of for Loop in Java is:

for (initialization; testExpression; update)


{
// codes inside for loop's body
}

Working of for loop

1. The initialization expression is executed only once.


2. Then, the test expression is evaluated. Here, test expression is a boolean expression.
3. If the test expression is evaluated to true,
Codes inside the body of for loop is executed.
Then the update expression is executed.
Again, the test expression is evaluated.
If the test expression is true, codes inside the body of for loop is executed and update expression is executed.
This process goes on until the test expression is evaluated to false.
4. If the test expression is evaluated to false, for loop terminates.

for Loop Flowchart

JAVA PROGRAMMING ▪ PAGE 45


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

Example/Activity 7.1: for Loop

// Program to print a sentence 10 times

class Loop {
public static void main(String[] args) {

for (int i = 1; i <= 10; ++i) {


System.out.println("Line " + i);
}
}
}

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

 initialization expression: int i = 1.e


 test expression: i <=10
 update expression: ++i
Here, initially, the value of i is 1. So the test expression evaluates to true for the first time. Hence, the print statement is
executed. Now the update expression is evaluated.
Each time the update expression is evaluated, the value of i is increased by 1. Again, the test expression is evaluated. And,
the same process is repeated.
This process goes on until i is 11. When i is 11, the test expression (i <= 10) is false and the for loop terminates.
Example/Activity 7.2: for Loop

// Program to find the sum of natural numbers from 1 to 1000.

class Number {
public static void main(String[] args) {

int sum = 0;

for (int i = 1; i <= 1000; ++i) {


sum += i; // sum = sum + i
}

JAVA PROGRAMMING ▪ PAGE 46


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

System.out.println("Sum = " + sum);


}
}

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.

In each iteration of for loop,

 the sum variable is assigned value: sum + i


 the value of i is increased by 1
The loop continues until the value of i is greater then 1000. For better visualization,

1st iteration: i = 1 and sum = 0+1 = 1


2nd iteration: i = 2 and sum = 1+2 = 3
3rd iteration: i = 3 and sum = 3+3 = 6
4th iteration: i = 4 and sum = 6+4 = 10
... .. ...

999th iteration: i = 999 and sum = 498501 + 999 = 499500


1000th iteration: i = 1000 and sum = 499500 + 1000 = 500500

infinite for Loop


We should be always careful while working with loops. It is because if we mistakenly set test expression in such a
way that it is never false , the for loop will run forever.
This is called infinite for loop. For example,

// Infinite for Loop

class Infinite {
public static void main(String[] args) {

int sum = 0;

for (int i = 1; i <= 10; --i) {


System.out.println("Hello");
}
}
}

Here, the test expression ( i <= 10 ) is never false and hello is printed infinite number to times (at least in theory).

JAVA PROGRAMMING ▪ PAGE 47


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

Note: The initialization, update and test expression used in for statement is optional. Here's another example of the
infinite for loop.

for ( ; ; ) {

Java for-each Loop

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.

Difference between for loop and for-each loop

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) {

char[] vowels = {'a', 'e', 'i', 'o', 'u'};

for (int i = 0; i < vowels.length; ++ i) {


System.out.println(vowels[i]);
}
}
}

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) {

char[] vowels = {'a', 'e', 'i', 'o', 'u'};


// foreach loop
for (char item: vowels) {
System.out.println(item);
}
}
}

JAVA PROGRAMMING ▪ PAGE 48


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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.

Let's first look at the syntax of for each loop:

for(data_type item : collections) {


...
}

Here,

 collection - a collection or array that you have to loop through.


 item - a single item from the collections.

How for-each loop works?

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.

Example/Activity 7.3: for-each loop

The program below calculates the sum of all elements of an integer array.

class EnhancedForLoop {
public static void main(String[] args) {

int[] numbers = {3, 4, 5, -5, 0, 12};


int sum = 0;

for (int number: numbers) {


sum += number;
}

System.out.println("Sum = " + sum);


}
}

JAVA PROGRAMMING ▪ PAGE 49


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

Output:

Sum = 19

Explanation
In the above program, the execution of the for-each loop looks as:

Iteration Value

1 number = 3 and sum = 0 + 3 = 3

2 number = 4 and sum = 3 + 4 = 7

3 number = 5 and sum = 7 + 5 = 12

4 number = -5 and sum = 12 + (-5) = 7

5 number = 0 and sum = 7 + 0 = 7

6 number = 12 and sum = 7 + 12 = 19

You can see during each iteration, the for-each loop


 iterates through each element in the numbers array
 stores it in the number variable
 and executes the body, i.e. adds the number to sum.

Java while Loop


The syntax of while loop in Java is:

while (testExpression) {
// codes inside the body of while loop
}

How while loop works?


In the above syntax, the test expression inside parenthesis is a boolean expression. If the test expression is
evaluated to true ,
 statements inside the while loop are executed.
 then, the test expression is evaluated again.
 This process goes on until the test expression is evaluated to false . If the test expression is evaluated to false ,
 the while loop is terminated.

JAVA PROGRAMMING ▪ PAGE 50


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

Flowchart of while Loop

Example/Activity 7.4: while Loop

// Program to print line 10 times

class Loop {
public static void main(String[] args) {

int i = 1;

while (i <= 10) {


System.out.println("Line " + i);
++i;
}
}
}

Output:

Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10

Explanation

JAVA PROGRAMMING ▪ PAGE 51


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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.

Example/Activity 7.5: Java while Loop

// Program to find the sum of natural numbers from 1 to 100.

class AssignmentOperator {
public static void main(String[] args) {

int sum = 0, i = 100;

while (i != 0) {
sum += i; // sum = sum + i;
--i;
}

System.out.println("Sum = " + sum);


}
}

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,

1st iteration: i = 100, sum = 0+100 = 100, and --i = 99


2nd iteration: i = 99, sum = 100+99 = 199, and --i = 98
3rd iteration: i = 98, sum = 199+98 = 297, and --i = 97
... .. ...
... .. ...
99th iteration: i = 2, sum = 5047+2 = 5049, and --i = 1
100th iteration: i = 1, sum = 5049+1 = 5050, and --i = 0

JAVA PROGRAMMING ▪ PAGE 52


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

Java do...while Loop


The do...while loop is similar to while loop with one key difference. The body of do...while loop is executed for once
before the test expression is checked.
Here is the syntax of the do...while loop.

do {
// codes inside body of do while loop
} while (testExpression);

How do...while loop works?


The body of do...while loop is executed once (before checking the test expression). Only then, the test expression is
checked.
If the test expression is evaluated to true , codes inside the body of the loop are executed, and the test expression is
evaluated again. This process goes on until the test expression is evaluated to false .
When the test expression is false , the do..while loop terminates.
Flowchart of do...while Loop

Example/Activity 7.6: do...while Loop

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) {

Double number, sum = 0.0;


// creates an object of Scanner class
Scanner input = new Scanner(System.in);

do {

// takes input from the user

System.out.print("Enter a number: ");


number = input.nextDouble();

JAVA PROGRAMMING ▪ PAGE 53


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

sum += number;
} while (number != 0.0); // test expression

System.out.println("Sum = " + sum);


}
}

Output:

Enter a number: 2.5


Enter a number: 23.3
Enter a number: -4.2
Enter a number: 3.4
Enter a number: 0
Sum = 25.0

Infinite while Loop


We should be always careful while working with loops. It is because if we mistakenly set the test expression in such
a way that it is never false, the while and do...while loop will run forever.
This is called infinite while and do...while loop. For example,

// Infinite while loop


while (true) {
// body of while loop
}

Let's take another example,

// Infinite while loop


int i = 100;
while (i == 100) {
System.out.print("Hey!");
}

The infinite do...while loop works in a similar way as while loop.

Nested Loop in Java

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.

for (int i = 1; i <= 5; ++i) {

// codes inside the body of outer loop

for (int j = 1; j <=2; ++j) {


// codes inside the body of both outer and inner loop
}

// codes inside the body of outer loop


}

JAVA PROGRAMMING ▪ PAGE 54


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

Here, a for loop is inside the body another for loop.


It should be noted that you can put one type of loop inside the body of another type. For example, you can put
a while loop inside the body of a for loop.

Example/Activity 7.7: Java Nested for Loop

class NestedForLoop {
public static void main(String[] args) {

for (int i = 1; i <= 5; ++i) {

System.out.println("Outer loop iteration " + i);

for (int j = 1; j <=2; ++j) {


System.out.println("i = " + i + "; j = " + j);
}
}
}
}

Output:

Outer loop iteration 1


i = 1; j = 1
i = 1; j = 2
Outer loop iteration 2
i = 2; j = 1
i = 2; j = 2
Outer loop iteration 3
i = 3; j = 1
i = 3; j = 2
Outer loop iteration 4
i = 4; j = 1
i = 4; j = 2
Outer loop iteration 5
i = 5; j = 1
i = 5; j = 2

Here, the outer loop iterates 5 times. In each iteration of outer loop, the inner loop iterates 2 times.

Example/Activity 7.8: Java Nested Loop

class NestedLoop {
public static void main(String[] args) {

int i = 1;

while (i <= 5) {

System.out.println("Outer loop iteration " + i);

for (int j = 1; j <= 2; ++j) {


System.out.println("i = " + i + "; j = " + j);

JAVA PROGRAMMING ▪ PAGE 55


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

++i;
}
}
}

Output:

Outer loop iteration 1


i = 1; j = 1
i = 1; j = 2
Outer loop iteration 2
i = 2; j = 1
i = 2; j = 2
Outer loop iteration 3
i = 3; j = 1
i = 3; j = 2
Outer loop iteration 4
i = 4; j = 1
i = 4; j = 2
Outer loop iteration 5
i = 5; j = 1
i = 5; j = 2

Here you can see that the output of this program and above program is same.

Example/Activity 6.9: Program to create a pattern

1 2

1 2 3

1 2 3 4

1 2 3 4 5

Here is a program to create the above pattern using nested loops.

class Pattern {
public static void main(String[] args) {

int rows = 5;

for(int i = 1; i <= rows; ++i)


{
for(int j = 1; j <= i; ++j)
{
System.out.print(j + " ");
}

JAVA PROGRAMMING ▪ PAGE 56


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

System.out.println("");
}
}
}

Java break Statement

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;

How break statement works?

Example/Activity 7.9: Java break statement

class Test {
public static void main(String[] args) {

// for loop
for (int i = 1; i <= 10; ++i) {

// if the value of i is 5 the loop terminates


if (i == 5) {
break;
}
System.out.println(i);
}
}
}

JAVA PROGRAMMING ▪ PAGE 57


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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.

Example 7.10: Java break statement


The program below calculates the sum of numbers entered by the user until user enters a negative number.
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 UserInputSum {
public static void main(String[] args) {

Double number, sum = 0.0;

// create an object of Scanner


Scanner input = new Scanner(System.in);

while (true) {
System.out.print("Enter a number: ");

// takes double input from user


number = input.nextDouble();

// if number is negative the loop terminates


if (number < 0.0) {
break;
}

sum += number;
}
System.out.println("Sum = " + sum);
}
}

Output:

Enter a number: 3.2


Enter a number: 5
Enter a number: 2.3

JAVA PROGRAMMING ▪ PAGE 58


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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,

if (number < 0.0) {


break;
}

This means when the user input negative numbers, the while loop is terminated.

Java break and Nested Loop


In the case of nested loops, the break statement terminates the innermost loop.

Here, the break statement terminates the innermost while loop, and control jumps to the outer loop.

Labeled break Statement


Till now, we have used the unlabeled break statement. It terminates the innermost loop and switch statement.
However, there is another form of break statement in Java known as the labeled break.

We can use the labeled break statement to terminate the outermost loop as well.

JAVA PROGRAMMING ▪ PAGE 59


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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.

Example/Activity 7.11: labeled break Statement

class LabeledBreak {
public static void main(String[] args) {

// the for loop is labeled as first


first:
for( int i = 1; i < 5; i++) {

// the for loop is labeled as second


second:
for(int j = 1; j < 3; j ++ ) {
System.out.println("i = " + i + "; j = " +j);

JAVA PROGRAMMING ▪ PAGE 60


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

// the break statement breaks the first for loop


if ( i == 2)
break first;
}
}
}
}

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) {

// the for loop is labeled as first


first:

for( int i = 1; i < 5; i++) {

// the for loop is labeled as second


second:
for(int j = 1; j < 3; j ++ ) {

System.out.println("i = " + i + "; j = " +j);

// the break statement terminates the loop labeled as second


if ( i == 2)
break second;
}
}
}
}

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

JAVA PROGRAMMING ▪ PAGE 61


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

Java continue Statement

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;

How continue statement works?

Example/Activity 7.12: Java continue statement

class Test {
public static void main(String[] args) {

// for loop
for (int i = 1; i <= 10; ++i) {

// if value of i is between 4 and 9, continue is executed


if (i > 4 && i < 9) {
continue;
}
System.out.println(i);
}
}
}

Output:

JAVA PROGRAMMING ▪ PAGE 62


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

2
3
4
9
10

In the above program, we are using for loop to print the value of i in each iteration.

if (i > 5 && i < 9) {


continue;
}

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.13: 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. To learn more about Scanner , visit Java Scanner.

import java.util.Scanner;

class AssignmentOperator {
public static void main(String[] args) {

Double number, sum = 0.0;


// create an object of Scanner
Scanner input = new Scanner(System.in);

for (int i = 1; i < 6; ++i) {


System.out.print("Enter a number: ");
// takes double type input from the user
number = input.nextDouble();

// if number is negative, the iteration is skipped


if (number <= 0.0) {
continue;
}

sum += number;
}
System.out.println("Sum = " + sum);
}
}

Output:

Enter a number: 2.2


Enter a number: 5.6
Enter a number: 0
Enter a number: -2.4
Enter a number: -3

JAVA PROGRAMMING ▪ PAGE 63


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

Sum = 7.8

In the above program, notice the line,

if (number < 0.0) {


continue;
}

This means when the user input negative numbers, the current iteration of the loop is skipped. And the next
iteration is started.

Example/Activity 7.14: Java continue statement

class Test {
public static void main(String[] args) {

// for loop
for (int i = 1; i <= 10; ++i) {

// if value of i is between 4 and 9, continue is executed


if (i > 4 && i < 9) {
continue;
}
System.out.println(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,

if (i > 5 && i < 9) {


continue;
}

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.

JAVA PROGRAMMING ▪ PAGE 64


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

import java.util.Scanner;

class AssignmentOperator {
public static void main(String[] args) {

Double number, sum = 0.0;


// create an object of Scanner
Scanner input = new Scanner(System.in);

for (int i = 1; i < 6; ++i) {


System.out.print("Enter a number: ");

// takes double type input from the user


number = input.nextDouble();

// if number is negative, the iteration is skipped


if (number <= 0.0) {
continue;
}

sum += number;
}
System.out.println("Sum = " + sum);
}
}

Output:

Enter a number: 2.2


Enter a number: 5.6
Enter a number: 0
Enter a number: -2.4
Enter a number: -3
Sum = 7.8

In the above program, notice the line,

if (number < 0.0) {


continue;
}

This means when the user input negative numbers, the current iteration of the loop is skipped. And the next
iteration is started.

JAVA PROGRAMMING ▪ PAGE 65


Lemery Colleges, Inc.
A. Bonifacio St., Brgy. Bagong Sikat, Lemery, Batangas

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.
*
* *
* * *
* * * *
* * *
* *
*

JAVA PROGRAMMING ▪ PAGE 66

You might also like