Day 4 - Object Oriented Programming
Day 4 - Object Oriented Programming
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
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.
switch statements
If Statement
if (expression) {
statement;
}
rest_of_program;
switch (expression) {
case value1:
statement1;
case value2:
statement2;
default:
default_statement;
}
Every statement after the true case is executed
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
2. for loops
( Java also has a specialized for loop called enhanced for -loop)
3. do-while loops
The while Loop
while (expression){
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
used to increment the loop counter. This is executed at the end of each loop
iteration.
For example:
int sum = 0;
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.
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;
}
primes[0]primes[1]primes[2]primes[3]primes[4] primes[9]
Declaring an Array Variable
For example:
int[] prices;
String[] names;
Creating a New "Empty" Array
Example syntax: int[] prices = new int[20];
compartments
The new array can then be assigned to the array variable prices:
Use curly brackets to surround the array’s data and separate the
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
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?
b. int[] arr;
arr = new int[4];
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?
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
not straightforward.
To read console input, you first need to construct a Scanner that
is attached to System.in:
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
name,
arguments,
body.
The return type and arguments may be either primitive data types or
method.
The main method is where a Java program always starts when you run a class
The main method is static and has a strict signature which must be followed:
. . .
}
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
}
}