0% found this document useful (0 votes)
9 views

All Slides Before OOP

The document explains the fundamentals of programming, focusing on Java as an object-oriented language. It covers the structure of programs, the role of compilers, data types, variable naming conventions, and operators. Additionally, it introduces concepts like classes and objects, emphasizing how they interact in programming.

Uploaded by

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

All Slides Before OOP

The document explains the fundamentals of programming, focusing on Java as an object-oriented language. It covers the structure of programs, the role of compilers, data types, variable naming conventions, and operators. Additionally, it introduces concepts like classes and objects, emphasizing how they interact in programming.

Uploaded by

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

 For a computer to be able to do anything

(multiply, play a song, run a word processor), it


must be given the instructions to do so.

 A program is a set of instructions written by


humans for computers to perform tasks.

 The instructions are written in programming


languages such as C, C++, Java, etc.
Food Recipe Computer Program

 a chef writes a set of instructions  a programmer writes a set of


called a recipe
instructions called a program

 the recipe requires specific


ingredients  the program requires specific
inputs
 the cook follows the instruction
step-by-step  the computer follows the
instructions step-by-step
 the food will vary depending on
the amount of ingredients and the cook  the output will vary depending on
the values of the inputs and the
computer
Food Recipe Computer Program

 a chef writes a set of instructions  a programmer writes a set of


called a recipe
instructions called a program

 the recipe requires specific


ingredients  the program requires specific
inputs
 the cook follows the instruction
step-by-step  the computer follows the
instructions step-by-step
 the food will vary depending on
the amount of ingredients and the cook  the output will vary depending on
the values of the inputs and the
computer
 Computers do not understand the languages (C++,
Java, etc) that programs are written in.

 Programs must first be compiled (converted) into


machine code that the computer can run.

 A compiler is a program that translates a


programming language into machine code.
 All programs follow a simple format:
Input Execution Output

 Inputs can be from users, files, or other


computer programs

 Outputs can take on many forms:


numbers, text, graphics, sound, or
commands to other programs
 Because different operating systems (Windows, Macs, Unix)
require different machine code, you must compile most
programming languages separately for each platform.

program

compiler compiler

compiler

Unix
Win
MAC
 Java is a little different.
 Java compiler produces bytecode not
machine code.
 Bytecode can be run on any computer
with the Java interpreter installed. Win

Java Program Java Bytecode


MAC

compiler Interpreter

Unix
Advantages:
 Java is platform independent. Once it's compiled, you can run the
bytecode on any machine with a Java interpreter. You do not have to
recompile for each platform.

 Java is safe. Certain common programming bugs and dangerous


operations are prevented by the language and compiler.

 Java standardizes many useful operations like managing network


connections and providing graphical user interfaces.

Disadvantages:
 Running bytecode through the interpreter is not as fast as running
machine code, which is specific to that platform.

 Because it is platform independent, it is difficult to use platform


specific features (e.g., Windows taskbar, quick launch) in Java.

 Java interpreter must be installed on the computer in order to run


Java programs.
 Open your text-editor and type the following
piece of Java code exactly:

class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}

 Save this file as HelloWorld.java (watch


capitalization) in the following directory:
c:\java
 Open the command prompt in Windows
 To run the program that you just wrote, type at the command
prompt:
cd c:\java
 Your command prompt should now look like this:
c:\java>
 To compile the program that you wrote, you need to run the Java
Development Tool Kit Compiler as follows:
At the command prompt type:
c:\java> javac HelloWorld.java
 You have now created your first compiled Java program named
HelloWorld.class
 To run your first program, type the following at the command
prompt:
c:\java>java HelloWorld

Although the file name includes the .class extension , this part of the name must be left off when
running the program with the Java interpreter
 Java is an object-oriented programming
language

 For the rest of this lecture, some introductory


concepts and basic principles of OOP are
introduced.

 The concept pf OOP won't be used


immediately, but they will become important
over the next few weeks.
 In object-oriented programming (OOP),
programs are organized into objects

 The properties of objects are determined by


their class

 Objects act on each other by passing


messages
 Definition: An object is a software bundle
that has State and Behavior.

 Software Objects are often used to model


real-world objects.

 Example: dogs have states (name, color,


hungry, breed) and behaviors (bark,
fetch, and wag tail).
 Example 1: Dogs
 States: name, color, breed, and “is hungry?”
 Behaviors: bark, run, and wag tail

 Example 2: Cars
 States: color, model, speed, direction
 Behaviors: accelerate, turn, change gears
 Definition: A class is a blueprint that defines the
states and the behaviors common to all objects of
a certain kind.

 In the real world, you often have many objects of


the same kind. For example, a guard dog,
herding dog, snoop dog . . .

 Even though all dogs have four legs, and bark,


each dog’s behavior is independent of other
dogs.

 For example: Dog #1 is a black Poodle, Dog #2 is


a red Irish Setter
 Definition: Software objects interact and
communicate with each other by sending
messages to each other.

 Example: when you want your dog to gather a


herd of goats, you whistle and send him out.
 When writing an object-oriented program, we
define classes, which describe categories of
objects, and the states and behaviors that they
have in common.

 We then create objects which belong to classes,


and share the common features of their class.

 Objects interact with each other by passing


messages.

 You will be creating your own classes and


objects soon!
 Variables are places where information can
be stored while a program is running.

 Their values can be changed at any point over


the course of a program
 To create a variable, declare its name and the type
of information that it will store.
 The type is listed first, followed by the name.
 Example: a variable that stores an integer
representing the highest score on an exam could
be declared as follows:
int highScore ;

type name
 Now you have the variable (highScore), you
will want to assign a value to it.

 Example: the highest score in the class exam is


98.

highScore = 98;

 Examples of other types of variables:

String studentName;
boolean gameOver;
 The name that you choose for a variable is called
an identifier. In Java, an identifier can be of any
length, but must start with:

a letter (a – z),
a dollar sign ($),
or, an underscore ( _ ).

 The rest of the identifier can include any character


except those used as operators in Java such as + , - ,
*.

 In addition, there are certain keywords reserved


(e.g., "class") in the Java language which can never
be used as identifiers.
Naming (Continued)
 Java is a case-sensitive language – the
capitalization of letters in identifiers matters.
A rose is not a Rose is not a ROSE

 It is good practice to select variable names that


give a good indication of the sort of data they
hold
 For example, if you want to record the size of a hat,
hatSize is a good choice for a name whereas qqq
would be a bad choice
 When naming a variable, the following
convention is commonly used:

 The first letter of a variable name is lowercase


 Each successive word in the variable name begins
with a capital letter
 All other letters are lowercase

 Here are some examples:

pageCount
loadFile
anyString
threeWordVariable
 Which of the following are valid variable
names?

1)$amount
2)6tally
3)my*Name
4)salary
5)_score
6)first Name
7)total#
 A statement is a command that causes
something to happen.
 All statements in Java are separated by
semicolons ;
 Example:
System.out.println(“Hello, World”);

 You have already used statements to create a


variable and assign it a value.
 One way is to declare a variable and then
assign a value to it with two statements:
int e; // declaring a variable
e = 5; // assigning a value to a variable

 Another way is to write a single initialization


statement:
int e = 5; // declaring AND assigning
 All variables must be declared with a data type
before they are used.
 Each variable's declared type does not change
over the course of the program.
 Certain operations are only allowed with
certain data types.
 If you try to perform an operation on an illegal
data type (like multiplying Strings), the
compiler will report an error.
 There are eight built-in (primitive) data types
in the Java language

 4 integer types (byte, short, int, long)


 2 floating point types (float, double)
 Boolean (boolean)
 Character (char)

**see Appendix II: Summary of Primitive Data Types for a


complete table of sizes and formats**
 There are four data types that can be used to store
integers.
 The one you choose to use depends on the size of
the number that we want to store.
 In this course, we will always use int when
dealing with integers.
Data Type Value Range

byte -128 to +127

short -32768 to +32767

int -2147483648 to +2147483647

long -9223372036854775808 to
+9223372036854775807
 Here are some examples of when you would
want to use integer types:

- byte smallValue;
smallValue = -55;
- int pageCount = 1250;
- long bigValue = 1823337144562L;

Note: By adding an L to the end of the value in the last


example, the program is “forced” to consider the value
to be of a type long even if it was small enough to be
an int
 There are two data types that can be used to
store decimal values (real numbers).

 The one you choose to use depends on the


size of the number that we want to store.

Data Type Value Range

float 1.4×10-45 to 3.4×1038

double 4.9×10-324 to 1.7×10308


 In this course, we will always use double
when dealing with decimal values.
 Here are some examples of when you would
want to use floating point types:

 double g = 7.7e100 ;
 double tinyNumber = 5.82e-203;
 float costOfBook = 49.99F;

 Note: In the last example we added an F to the


end of the value. Without the F, it would have
automatically been considered a double
instead.
 Boolean is a data type that can be used
in situations where there are two
options, either true or false.

 Example:
boolean monsterHungry = true;
boolean fileOpen = false;
 Character is a data type that can be used to
store a single characters such as a letter,
number, punctuation mark, or other symbol.

 Example:
 char firstLetterOfName = 'e' ;
 char myQuestion = '?' ;

 Note that you need to use singular quotation


marks when assigning char data types.
 Strings consist of a series of characters inside double
quotation marks.

 Examples statements assign String variables:


String coAuthor = "John Smith";
String password = "swordfish786";

 Strings are not one of the primitive data types,


although they are very commonly used.

 Strings are constant; their values cannot be changed


after they are created.
What data types would you use to store the
following types of information?:

1)Population of Ethiopia int


2)Approximation of π double
3)Open/closed status of a file boolean
4)Your name String
5)First letter of your name char
6)$237.66 double
Appendix I: Reserved Words

The following keywords are reserved in the Java


language. They can never be used as identifiers:
abstract assert boolean break byte

case catch char class const

continue default do double else

extends final finally float for

goto if implements import instanceof

int interface long native new

package private protected public return

short static strictfp super switch

synchronized this throw throws transient


The following tables show all of the primitive
data types along with their sizes and formats:
Integers

Data Type Description

byte Variables of this kind can have a value from:


-128 to +127 and occupy 8 bits in memory

short Variables of this kind can have a value from:


-32768 to +32767 and occupy 16 bits in memory

int Variables of this kind can have a value from:


-2147483648 to +2147483647 and occupy 32 bits in memory

long Variables of this kind can have a value from:


-9223372036854775808 to +9223372036854775807 and occupy
64 bits in memory
Real Numbers

Data Type Description

float Variables of this kind can have a value from:


1.4e(-45) to 3.4e(+38)

double Variables of this kind can have a value from:


4.9e(-324) to 1.7e(+308)

Other Primitive Data Types

char Variables of this kind can have a value from:


A single character

boolean Variables of this kind can have a value from:


True or False
• Operators are special symbols used for
– mathematical functions
– assignment statements
– logical comparisons

• Examples:
3 + 5 // uses + operator
14 + 5 – 4 * (5 – 3) // uses +, -, * operators

• Expressions can be combinations of variables, primitives


and operators that result in a value
The Operator Groups
 There are 5 different groups of operators:

 Arithmetic operators
 Assignment operator
 Increment/Decrement operators
 Relational operators
 Conditional operators
 Java has 6 basic arithmetic operators
+ add
- subtract
* multiply
/ divide
% modulo (remainder)
^ exponent (to the power of)

 Order of operations (or precedence) when


evaluating an expression is the same as you
learned in school (PEMDAS).
 Example: 10 + 15 / 5;

 The result is different depending on whether


the addition or division is performed first
(10 + 15) / 5 = 5
10 + (15 / 5) = 13

Without parentheses, Java will choose the


second case

 Note: you should be explicit and use


parentheses to avoid confusion
 In the previous example, we were
lucky that (10 + 15) / 5 gives an
exact integer answer (5).

 But what if we divide 63 by 35?

 Depending on the data types of the


variables that store the numbers, we
will get different results.
 int i = 63;
int j = 35;
System.out.println(i / j);
Output: 1

 double x = 63;
double y = 35;
System.out.println(x / y);
Ouput: 1.8

 The result of integer division is just


the integer part of the quotient!
 The basic assignment operator (=) assigns the
value of var to expr
var = expr ;
 Java allows you to combine arithmetic and
assignment operators into a single operator.
 Examples:
x = x + 5; is equivalent to x += 5;
y = y * 7; is equivalent to y *= 7;
count = count + 1;
can be written as:
++count; or count++;

++ is called the increment operator.

count = count - 1;
can be written as:
--count; or count--;

-- is called the decrement operator.


The increment/decrement operator has two forms:

 The prefix form ++count, --count


first adds 1 to the variable and then continues to any other
operator in the expression

int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = ++numOranges + numApples;
numFruit has value 16
numOranges has value 6

 The postfix form count++, count--


first evaluates the expression and then adds 1 to the variable

int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = numOranges++ + numApples;
numFruit has value 15
numOranges has value 6
• Relational operators compare two values
• Produces a boolean value (true or false)
depending on the relationship
operation is true when . . .

a > b a is greater than b

a >= b a is greater than or equal to b

a == b a is equal to b

a != b a is not equal to b

a <= b a is less than or equal to b


Examples of Relational Operations

int x = 3;
int y = 5;
boolean result;

1) result = (x > y);


now result is assigned the value false because
3 is not greater than 5

2) result = (15 == x*y);


now result is assigned the value true because the product of
3 and 5 equals 15

3) result = (x != x*y);
now result is assigned the value true because the product of
x and y (15) is not equal to x (3)
Symbol Name

&& AND

|| OR

! NOT
 Conditional operators can be referred to as boolean
operators, because they are only used to combine
expressions that have a value of true or false.
x y x && y x || y !x

True True True True False

True False False True False

False True False True True

False False False False True


Examples of Conditional Operators
boolean x = true;
boolean y = false;
boolean result;

1. Let result = (x && y);

now result is assigned the value false


(see truth table!)

2. Let result = ((x || y) && x);

(x || y) evaluates to true
(true && x) evaluates to true

now result is assigned the value true


Using && and ||
 Examples:
(a && (b++ > 3))
(x || y)

 Java will evaluate these expressions from left to


right and so will evaluate
a before (b++ > 3)
x before y

 Java performs short-circuit evaluation:


it evaluates && and || expressions from left to
right and once it finds the result, it stops.
(a && (b++ > 3))
What happens if a is false?
 Java will not evaluate the right-hand expression (b++
> 3) if the left-hand operator a is false, since the
result is already determined in this case to be false.
This means b will not be incremented!

(x || y)
What happens if x is true?
 Similarly, Java will not evaluate the right-hand
operator y if the left-hand operator x is true, since
the result is already determined in this case to be
true.
1) What is the value of number? -12
int number = 5 * 3 – 3 / 6 – 9 * 3;

2) What is the value of result? false


int x = 8;
int y = 2;
boolean result = (15 == x * y);

3) What is the value of result? true


int x = 7;
boolean result = (x < 8) && (x > 4);

4) What is the value of numCars? 27


int numBlueCars = 5;
int numGreenCars = 10;
int numCars = numGreenCars++ + numBlueCars + ++numGreeenCars;
 Java will execute the a more sophisticated program
statements in your code in a
statement
specific sequence, or "flow".
 The "flow" of the program and statement
can be described through a
"flow diagram":

statement statement
a simple program

statement
statement
statement

statement

statement statement
 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
 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 (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
The if decision statement executes
a statement if an expression is true
Is expression no
true?

if (expression) { yes
statement1;
} execute
statement
rest_of_program

execute
rest_of_program
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.
The if-else decision
statement executes a is
statement if an expression yes no
“expression”
is true and a different true?

statement if it is not true.

if (expression){ execute execute


statement1 statement2
statement1;
} else {
statement2;
} execute
rest_of_program rest_of_program
if (grade == 'A')
System.out.println("You got an A.");
else if (grade == 'B')
System.out.println("You got a B.");
else if (grade == 'C')
System.out.println("You got a C.");
else
System.out.println("You got an F.");
 The switch statement enables you to test several cases generated by
a given expression.

 For example:
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, int or


String (latest versions of java), but not long, float, or
double.
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
 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 (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
if (grade == 'A')
System.out.println("You got an A.");
else if (grade == 'B')
System.out.println("You got a B.");
else if (grade == 'C')
System.out.println("You got a C.");
else
System.out.println("You got an F.");
 This is how it is accomplished with a switch:
switch (grade) {
case 'A':
System.out.println("You got an A.");
break;
case 'B':
System.out.println("You got a B.");
break;
case 'C':
System.out.println("You got a C.");
break;
default:
System.out.println("You got an F.");
}
 if-else chains can be sometimes be rewritten as a
“switch” statement.
 switches are usually simpler and faster. Why???
 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
3. do-while loops (not discussed in this course)
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.
 For example:

int sum = 0;
int i = 1;

while (i <= 10){


sum += i;
i++;
}

 What is the value of sum?

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
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.

1. Loop executes so long as the loop_condition is true and


exits otherwise.

1. 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
 Example 3:

for(int div = 0; div < 1000; div++){


if(div % 2 == 0) {
System.out.println("even: " + div);
} else {
System.out.println("odd: " + div);
}
}

 What will this for loop do?

prints out each integer from 0 to 999,


correctly labeling them even or odd
 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 for loop

Initialize count
The while loop

n n
Test condition Test condition
is true? is true?

y
y
Execute loop
statement(?) Execute loop
statement(s)

Increment
Next statement count

New 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
 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;
}
 You can nest loops of any kind one inside
another to any depth. What does this print?
for(int i = 10; i > 0; i--) {
if (i > 7) {
continue;
6
} 5
while (i > 3) { 5
if(i == 5) { 4
break; 3
}
2
System.out.println(--i);
}
1
System.out.println(i);
}
1. In the switch statement, which types can
expression evaluate to? char, byte, short, int, String

1. What must be used to separate each section of a


for statement. semicolons
1. Which statement causes a program to skip to the
next iteration of a loop. continue
1. Write a for loop that outputs 100-1 in reverse
sequence.

1. Write a for loop that outputs all numbers that


are divisible by 3 between 0-50.
A way to organize data
 An array is a series of compartments to
store data.

 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
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]


 Array declarations use square brackets.
datatype[] label;

 For example:
int[] prices;
String[] names;
Use this syntax: new int[20]
 The new keyword creates an array of type
int that has 20 compartments
 The new array can then be assigned to an
array variable:
int[] prices = new int[20];
 When first created as above, the items in the
array are initialized to the zero value of the
datatype
int: 0 double: 0.0 String:
null
 Every compartment in an array is assigned an
integer reference.

 This number is called the index of the


compartment

 Important: In Java (and most other languages),


the index starts from 0 and ends at n-1, where n
is the size of the array
 To access an item in an array, type the
name of the array followed by the
item’s index in square brackets.

 For example, the expression:


names[0]
will return the first element in the
names array
 Assign values to compartments:

prices[0] = 6.75;
prices[1] = 80.43;
prices[2] = 10.02;
 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";
 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};
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!
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
Modifying Array Elements

 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
c. temperature readings taken every hour throughout
a day
d. your expenses each month for an entire year
Example

 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

0 1
 The arrays we've used so far can be
thought of as a single row of values. 0 8 4
 A 2-dimensional array can be thought
of as a grid (or matrix) of values 1 9 7
 Each element of the 2-D array is
accessed by providing two indexes:
2 3 6
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 Concept of a Method
 Methods also known as functions or procedures.

 Methods are a way of capturing a sequence of


computational steps into a reusable unit.

 Methods can accept inputs in the form of


arguments, perform some operations with the
arguments, and then can return a value: the
output, or result of their computations.

inputs outputs
method
Square Root Method
 Square root is a good example of a method.

 The square root method accepts a single number as an


argument and returns the square root of that number.

 The computation of square roots involves many


intermediate steps between input and output.

 When we use square root, we don’t care about these steps.


All we need is to get the correct output.
Hiding the internal workings of a
method from a user but providing the
correct answer is known as abstraction
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
The Return Type of a Method

 The return type of a method may be any


data type.

 The type of a method designates the data


type of the output it produces.

 Methods can also return nothing in which


case they are declared void.
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?
Brain Teaser Answer

 Example:
int absoluteValue (int num){
if (num < 0)
return –num;
else
return num;
}
void Methods

 A method of type void has a return statement without


any specified value. i.e. return;

 This may seem useless, but in practice void is used


often.

 A good example is when a methods only purpose is to


print to the screen.

 If no return statement is used in a method of type void,


it automatically returns at the end
Method Arguments

 Methods can take input in the form of


arguments.

 Arguments are used as variables inside


the method body.

 Like variables, arguments, must have their


type specified.

 Arguments are specified inside the paren-


theses that follow the name of the method.
Example Method

 Here is an example of a method that divides


two doubles:

double divide(double a, double b) {


double answer;
answer = a / b;
return answer;
}
Method Arguments

 Multiple method arguments are separated


by commas:
double pow(double x, double y)

 Arguments may be of different types


int indexOf(String str,
int fromIndex)
The Method Body

 The body of a method is a block specified


by curly brackets. The body defines the
actions of the method.

 The method arguments can be used


anywhere inside of the body.

 All methods must have curly brackets to


specify the body even if the body contains
only one or no statement.
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;
}

 We'll learn what it means for a method to be


static in a later lecture

 For now, all the methods we write in lab will


be static.
main - A Special Method

 The only method that we have used in lab up 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 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 Program 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.println(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));
}

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
Summary

 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 complex data types
(Objects)
 main is a special Java method which the java
interpreter looks for when you try to run a class
file
 main has a strict signature that must be followed:
public static void main(String args[])

You might also like