SlideShare a Scribd company logo
Module 03 – Control Flow and
Exception Handling
Danairat T.
Line ID: Danairat
FB: Danairat Thanabodithammachari
+668-1559-1446
Fundamental Java Programming
The Course Outline
Module 01 – Introduction to Java
Module 02 – Basic Java Programming
Module 03 – Control Flow and Exception Handling
Module 04 – Object Oriented in Java
Module 05 – Java Package and Access Control
Module 06 – Java File IO
Module 07 – Java Networking
Module 08 – Java Threading
Module 03 – Control Flow and Exception Handling
‱ The if-then and if-then-else Statements
‱ The switch Statement
‱ The while and do-while Statements
‱ The for Statement
‱ Branching Statements
‱ Exception Handling
Control Flow Statements
The statements inside your source files are generally
executed from top to bottom, in the order that they appear.
Control flow statements break up the flow of execution by
employing decision making, looping, and branching,
enabling your program to conditionally execute particular
blocks of code.
The if-then Statement
void applyBrakes(){
if (isMoving){ // the "if" clause: bicycle must be moving
currentSpeed--; // the "then" clause: decrease current speed
}
}
The if-then-else Statement
void applyBrakes(){
if (isMoving) {
currentSpeed--;
} else {
System.err.println("The bicycle has already stopped!");
}
}
LAB - IfElseDemo
class IfElseDemo {
public static void main(String[] args) {
int testscore = 76;
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
LAB - SwitchDemo
A statement in the switch block can be labeled with one or more case or default labels with
break label.
public class SwitchDemo {
public static void main(String[] args) {
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January"; break;
case 2: monthString = "February"; break;
case 3: monthString = "March"; break;
case 4: monthString = "April"; break;
case 5: monthString = "May"; break;
case 6: monthString = "June"; break;
case 7: monthString = "July"; break;
case 8: monthString = "August"; break;
case 9: monthString = "September"; break;
case 10: monthString = "October"; break;
case 11: monthString = "November"; break;
case 12: monthString = "December"; break;
default: monthString = "Invalid month"; break;
}
System.out.println(monthString);
}
}
LAB - SwitchDemoFallThrough
A statement in the switch block can be labeled with one or more case or default labels with
break label.
public class SwitchDemoFallThrough {
public static void main(String args[]) {
java.util.ArrayList<String> futureMonths = new
java.util.ArrayList<String>();
int month = 8;
switch (month) {
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");
case 3: futureMonths.add("March");
case 4: futureMonths.add("April");
case 5: futureMonths.add("May");
case 6: futureMonths.add("June");
case 7: futureMonths.add("July");
case 8: futureMonths.add("August");
case 9: futureMonths.add("September");
case 10: futureMonths.add("October");
case 11: futureMonths.add("November");
case 12: futureMonths.add("December"); break;
default: break;
}
if (futureMonths.isEmpty()) {
System.out.println("Invalid month number");
} else {
for (String monthName : futureMonths) {
System.out.println(monthName);
}
}
}
}
August
September
October
November
December
LAB - SwitchDemo2
class SwitchDemo2 {
public static void main(String[] args) {
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if ( ((year % 4 == 0) && !(year % 100 == 0))
|| (year % 400 == 0) )
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = " + numDays);
}
}
Number of Days = 29
LAB - StringSwitchDemo
public class StringSwitchDemo {
public static int getMonthNumber(String month) {
int monthNumber = 0;
if (month == null) { return monthNumber; }
switch (month.toLowerCase()) {
case "january": monthNumber = 1; break;
case "february": monthNumber = 2; break;
case "march": monthNumber = 3; break;
case "april": monthNumber = 4; break;
case "may": monthNumber = 5; break;
case "june": monthNumber = 6; break;
case "july": monthNumber = 7; break;
case "august": monthNumber = 8; break;
case "september": monthNumber = 9; break;
case "october": monthNumber = 10; break;
case "november": monthNumber = 11; break;
case "december": monthNumber = 12; break;
default: monthNumber = 0; break;
}
return monthNumber;
}
public static void main(String[] args) {
String month = "August";
int returnedMonthNumber =
StringSwitchDemo.getMonthNumber(month);
if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
}
}
}
The output from this code is 8.
The while and do-while Statements
The while statement evaluates expression, which must return a
boolean value. If the expression evaluates to true, the while
statement executes the statement(s) in the while block. The while
statement continues testing the expression and executing its block
until the expression evaluates to false.
class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}
LAB – Do-While
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count <= 11);
}
}
The for Statement
The for statement provides a compact way to iterate over a
range of values.
class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
LAB - ForEachDemo
class ForEachDemo {
public static void main(String[] args){
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
The break Statement
The break statement has two forms: labeled and unlabeled.
You saw the unlabeled form in the previous discussion of
the switch statement. You can also use an unlabeled break
to terminate a for, while, or do-while loop
class BreakDemo {
public static void main(String[] args) {
int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,
2000, 8, 622, 127 };
int searchfor = 12;
int i;
boolean foundIt = false;
for (i = 0; i < arrayOfInts.length; i++) {
if (arrayOfInts[i] == searchfor) {
foundIt = true;
break;
}
}
if (foundIt) {
System.out.println("Found " + searchfor
+ " at index " + i);
} else {
System.out.println(searchfor
+ " not in the array");
}
}
} Found 12 at index 4
LAB - BreakWithLabelDemo
The following program, BreakWithLabelDemo, is similar to the previous program, but uses nested for loops to
search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop
(labeled "search"):
Found 12 at 1, 0
class BreakWithLabelDemo {
public static void main(String[] args) {
int[][] arrayOfInts = { { 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor +
" at " + i + ", " + j);
} else {
System.out.println(searchfor
+ " not in the array");
}
}
}
The continue Statement
The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled
form skips to the end of the innermost loop's body and evaluates the boolean expression that
controls the loop.
class ContinueDemo {
public static void main(String[] args) {
String searchMe = "peter piper picked a peck of pickled peppers";
int max = searchMe.length();
int numPs = 0;
for (int i = 0; i < max; i++) {
//interested only in p's
if (searchMe.charAt(i) != 'p')
continue;
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
}
Found 9 p's in the string.
LAB - ContinueWithLabelDemo
class ContinueWithLabelDemo {
public static void main(String[] args) {
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() - substring.length();
test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++)
!= substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" :
"Didn't find it");
}
}
A labeled continue statement skips the current iteration of an outer loop marked with the given label. The following example
program, ContinueWithLabelDemo, uses nested loops to search for a substring within another string. Two nested loops are
required: one to iterate over the substring and one to iterate over the string being searched. The following program,
ContinueWithLabelDemo, uses the labeled form of continue to skip an iteration in the outer loop.
Found it
The return Statement
The return statement has two forms: one that returns a value, and one that
doesn't. To return a value, simply put the value (or an expression that calculates
the value) after the return keyword.
return countResult;
The data type of the returned value must match the type of the method's declared
return value. When a method is declared void, use the form of return that doesn't
return a value.
return;
The Classes and Objects lesson will cover everything you need to know about
writing methods.
Java Exceptions Handling
When an error occurs within a method, the method creates an object and
hands it off to the runtime system. The object, called an exception object,
contains information about the error, including its type and the state of the
program when the error occurred. Creating an exception object and
handing it to the runtime system is called throwing an exception.
Method Call Exception Call
LAB - DivideException1
public class DivideException1 {
static int quotient = -1;
public static void main(String[] args) {
int result = division(100, 0); // Line 2
System.out.println("result : " + result);
}
public static int division(int totalSum, int totalNumber) {
System.out.println("Computing Division.");
try {
quotient = totalSum / totalNumber;
} catch (Exception e) {
System.out.println("Exception : " + e.getMessage());
} finally {
if (quotient != -1) {
System.out.println("Finally Block Executes");
System.out.println("Result : " + quotient);
} else {
System.out.println("Finally Block Executes. Exception Occurred");
}
}
return quotient;
}
}
Computing Division.
Exception : / by zero
Finally Block Executes. Exception Occurred
result : -1
LAB – DivideException2
public class DivideException2 {
static int quotient = -1;
public static void main(String[] args) {
try {
int result = division(100, 0); // Line 2
System.out.println("result : " + result);
} catch (Exception e) {
System.out.println("Exception : " + e.getMessage());
} finally {
if (quotient != -1) {
System.out.println("Finally Block Executes");
System.out.println("Result : " + quotient);
} else {
System.out.println("Finally Block Executes. Exception
Occurred");
}
}
}
public static int division(int totalSum,
int totalNumber) throws Exception {
System.out.println("Computing Division.");
quotient = totalSum / totalNumber;
return quotient;
}
}
Computing Division.
Exception : / by zero
Finally Block Executes.
Exception Occurred
Danairat T.
Line ID: Danairat
FB: Danairat Thanabodithammachari
+668-1559-1446
Thank you

More Related Content

What's hot (20)

PPTX
Java generics final
Akshay Chaudhari
 
PDF
Lambda Functions in Java 8
Ganesh Samarthyam
 
PPT
Java tut1
Ajmal Khan
 
PPT
Tutorial java
Abdul Aziz
 
PDF
Java programming-examples
Mumbai Academisc
 
PPTX
Unit 4 exceptions and threads
DevaKumari Vijay
 
PDF
Java Simple Programs
Upender Upr
 
PDF
Java programs
Mukund Gandrakota
 
PPTX
Java Programs
vvpadhu
 
ODP
Java Generics
Carol McDonald
 
PPT
Effective Java - Generics
Roshan Deniyage
 
PDF
Java Concurrency by Example
Ganesh Samarthyam
 
PPTX
Lecture - 3 Variables-data type_operators_oops concept
manish kumar
 
PDF
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
ODP
Java Concurrency
Carol McDonald
 
PDF
On Parameterised Types and Java Generics
Yann-Gaël Guéhéneuc
 
PDF
Java ppt Gandhi Ravi ([email protected])
Gandhi Ravi
 
PDF
Advanced Java Practical File
Soumya Behera
 
PDF
Java Programming - 06 java file io
Danairat Thanabodithammachari
 
Java generics final
Akshay Chaudhari
 
Lambda Functions in Java 8
Ganesh Samarthyam
 
Java tut1
Ajmal Khan
 
Tutorial java
Abdul Aziz
 
Java programming-examples
Mumbai Academisc
 
Unit 4 exceptions and threads
DevaKumari Vijay
 
Java Simple Programs
Upender Upr
 
Java programs
Mukund Gandrakota
 
Java Programs
vvpadhu
 
Java Generics
Carol McDonald
 
Effective Java - Generics
Roshan Deniyage
 
Java Concurrency by Example
Ganesh Samarthyam
 
Lecture - 3 Variables-data type_operators_oops concept
manish kumar
 
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
Java Concurrency
Carol McDonald
 
On Parameterised Types and Java Generics
Yann-Gaël Guéhéneuc
 
Java ppt Gandhi Ravi ([email protected])
Gandhi Ravi
 
Advanced Java Practical File
Soumya Behera
 
Java Programming - 06 java file io
Danairat Thanabodithammachari
 

Viewers also liked (20)

PDF
Modul6 1225443461187631-8
aan_junior147
 
ZIP
Introduction to the Java(TM) Advanced Imaging API
white paper
 
PPT
C0 review core java1
tam53pm1
 
PPT
Chapter 4 Powerpoint
Gus Sandoval
 
PPT
Eo gaddis java_chapter_02_5e
Gina Bullock
 
PPT
Java basic
Arati Gadgil
 
PPTX
Module 03
danpeterson11
 
PDF
Seri Belajar Mandiri – Pemrograman Java Untuk Pemula
Agus Kurniawan
 
PPTX
Module 03 searching and seizing computers
sagaroceanic11
 
DOCX
contoh Program sederhana Java dan penjelasan programnya
stephan EL'wiin Shaarawy
 
PDF
Java Programming - 01 intro to java
Danairat Thanabodithammachari
 
PPTX
Control flow statements in java
yugandhar vadlamudi
 
PPTX
Datacom module 3: Data Communications Circuits, Arrangements, and Networks
Jeffrey Des Binwag
 
PDF
02 basic java programming and operators
Danairat Thanabodithammachari
 
PDF
JEE Programming - 03 Model View Controller
Danairat Thanabodithammachari
 
PPTX
Sektor ng agrikultura
aidacomia11
 
PPT
Sektor ng agrikultura
Mark Joseph Hao
 
PDF
03. prak.-pemrograman-visual-i-vb.net
Ayu Karisma Alfiana
 
PPTX
Network topology.ppt
Siddique Ibrahim
 
PDF
Cehv8 module 01 introduction to ethical hacking
polichen
 
Modul6 1225443461187631-8
aan_junior147
 
Introduction to the Java(TM) Advanced Imaging API
white paper
 
C0 review core java1
tam53pm1
 
Chapter 4 Powerpoint
Gus Sandoval
 
Eo gaddis java_chapter_02_5e
Gina Bullock
 
Java basic
Arati Gadgil
 
Module 03
danpeterson11
 
Seri Belajar Mandiri – Pemrograman Java Untuk Pemula
Agus Kurniawan
 
Module 03 searching and seizing computers
sagaroceanic11
 
contoh Program sederhana Java dan penjelasan programnya
stephan EL'wiin Shaarawy
 
Java Programming - 01 intro to java
Danairat Thanabodithammachari
 
Control flow statements in java
yugandhar vadlamudi
 
Datacom module 3: Data Communications Circuits, Arrangements, and Networks
Jeffrey Des Binwag
 
02 basic java programming and operators
Danairat Thanabodithammachari
 
JEE Programming - 03 Model View Controller
Danairat Thanabodithammachari
 
Sektor ng agrikultura
aidacomia11
 
Sektor ng agrikultura
Mark Joseph Hao
 
03. prak.-pemrograman-visual-i-vb.net
Ayu Karisma Alfiana
 
Network topology.ppt
Siddique Ibrahim
 
Cehv8 module 01 introduction to ethical hacking
polichen
 
Ad

Similar to Java Programming - 03 java control flow (20)

PPT
4.CONTROL STATEMENTS_MB.ppt .
happycocoman
 
PPTX
Pj01 5-exceution control flow
SasidharaRaoMarrapu
 
PPT
05. Control Structures.ppt
AyushDut
 
PDF
Control structures in Java
Ravi_Kant_Sahu
 
PPTX
control statements
Azeem Sultan
 
PPTX
DAY_1.2.pptx
ishasharma835109
 
PDF
Java chapter 5
Mukesh Tekwani
 
PPTX
Control statements in java
Madishetty Prathibha
 
PDF
9-java language basics part3
Amr Elghadban (AmrAngry)
 
PPT
Control statements
raksharao
 
PPTX
07 flow control
dhrubo kayal
 
PDF
Control flow statements in java web applications
RajithKarunarathne1
 
PDF
how to write loops in java explained vividly
shadtarq07
 
PPTX
Java chapter 3
Abdii Rashid
 
PPTX
130706266060138191
Tanzeel Ahmad
 
PDF
Android Application Development - Level 3
Isham Rashik
 
PPTX
controlStatement.pptx, CONTROL STATEMENTS IN JAVA
DrNeetuSharma5
 
PPT
Control statements in java programmng
Savitribai Phule Pune University
 
PPT
6_A1944859510_21789_2_2018_06. Branching Statements.ppt
RithwikRanjan
 
PDF
C sharp chap4
Mukesh Tekwani
 
4.CONTROL STATEMENTS_MB.ppt .
happycocoman
 
Pj01 5-exceution control flow
SasidharaRaoMarrapu
 
05. Control Structures.ppt
AyushDut
 
Control structures in Java
Ravi_Kant_Sahu
 
control statements
Azeem Sultan
 
DAY_1.2.pptx
ishasharma835109
 
Java chapter 5
Mukesh Tekwani
 
Control statements in java
Madishetty Prathibha
 
9-java language basics part3
Amr Elghadban (AmrAngry)
 
Control statements
raksharao
 
07 flow control
dhrubo kayal
 
Control flow statements in java web applications
RajithKarunarathne1
 
how to write loops in java explained vividly
shadtarq07
 
Java chapter 3
Abdii Rashid
 
130706266060138191
Tanzeel Ahmad
 
Android Application Development - Level 3
Isham Rashik
 
controlStatement.pptx, CONTROL STATEMENTS IN JAVA
DrNeetuSharma5
 
Control statements in java programmng
Savitribai Phule Pune University
 
6_A1944859510_21789_2_2018_06. Branching Statements.ppt
RithwikRanjan
 
C sharp chap4
Mukesh Tekwani
 
Ad

More from Danairat Thanabodithammachari (20)

PDF
Thailand State Enterprise - Business Architecture and SE-AM
Danairat Thanabodithammachari
 
PDF
Agile Management
Danairat Thanabodithammachari
 
PDF
Agile Organization and Enterprise Architecture v1129 Danairat
Danairat Thanabodithammachari
 
PDF
Blockchain for Management
Danairat Thanabodithammachari
 
PDF
Enterprise Architecture and Agile Organization Management v1076 Danairat
Danairat Thanabodithammachari
 
PDF
Agile Enterprise Architecture - Danairat
Danairat Thanabodithammachari
 
PDF
Digital Transformation, Enterprise Architecture, Big Data by Danairat
Danairat Thanabodithammachari
 
PDF
Big data Hadoop Analytic and Data warehouse comparison guide
Danairat Thanabodithammachari
 
PDF
Big data hadooop analytic and data warehouse comparison guide
Danairat Thanabodithammachari
 
PDF
Perl for System Automation - 01 Advanced File Processing
Danairat Thanabodithammachari
 
PDF
Perl Programming - 04 Programming Database
Danairat Thanabodithammachari
 
PDF
Perl Programming - 03 Programming File
Danairat Thanabodithammachari
 
PDF
Perl Programming - 02 Regular Expression
Danairat Thanabodithammachari
 
PDF
Perl Programming - 01 Basic Perl
Danairat Thanabodithammachari
 
PDF
Setting up Hadoop YARN Clustering
Danairat Thanabodithammachari
 
PDF
JEE Programming - 05 JSP
Danairat Thanabodithammachari
 
PDF
JEE Programming - 04 Java Servlets
Danairat Thanabodithammachari
 
PDF
JEE Programming - 08 Enterprise Application Deployment
Danairat Thanabodithammachari
 
PDF
JEE Programming - 07 EJB Programming
Danairat Thanabodithammachari
 
PDF
JEE Programming - 06 Web Application Deployment
Danairat Thanabodithammachari
 
Thailand State Enterprise - Business Architecture and SE-AM
Danairat Thanabodithammachari
 
Agile Management
Danairat Thanabodithammachari
 
Agile Organization and Enterprise Architecture v1129 Danairat
Danairat Thanabodithammachari
 
Blockchain for Management
Danairat Thanabodithammachari
 
Enterprise Architecture and Agile Organization Management v1076 Danairat
Danairat Thanabodithammachari
 
Agile Enterprise Architecture - Danairat
Danairat Thanabodithammachari
 
Digital Transformation, Enterprise Architecture, Big Data by Danairat
Danairat Thanabodithammachari
 
Big data Hadoop Analytic and Data warehouse comparison guide
Danairat Thanabodithammachari
 
Big data hadooop analytic and data warehouse comparison guide
Danairat Thanabodithammachari
 
Perl for System Automation - 01 Advanced File Processing
Danairat Thanabodithammachari
 
Perl Programming - 04 Programming Database
Danairat Thanabodithammachari
 
Perl Programming - 03 Programming File
Danairat Thanabodithammachari
 
Perl Programming - 02 Regular Expression
Danairat Thanabodithammachari
 
Perl Programming - 01 Basic Perl
Danairat Thanabodithammachari
 
Setting up Hadoop YARN Clustering
Danairat Thanabodithammachari
 
JEE Programming - 05 JSP
Danairat Thanabodithammachari
 
JEE Programming - 04 Java Servlets
Danairat Thanabodithammachari
 
JEE Programming - 08 Enterprise Application Deployment
Danairat Thanabodithammachari
 
JEE Programming - 07 EJB Programming
Danairat Thanabodithammachari
 
JEE Programming - 06 Web Application Deployment
Danairat Thanabodithammachari
 

Recently uploaded (20)

PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PDF
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 

Java Programming - 03 java control flow

  • 1. Module 03 – Control Flow and Exception Handling Danairat T. Line ID: Danairat FB: Danairat Thanabodithammachari +668-1559-1446
  • 2. Fundamental Java Programming The Course Outline Module 01 – Introduction to Java Module 02 – Basic Java Programming Module 03 – Control Flow and Exception Handling Module 04 – Object Oriented in Java Module 05 – Java Package and Access Control Module 06 – Java File IO Module 07 – Java Networking Module 08 – Java Threading
  • 3. Module 03 – Control Flow and Exception Handling ‱ The if-then and if-then-else Statements ‱ The switch Statement ‱ The while and do-while Statements ‱ The for Statement ‱ Branching Statements ‱ Exception Handling
  • 4. Control Flow Statements The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code.
  • 5. The if-then Statement void applyBrakes(){ if (isMoving){ // the "if" clause: bicycle must be moving currentSpeed--; // the "then" clause: decrease current speed } }
  • 6. The if-then-else Statement void applyBrakes(){ if (isMoving) { currentSpeed--; } else { System.err.println("The bicycle has already stopped!"); } }
  • 7. LAB - IfElseDemo class IfElseDemo { public static void main(String[] args) { int testscore = 76; char grade; if (testscore >= 90) { grade = 'A'; } else if (testscore >= 80) { grade = 'B'; } else if (testscore >= 70) { grade = 'C'; } else if (testscore >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Grade = " + grade); } }
  • 8. LAB - SwitchDemo A statement in the switch block can be labeled with one or more case or default labels with break label. public class SwitchDemo { public static void main(String[] args) { int month = 8; String monthString; switch (month) { case 1: monthString = "January"; break; case 2: monthString = "February"; break; case 3: monthString = "March"; break; case 4: monthString = "April"; break; case 5: monthString = "May"; break; case 6: monthString = "June"; break; case 7: monthString = "July"; break; case 8: monthString = "August"; break; case 9: monthString = "September"; break; case 10: monthString = "October"; break; case 11: monthString = "November"; break; case 12: monthString = "December"; break; default: monthString = "Invalid month"; break; } System.out.println(monthString); } }
  • 9. LAB - SwitchDemoFallThrough A statement in the switch block can be labeled with one or more case or default labels with break label. public class SwitchDemoFallThrough { public static void main(String args[]) { java.util.ArrayList<String> futureMonths = new java.util.ArrayList<String>(); int month = 8; switch (month) { case 1: futureMonths.add("January"); case 2: futureMonths.add("February"); case 3: futureMonths.add("March"); case 4: futureMonths.add("April"); case 5: futureMonths.add("May"); case 6: futureMonths.add("June"); case 7: futureMonths.add("July"); case 8: futureMonths.add("August"); case 9: futureMonths.add("September"); case 10: futureMonths.add("October"); case 11: futureMonths.add("November"); case 12: futureMonths.add("December"); break; default: break; } if (futureMonths.isEmpty()) { System.out.println("Invalid month number"); } else { for (String monthName : futureMonths) { System.out.println(monthName); } } } } August September October November December
  • 10. LAB - SwitchDemo2 class SwitchDemo2 { public static void main(String[] args) { int month = 2; int year = 2000; int numDays = 0; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numDays = 31; break; case 4: case 6: case 9: case 11: numDays = 30; break; case 2: if ( ((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0) ) numDays = 29; else numDays = 28; break; default: System.out.println("Invalid month."); break; } System.out.println("Number of Days = " + numDays); } } Number of Days = 29
  • 11. LAB - StringSwitchDemo public class StringSwitchDemo { public static int getMonthNumber(String month) { int monthNumber = 0; if (month == null) { return monthNumber; } switch (month.toLowerCase()) { case "january": monthNumber = 1; break; case "february": monthNumber = 2; break; case "march": monthNumber = 3; break; case "april": monthNumber = 4; break; case "may": monthNumber = 5; break; case "june": monthNumber = 6; break; case "july": monthNumber = 7; break; case "august": monthNumber = 8; break; case "september": monthNumber = 9; break; case "october": monthNumber = 10; break; case "november": monthNumber = 11; break; case "december": monthNumber = 12; break; default: monthNumber = 0; break; } return monthNumber; } public static void main(String[] args) { String month = "August"; int returnedMonthNumber = StringSwitchDemo.getMonthNumber(month); if (returnedMonthNumber == 0) { System.out.println("Invalid month"); } else { System.out.println(returnedMonthNumber); } } } The output from this code is 8.
  • 12. The while and do-while Statements The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false. class WhileDemo { public static void main(String[] args){ int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } } }
  • 13. LAB – Do-While class DoWhileDemo { public static void main(String[] args){ int count = 1; do { System.out.println("Count is: " + count); count++; } while (count <= 11); } }
  • 14. The for Statement The for statement provides a compact way to iterate over a range of values. class ForDemo { public static void main(String[] args){ for(int i=1; i<11; i++){ System.out.println("Count is: " + i); } } } Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count is: 10
  • 15. LAB - ForEachDemo class ForEachDemo { public static void main(String[] args){ int[] numbers = {1,2,3,4,5,6,7,8,9,10}; for (int item : numbers) { System.out.println("Count is: " + item); } } } Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count is: 10
  • 16. The break Statement The break statement has two forms: labeled and unlabeled. You saw the unlabeled form in the previous discussion of the switch statement. You can also use an unlabeled break to terminate a for, while, or do-while loop class BreakDemo { public static void main(String[] args) { int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 }; int searchfor = 12; int i; boolean foundIt = false; for (i = 0; i < arrayOfInts.length; i++) { if (arrayOfInts[i] == searchfor) { foundIt = true; break; } } if (foundIt) { System.out.println("Found " + searchfor + " at index " + i); } else { System.out.println(searchfor + " not in the array"); } } } Found 12 at index 4
  • 17. LAB - BreakWithLabelDemo The following program, BreakWithLabelDemo, is similar to the previous program, but uses nested for loops to search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop (labeled "search"): Found 12 at 1, 0 class BreakWithLabelDemo { public static void main(String[] args) { int[][] arrayOfInts = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 }, { 622, 127, 77, 955 } }; int searchfor = 12; int i; int j = 0; boolean foundIt = false; search: for (i = 0; i < arrayOfInts.length; i++) { for (j = 0; j < arrayOfInts[i].length; j++) { if (arrayOfInts[i][j] == searchfor) { foundIt = true; break search; } } } if (foundIt) { System.out.println("Found " + searchfor + " at " + i + ", " + j); } else { System.out.println(searchfor + " not in the array"); } } }
  • 18. The continue Statement The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. class ContinueDemo { public static void main(String[] args) { String searchMe = "peter piper picked a peck of pickled peppers"; int max = searchMe.length(); int numPs = 0; for (int i = 0; i < max; i++) { //interested only in p's if (searchMe.charAt(i) != 'p') continue; numPs++; } System.out.println("Found " + numPs + " p's in the string."); } } Found 9 p's in the string.
  • 19. LAB - ContinueWithLabelDemo class ContinueWithLabelDemo { public static void main(String[] args) { String searchMe = "Look for a substring in me"; String substring = "sub"; boolean foundIt = false; int max = searchMe.length() - substring.length(); test: for (int i = 0; i <= max; i++) { int n = substring.length(); int j = i; int k = 0; while (n-- != 0) { if (searchMe.charAt(j++) != substring.charAt(k++)) { continue test; } } foundIt = true; break test; } System.out.println(foundIt ? "Found it" : "Didn't find it"); } } A labeled continue statement skips the current iteration of an outer loop marked with the given label. The following example program, ContinueWithLabelDemo, uses nested loops to search for a substring within another string. Two nested loops are required: one to iterate over the substring and one to iterate over the string being searched. The following program, ContinueWithLabelDemo, uses the labeled form of continue to skip an iteration in the outer loop. Found it
  • 20. The return Statement The return statement has two forms: one that returns a value, and one that doesn't. To return a value, simply put the value (or an expression that calculates the value) after the return keyword. return countResult; The data type of the returned value must match the type of the method's declared return value. When a method is declared void, use the form of return that doesn't return a value. return; The Classes and Objects lesson will cover everything you need to know about writing methods.
  • 21. Java Exceptions Handling When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception. Method Call Exception Call
  • 22. LAB - DivideException1 public class DivideException1 { static int quotient = -1; public static void main(String[] args) { int result = division(100, 0); // Line 2 System.out.println("result : " + result); } public static int division(int totalSum, int totalNumber) { System.out.println("Computing Division."); try { quotient = totalSum / totalNumber; } catch (Exception e) { System.out.println("Exception : " + e.getMessage()); } finally { if (quotient != -1) { System.out.println("Finally Block Executes"); System.out.println("Result : " + quotient); } else { System.out.println("Finally Block Executes. Exception Occurred"); } } return quotient; } } Computing Division. Exception : / by zero Finally Block Executes. Exception Occurred result : -1
  • 23. LAB – DivideException2 public class DivideException2 { static int quotient = -1; public static void main(String[] args) { try { int result = division(100, 0); // Line 2 System.out.println("result : " + result); } catch (Exception e) { System.out.println("Exception : " + e.getMessage()); } finally { if (quotient != -1) { System.out.println("Finally Block Executes"); System.out.println("Result : " + quotient); } else { System.out.println("Finally Block Executes. Exception Occurred"); } } } public static int division(int totalSum, int totalNumber) throws Exception { System.out.println("Computing Division."); quotient = totalSum / totalNumber; return quotient; } } Computing Division. Exception : / by zero Finally Block Executes. Exception Occurred
  • 24. Danairat T. Line ID: Danairat FB: Danairat Thanabodithammachari +668-1559-1446 Thank you