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)

Java generics final
Java generics finalJava generics final
Java generics final
Akshay Chaudhari
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
Ganesh Samarthyam
 
Java tut1
Java tut1Java tut1
Java tut1
Ajmal Khan
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
Abdul Aziz
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
Mumbai Academisc
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
SRM Institute of Science & Technology, Tiruchirappalli
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
DevaKumari Vijay
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
Upender Upr
 
Java programs
Java programsJava programs
Java programs
Mukund Gandrakota
 
Java Programs
Java ProgramsJava Programs
Java Programs
vvpadhu
 
Java Generics
Java GenericsJava Generics
Java Generics
Carol McDonald
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - Generics
Roshan Deniyage
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
Ganesh Samarthyam
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
manish kumar
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
Carol McDonald
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java Generics
Yann-Gaël Guéhéneuc
 
Java ppt Gandhi Ravi ([email protected])
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi ([email protected])
Gandhi Ravi
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 
Java Programming - 06 java file io
Java Programming - 06 java file ioJava Programming - 06 java file io
Java Programming - 06 java file io
Danairat Thanabodithammachari
 

Viewers also liked (20)

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

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

4.CONTROL STATEMENTS_MB.ppt .
4.CONTROL STATEMENTS_MB.ppt                 .4.CONTROL STATEMENTS_MB.ppt                 .
4.CONTROL STATEMENTS_MB.ppt .
happycocoman
 
Pj01 5-exceution control flow
Pj01 5-exceution control flowPj01 5-exceution control flow
Pj01 5-exceution control flow
SasidharaRaoMarrapu
 
05. Control Structures.ppt
05. Control Structures.ppt05. Control Structures.ppt
05. Control Structures.ppt
AyushDut
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
Ravi_Kant_Sahu
 
control statements
control statementscontrol statements
control statements
Azeem Sultan
 
DAY_1.2.pptx
DAY_1.2.pptxDAY_1.2.pptx
DAY_1.2.pptx
ishasharma835109
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
Mukesh Tekwani
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
Madishetty Prathibha
 
9-java language basics part3
9-java language basics part39-java language basics part3
9-java language basics part3
Amr Elghadban (AmrAngry)
 
Control statements
Control statementsControl statements
Control statements
raksharao
 
07 flow control
07   flow control07   flow control
07 flow control
dhrubo kayal
 
Control flow statements in java web applications
Control flow statements in java web applicationsControl flow statements in java web applications
Control flow statements in java web applications
RajithKarunarathne1
 
Java chapter 3
Java chapter 3Java chapter 3
Java chapter 3
Abdii Rashid
 
130706266060138191
130706266060138191130706266060138191
130706266060138191
Tanzeel Ahmad
 
Android Application Development - Level 3
Android Application Development - Level 3Android Application Development - Level 3
Android Application Development - Level 3
Isham Rashik
 
controlStatement.pptx, CONTROL STATEMENTS IN JAVA
controlStatement.pptx, CONTROL STATEMENTS IN JAVAcontrolStatement.pptx, CONTROL STATEMENTS IN JAVA
controlStatement.pptx, CONTROL STATEMENTS IN JAVA
DrNeetuSharma5
 
Control statements in java programmng
Control statements in java programmngControl statements in java programmng
Control statements in java programmng
Savitribai Phule Pune University
 
6_A1944859510_21789_2_2018_06. Branching Statements.ppt
6_A1944859510_21789_2_2018_06. Branching Statements.ppt6_A1944859510_21789_2_2018_06. Branching Statements.ppt
6_A1944859510_21789_2_2018_06. Branching Statements.ppt
RithwikRanjan
 
C sharp chap4
C sharp chap4C sharp chap4
C sharp chap4
Mukesh Tekwani
 
java notes.pdf
java notes.pdfjava notes.pdf
java notes.pdf
RajkumarHarishchandr1
 
4.CONTROL STATEMENTS_MB.ppt .
4.CONTROL STATEMENTS_MB.ppt                 .4.CONTROL STATEMENTS_MB.ppt                 .
4.CONTROL STATEMENTS_MB.ppt .
happycocoman
 
05. Control Structures.ppt
05. Control Structures.ppt05. Control Structures.ppt
05. Control Structures.ppt
AyushDut
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
Ravi_Kant_Sahu
 
control statements
control statementscontrol statements
control statements
Azeem Sultan
 
Control statements
Control statementsControl statements
Control statements
raksharao
 
Control flow statements in java web applications
Control flow statements in java web applicationsControl flow statements in java web applications
Control flow statements in java web applications
RajithKarunarathne1
 
Android Application Development - Level 3
Android Application Development - Level 3Android Application Development - Level 3
Android Application Development - Level 3
Isham Rashik
 
controlStatement.pptx, CONTROL STATEMENTS IN JAVA
controlStatement.pptx, CONTROL STATEMENTS IN JAVAcontrolStatement.pptx, CONTROL STATEMENTS IN JAVA
controlStatement.pptx, CONTROL STATEMENTS IN JAVA
DrNeetuSharma5
 
6_A1944859510_21789_2_2018_06. Branching Statements.ppt
6_A1944859510_21789_2_2018_06. Branching Statements.ppt6_A1944859510_21789_2_2018_06. Branching Statements.ppt
6_A1944859510_21789_2_2018_06. Branching Statements.ppt
RithwikRanjan
 
Ad

More from Danairat Thanabodithammachari (20)

Thailand State Enterprise - Business Architecture and SE-AM
Thailand State Enterprise - Business Architecture and SE-AMThailand State Enterprise - Business Architecture and SE-AM
Thailand State Enterprise - Business Architecture and SE-AM
Danairat Thanabodithammachari
 
Agile Management
Agile ManagementAgile Management
Agile Management
Danairat Thanabodithammachari
 
Agile Organization and Enterprise Architecture v1129 Danairat
Agile Organization and Enterprise Architecture v1129 DanairatAgile Organization and Enterprise Architecture v1129 Danairat
Agile Organization and Enterprise Architecture v1129 Danairat
Danairat Thanabodithammachari
 
Blockchain for Management
Blockchain for ManagementBlockchain for Management
Blockchain for Management
Danairat Thanabodithammachari
 
Enterprise Architecture and Agile Organization Management v1076 Danairat
Enterprise Architecture and Agile Organization Management v1076 DanairatEnterprise Architecture and Agile Organization Management v1076 Danairat
Enterprise Architecture and Agile Organization Management v1076 Danairat
Danairat Thanabodithammachari
 
Agile Enterprise Architecture - Danairat
Agile Enterprise Architecture - DanairatAgile Enterprise Architecture - Danairat
Agile Enterprise Architecture - Danairat
Danairat Thanabodithammachari
 
Digital Transformation, Enterprise Architecture, Big Data by Danairat
Digital Transformation, Enterprise Architecture, Big Data by DanairatDigital Transformation, Enterprise Architecture, Big Data by Danairat
Digital Transformation, Enterprise Architecture, Big Data by Danairat
Danairat Thanabodithammachari
 
Big data Hadoop Analytic and Data warehouse comparison guide
Big data Hadoop Analytic and Data warehouse comparison guideBig data Hadoop Analytic and Data warehouse comparison guide
Big data Hadoop Analytic and Data warehouse comparison guide
Danairat Thanabodithammachari
 
Big data hadooop analytic and data warehouse comparison guide
Big data hadooop analytic and data warehouse comparison guideBig data hadooop analytic and data warehouse comparison guide
Big data hadooop analytic and data warehouse comparison guide
Danairat Thanabodithammachari
 
Perl for System Automation - 01 Advanced File Processing
Perl for System Automation - 01 Advanced File ProcessingPerl for System Automation - 01 Advanced File Processing
Perl for System Automation - 01 Advanced File Processing
Danairat Thanabodithammachari
 
Perl Programming - 04 Programming Database
Perl Programming - 04 Programming DatabasePerl Programming - 04 Programming Database
Perl Programming - 04 Programming Database
Danairat Thanabodithammachari
 
Perl Programming - 03 Programming File
Perl Programming - 03 Programming FilePerl Programming - 03 Programming File
Perl Programming - 03 Programming File
Danairat Thanabodithammachari
 
Perl Programming - 02 Regular Expression
Perl Programming - 02 Regular ExpressionPerl Programming - 02 Regular Expression
Perl Programming - 02 Regular Expression
Danairat Thanabodithammachari
 
Perl Programming - 01 Basic Perl
Perl Programming - 01 Basic PerlPerl Programming - 01 Basic Perl
Perl Programming - 01 Basic Perl
Danairat Thanabodithammachari
 
Setting up Hadoop YARN Clustering
Setting up Hadoop YARN ClusteringSetting up Hadoop YARN Clustering
Setting up Hadoop YARN Clustering
Danairat Thanabodithammachari
 
JEE Programming - 05 JSP
JEE Programming - 05 JSPJEE Programming - 05 JSP
JEE Programming - 05 JSP
Danairat Thanabodithammachari
 
JEE Programming - 04 Java Servlets
JEE Programming - 04 Java ServletsJEE Programming - 04 Java Servlets
JEE Programming - 04 Java Servlets
Danairat Thanabodithammachari
 
JEE Programming - 08 Enterprise Application Deployment
JEE Programming - 08 Enterprise Application DeploymentJEE Programming - 08 Enterprise Application Deployment
JEE Programming - 08 Enterprise Application Deployment
Danairat Thanabodithammachari
 
JEE Programming - 07 EJB Programming
JEE Programming - 07 EJB ProgrammingJEE Programming - 07 EJB Programming
JEE Programming - 07 EJB Programming
Danairat Thanabodithammachari
 
JEE Programming - 06 Web Application Deployment
JEE Programming - 06 Web Application DeploymentJEE Programming - 06 Web Application Deployment
JEE Programming - 06 Web Application Deployment
Danairat Thanabodithammachari
 
Thailand State Enterprise - Business Architecture and SE-AM
Thailand State Enterprise - Business Architecture and SE-AMThailand State Enterprise - Business Architecture and SE-AM
Thailand State Enterprise - Business Architecture and SE-AM
Danairat Thanabodithammachari
 
Agile Organization and Enterprise Architecture v1129 Danairat
Agile Organization and Enterprise Architecture v1129 DanairatAgile Organization and Enterprise Architecture v1129 Danairat
Agile Organization and Enterprise Architecture v1129 Danairat
Danairat Thanabodithammachari
 
Enterprise Architecture and Agile Organization Management v1076 Danairat
Enterprise Architecture and Agile Organization Management v1076 DanairatEnterprise Architecture and Agile Organization Management v1076 Danairat
Enterprise Architecture and Agile Organization Management v1076 Danairat
Danairat Thanabodithammachari
 
Digital Transformation, Enterprise Architecture, Big Data by Danairat
Digital Transformation, Enterprise Architecture, Big Data by DanairatDigital Transformation, Enterprise Architecture, Big Data by Danairat
Digital Transformation, Enterprise Architecture, Big Data by Danairat
Danairat Thanabodithammachari
 
Big data Hadoop Analytic and Data warehouse comparison guide
Big data Hadoop Analytic and Data warehouse comparison guideBig data Hadoop Analytic and Data warehouse comparison guide
Big data Hadoop Analytic and Data warehouse comparison guide
Danairat Thanabodithammachari
 
Big data hadooop analytic and data warehouse comparison guide
Big data hadooop analytic and data warehouse comparison guideBig data hadooop analytic and data warehouse comparison guide
Big data hadooop analytic and data warehouse comparison guide
Danairat Thanabodithammachari
 
Perl for System Automation - 01 Advanced File Processing
Perl for System Automation - 01 Advanced File ProcessingPerl for System Automation - 01 Advanced File Processing
Perl for System Automation - 01 Advanced File Processing
Danairat Thanabodithammachari
 
JEE Programming - 08 Enterprise Application Deployment
JEE Programming - 08 Enterprise Application DeploymentJEE Programming - 08 Enterprise Application Deployment
JEE Programming - 08 Enterprise Application Deployment
Danairat Thanabodithammachari
 

Recently uploaded (20)

Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Integrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FMEIntegrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FME
Safe Software
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
Migrating to Azure Cosmos DB the Right Way
Migrating to Azure Cosmos DB the Right WayMigrating to Azure Cosmos DB the Right Way
Migrating to Azure Cosmos DB the Right Way
Alexander (Alex) Komyagin
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage OverlookCode and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Integrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FMEIntegrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FME
Safe Software
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage OverlookCode and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 

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