Your Federal Quarterly Tax Payments are due April 15th

VIEWS: 0 PAGES: 61

java programming language lecture

• pg 1
```									Lecture 2
Control Statements, Methods and
Arrays

1
Chapter 3 Control
Statements
Selection   Statements
Using if and if...else
Nested if Statements
Using switch Statements
Conditional   Operator

Repetition    Statements
Looping:while, do-while, and for
Using break and continue

2
Selection Statements
   if Statements
   switch Statements
   Conditional Operators

3
if Statements
if (booleanExpression) {
statement or statements;
}

Example:
if ((i > 0) && (i < 10)) {
System.out.println("i is an " +
"integer between 0 and 10");
}
4
if...else Example

System.out.println("The area for the “
" is " + area);
}
else {
System.out.println("Negative input");
}

5
Multiple Alternative if
Statements
if (score >= 90)          if (score >= 90)
else                      else if (score >= 80)
if (score >= 80)
else                    else if (score >= 70)
if (score >= 70)        grade = ‘C’;
grade = ‘C’;       else if (score >= 60)
if (score >= 60)   else
else
6
Note
The else clause matches the most recent if clause in the
same block. For example, the following statement
int i = 1; int j = 2; int k = 3;
if (i > j)
if (i > k)
System.out.println("A");
else                                    Output?
System.out.println("B");
is equivalent to
int i = 1; int j = 2; int k = 3;
if (i > j)
if (i > k)
System.out.println("A");
else
System.out.println("B");
7
Note, cont.
To force the else clause to match the first if clause,
you must add a pair of braces:
int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");
This statement prints B.

8
switch Statements
switch (year) {
case 7: annualInterestRate = 7.25;
break;
case 15: annualInterestRate = 8.50;
break;
case 30: annualInterestRate = 9.0;
break;
default: System.out.println(
"Wrong number of years, enter 7, 15, or 30");
}

9
switch Statement Rules
 The switch-expression must yield a value of char, byte, short, or
int type
and must always be enclosed in parentheses.

The resulting statements in the case statement are executed when
the value in the case statement matches the value of the switch-
expression. (The case statements are executed in sequential order.)

The keyword break is optional, but it should be used at the end of
each case in order to terminate the remainder of the switch
statement. If the break statement is not present, the next case
statement will be executed.

10
Caution
Do not forget to use a break statement when one is
needed. For example, the following code always
displays Wrong number of years regardless of what
numOfYears is. Suppose the numOfYears is 15. The
statement annualInterestRate = 8.50 is executed, then
the statement annualInterestRate = 9.0, and finally the
statement System.out.println("Wrong number of years").

switch (numOfYears) {
case 7: annualInterestRate = 7.25;
case 15: annualInterestRate = 8.50;
case 30: annualInterestRate = 9.0;
default: System.out.println("Wrong number of years");
}

11
Conditional Operator
(booleanExp) ? exp1 : exp2

12
Conditional Operator
if (x > 0) y = 1
else y = -1;

is equivalent to

y = (x > 0) ? 1 : -1;

Ternary operator

13
Conditional Operator
if (num % 2 == 0)
System.out.println(num + “is even”);
else
System.out.println(num + “is odd”);

System.out.println(
(num % 2 == 0)? num + “is even” :
num + “is odd”);

14
Repetitions
   while Loops
   do-while Loops
   for Loops
   break and continue

15
while Loop Flow Chart
while (continuation-condition) {
// loop-body;
}
false
Continuation
condition?

true

Statement(s)

Next
Statement
16
while Loop Flow Chart, cont.
i = 0;

int i = 0;
while (i < 100) {                                                 false
(i < 100)
System.out.println(
"Welcome to Java!");
i++;
true
}
System.out.println("Welcoem to Java!");
i++;

Next
Statement

17
do-while Loop
do {                                   Statement(s)

// Loop body;
true
} while (continue-condition);           Continue
condition?

false

Next
Statement

18
for Loops
for (initial-action; loop-continuation-condition;
action-after-each-iteration) {
//loop body;
}

int i = 0;
while (i < 100) {
System.out.println("Welcome to Java! ” + i);
i++;
}
Example:
int i;
for (i = 0; i < 100; i++) {
System.out.println("Welcome to Java! ” + i);
}

19
for Loop Flow Chart
for (initial-action;                         Initial-Action
loop-continuation-condition;
action-after-each-iteration) {
//loop body;
}
false
Action-After-    Continuation
Each-Iteration    condition?

true

Statement(s)
(loop-body)

Next
Statement

20
for Loop Example
int i;
i=0
for (i = 0; i<100; i++) {
System.out.println(
"Welcome to Java");                            false
i++        i<100?
}
true

System.out.println(
“Welcom to Java!”);

Next
Statement

21
The break Keyword
false
Continuation
condition?

true

Statement(s)

break

Statement(s)

Next
Statement
22
The continue Keyword
false
Continue
condition?

true

Statement(s)

continue

Statement(s)

Next
Statement
23
Chapter 4 Methods
   Introducing Methods
   Benefits of methods, Declaring Methods, and
Calling Methods

   Passing Parameters
   Pass by Value

   Scope of Local Variables
   The Math Class

24
Introducing Methods
Method Structure
A method is a
collection of
statements that are
grouped together
to perform an
operation.

25
Introducing Methods, cont.
•parameter profile refers to the type,
order, and number of the parameters of a
method.
•method signature is the combination of the
method name and the parameter profiles.
•The parameters defined in the method
header are known as formal parameters.
•When a method is invoked, its formal
parameters are replaced by variables or   26

data, which are referred to as actual
Declaring Methods
public static int max(int num1, int
num2) {
if (num1 > num2)
return num1;
else
return num2;
}

27
Calling Methods
pass i
pass j

public static void main(String[] args) {   public static int max(int num1, int num2) {
int i = 5;                                 int result;
int j = 2;
int k = max(i, j);                           if (num1 > num2)
result = num1;
System.out.println(                        else
"The maximum between " + i +                result = num2;
" and " + j + " is " + k);
}                                              return result;
}

28
Calling Methods, cont.
The main method   pass 5   The max method

i:        5                num1:           5
pass 2
parameters

j:        2                num2:           2

k:        5                result:         5

29
CAUTION
A return statement is required for a nonvoid
method. The following method is logically correct,
but it has a compilation error, because the Java
compiler thinks it possible that this method does
not return any value.
public static int xMethod(int n) {
if (n > 0) return 1;
else if (n == 0) return 0;
else if (n < 0) return –1;
}
To fix this problem, delete if (n<0) in the code.

30
Passing Parameters
public static void nPrintln(String message, int n)
{
for (int i = 0; i < n; i++)
System.out.println(message);
}

31
Pass by Value
This program demonstrates passing values
to the methods.
Define a swap method that swaps two input
values. Show the two values before, during
and after calling the method.

TestPassByValue

32
Pass by Value, cont.
Invoke swap                                 The values of num1 and
num1    1
num2 are passed to n1 and
swap(num1, num2)                     n2. Executing swap does not
num2    2
affect num1 and num2.

Pass by value

swap( n1,    n2)            n1   1       Swap           n1         2

n2   2                      n2         1

temp         1

Execute swap inside the swap body

33
Scope of Local Variables
A local variable: a variable defined inside a
method.
Scope: the part of the program where the
variable can be referenced.
The scope of a local variable starts
from its declaration and continues to
the end of the block that contains the
variable.
34
Scope of Local Variables, cont.
You can declare a local variable with
the same name multiple times in
different blocks in a method.

35
Scope of Local Variables, cont.
// Fine with no errors
public static void correctMethod() {
int x = 1;
int y = 1;
// i is declared
for (int i = 1; i < 10; i++) {
x += i;
}
// i is declared again
for (int i = 1; i < 10; i++) {
y += i;
}
}
36
The Math Class
   Class constants:
   PI
java.lang.Math
   E
   Class methods:
   Trigonometric Methods
   Exponent Methods
   Rounding Methods
   min, max, abs, and random Methods

37
Trigonometric Methods
   sin(double a)
   cos(double a)
   tan(double a)
   acos(double a)
   asin(double a)
   atan(double a)

38
Exponent Methods
   exp(double a)
Returns e raised to the power of a.
   log(double a)
Returns the natural logarithm of a.
   pow(double a, double b)
Returns a raised to the power of b.
   sqrt(double a)
Returns the square root of a.

39
Rounding Methods
   double ceil(double x)
x rounded up to its nearest integer. This integer is
returned as a double value.
   double floor(double x)
x is rounded down to its nearest integer. This integer
is returned as a double value.
   int round(float x)
Return (int)Math.floor(x+0.5).
   long round(double x)
Return (long)Math.floor(x+0.5).

40
min, max, abs, and random
   max(a, b)and min(a, b)
Returns the maximum or minimum of two
parameters.
   abs(a)
Returns the absolute value of the parameter.
   random()
Returns a random double value
in the range [0.0, 1.0).

41
Chapter 5 Arrays
   Introducing Arrays
   Declaring Array Variables, Creating Arrays,
and Initializing Arrays
   Passing Arrays to Methods
   Copying Arrays
   Multidimensional Arrays

42
Introducing Arrays
Array is a data structure that represents a collection of the
same type of data.
double[] myList = new double[10];

myList   reference              myList[0]
myList[1]
myList[2]                An Array of 10
myList[3]
Elements
myList[4]
myList[5]
of type double
myList[6]
myList[7]
myList[8]
myList[9]

43
Declaring Array Variables
   datatype[] arrayname;

Example:
double[] myList;

   datatype arrayname[];

Example:
double myList[];

44
Creating Arrays
arrayName = new datatype[arraySize];

Example:
myList = new double[10];

myList[0] references the first element in the array.
myList[9] references the last element in the array.

45
Declaring and Creating
in One Step
   datatype[] arrayname = new
datatype[arraySize];
double[] myList = new double[10];

   datatype arrayname[] = new
datatype[arraySize];
double myList[] = new double[10];

46
The Length of Arrays
   Once an array is created, its size is fixed. It
cannot be changed. You can find its size using

arrayVariable.length

For example:
myList.length returns 10

47
Initializing Arrays
   Using a loop:
for (int i = 0; i < myList.length; i++)
myList[i] = i;

   Declaring, creating, initializing in one step:
double[] myList = {1.9, 2.9, 3.4, 3.5};

This shorthand syntax must be in one
statement.

48
Declaring, creating, initializing
Using the Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};

This shorthand notation is equivalent to the
following statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;

49
CAUTION
Using the shorthand notation, you have
to declare, create, and initialize the
array all in one statement. Splitting it
would cause a syntax error. For
example, the following is wrong:
double[] myList;

myList = {1.9, 2.9, 3.4, 3.5};

50
Passing Arrays to Methods
Java uses pass by value to pass parameters to a
method. There are important differences between
passing a value of variables of primitive data types
and passing arrays.
 For a parameter of a primitive type value, the actual
value is passed. Changing the value of the local
parameter inside the method does not affect the
value of the variable outside the method.
 For a parameter of an array type, the value of the
parameter contains a reference to an array; this
reference is passed to the method. Any changes to
the array that occur inside the method body will
affect the original array that was passed as the
argument.                                         51
Example: Passing Arrays as
Arguments

   Objective: Demonstrate differences of
passing primitive data type variables and
array variables.

TestPassArray

52
Example, cont.
swap(a[0], a[1])           a[0]     1       a[1]      2

Pass by value

swap( n1,     n2)            n1     1        n2       2

swapFirstTwoInArray(a)      a Reference           a[0]
:           a[1]
Pass by value (Reference value)

swapFirstTwoInArray(array)   array Reference

53
Example: Copying Arrays
In this example, you will see that a simple
assignment cannot copy arrays in the
following program. The program simply
creates two arrays and attempts to copy one
to the other, using an assignment statement.

TestCopyArray
54
Copying Arrays

Before the assignment               After the assignment
list2 = list1;                      list2 = list1;

list1                               list1
Contents                           Contents
of list1                           of list1

list2                               list2
Contents                           Contents
of list2                           of list2
Garbage

55
Copying Arrays
Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[sourceArray.length];

for (int i = 0; i < sourceArrays.length; i++)
targetArray[i] = sourceArray[i];

56
The arraycopy Utility
arraycopy(sourceArray, src_pos,
targetArray, tar_pos, length);

Example:
System.arraycopy(sourceArray, 0,
targetArray, 0, sourceArray.length);

57
Multidimensional Arrays
Declaring Variables of Multidimensional Arrays and
Creating Multidimensional Arrays

int[][] matrix = new int[10][10];
or
int matrix[][] = new int[10][10];
matrix[0][0] = 3;

for (int i=0; i<matrix.length; i++)
for (int j=0; j<matrix[i].length; j++)
{
matrix[i][j] = (int)(Math.random()*1000);
}

58
Multidimensional Array Illustration

0 1   2   3   4           0 1   2   3   4       0    1       2
0                         0                     0   1    2       3

1                         1                     1   4    5       6

2                         2     7               2   7        8   9

3                         3                     3   10   11      12

4                         4                     int[][] array = {
{1, 2, 3},
matrix = new int[5][5];   matrix[2][1] = 7;       {4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};

59
Declaring, Creating, and Initializing Using
Shorthand Notations
You can also use a shorthand notation to declare,
create and initialize a two-dimensional array.
Ex:
int[][] x = {
{1, 2, 3,4},
{5, 6,7,8},
{9,10,11,12}
};
This is equivalent to the following statements:
int[][] x = new int[3][4];
x[0][0] = 1; x[0][1] = 2; x[0][2] = 3; x[0][3] = 4;
x[1][0] = 5; x[1][1] = 6; x[1][2] = 7; x[1][3] = 8;
x[2][0] = 9; x[2][1] = 10; x[2][2] = 11; x[2][3] = 12;
60
Ragged Arrays
Each row in a two-dimensional array is itself an
array. So, the rows can have different lengths.
Such an array is known as a ragged array. For
example,
int[][] matrix = {
{1, 2, 3, 4, 5},
{2, 3, 4, 5},
{3, 4, 5},
{4, 5},
{5}
};
61

```
To top