0% found this document useful (0 votes)
4 views26 pages

Lecture-9-Java Language (Control Flow & Interactive Input)

The document outlines the Java programming language focusing on control flow and interactive input. It covers various control flow statements including selection, iteration, and jump statements, providing examples and syntax for each. Key topics include if statements, switch statements, while loops, for loops, and the use of break and continue statements.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views26 pages

Lecture-9-Java Language (Control Flow & Interactive Input)

The document outlines the Java programming language focusing on control flow and interactive input. It covers various control flow statements including selection, iteration, and jump statements, providing examples and syntax for each. Key topics include if statements, switch statements, while loops, for loops, and the use of break and continue statements.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Language

Control Flow & Interactive Input

XP
Course Outline
1) introduction 3) object-orientation 4) horizontal libraries
2) language a) objects a) string handling
a) syntax b) classes b) event handling
b) types c) inheritance c) object collections
c) variables d) polymorphism
5) vertical libraries
d) arrays e) access
a) graphical interface
e) operators f) interfaces
b) applets
f) control flow g) exception handling
c) input/output
h) multi-threading
d) networking
6) summary

CS103-OOPS with JAVA


Dr. V. K. Jain 1
XP
Control Flow
Writing a program means typing statements into
a file.
Without control flow, the interpreter would
execute these statements in the order they
appear in the file, left-to-right, top-down.
Control flow statements, when inserted into the
text of the program, determine in which order the
program should be executed.

XP
Control Flow Statements
Java control statements cause the flow of execution to
advance and branch based on the changes to the state of
the program.
Control statements are divided into three groups:
1) selection statements allow the program to choose
different parts of the execution based on the outcome of
an expression
2) iteration statements enable program execution to
repeat one or more statements
3) jump statements enable your program to execute in a
non-linear fashion

CS103-OOPS with JAVA


Dr. V. K. Jain 2
XP
Selection Statements
Java selection statements allow to control the flow of
program’s execution based upon conditions known only
during run-time.
Java provides four selection statements:
1) if
2) if-else
3) if-else-if
4) switch

XP
if Statement
General form:
if (expression) statement
If expression evaluates to true, execute
statement, otherwise do nothing.
The expression must be of type boolean.

CS103-OOPS with JAVA


Dr. V. K. Jain 3
XP
Simple/Compound Statement
The component statement may be:
1) simple
if (expression) statement;
2) compound
if (expression) {
statement;
}

XP
if-else Statement
Suppose you want to perform two different
statements depending on the outcome of a
boolean expression. if-else statement can be
used.
General form:
if (expression) statement1
else statement2
Again, statement1 and statement2 may be
simple or compound.

CS103-OOPS with JAVA


Dr. V. K. Jain 4
XP
if-else-if Statement
General form:
if (expression1) statement1
else if (expression2) statement2
else if (expression3) statement3

else statement

Semantics:
1) statements are executed top-down
2) as soon as one expressions is true, its statement is
executed
3) if none of the expressions is true, the last statement is
executed

XP
Example: if-else-if
class IfElse {
public static void main(String args[]) {
int month = 4;
String season;
if (month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else season = "Bogus Month";
[Link]("April is in the " + season + ".");
}
}

10

CS103-OOPS with JAVA


Dr. V. K. Jain 5
XP
switch Statement
switch provides a better alternative than if-
else-if when the execution follows several
branches depending on the value of an
expression.
General form:
switch (expression) {
case value1: statement1; break;
case value2: statement2; break;
case value3: statement3; break;

default: statement;
}

11

XP
switch Assumptions/Semantics
Assumptions:
1) expression must be of type byte, short, int or char
2) each of the case values must be a literal of the compatible type
3) case values must be unique

Semantics:
1) expression is evaluated
2) its value is compared with each of the case values
3) if a match is found, the statement following the case is executed
4) if no match is found, the statement following default is executed

break makes sure that only the matching statement is executed.

Both default and break are optional.

12

CS103-OOPS with JAVA


Dr. V. K. Jain 6
XP
Example: switch 1
class Switch {
public static void main(String args[]) {
int month = 4;
String season;
switch (month) {
case 12:
case 1:
case 2: season = "Winter"; break;
case 3:
case 4:
case 5: season = "Spring"; break;
case 6:
case 7:
case 8: season = "Summer"; break;

13

XP
Example: switch 2
case 9:
case 10:
case 11: season = "Autumn"; break;
default: season = "Bogus Month";
}
[Link]("April is in " + season + ".");
}
}

14

CS103-OOPS with JAVA


Dr. V. K. Jain 7
XP
Nested switch Statement
A switch statement can be nested within another switch statement:

switch(count) {
case 1:
switch(target) {
case 0:[Link](“target is zero”);
break;
case 1:[Link](“target is one”);
break;
}
break;
case 2: …
}
Since, every switch statement defines its own block, no conflict arises
between the case constants in the inner and outer switch statements.

15

XP
Comparing switch and if
Two main differences:
1) switch can only test for equality, while if can
evaluate any kind of boolean expression

2) Java creates a “jump table” for switch


expressions, so a switch evaluated if the value of
op1 is insufficient to determine the final outcome

16

CS103-OOPS with JAVA


Dr. V. K. Jain 8
XP
Iteration Statements
Java iteration statements enable repeated
execution of part of a program until a certain
termination condition becomes true.
Java provides three iteration statements:
1) while
2) do-while
3) for

17

XP
while Statement
General form:
while (expression) statement
where expression must be of type boolean.
Semantics:
1) repeat execution of statement until
expression becomes false
2) expression is always evaluated before
statement
3) if expression is false initially, statement will
never get executed

18

CS103-OOPS with JAVA


Dr. V. K. Jain 9
XP
Simple/Compound Statement
The component statement may be:
1) simple
while (expression) statement;
2) compound
while (expression) {
statement;
}

19

XP
Example: while
class MidPoint {
public static void main(String args[]) {
int i, j;
i = 100;
j = 200;
while(++i < --j) {
[Link](“i is " + i);
[Link](“j is " + j);
}
[Link](“The midpoint is " + i);
}
}

20

CS103-OOPS with JAVA


Dr. V. K. Jain 10
XP
do-while Statement
If a component statement has to be executed at least once, the do-while
statement is more appropriate than the while statement.

General form:

do statement
while (expression);

where expression must be of type boolean.

Semantics:

1) repeat execution of statement until expression becomes false


2) expression is always evaluated after statement
3) even if expression is false initially, statement will be executed

21

XP
Example: do-while
class DoWhile {
public static void main(String args[]) {
int i;
i = 0;
do
i++;
while ( 1/i < 0.001);
[Link](“i is “ + i);
}
}

22

CS103-OOPS with JAVA


Dr. V. K. Jain 11
XP
for Statement
When iterating over a range of values, for statement is
more suitable to use then while or do-while.
General form:

for (initialization; termination; increment)


statement

Where:
1) initialization statement is executed once before
the first iteration
2) termination expression is evaluated before each
iteration to determine when the loop should terminate
3) increment statement is executed after each iteration

23

XP
for Statement Semantics
This is how the for statement is executed:
1) initialization is executed once
2) termination expression is evaluated:
a) if false, the statement terminates
b) otherwise, continue to (3)
3) increment statement is executed
4) component statement is executed
5) control flow continues from (2)

24

CS103-OOPS with JAVA


Dr. V. K. Jain 12
XP
Loop Control Variable
The for statement may include declaration of a
loop control variable:
for (int i = 0; i < 1000; i++) {

}

The variable does not exist outside the for


statement.

25

XP
Example: for
class FindPrime {
public static void main(String args[]) {
int num = 14;
boolean isPrime = true;
for (int i=2; i < num/2; i++) {
if ((num % i) == 0) {
isPrime = false;
break;
}
}
if (isPrime) [Link]("Prime");
else [Link]("Not Prime");
}
}

26

CS103-OOPS with JAVA


Dr. V. K. Jain 13
XP
Many Initialization/Iteration Parts
The for statement may include several
initialization and iteration parts.
Parts are separated by a comma:
int a, b;
for (a = 1, b = 4; a < b; a++, b--) {

}

27

XP
for Statement Variations
The for statement need not have all components:
class ForVar {
public static void main(String args[]) {
int i = 0;
boolean done = false;
for( ; !done; ) {
[Link]("i is " + i);
if(i == 10) done = true;
i++;
}
}
}

28

CS103-OOPS with JAVA


Dr. V. K. Jain 14
XP
Empty for
In fact, all three components may be omitted:

public class EmptyFor {


public static void main(String[] args) {
int i = 0;
for (; ;) {
[Link](“Infinite Loop “ + i);
}
}
}

29

XP
Jump Statements
Java jump statements enable transfer of control
to other parts of program.
Java provides three jump statements:
1) break
2) continue
3) return
In addition, Java supports exception handling that
can also alter the control flow of a program.
Exception handling will be explained in its own
section.

30

CS103-OOPS with JAVA


Dr. V. K. Jain 15
XP
break Statement
The break statement has three uses:

1) to terminate a case inside the switch statement


2) to exit an iterative statement
3) to transfer control to another statement
(1) has been described.
We continue with (2) and (3).

31

XP
Loop Exit with break
When break is used inside a loop, the loop
terminates and control is transferred to the
following instruction.
class BreakLoop {
public static void main(String args[]) {
for (int i=0; i<100; i++) {
if (i == 10) break;
[Link]("i: " + i);
}
[Link]("Loop complete.");
}
}

32

CS103-OOPS with JAVA


Dr. V. K. Jain 16
XP
break in Nested Loops
Used inside nested loops, break will only terminate the
innermost loop:
class NestedLoopBreak {
public static void main(String args[]) {
for (int i=0; i<3; i++) {
[Link]("Pass " + i + ": ");
for (int j=0; j<100; j++) {
if (j == 10) break;
[Link](j + " ");
}
[Link]();
}
[Link]("Loops complete.");
}
}

33

XP
Control Transfer with break
Java does not have an unrestricted “goto”
statement, which tends to produce code that is
hard to understand and maintain.
However, in some places, the use of goto’s is well
justified. In particular, when breaking out from the
deeply nested blocks of code.
break occurs in two versions:
1) unlabelled
2) labeled
The labeled break statement is a “civilized”
replacement for goto.

34

CS103-OOPS with JAVA


Dr. V. K. Jain 17
XP
Labeled break
General form:
break label;
where label is the name of a label that identifies
a block of code:
label: { … }

The effect of executing break label; is to


transfer control immediately after the block of
code identified by label.

35

XP
Example: Labeled break
class Break {
public static void main(String args[]) {
boolean t = true;
first: {
second: {
third: {
[Link]("Before the break.");
if (t) break second;
[Link]("This won't execute");
}
[Link]("This won't execute");
}
[Link](“After second block.");
}
} }

36

CS103-OOPS with JAVA


Dr. V. K. Jain 18
XP
Example: Nested Loop break
class NestedLoopBreak {
public static void main(String args[]) {
outer: for (int i=0; i<3; i++) {
[Link]("Pass " + i + ": ");
for (int j=0; j<100; j++) {
if (j == 10) break outer; // exit both loops
[Link](j + " ");
}
[Link]("This will not print");
}
[Link]("Loops complete.");
}
}

37

XP
break Without Label
It is not possible to break to any label which is not
defined for an enclosing block. Trying to do so will
result in a compiler error.
class BreakError {
public static void main(String args[]) {
one: for(int i=0; i<3; i++) {
[Link]("Pass " + i + ": ");
}
for (int j=0; j<100; j++) {
if (j == 10) break one;
[Link](j + " ");
}
}
}

38

CS103-OOPS with JAVA


Dr. V. K. Jain 19
XP
continue Statement
The break statement terminates the block of
code, in particular it terminates the execution of an
iterative statement.
The continue statement forces the early
termination of the current iteration to begin
immediately the next iteration.
Like break, continue has two versions:
1) unlabelled - continue with the next iteration of
the current loop
2) labeled - specifies which enclosing loop to
continue

39

XP
Example: Unlabeled continue
class Continue {
public static void main(String args[]) {
for (int i=0; i<10; i++) {
[Link](i + " ");
if (i%2 == 0) continue;
[Link]("");
}
}
}

40

CS103-OOPS with JAVA


Dr. V. K. Jain 20
XP
Example: Labeled continue
class LabeledContinue {
public static void main(String args[]) {
outer: for (int i=0; i<10; i++) {
for (int j=0; j<10; j++) {
if (j > i) {
[Link]();
continue outer;
}
[Link](" " + (i * j));
}
}
[Link]();
}
}

41

XP
Return Statement
The return statement is used to return from the
current method: it causes program control to
transfer back to the caller of the method.
Two forms:
1) return without value
return;
2) return with value
return expression;

42

CS103-OOPS with JAVA


Dr. V. K. Jain 21
XP
Example: Return

class Return {
public static void main(String args[]) {
boolean t = true;
[Link]("Before the return.");
if (t) return; // return to caller
[Link]("This won't execute.");
}
}

43

Interactive Input

44

CS103-OOPS with JAVA


Dr. V. K. Jain 22
Interactive Input XP

❑ We have written programs that print console


output, but it is also possible to read input
from the console.
❑ The user types input into the console. We capture the
input and use it in our program.
❑ Such a program is called an interactive program.

❑ Interactive programs can be challenging.


❑ Computers and users think in very different ways.
❑ Users misbehave.

45

Input using the Scanner class XP

❑ [Link]
❑ An object with methods named println and print

❑ [Link]
❑ not intended to be used directly
❑ We use a second object, from a class Scanner, to help us.

❑ Constructing a Scanner object to read console input:


Scanner name = new Scanner([Link]);

❑ Example:
Scanner console = new Scanner([Link]);

46

CS103-OOPS with JAVA


Dr. V. K. Jain 23
Packages and import Statements XP
❑ Java class libraries: Classes included with Java's
JDK.
❑ organized into groups named packages
❑ To use a package, put an import declaration in your program.
❑ Syntax:
//put this at top of your program
import packageName.*;

❑ Scanner is in a package named [Link]


import [Link].*;
❑ To use Scanner, you must place the above line at the top of your
program (before the public class header).

47

Scanner Methods XP

Methods from Scanner class:

Method Description
nextInt() reads a token of user’s input as an int
nextDouble() reads a token of user input as double
next() reads a token of user input as a String
nextLine() reads a line of user input as a String

48

CS103-OOPS with JAVA


Dr. V. K. Jain 24
Scanner Methods XP

❑ Each method waits until the user presses Enter.


❑ The value entered by the user is returned by method.
❑ token = value typed by user. Tokens are separated by whitespace
(blank spaces, tabs, newlines).

[Link]("How old are you? "); // prompt


int age = [Link]();
[Link]("You'll be 40 in " + (40 - age) + " years.");

❑ prompt: A message telling the user what input to type.

49

Fun Stuff with User Input XP

import [Link].*; // so I can use Scanner


public class TwoTokens {
public static void main(String[] args) {
Scanner keyboard = new Scanner([Link]);
[Link](“Enter two integers: “); // prompt
int num1 = [Link](); // get first number
int num2 = [Link](); // get second number

int sum = num1 + num2; // sum ‘em


[Link](“Sum of “ + num1 + “ and “ + num2
+ “ is “ + sum);
}
}

50

CS103-OOPS with JAVA


Dr. V. K. Jain 25
Sample Run XP

❑Output (user’s input is underlined):


Enter two integers: 12 3
Sum of 12 and 3 is 15

51

Reading Strings XP

Scanner reader = new Scanner([Link]);


[Link](“What is your first name? “); // prompt
String firstName = [Link]();
[Link](“Where do you work? “);
String employer = [Link]();
[Link](“Name: “ + firstName);
[Link](“Employer: “ + employer);
Sample Run:
What is your first name? Mary
Where do you work? The University of Texas at Austin
Name: Mary
Employer: The University of Texas at Austin

52

CS103-OOPS with JAVA


Dr. V. K. Jain 26

You might also like