0% found this document useful (0 votes)
42 views50 pages

Day 4 - Object Oriented Programming

The document discusses control structures, arrays, and methods in Java. It describes: 1) Control structures like if/else statements, switch statements, and loops (while, for, do-while) that alter the flow of a program. 2) Arrays which store a collection of values of the same type. Arrays can be declared with a size and initialized with values. 3) Methods which are code blocks that perform tasks and are reused.

Uploaded by

yosef
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views50 pages

Day 4 - Object Oriented Programming

The document discusses control structures, arrays, and methods in Java. It describes: 1) Control structures like if/else statements, switch statements, and loops (while, for, do-while) that alter the flow of a program. 2) Arrays which store a collection of values of the same type. Arrays can be declared with a size and initialized with values. 3) Methods which are code blocks that perform tasks and are reused.

Uploaded by

yosef
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50

Fundamental

Programming
Structures in Java- II
Lecture - 03
March 15,2013
1
Outline
Control Structures

Arrays

Methods

2
Program Flow
a more sophisticated program
Java will execute the statements in your code in
statement
a specific sequence, or "flow".
The "flow" of the program and can be described statement

through a "flow diagram":

a simple program
statement statement
statement

statement statement

statement

statement
statement
What are Control
Structures?
Control structures alter the flow of the program, the
sequence of statements that are executed in a
program.

They act as "direction signals" to control the path a


program takes.

Two types of control structures in Java:


 decision statements
 loops
Decision Statements
A decision statement allows the code to execute a

statement or block of statements conditionally.

Two types of decisions statements in Java:


 if statements

 switch statements
If Statement
if (expression) {
statement;
}
rest_of_program;

expression must evaluate to a boolean value, either


true or false
If expression is true, statement is executed and
then rest_of_program
If expression is false, statement is not executed
and the program continues at rest_of_program
If-Else Statement
if (expression) {
statement1;
}
else{
statement2;
}
next_statement;

Again, expression must produce a boolean value

If expression is true, statement1 is executed and


then next_statement is executed.
If expression is false, statement2 is executed and
then next_statement is executed.
Switch Statements
 The switch statement enables you to test several cases generated by a
given expression.

switch (expression) {
case value1:
statement1;
case value2:
statement2;
default:
default_statement;
}
Every statement after the true case is executed

 The expression must evaluate to a char, byte, short or int,


but not long, float, or double.
Switch Flow Chart
expression y
equals Do value1 thing
value1?
switch (expression){
case value1:
// Do value1 thing n
case value2:
// Do value2 thing
expression y
equals Do value2 thing
...
default: value2?
// Do default action
}
// Continue the program n

Do default action

Continue the
program
Break Statements in Switch Statements
The break statement tells the computer to exit
the switch statement
For example:
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
default:
default_statement;
break;
}
Switch & Break Flow Analysis
switch (expression){ expression y
case value1: equals Do value1 thing break
// Do value1 thing value1?
break;

case value2: n
// Do value2 thing
break;
expression y
... equals Do value2 thing break
default: value2?
// Do default action
break;
} n
// Continue the program

do default action

Continue the
break
program
Loops
 A loop allows you to execute a statement or

block of statements repeatedly.


 Three types of loops in Java:
1. while loops

2. for loops
( Java also has a specialized for loop called enhanced for -loop)

3. do-while loops
The while Loop
while (expression){
statement;
}

This while loop executes as long as the given logical expression

between parentheses is true. When expression is false,


execution continues with the statement following the loop block.

The expression is tested at the beginning of the loop, so if it is

initially false, the loop will not be executed at all.


The for Loop
for (init_expr; loop_condition; increment_expr) {
statement;
}

The control of the for loop appear in parentheses and is made up of three parts:

1. The first part, the init_expression,sets the initial conditions for the

loop and is executed before the loop starts.

2. Loop executes so long as the loop_condition is true and exits otherwise.

3. The third part of the control information, the increment_expr, is usually

used to increment the loop counter. This is executed at the end of each loop
iteration.
For example:

int sum = 0;

for (int i = 1; i <= 10; i++) {


sum += i;
}

What is the value of sum?

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
If there is more than one variable to set up or
increment they are separated by a comma.

for(i=0, j=0; i*j < 100; i++, j+=2) {


System.out.println(i * j);
}

You do not have to fill all three control expressions


but you must still have two semicolons.

int n = 0;
for(; n <= 100;) {
System.out.println(++n);
}
The continue Statement
The continue statement causes the program to
jump to the next iteration of the loop.

/**
* prints out "5689"
*/
for(int m = 5; m < 10; m++) {
if(m == 7) {
continue;
}
System.out.print(m);
}
Another continue example:

int sum = 0;
for(int i = 1; i <= 10; i++){
if(i % 3 == 0) {
continue;
}
sum += i;
}

What is the value of sum?


1 + 2 + 4 + 5 + 7 + 8 + 10 = 37
The break Statement
We have seen the use of the break statement
in the switch statement.
You can also use the break statement to exit
the loop entirely.
// prints out numbers unless
// num is ever exactly 400
while (num > 6) {
if(num == 400) {
break;
}
System.out.println(num);
num += 8;
}
POP QUIZ
1. In the switch statement, which types can
expression evaluate to?
char, byte, short, int

2. What must be used to separate each section


of a for statement. semicolons

3. Which statement causes a program to skip


continue
to the next iteration of a loop.
What are Arrays?
An array is a data structure that stores a collection of

values of the same type.

Each compartment is appropriately sized for the

particular data type the array is declared to store.

An array can hold only one type of data!


E.g. int[] can hold only integers

char[] can hold only characters


Array Visualization
Specifies an array of
variables of type int
We are creating
a new array object

int[] primes = new int[10]; // An array of 10 integers

The name of The array object is of


the array type int
and has ten elements index values

primes[0]primes[1]primes[2]primes[3]primes[4] primes[9]
Declaring an Array Variable

Array declarations use square brackets.


datatype[] label;

For example:
int[] prices;
String[] names;
Creating a New "Empty" Array
Example syntax: int[] prices = new int[20];

The new keyword creates an array of type int that has 20

compartments

The new array can then be assigned to the array variable prices:

When first created as above, the items in the array are

initialized to the zero value of the data type


int: 0 double: 0.0 String: null
Constructing Arrays
 To construct an array, you can declare a new empty
array and then assign values to each of the
compartments:

String[] names = new String[5];


names[0] = "David";
names[1] = "Qian";
names[2] = "Emina";
names[3] = "Jamal";
names[4] = "Ashenafi";
Another Way to Construct Arrays
You can also specify all of the items in an array at its creation.

Use curly brackets to surround the array’s data and separate the

values with commas:


String[] names = { "David", "Qian",
"Emina", "Jamal", "Ashenafi"};

Note that all the items must be of the same type. Here they are of

type String.

Another example:
int[] powers = {0, 1, 10, 100};
Length of array
String[] names = {
"David", "Qian", "Emina",
"Jamal", "Ashenafi" };
int numberOfNames = names.length;
System.out.println(numberOfNames);

Output: 5

Important: Arrays are always of the same size:


their lengths cannot be changed once they are
created!
Example
String[] names = {
"Aisha", "Tamara", "Gikandi", "Ato", "Lauri"};
for(int i = 0; i < names.length; i++){
System.out.println("Hello " + names[i] + ".");
}

Output:
Hello Aisha.
Hello Tamara.
Hello Gikandi.
Hello Ato.
Hello Lauri.
Modifying Array Elements
Example:
names[0] = “Bekele"
Now the first name in names[] has been changed
from "Aisha" to "Bekele".
So the expression names[0] now evaluates to
"Bekele".
Note: The values of compartments can change,
but no new compartments may be added.
Example
int[] fibs = new int[10];
fibs[0] = 1;
fibs[1] = 1;
for(int i = 2; i < fibs.length; i++) {
fibs[i] = fibs[i-2] + fibs[i-1];
}
Note: array indexes can be expressions
After running this code, the array fibs[]
contains the first ten Fibonacci numbers:
1 1 2 3 5 8 13 21 34 55
Exercise 1
 Which of the following sequences of statements
does not create a new array?

a. int[] arr = new int[4];

b. int[] arr;
arr = new int[4];

c. int[] arr = { 1, 2, 3, 4};

d. int[] arr; just declares an array variable


Exercise 2
Given this code fragment,
int[] data = new int[10];
System.out.println(data[j]);

Which of the following is a legal value of j?

a. -1 // out of range
b. 0 // legal value
c. 3.5 // out of range
d. 10 // out of range
Exercise 3
 Which set of data would not be suitable for
storing in an array?
a. the score for each of the four quarters of a Football
match
b. your name, date of birth, and score on your physics
test // these are different types
c. temperature readings taken every hour throughout a
day
d. your expenses each month for an entire year
Exercise 4
 What is the value of c after the following code
segment?

int [] a = {1, 2, 3, 4, 5};


int [] b = {11, 12, 13};
int [] c = new int[4];
for (int j = 0; j < 3; j++) {
c[j] = a[j] + b[j];
}
c = [12, 14, 16, 0]
2-Dimensional Arrays
The arrays we've used so far can be
thought of as a single row of values.
0 1
A 2-dimensional array can be thought 0 8 4
of as a grid (or matrix) of values
1 9 7
Each element of the 2-D array is
2 3 6
accessed by providing two indexes:
a row index and a column index value at row index 2,
column index 0 is 3
(A 2-D array is actually just an array of arrays)
2-D Array Example
Example:

A landscape grid of a 20 x 55 acre piece of land:


We want to store the height of the land at each
row and each column of the grid.

We declare a 2D array two sets of square brackets:


double[][] heights = new double[20][55];

This 2D array has 20 rows and 55 columns

To access the acre at row index 11 and column index 23 user:
heights[11][23]
The Enhanced for-loop: “for each” loop
Java SE 5.0 introduced a powerful looping construct that allows you to loop
through each element in an array( as well as other collection of elements)

The Enhanced for loop:
for( variable : collection)statement
Sets the given variable to each element of the collection and then executes the
statement.
For example: int [] a = {1, 2, 3, 4, 5};
for( int element : a)
System.out.println(element);
Output: 1
2
3
4
5 37
Reading Input: Scanner
To print output to the “standard output stream” ( i.e. console

window) we call System.out.println.


Reading input from the “standard input stream” System.in is

not straightforward.
To read console input, you first need to construct a Scanner that

is attached to System.in:

Scanner input = new Scanner(System.in);

Now you can use various methods of the Scanner class to

read input. 38
Example
System.out.print(“What is your name?”);
String fullname = input.nextLine();
To read a single word (delimited by whitespace) call:
String firstname = input.next();
 To read an integer, use the nextInt method:
System.out.print(“How old are you?”);
int age = input.nextInt();
Before you use the Scanner class write the following
line of code at the top of your program:
 import java.util.*;
Scanner is not in the basic java.lang package

39
Methods
Methods capture a piece of computation we wish to perform

repeatedly into a single abstraction

Methods in Java have 4 parts:


 return type,

 name,

 arguments,

 body.

The return type and arguments may be either primitive data types or

abstract data types (Objects)


Declaring Methods
A method has 4 parts: the return type, the
name, the arguments, and the body:
type name arguments

double sqrt(double num) {


// a set of operations that compute
body // the square root of a number
}

The type, name and arguments together is


referred to as the signature of the method
Return Statements
The return statement is used in a method to output the
result of the methods computation.
It has the form: return expression_value;

The type of the expression_value must be the same as


the type of the method:
double sqrt(double num){
double answer;
// Compute the square root of num and store
// the value into the variable answer
return answer;
}
Return Statements
A method exits immediately after it executes the
return statement

Therefore, the return statement is usually the last


statement in a method

A method may have multiple return statements. Can


you think of an example of such a case?
Invoking Methods
To call a method, specify the name of the method
followed by a list of comma separated arguments in
parentheses:
pow(2, 10); //Computes 210

If the method has no arguments, you still need to


follow the method name with empty parentheses:
size();
Static Methods
Some methods have the keyword static before the
return type:
static double divide(double a, double b) {
return a / b;
}

Static methods are methods that directly belong to a


class.

Static methods can be called by specifying the name of


the class followed by a dot operator and the name of
the method.
E.g. Math.pow(2,10); //Computes 210
main - A Special Method
The only method that we have used so far until this point is the main

method.

The main method is where a Java program always starts when you run a class

file with the java command

The main method is static and has a strict signature which must be followed:

public static void main(String[] args) {

. . .

}
main continued
class SayHi {
public static void main(String[] args) {
System.out.println("Hi, " + args[0]);
}
}
When java Classname arg1 arg2 … argN is typed on
the command line, anything after the name of the class file is
automatically entered into the args array:
java SayHi Sonia

In this example args[0] will contain the String "Sonia",


and the output of the program will be
Hi, Sonia
Example main method
class Greetings {
public static void main(String [] args) {
String greeting = "";
for (int i=0; i < args.length; i++) {
greeting += "Jambo " + args[i] + "! ";
System.out.print(greeting);
}

}
}

After compiling, if you type


java Greetings Alice Bob Charlie
prints out "Jambo Alice! Jambo Bob! Jambo Charlie!"
Recursive Example
class Factorial {
public static void main (String[] args) {
int num = Integer.parseInt(args[0]);
System.out.println(fact(num));
}

public static int fact(int n) {


if (n <= 1)
return 1;
else
return n * fact(n – 1);
}
}
After compiling, if you type java Factorial 4 the
program will print out 24
Another Example
class Max {
public static void main(String args[]) {
if (args.length == 0)
return;
int max = Integer.parseInt(args[0]);
for (int i=1; i < args.length; i++) {
if (Integer.parseInt(args[i]) > max)
{
max = Integer.parseInt(args[i]);
}
}
System.out.println(max);
}
}
After compiling, if you type java Max 3 2 9 2 4 the
program will print out 9

You might also like