Download - Chapter 5: Control Statements
![Page 1: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/1.jpg)
Chapter 5: Control StatementsControl Flow: A control flow Statement
regulates the order in which statements get executed.
Flow-order in which the computer executes the lines of code in our program
Control flow blocks are basically blocks of code that control the way data flows, or else which statements are executed when. This can be useful if you only want certain areas of your code to be executed under a given condition.
![Page 2: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/2.jpg)
The default flow of control in a program is TOP to BOTTOM, i.e. all the statements of a program are executed one by one in the sequence from top to Bottom. This execution order can be altered with the help of control instructions.
Java supports three types of control instructions -
1. Sequence Statement 2.Decision Making / Conditional / Selection
Statements 3..Looping / Iterative Statements
![Page 3: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/3.jpg)
Program Structure
public class MyProgram
{
}
// comments about the class
public static void main (String[] args)
{
}
// comments about the method
method headermethod body
![Page 4: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/4.jpg)
SEQUENCE The sequence means the statements are
being executed sequentially. This represents default flow of statement.
Statement 1
Statement 3
Statement 2
![Page 5: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/5.jpg)
Statement 1
Statement 2
SELECTION
The sequence Statements means the execution of statement(s) depending upon a given condition.
Statement 1
Statement 2
Condition ?
true falseCondition ?
Statement 1
Condition ?
Statement 2
Statement 1
Condition ?
Statement 1
Statement 2
Statement 1
Condition ?
Statement 2
Statement 1
Statement 2
Statement 1
Condition ?
Statement 1
Statement 2
Statement 1
Condition ?
Statement 1
Statement 2
Statement 1
Condition ?
Statement 2
Statement 1
Condition ?
Statement 2
Statement 1
Condition ?
Statement 2
Statement 1
Condition ?
Statement 2
Statement 1
Condition ?
true
Statement 2
Statement 1
Condition ?
true
Statement 2
Body of iF
Condition ?
false
Statement 1
Statement 1
false
Statement 1
false
Statement 1
false
Statement 1
false
Body of else
falseCondition?
Statement 2
Statement 1
Statement 2
![Page 6: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/6.jpg)
Conditional Statement - if Statement First Form of if Statement
if ( <conditional expression> ) {
execute statements -for-the-true-case;
}
=>Second form
if ( < conditional expression > ) {
execute statement1 -for-the-true-case
}
else {
execute statement2 -for-the-false-case
}Result of conditional expression : Logical Type(true or false)
![Page 7: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/7.jpg)
There are certain points worth remembering about the if statement as outlined below:
The conditional expression is always enclosed in parenthesis.
The conditional expression may be a simple expression or a compound expression.
Each statement block may have a single or multiple statements to be executed.
![Page 8: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/8.jpg)
In case there is a single statement to be executed then it is not mandatory to enclose it in curly braces ({}) but if there are multiple statements then they must be enclosed in curly braces ({})
The else clause is optional and needs to be included only when some action is to be taken if the test condition evaluates to false.
![Page 9: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/9.jpg)
Example– if ( j<5 ) { // This is recommended
System.out.println(“j is less than 5”):
}
Else
{
System.out.println(“j is no less than 5”):
}
OR
if ( j<5 ) System.out.println(“j is less than 5”): //single statement
else
System.out.println(“j is no less than 5”):
![Page 10: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/10.jpg)
if ( testScore < 70 )
JOptionPane.showMessageDialog(null, "You did not pass" );
else
JOptionPane.showMessageDialog(null, "You did pass " );
Syntax for the if Statementif ( <boolean expression> )
<then block>
else
<else block>
Then BlockThen Block
Else BlockElse Block
Boolean ExpressionBoolean Expression
Indentation is important!
Can be visualized as a flowchart
![Page 11: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/11.jpg)
Nested if statementif (<cond. expr.>) if (<cond. expr.>) // . . . <statement>
if (<cond. expr.1>) <statement 1> else if (<cond. expr.2>) < statement 2> … else if (<cond. expr. n>) < statement n> else < statement>
![Page 12: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/12.jpg)
![Page 13: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/13.jpg)
Conditional Operator(?)if (x > 0)
{
y = 1
}else{ y = -1;}
is equivalent toy = (x > 0) ? 1 : -1;
![Page 14: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/14.jpg)
Syntax for the switch Statement
switch ( gradeLevel ) {
case 1: System.out.print("Go to the Gymnasium");
break;
case 2: System.out.print("Go to the Science Auditorium");
break;
case 3: System.out.print("Go to Harris Hall Rm A3");
break;
case 4: System.out.print("Go to Bolt Hall Rm 101");
break;
}
switch ( <arithmetic expression> ) {
<case label 1> : <case body 1>
…
<case label n> : <case body n>
}
Case Body
Case Body
Arithmetic ExpressionArithmetic Expression
Case Label
Case Label
This is the general syntax rule for a switch statement. The case body may contain zero or more statements.
![Page 15: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/15.jpg)
Exampleswitch(x) { case 1:
System.out.println(“go to 1”); break; // what happened if break is not here?case 2:case 3:
System.out.println(“go to 2 or 3”); break;
default : System.out.println(“not 1, 2 or 3”);
}
![Page 16: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/16.jpg)
=>The expression of switch must not be long, float, double, or Boolean, it must be either byte, short, char, or int. (assignment compatible with int)
=>The arguments to case labels must be constants, or at least a constant expression that can be fully evaluated at compile time.
=>Can not use a variable or expression involving variables.
=>Default clause can be placed any where in, the block.
=> The fall of control to the following cses of matching case is called FALL –THROUGH.
![Page 17: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/17.jpg)
Switch There are times in which you wish to check for a number
of conditions, and to execute different code depending on the condition. One way to do this is with if/else logic, such as the example below:
int x = 1; int y = 2; if (SOME_INT == x) { //DO SOMETHING } else if (SOME_INT == y) { //DO SOMETHING ELSE } else { //DEFAULT CONDITION }
![Page 18: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/18.jpg)
This works, however another structure exists which allows us to do the same thing. Switch statements allow the programmer to execute certain blocks of code depending on exclusive conditions. The example below shows how a switch statement can be used:
int x = 1; int y = 2; switch (SOME_INT) { case x: method1(SOME_INT); break; case y: method2(SOME_INT); break; default: method3(); break; }
![Page 19: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/19.jpg)
Switch takes a single parameter, which can be either an integer or a char. In this case the switch statement is evaluating SOME_INT, which is presumably an integer. When the switch statement is encountered SOME_INT is evaluated, and when it is equal to x or y, method1 and method2 are executed, respectively. The default case executes if SOME_INT does not equal x or y, in this case method3 is executed. You may have as many case statements as you wish within a switch statement.
Notice in the example above that "break" is listed after each case. This keyword ensures that execution of the switch statement stops immediately, rather than continuing to the next case. Were the break statement were not included "fall-through" would occur and the next case would be evaluated (and possibly executed if it meets the conditions).
![Page 20: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/20.jpg)
Differences between the If-else and Switch ST: Switch can only test for equality whereas if can evaluate a
relational or logical expression that is multiple condition. The switch statement select its branches by testing the value of
same variable whereas the if-else construction allow you use a series of expression that may
involve unrelated variables and complex expressions. The if-else is more versatile of the two statements. The if-else statement can handle floating-point tests also apart
from handling integer and character test whereas a switch cannot handle floating-point test. the case labels of switch must be an integer byte,short,int or a char.
The switch case label value must be a constant. so if two or more variables are to be compared ,use if-else.
The switch statement is more efficient choice in terms of code used in a situation that supports the nature of switch operation( testing a value against a se of constant).
![Page 21: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/21.jpg)
Repetitions for Loops while Loops
do Loops break and continue
![Page 22: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/22.jpg)
Looping / Repetitive Statement Some time some portion of the program (one or more statement) needs to be executed repeatedly for fixed no. of time or till a particular condition is being satisfied. This repetitive operation is done through a looping statement.
A loop is repetition of one or more instructions, which continues till certain condition is met.
Definition
![Page 23: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/23.jpg)
Statement 1
Statement 2
Statement n
ITERATION / LOOP
Looping structures are the statements that execute instructions repeatedly until a certain condition is fulfilled(true).
Condition?
false
True
![Page 24: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/24.jpg)
In an Entry-Controlled loop/Top-Tested/Pre-Tested loop the test expression is evaluated before entering into a loop.
for Examples: For loop and While loop. In an Exit-Controlled loop/Bottom-Tested/Post-
Tested loop the test expression is evaluated before exiting from the loop.
for Examples: do-While loop. Do not put a semicolon after the right parenthesis. If
you do, the for loop would think that there no statements to execute. it would continue looping, doing nothing each time until the test expression becomes false.
![Page 25: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/25.jpg)
for Loopsfor (initialization; Test-condition; update-statement){ //loop body;}
Example:
int i;for (i = 0; i<100; i++) { System.out.println("Welcome to Java! ” + i); }
![Page 26: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/26.jpg)
In for loop contains three parts separated by semicolons(;) Initialization Before entering in a loop, its variables
must be initialized. The initialization expression is executed only once in the beginning of the loop.
Test Expression It decides whether the loop-body will be executed or not. if the test expression evaluates to true the loop-body gets executed, otherwise the loop is terminated. Test expression gets checked every time before entering in the body of the loop.
Update Expression(s) The update expressions change the values of loop variables. The update expression is executed every time after executing the loop-body .
The body of the loop The statements that are executed repeatedly (as long as the test-expression is nonzero) from the body of the loop.
![Page 27: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/27.jpg)
for Loop Flow Chart
![Page 28: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/28.jpg)
for// print 1 2 3 4 5 6 7 8 9 10public class ClassXI {
public static void main(String args[]) {
int n; for(n=1; n<=10; n++)
{ System.out.println(“ ” + n);
}// end for loop }// end main} // end class
![Page 29: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/29.jpg)
INFINITE LOOP: An infinite loop can be created by omitting the test expression as shown below:
1. for( int j=25; ; --j)
{
System.out.println(“ An infinite for Loop”);
}
2. for ( ; ; ) // infinite loop
{
System.out.println(“ An infinite for Loop”);
}
![Page 30: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/30.jpg)
3.Empty Loop: If a loop does not contain any statement in its loop-body, it is said to be an empty loop.
For(int j=20;j>=0;--j); 4. Declaration of variable inside the loops
and if: A variable declared within an if or for/while/do-while statement cannot be accessed after the statement is over, because its scope becomes the body of the statement(if/for/while/ do-while). It cannot be accessed outside the statement body.
![Page 31: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/31.jpg)
if( ch= =‘a’){ int ans=1; }else {int b=2; } System.out.print(ans);// invalid
for( int ans=1; ans<100; ans+=20) { System.out.print(“ ” +ans);//valid }System.out.print(ans);//invalid
=>A variable scope is the part of program within which you can access the variable . A variable scope is the block of code( that is the part of code enclosed within{}) where the variable has been declared.
![Page 32: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/32.jpg)
while Loopswhile (condition) { // loop-body;} Note: A while loop is pre-test loop. It first tests a
specified conditional expression and as long as the conditional expression is evaluated to non zero (true), action taken (i.e. statements or block after the loop is executed).
![Page 33: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/33.jpg)
while Loop Flow ChartSTART
![Page 34: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/34.jpg)
while// Demonstrate the while loop.public class While {
public static void main(String args[]) {int n = 1;while(n<=1 0) {
System.out.println(“ " + n);n++;
} //end while} // end main
} // end class
![Page 35: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/35.jpg)
do Loops
do{ // Loop body;} while (continue-condition);
The Do-while loop is an POST-TEST or bottom test loop.that is, it executes its body at least once without testing specified conditional expression and then makes test. the do-while loop terminates when the text expression is evaluated to be False(0).
![Page 36: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/36.jpg)
do Loop Flow Chart
![Page 37: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/37.jpg)
do-while
// Demonstrate the do-while loop.public class DoWhile {
public static void main(String args[]) {int n =1;do { System.out.println(" " + n); n++; } while(n <= 0);
} // main} // class
![Page 38: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/38.jpg)
Jump
Java supports three jump statements: break, continue, and return.
These statements transfer control to another part of your program.
![Page 39: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/39.jpg)
breakIn Java, the break statement has three
uses. First, as you have seen, it terminates a
statement sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be used as a "civilized" form
of goto. java does not support goto statement
![Page 40: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/40.jpg)
break statement Alter flow of control– Causes immediate exit from control structure
Used in while, for, do…while or switch statements
Labeled break Labeled block– Set of statements enclosed by { }– Preceded by a label Labeled break statement – Exit from nested control structures– Proceeds to end of specified labeled block
![Page 41: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/41.jpg)
breakThe general form of the labeled break
statement is shown here:break label;
![Page 42: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/42.jpg)
The break Keyword
![Page 43: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/43.jpg)
break// Using break to exit from for loop.class BreakLoop {
public static void main(String args[]) {for(int i=0; i<100; i++)
{if(i = = 10)
break; // terminate loop if i is 10System.out.println(“ i: " + i);
}System.out.println("Loop complete.");
}}
![Page 44: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/44.jpg)
break// Using break to exit from while loop.class BreakLoop2 {
public static void main(String args[]) {int i = 0;while(i < 100) { if(i == 10) break; // terminate loop if i is 10 System.out.println("i: " + i); i++;}System.out.println("Loop complete.");
}}
![Page 45: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/45.jpg)
break// Using break to exit from do while loop.class BreakLoop2 {
public static void main(String args[]) {int i = 0;
do {
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i); i++;
} while(i < 100);}System.out.println("Loop complete.");
}
![Page 46: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/46.jpg)
Branch Statement - break Statement
To move control to the out of the block From of break statement
break [label] ;
int i = 1; while (true) { if (i = = 3) break; System.out.println("This is a " + i + " iteration"); ++i; }
![Page 47: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/47.jpg)
continue you might want to continue running the loop,
but stop processing the remainder of the code in its body for particular iteration. This is, in effect, a goto just past the body of the loop, to the loop's end.
In while and do-while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop.
In a for loop, control goes first to the iteration portion of the for statement and then to the conditional expression.
![Page 48: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/48.jpg)
continue statement As with the break statement, continue may
specify a label to describe which enclosing loop to continue.– Skips remaining statements in loop body– Proceeds to next iteration
Used in while, for or do…while statements
Labeled continue statement – Skips remaining statements in nested-loop body– Proceeds to beginning of specified labeled block
![Page 49: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/49.jpg)
The continue Keyword
![Page 50: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/50.jpg)
// Demonstrate continue.class Continue {
public static void main(String args[]) {for(int i=0; i<10; i++) {
System.out.print(i + " ");if (i%2 == 0)
continue;System.out.println("");
}}
}
![Page 51: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/51.jpg)
// Using continue with a label.class ContinueLabel {
public static void main(String args[]) {outer: for (int i=0; i<10; i++) {
for(int j=0; j<10; j++) { if(j > i) {
System.out.println();continue outer;
} System.out.print(" " + (i * j));}
}System.out.println();
}}
![Page 52: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/52.jpg)
Branch Statement – continue Statement
To move control to the start of next repeatation From of continue statement
continue [Label] ;
When used in for statement
for (i=0; i<=5; ++i) { if (i % 2 == 0) continue; System.out.println("This is a " + i + " iteration"); }
![Page 53: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/53.jpg)
Branch Statement – continue Statement
When used in while statement
i = 0; while (i <= 5) { ++i; if (i % 2) == 0) continue; System.out.println("This is a odd iteration - " + i); }
![Page 54: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/54.jpg)
Branch Statement – continue Statement
Label continue statement
[LabeledContinue.java]
labelName:labelName: Rep. St. 1 { Rep. St. 2 { // ... continue; // ... continue labelName;continue labelName; } }
![Page 55: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/55.jpg)
returnThe return statement is used to
explicitly return from a method. That is, it causes program control to transfer back to the caller of the method.
The following example illustrates this point. Here, return causes execution to return to the Java run-time system, since it is the run-time system that calls main( ).
![Page 56: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/56.jpg)
Branch Statement – return Statement
To terminate the execution of method, then pass the method of caller that control
Forms of return statement – return; return;
– return <expr.>;return <expr.>;
![Page 57: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/57.jpg)
return
// Demonstrate return.class Return {
public static void main(String args[]) {boolean t = true;System.out.println("Before the return.");if(t) return; // return to callerSystem.out.println("This won't
execute.");}
}
![Page 58: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/58.jpg)
END
![Page 59: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/59.jpg)
Objects and Classes
Object = active program unit containing both data and procedures
Class = a template for all objects of the same type
An Object is often called an instance of the class.
![Page 60: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/60.jpg)
Components of an object
Instance variable = variable within an object
Method = function or procedure within an object– Can manipulate the object’s instance variables
Constructor = special method to initialize a new object instance
![Page 61: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/61.jpg)
Encapsulation
Encapsulation = a way of restricting access to the internal components of an object– Private– Public
![Page 62: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/62.jpg)
Additional object-oriented concepts
Inheritance: allows new classes to be defined in terms of previously defined classes
Polymorphism: allows method calls to be interpreted by the object that receives the call
![Page 63: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/63.jpg)
Figure 6.22 The structure of a class describing a laser weapon
in a computer game
![Page 64: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/64.jpg)
Figure 6.23 A class with a constructor
![Page 65: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/65.jpg)
Figure 6.24 Our LaserClass definition using encapsulation as it would appear in
a Java or C# program
![Page 66: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/66.jpg)
Programming concurrent activities
Parallel or concurrent processing = simultaneous execution of multiple processes– True concurrent processing requires multiple
CPUs– Can be simulated using time-sharing with a
single CPU
![Page 67: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/67.jpg)
Interaction between processes
Mutual exclusion = a method for ensuring that data can be accessed by only one process at a time
Monitor = a data item augmented with the ability to control access to itself
![Page 68: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/68.jpg)
Figure 6.25 Spawning processes
![Page 69: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/69.jpg)
Comparing Objects
String str1 = new String("Java");String str2 = new String("Java");
if (str1 == str2) {System.out.println("They are equal");
} else {
System.out.println("They are not equal");} Solution : They are not equal
Discussion of some string methods
With primitive data types, we have only one way to compare them, but with objects (reference data type), we have two ways to compare themWe can test whether two variables point to the same object (use ==), or We can test whether two distinct objects have the same contents.
![Page 70: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/70.jpg)
Explanation of the above Program: When we use the equality operator (==), we can
comparing the contents of the variables str1 and str2. So str1 == str2 being true means the contents are the same, which in turn, means they are pointing to the same object because the content of a reference data type is an address. Therefore, if there are two distinct objects, even the values hold by these objects are the same, the equality testing by the equality operator will always result in false.
![Page 71: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/71.jpg)
![Page 72: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/72.jpg)
PROGRAM import javax.swing.*; // To support simple input public class Control { // Quadratic formula public static void main(String[] args) { final double TOL= 1E-15; // Constant(use ‘final’) String input; input= JOptionPane.showInputDialog("Enter a"); double a= Double.parseDouble(input); input= JOptionPane.showInputDialog("Enter b"); double b= Double.parseDouble(input); input= JOptionPane.showInputDialog("Enter c"); double c= Double.parseDouble(input);
![Page 73: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/73.jpg)
double discriminant= b*b - 4.0*a*c; if ( discriminant < 0) System.out.println("Sorry, no real root"); else if (Math.abs(discriminant) <= TOL) { double root= -0.5 * b / a; System.out.println("Root is " + root); } else { // Redefine ‘root’; blocks have own scopes double root=(-b + Math.sqrt(discriminant))/ (2.0*a); double root2=(-b- Math.sqrt(discriminant))/ (2.0*a); System.out.println("Roots" + root + “," + root2); } System.exit(0); } }
![Page 74: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/74.jpg)
Arithmetic Operators
Intro to OOP with Java,=> C. Thomas Wu
The precedence table shows the order of operator evaluation. Instead of memorizing this table, it is more convenient and the code more readable if you use the parentheses judiciously.
![Page 75: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/75.jpg)
Operator Precedence Rules
![Page 76: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/76.jpg)
Selection Statements–Using if and if...else–Nested if Statements–Using switch Statements–Conditional Operator
Repetition Statements–Looping: while, do, and for–Nested loops–Using break and continue
Note: Java does NOT support goto
![Page 77: Chapter 5: Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081414/568138a8550346895da06534/html5/thumbnails/77.jpg)
Java Statement
Assign Statement. : var = exp
Compound Statement. : { }
Condition Statement. : if St., switch St.
Control Loop Statement. : for St., while St., do-while St.
Branch Statement. : break St., continue St., return St.
Exception Handling St.: try-catch-finally
Synchronization St. : synchronized
Standard I/O : System.in.read(), System.out.println()Assignment Statement: Assignment Statement: Assign the value to variableForm : <variable> = <expression> remainder = dividend % divisor; i = j = k = 0; x *= y;
Statement