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

PDF
Java Programming - 04 object oriented in java
PPTX
Migrating to JUnit 5
PPTX
Unit testing concurrent code
PDF
Java Fundamentals
PPT
Java tut1 Coderdojo Cahersiveen
PPTX
Lecture - 5 Control Statement
PDF
Java Generics - by Example
PPTX
Byte code field report
Java Programming - 04 object oriented in java
Migrating to JUnit 5
Unit testing concurrent code
Java Fundamentals
Java tut1 Coderdojo Cahersiveen
Lecture - 5 Control Statement
Java Generics - by Example
Byte code field report

What's hot (20)

PPTX
Java generics final
PDF
Lambda Functions in Java 8
PPT
Java tut1
PPT
Tutorial java
PDF
Java programming-examples
PPTX
Unit 4 exceptions and threads
PDF
Java Simple Programs
PDF
Java programs
PPTX
Java Programs
ODP
Java Generics
PPT
Effective Java - Generics
PDF
Java Concurrency by Example
PPTX
Lecture - 3 Variables-data type_operators_oops concept
PDF
Java 8 Lambda Built-in Functional Interfaces
ODP
Java Concurrency
PDF
On Parameterised Types and Java Generics
PDF
Java ppt Gandhi Ravi (gandhiri@gmail.com)
PDF
Advanced Java Practical File
PDF
Java Programming - 06 java file io
Java generics final
Lambda Functions in Java 8
Java tut1
Tutorial java
Java programming-examples
Unit 4 exceptions and threads
Java Simple Programs
Java programs
Java Programs
Java Generics
Effective Java - Generics
Java Concurrency by Example
Lecture - 3 Variables-data type_operators_oops concept
Java 8 Lambda Built-in Functional Interfaces
Java Concurrency
On Parameterised Types and Java Generics
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Advanced Java Practical File
Java Programming - 06 java file io
Ad

Viewers also liked (20)

PDF
Modul6 1225443461187631-8
ZIP
Introduction to the Java(TM) Advanced Imaging API
PPT
C0 review core java1
PPT
Chapter 4 Powerpoint
PPT
Eo gaddis java_chapter_02_5e
PPT
Java basic
PPTX
Module 03
PDF
Seri Belajar Mandiri – Pemrograman Java Untuk Pemula
PPTX
Module 03 searching and seizing computers
DOCX
contoh Program sederhana Java dan penjelasan programnya
PDF
Java Programming - 01 intro to java
PPTX
Control flow statements in java
PPTX
Datacom module 3: Data Communications Circuits, Arrangements, and Networks
PDF
02 basic java programming and operators
PDF
JEE Programming - 03 Model View Controller
PPTX
Sektor ng agrikultura
PPT
Sektor ng agrikultura
PDF
03. prak.-pemrograman-visual-i-vb.net
PPTX
Network topology.ppt
PDF
Cehv8 module 01 introduction to ethical hacking
Modul6 1225443461187631-8
Introduction to the Java(TM) Advanced Imaging API
C0 review core java1
Chapter 4 Powerpoint
Eo gaddis java_chapter_02_5e
Java basic
Module 03
Seri Belajar Mandiri – Pemrograman Java Untuk Pemula
Module 03 searching and seizing computers
contoh Program sederhana Java dan penjelasan programnya
Java Programming - 01 intro to java
Control flow statements in java
Datacom module 3: Data Communications Circuits, Arrangements, and Networks
02 basic java programming and operators
JEE Programming - 03 Model View Controller
Sektor ng agrikultura
Sektor ng agrikultura
03. prak.-pemrograman-visual-i-vb.net
Network topology.ppt
Cehv8 module 01 introduction to ethical hacking
Ad

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

PPT
4.CONTROL STATEMENTS_MB.ppt .
PPTX
Pj01 5-exceution control flow
PPT
05. Control Structures.ppt
PDF
Control structures in Java
PPTX
control statements
PPTX
DAY_1.2.pptx
PDF
Java chapter 5
PPTX
Control statements in java
PDF
9-java language basics part3
PPT
Control statements
PPTX
07 flow control
PDF
Control flow statements in java web applications
PDF
how to write loops in java explained vividly
PPTX
Java chapter 3
PPTX
130706266060138191
PDF
Android Application Development - Level 3
PPTX
controlStatement.pptx, CONTROL STATEMENTS IN JAVA
PPT
Control statements in java programmng
PPT
6_A1944859510_21789_2_2018_06. Branching Statements.ppt
PDF
C sharp chap4
4.CONTROL STATEMENTS_MB.ppt .
Pj01 5-exceution control flow
05. Control Structures.ppt
Control structures in Java
control statements
DAY_1.2.pptx
Java chapter 5
Control statements in java
9-java language basics part3
Control statements
07 flow control
Control flow statements in java web applications
how to write loops in java explained vividly
Java chapter 3
130706266060138191
Android Application Development - Level 3
controlStatement.pptx, CONTROL STATEMENTS IN JAVA
Control statements in java programmng
6_A1944859510_21789_2_2018_06. Branching Statements.ppt
C sharp chap4

More from Danairat Thanabodithammachari (20)

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

Recently uploaded (20)

PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
Introduction to Artificial Intelligence
PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
AI in Product Development-omnex systems
PDF
System and Network Administration Chapter 2
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
Digital Strategies for Manufacturing Companies
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
L1 - Introduction to python Backend.pptx
Design an Analysis of Algorithms I-SECS-1021-03
Odoo POS Development Services by CandidRoot Solutions
Wondershare Filmora 15 Crack With Activation Key [2025
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
CHAPTER 2 - PM Management and IT Context
Design an Analysis of Algorithms II-SECS-1021-03
How to Choose the Right IT Partner for Your Business in Malaysia
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Which alternative to Crystal Reports is best for small or large businesses.pdf
Introduction to Artificial Intelligence
ISO 45001 Occupational Health and Safety Management System
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
AI in Product Development-omnex systems
System and Network Administration Chapter 2
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Digital Strategies for Manufacturing Companies
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
L1 - Introduction to python Backend.pptx

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