Selection Statements in Programming

Selections
 
The program can decide which
statements to execute based on a
condition.
Selection statements use conditions that
are Boolean expressions.
A 
Boolean expression 
is an expression that
evaluates to a 
Boolean value
: 
true 
or 
false
.
Object Oriented Programming
1
Boolean data type
The 
boolean 
data type declares a
variable with the value either 
true 
or
false 
(they are literals like number).
Object Oriented Programming
2
Ex. 
boolean 
lightsOn = 
true
;
If (one-way) statement
An 
if 
statement is a construct that
enables a program to specify alternative
paths of execution.
if 
(boolean-expression)
{
statement(s);
}
Object Oriented Programming
3
Cont.
Object Oriented Programming
4
Two-way if else
An 
if-else 
statement decides the
execution path based on whether the
condition is 
true or false.
if 
(boolean-expression) {
statement(s)-for-the-true-case;
}
else 
{
statement(s)-for-the-false-case;
}
Object Oriented Programming
5
Nested or Multi-way if
An 
if 
statement can be inside another 
if
statement to form a nested 
if 
statement.
The 
if (j > k) 
statement is nested inside
the 
if (i > k) 
statement in the following.
Object Oriented Programming
6
Generating Random Numbers
You can use 
Math.random() 
to obtain a
random double value between 
0.0 
and
1.0
, 
excluding 
1.0
.
SubtractionQuiz.java
Object Oriented Programming
7
Computing Body Mass Index (BMI)
 BMI =  weigh in KG/ (height in meters)
2
ComputeAndInterpretBMI.java
Object Oriented Programming
8
Logical Operators
The logical operators 
!
, 
&&
, 
||
, and 
^ 
can
be used to create a compound Boolean
expression.
Object Oriented Programming
9
undefined
Object Oriented Programming
10
Cont.
 
Write a program that checks whether a
number is divisible by 
2 
and 
3
, by 
2 
or 
3
,
and by 
2 
or 
3 
but not both.
TestBooleanOperators.java
LeapYear.java 
(
A leap year is divisible by 4 but not by 100
or divisible by 400.)
Lottery.java
Object Oriented Programming
11
Switch statement
A 
switch 
statement executes statements based
on the value of a variable or an 
expression.
switch 
(
switch
-expression) {
case 
value1: statement(s)1;
break
;
case 
value2: statement(s)2;
break
;
case 
valueN: statement(s)N;
break
;
default
: statement(s)-
for
-
default
;
}
Object Oriented Programming
12
The 
switch 
statement observes the following rules:
 
The 
switch-expression 
must yield a value of 
char
, 
byte
, 
short
, 
int
,
or 
String 
type and must always be enclosed in parentheses. (The 
char
and 
String 
types will be introduced in the next chapter.)
 The 
value1
, . . ., and 
valueN 
must have the same data type as the
value of the 
switchexpression
. Note that 
value1
, . . ., and 
valueN 
are
constant expressions, meaning that they cannot contain variables, such
as 
1 + x
.
 When the value in a 
case 
statement matches the value of the
switch-expression
, the statements 
starting from this case 
are executed
until either a 
break 
statement or the end of the 
switch 
statement is
reached.
 The 
default 
case, which is optional, can be used to perform actions
when none of the specified cases matches the 
switch-expression
.
 The keyword 
break 
is optional. The 
break 
statement immediately
ends the 
switch 
statement.
Conditional Expression
A conditional expression evaluates an
expression based on a condition.
Object Oriented Programming
13
Operator Precedence and
Associativity
Operator precedence and associativity
determine the order in which operators
are 
evaluated
Object Oriented Programming
14
undefined
Object Oriented Programming
15
Decreasing order of precedence
All binary operators except assignment operators are 
left associative
.
Mathematical functions
They can be categorized as trigonometric
methods, exponent methods, 
and service
methods.
 They all are used like Math.?
Object Oriented Programming
16
Cont.
 
Object Oriented Programming
17
Character data type
A character data type represents a single
character.
Computers use binary numbers internally.
A character is stored in a computer as a
sequence of 0s and 1s.
Mapping a character to its binary
representation is called 
encoding
.
Object Oriented Programming
18
Cont.
 
Java supports 
Unicode
, an encoding
scheme established by the Unicode
Consortium to support the interchange,
processing, and display of written texts.
Unicode was originally designed as a 16-
bit character encoding.
The Unicode 
standard therefore has been
extended to allow up to 1,112,064
characters.
Object Oriented Programming
19
Cont.
Those characters 
that go beyond the original
16-bit limit are called 
supplementary
characters
. Java supports 
the supplementary
characters.
A 16-bit Unicode takes two bytes, preceded
by 
\u
, expressed in four hexadecimal digits
that run from 
\u0000 
to 
\uFFFF.
Unicode includes ASCII code, with 
\u0000
to 
\u007F 
corresponding 
to the 128 ASCII
characters.
Object Oriented Programming
20
Escape Sequence for special
characters
Java uses a special notation to represent
special characters.
Object Oriented Programming
21
Casting between character and
numeric type
A 
char 
can be cast into any numeric type,
and vice versa.
Object Oriented Programming
22
Comparing and Testing Character
Two characters can be compared using
the relational operators just like
comparing two 
numbers.
This is done by comparing the Unicodes
of the two characters
Object Oriented Programming
23
Cont.
 
Object Oriented Programming
24
String
A string is a sequence of characters.
To represent a string of characters, use
the data type called 
String
. For example;
String message = 
"Welcome to Java"
;
 
String 
is a predefined class in the Java
library, just like the classes 
System 
and
Scanner
.
The 
String 
type is not a primitive type. It
is known as a 
reference type
.
Object Oriented Programming
25
Cont.
Strings are objects in Java.
Instance method and static method
Object Oriented Programming
26
Reading a string from the console
 
Object Oriented Programming
27
Enter three words separated by spaces:  Welcome to Java
Reading single character
Object Oriented Programming
28
char c = (char) System.in.read();
String Comparison
Object Oriented Programming
29
OrderTwoCities.java
Obtain substring
You can obtain a single character from a
string using the 
charAt 
method. You can
also obtain a substring from a string using
the 
substring 
method in the 
String
class
Object Oriented Programming
30
Finding a Character or a Substring
in a String
The 
String 
class provides several
versions of 
indexOf 
and 
lastIndexOf
methods to find a character or a
substring in a string.
Object Oriented Programming
31
Conversion between strings and
numbers
You can convert a numeric string into a
number. To convert a string into an 
int 
value,
use the 
Integer.parseInt 
method, as
follows.
int 
intValue = Integer.parseInt(intString);
(“123”)
Double 
doubleValue =
Double.parseDouble(doubleString);
(“65.35”)
If the string is not a numeric string, the
conversion would cause a runtime error.
Object Oriented Programming
32
Cont.
You can convert a number into a string,
simply use the string concatenating
operator as 
follows:
      String s = number + 
""
;
Object Oriented Programming
33
HexDigit2Dec.java
Formatting console output
You can use the 
System.out.printf
method to display formatted output on
the 
console.
Object Oriented Programming
34
Cont.
Object Oriented Programming
35
System.out.printf(format, item1, item2, ..., item
k
)
Cont.
Object Oriented Programming
36
Cont.
By default, the output is right justified.
You can put the minus sign (
-
) in the
format specifier to specify that the item is
left justified in the output within the
specified field.
Object Oriented Programming
37
Loops
A loop can be used to tell a program to
execute statements repeatedly.
While
Do… while
For
Object Oriented Programming
38
While
SubtractionQuizLoop.java
Controlling loop with sentinel value
SentinelValue.java
Input/output redirection
java SentinelValue < input.txt
java ClassName > output.txt
Object Oriented Programming
39
Do…while
A 
do-while 
loop is the same as a 
while
loop except that it executes the loop
body first and then checks the loop
continuation condition.
Object Oriented Programming
40
For loop
A 
for 
loop has a concise syntax for
writing loops.
Object Oriented Programming
41
Which loop to use?
You can use a 
for 
loop, a 
while 
loop, or a
do-while 
loop, whichever is convenient.
Pre test loop (while and for)
Post test loop (do…while)
Object Oriented Programming
42
Break and Continue
The 
break 
and 
continue 
keywords
provide additional controls in a loop.
Object Oriented Programming
43
Methods
Methods can be used to define reusable
code and organize and simplify coding.
Object Oriented Programming
44
Defining method
A method definition consists of its
method name, parameters, return value
type, and body.
Object Oriented Programming
45
Modularizing Code
Modularizing makes the code easy to
maintain and debug and enables the code to
be 
reused.
By encapsulating the code for obtaining the
gcd in a method, this program has several
advantages:
1. It isolates the problem for computing the gcd from the rest
of the code in the main method. Thus, the logic becomes clear
and the program is easier to read.
2. The errors on computing the gcd are confined in the 
gcd
method, which narrows the 
scope of debugging.
3. The 
gcd 
method now can be reused by other programs.
Object Oriented Programming
46
Overloading methods
Overloading methods enables you to
define the methods with the same name
as long as their signatures are different.
Overloaded methods must have different
parameter lists. You cannot overload
methods based on different modifiers or
return types.
TestMethodOverloading.java
Object Oriented Programming
47
Cont.
 
Can you invoke the 
max 
method with an 
int
value and a 
double 
value, such as 
max(2,
2.5)
?
If so, which of the 
max 
methods is invoked?
The answer to the first question is yes.
The answer to the second question is that the
max 
method for finding the maximum of two
double 
values is invoked.
The argument value 
2 
is automatically
converted into a 
double 
value and passed to
this method.
The Java compiler finds the method that best matches a method invocation. Since the method
max(int, int) 
is a better matches for 
max(3, 4) 
than 
max(double, double)
, 
max(int, int)
is used to invoke 
max(3, 4)
.
Object Oriented Programming
48
Scope of Variables
The scope of a variable is the part of the
program where the variable can be
referenced.
The scope of a method parameter covers
the entire method.
A variable declared in the initial-action part
of a 
for
-loop header has its scope in the
entire loop.
However, a variable declared inside a 
for
-
loop body has its scope limited in the loop
body from its declaration to the end o the
block that contains the variable
Object Oriented Programming
49
 
You can declare a local variable with the
same name in different blocks in a method,
but you cannot declare a local variable twice
in the same block or in nested blocks
Object Oriented Programming
50
Cont.
Object Oriented Programming
51
 
for 
(
int 
i = 
0
; i < 
10
; i++) {
}
System.out.println(i);
 
The last statement would cause a syntax error, because variable 
i 
is not
defined outside 
of the 
for 
loop.
Single Dimensional Array
elementType[] arrayRefVar
 : The
elementType 
can be any data type, and
all elements in the array will have the
same data type
double
[] myList
 : For example, this code
declares a variable 
myList 
that
references an array of double elements
Object Oriented Programming
52
Cont.
Unlike declarations for primitive data type
variables, the declaration of an array
variable 
does not allocate
 any space in
memory for the array.
It creates only a storage location for the
reference to an array.
If a variable does not contain a reference
to an array, the value of the variable is
null
Object Oriented Programming
53
Cont.
You can create an array by using the 
new
operator and assign its reference to the
variable with the following syntax:
arrayRefVar = 
new 
elementType[arraySize];
 This statement does two things: (1) it
creates an array using 
new
elementType[arraySize]
;
(2) it assigns the reference of the newly
created array to the variable
arrayRefVar
.
Object Oriented Programming
54
Cont.
Declaring an array variable, creating an
array, and assigning the reference of the
array to the variable can be combined in
one statement as:
elementType[] arrayRefVar = 
new
elementType[arraySize];
OR
elementType arrayRefVar[] = 
new
elementType[arraySize];
Object Oriented Programming
55
Cont.
Size can be obtained using
arrayRefVar.length
When an array is created, its elements are
assigned the default value of 
0 
for the
numeric primitive data types, 
\u0000
(NULL) 
for 
char 
types, and 
false 
for
boolean 
types.
Each element in the array is represented
using the following syntax, known as an
indexed variable: 
arrayRefVar[index];
Object Oriented Programming
56
Initializing Array
Java has a shorthand notation, known as the 
array initializer
, which
combines the declaration, creation, and initialization of an array in
one statement using the following syntax:
elementType[] arrayRefVar = {value0, value1, ..., valuek};
double
[] myList = {
1.9
, 
2.9
, 
3.4
, 
3.5
};
                        OR
double
[] myList = 
new double
[
4
];
myList[
0
] = 
1.9
;
myList[
1
] = 
2.9
;
myList[
2
] = 
3.4
;
myList[
3
] = 
3.5
;
Splitting it would cause a syntax error. Thus, the next statement is
wrong:
double
[] myList;
myList = {
1.9
, 
2.9
, 
3.4
, 
3.5
};
Object Oriented Programming
57
Processing Array
Initializing arrays with input
values/Initializing arrays with random
values
Displaying arrays
Summing all elements
Finding the largest element
Finding the smallest index of the largest
element
Random shuffling
Object Oriented Programming
58
Foreach loop
Java supports convenient 
for 
loop, known
as a 
foreach loop
, which enables you to
traverse the array sequentially without
using an index variable.
for 
(
double 
e: myList) {
System.out.println(e); }
Object Oriented Programming
59
Copying Arrays
To copy the contents of one array into
another, you have to copy the array’s
individual elements into the other array.
list2 = list1; - 
However, this statement
does not copy the contents of the array
referenced by 
list1 
to 
list2
, but instead
merely copies the reference value from
list1 
to 
list2
.
Object Oriented Programming
60
Cont.
Object Oriented Programming
61
 
Another approach is to use the
arraycopy 
method in the
java.lang.System 
class to copy arrays
instead of using a loop
arraycopy(sourceArray, srcPos, targetArray, tarPos, length);
System.arraycopy(sourceArray, 
0
, targetArray, 
0
, sourceArray.length);
Passing array to the method
When passing an array to a method, the
reference of the array is passed to the
method.
Object Oriented Programming
62
Returning array from the method
When a method returns an array, the
reference of the array is returned.
You can pass arrays when invoking a
method. A method may also return an
array.
Object Oriented Programming
63
Counting occurrence of each letter
CountLettersInArray.java
Object Oriented Programming
64
Variable length arguments list
A variable number of arguments of the same type
can be passed to a method and 
treated as an
array.
You can pass a variable number of arguments of
the same type to a method.
Declared as follows:
             typeName... parameterName
Only one 
variable-length parameter may be
specified in a method, and this parameter must be
the last parameter.
Any regular parameters must precede it.
VarArgsDemo.java
Object Oriented Programming
65
Searching array
 
Linear search and Binary search.
If an array is sorted, binary search is more
efficient than linear search for finding an
element in the array.
Linear search
Object Oriented Programming
66
Cont.
Binary search
Object Oriented Programming
67
Sorting array
Sorting, like searching, is a common task
in computer programming.
Many different algorithms have been
developed for sorting.
Bubble sort, insertion sort, selection sort,
quick sort, merge sort, radix sort etc.
SelectionSort.java
Object Oriented Programming
68
Array class
The 
java.util.Arrays 
class contains
useful methods for common array
operations such as sorting and searching.
Object Oriented Programming
69
Binary search
Sort
Command line arguments
The 
main 
method can receive string
arguments from the command line.
commandLineArgs.java
Object Oriented Programming
70
Multi dimensional array
An element in a two-dimensional array is
accessed through a row and column
index.
elementType[][] arrayRefVar;
OR
elementType arrayRefVar[][];
 int[][] matrix = new int[3][3];
matrix.length gives entire array size
matrix[0].length gives size of 0
th
 row
Object Oriented Programming
71
Cont.
Each row in a two-dimensional array is
itself an array.
Thus, the rows can have different lengths.
An array of this kind is known as a 
ragged
array.
Object Oriented Programming
72
 
If you don’t know the values in a ragged
array in advance, but do know the sizes—
say, the same as before—you can create a
ragged array 
using the following syntax
Object Oriented Programming
73
Passing two – d array to methods
When passing a two-dimensional array to
a method, the reference of the array is
passed to the method.
PassTwoDimensionalArray.java
Multi dimensional array
double
[][][] scores = 
new double
[
6
][
5
][
2
];
Object Oriented Programming
74
Multi dimensional array
 
Object Oriented Programming
75
Slide Note
Embed
Share

Selection statements in programming use Boolean expressions to control program flow. Learn about if statements, if-else statements, nested if statements, and logical operators. Explore how to generate random numbers, compute BMI, and work with the boolean data type.

  • Programming Basics
  • Boolean Expressions
  • If Statements
  • Logical Operators
  • Random Numbers

Uploaded on Mar 10, 2025 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Selections The statements condition. program can execute decide based which on to a Selection statements use conditions that are Boolean expressions. A Boolean expression is an expression that evaluates to a Boolean value:true or false. Object Oriented Programming 1

  2. Boolean data type The boolean data type declares a variable with the value either true or false (they are literals like number). Ex. boolean lightsOn = true; Object Oriented Programming 2

  3. If (one-way) statement An if statement is a construct that enables a program to specify alternative paths of execution. if (boolean-expression) { statement(s); } Object Oriented Programming 3

  4. Cont. Object Oriented Programming 4

  5. Two-way if else An execution path based on whether the condition is true or false. if (boolean-expression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; } if-else statement decides the Object Oriented Programming 5

  6. Nested or Multi-way if An if statement can be inside another if statement to form a nested if statement. The if (j > k) statement is nested inside the if (i > k) statement in the following. Object Oriented Programming 6

  7. Generating Random Numbers You can use Math.random() to obtain a random double value between 0.0 and 1.0, excluding 1.0. SubtractionQuiz.java Object Oriented Programming 7

  8. Computing Body Mass Index (BMI) BMI = weigh in KG/ (height in meters)2 ComputeAndInterpretBMI.java Object Oriented Programming 8

  9. Logical Operators The logical operators !, &&, ||, and ^ can be used to create a compound Boolean expression. Object Oriented Programming 9

  10. Object Oriented Programming 10

  11. Cont. Write a program that checks whether a number is divisible by 2 and 3, by 2 or 3, and by 2 or 3 but not both. TestBooleanOperators.java LeapYear.java (A leap year is divisible by 4 but not by 100 or divisible by 400.) Lottery.java Object Oriented Programming 11

  12. Switch statement A switch statement executes statements based on the value of a variable or an expression. switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; case valueN: statement(s)N; break; default: statement(s)-for-default; } The keyword break is optional. The break statement immediately ends the switch statement. The switch statement observes the following rules: The switch-expression must yield a value of char, byte, short, int, or String type and must always be enclosed in parentheses. (The char and String types will be introduced in the next chapter.) The value1, . . ., and valueN must have the same data type as the value of the switchexpression. Note that value1, . . ., and valueN are constant expressions, meaning that they cannot contain variables, such as 1 + x. When the value in a case statement matches the value of the switch-expression, the statements starting from this case are executed until either a break statement or the end of the switch statement is reached. The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression. Object Oriented Programming 12

  13. Conditional Expression A conditional expression evaluates an expression based on a condition. Object Oriented Programming 13

  14. Operator Precedence and Associativity Operator precedence and associativity determine the order in which operators are evaluated Object Oriented Programming 14

  15. Decreasing order of precedence All binary operators except assignment operators are left associative. Object Oriented Programming 15

  16. Mathematical functions They can be categorized as trigonometric methods, exponent methods, and service methods. They all are used like Math.? Object Oriented Programming 16

  17. Cont. Object Oriented Programming 17

  18. Character data type A character data type represents a single character. Computers use binary numbers internally. A character is stored in a computer as a sequence of 0s and 1s. Mapping a character to its binary representation is called encoding. Object Oriented Programming 18

  19. Cont. Java supports Unicode, an encoding scheme established by the Unicode Consortium to support the interchange, processing, and display of written texts. Unicode was originally designed as a 16- bit character encoding. The Unicode standard therefore has been extended to allow up to 1,112,064 characters. Object Oriented Programming 19

  20. Cont. Those characters that go beyond the original 16-bit limit are characters. Java supports the supplementary characters. A 16-bit Unicode takes two bytes, preceded by \u, expressed in four hexadecimal digits that run from \u0000 to \uFFFF. Unicode includes ASCII code, with \u0000 to \u007F corresponding to the 128 ASCII characters. called supplementary Object Oriented Programming 20

  21. Escape Sequence for special characters Java uses a special notation to represent special characters. Object Oriented Programming 21

  22. Casting between character and numeric type A char can be cast into any numeric type, and vice versa. Object Oriented Programming 22

  23. Comparing and Testing Character Two characters can be compared using the relational operators comparing two numbers. This is done by comparing the Unicodes of the two characters just like Object Oriented Programming 23

  24. Cont. Object Oriented Programming 24

  25. String A string is a sequence of characters. To represent a string of characters, use the data type called String. For example; String message = "Welcome to Java"; String is a predefined class in the Java library, just like the classes System and Scanner. The String type is not a primitive type. It is known as a reference type. Object Oriented Programming 25

  26. Cont. Strings are objects in Java. Instance method and static method Object Oriented Programming 26

  27. Reading a string from the console Enter three words separated by spaces: Welcome to Java Object Oriented Programming 27

  28. Reading single character char c = (char) System.in.read(); Object Oriented Programming 28

  29. String Comparison OrderTwoCities.java Object Oriented Programming 29

  30. Obtain substring You can obtain a single character from a string using the charAt method. You can also obtain a substring from a string using the substring method in the String class Object Oriented Programming 30

  31. Finding a Character or a Substring in a String The String class provides several versions of indexOf and lastIndexOf methods to find a character or a substring in a string. Object Oriented Programming 31

  32. Conversion between strings and numbers You can convert a numeric string into a number. To convert a string into an int value, use the Integer.parseInt method, as follows. int intValue = Integer.parseInt(intString); ( 123 ) Double doubleValue Double.parseDouble(doubleString); ( 65.35 ) If the string is not a numeric string, the conversion would cause a runtime error. = Object Oriented Programming 32

  33. Cont. You can convert a number into a string, simply use the string concatenating operator as follows: String s = number + ""; HexDigit2Dec.java Object Oriented Programming 33

  34. Formatting console output You can use the System.out.printf method to display formatted output on the console. Object Oriented Programming 34

  35. Cont. System.out.printf(format, item1, item2, ..., itemk) Object Oriented Programming 35

  36. Cont. Object Oriented Programming 36

  37. Cont. By default, the output is right justified. You can put the minus sign (-) in the format specifier to specify that the item is left justified in the output within the specified field. Object Oriented Programming 37

  38. Loops A loop can be used to tell a program to execute statements repeatedly. While Do while For Object Oriented Programming 38

  39. While SubtractionQuizLoop.java Controlling loop with sentinel value SentinelValue.java Input/output redirection java SentinelValue < input.txt java ClassName > output.txt Object Oriented Programming 39

  40. Dowhile A do-while loop is the same as a while loop except that it executes the loop body first and then checks the loop continuation condition. Object Oriented Programming 40

  41. For loop A for loop has a concise syntax for writing loops. Object Oriented Programming 41

  42. Which loop to use? You can use a for loop, a while loop, or a do-while loop, whichever is convenient. Pre test loop (while and for) Post test loop (do while) Object Oriented Programming 42

  43. Break and Continue The break and continue keywords provide additional controls in a loop. Object Oriented Programming 43

  44. Methods Methods can be used to define reusable code and organize and simplify coding. Object Oriented Programming 44

  45. Defining method A method definition consists of its method name, parameters, return value type, and body. Object Oriented Programming 45

  46. Modularizing Code Modularizing makes the code easy to maintain and debug and enables the code to be reused. By encapsulating the code for obtaining the gcd in a method, this program has several advantages: 1. It isolates the problem for computing the gcd from the rest of the code in the main method. Thus, the logic becomes clear and the program is easier to read. 2. The errors on computing the gcd are confined in the gcd method, which narrows the scope of debugging. 3. The gcd method now can be reused by other programs. Object Oriented Programming 46

  47. Overloading methods Overloading methods enables you to define the methods with the same name as long as their signatures are different. Overloaded methods must have different parameter lists. You cannot overload methods based on different modifiers or return types. TestMethodOverloading.java Object Oriented Programming 47

  48. Cont. Can you invoke the max method with an int value and a double value, such as max(2,2.5)? If so, which of the max methods is invoked? The answer to the first question is yes. The answer to the second question is that the max method for finding the maximum of two double values is invoked. The argument value 2 is automatically converted into a double value and passed to this method. The Java compiler finds the method that best matches a method invocation. Since the method max(int, int) is a better matches for max(3, 4) than max(double, double), max(int, int) is used to invoke max(3, 4). Object Oriented Programming 48

  49. Scope of Variables The scope of a variable is the part of the program where the variable can be referenced. The scope of a method parameter covers the entire method. A variable declared in the initial-action part of a for-loop header has its scope in the entire loop. However, a variable declared inside a for- loop body has its scope limited in the loop body from its declaration to the end o the block that contains the variable Object Oriented Programming 49

  50. You can declare a local variable with the same name in different blocks in a method, but you cannot declare a local variable twice in the same block or in nested blocks Object Oriented Programming 50

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#