Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Java Programming Chapter 1(1)

Chapter 1 covers the basics of Java programming, focusing on variables, their creation, naming conventions, and data types. It explains the importance of declaring variables with specific data types, introduces primitive data types, and discusses operators used for mathematical and logical operations. The chapter also highlights the significance of literals and expressions in Java programming.

Uploaded by

Tesfalegn Yakob
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Java Programming Chapter 1(1)

Chapter 1 covers the basics of Java programming, focusing on variables, their creation, naming conventions, and data types. It explains the importance of declaring variables with specific data types, introduces primitive data types, and discusses operators used for mathematical and logical operations. The chapter also highlights the significance of literals and expressions in Java programming.

Uploaded by

Tesfalegn Yakob
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 149

Chapter 1

Java Basics
What is a Variable?

• 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.
• Each one has a name, a type, and a
value.
Creating Variables
• 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
Creating Variables (continued)

• 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;
Naming Variables
• 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
POP QUIZ
• Which of the following are valid variable
names?
1)$amount
2)6tally
3)my*Name
4)salary
5)_score
6)first Name
7)total#
Statements
• 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.
Variables and Statements
• 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
Java is a Strongly-Typed Language
• 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.
• Each variable has a name, a type, and a
value.
• Before we can use a variable, we have to
declare it.
• After it is declared, we can then assign
values to it.
• We can also declare and assign a value to
a variable at the same time.
Primitive Data Types
• 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)
Integer Data Types
• 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.
Data Type Value Range
byte -128 to +127
short -32768 to +32767
int -2147483648 to +2147483647
long -9223372036854775808 to +9223372036854775807

• In this course, we will always use int when


dealing with integers.
• 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
Floating Point Data Types
• 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 Data Type

• Boolean is a data type that can be


used in situations where there are
two options, either true or false.

• Example:
boolean Hungry = true;
boolean fileOpen = false;
Character Data Types
• 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.
Introduction to Strings
• 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.
POP QUIZ
• 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
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
try void violate while
Primitive Data Types

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
Primitive Data Types (cont)

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
Literals
• Literal is the term which means - what
you type is what you get.
• For example, if you type 4 in a Java
program, you automatically get an integer
with the value 4.
• If you type 'a', you get a character with the
value a.
• Literals are used to indicate simple values
in your Java programs.
Number Literals
Integer literals
• 4, for example, is a decimal integer literal
of type int.
• A decimal integer literal larger than an int
is automatically of type long.
• A smaller number can be assigned to a
long by appending an L or l to that number
(for example, 4L is a long integer of value
4).
• Negative integers are preceded by a
minus sign-for example, -45.
Floating-point literals
• Usually have two parts, the integer part and the
decimal part-for example, 5.77777.
• A floating-point literal results in a floating-point
number of type double, regardless of the
precision of the number.
• But we can assign the number to the type float
by appending the letter f (or F) to that number-
for example, 2.56F.
• We can use exponents in floating-point literals
using the letter e or E followed by the exponent
10e45 or .36E-2.
Boolean Literals
• Boolean literals consist of the keywords
true and false.
• These keywords can be used anywhere
you need a test or as the only possible
values for boolean variables.
Character Literals

• Character literals are expressed by a


single character surrounded by single
quotes: 'a', '#', '3', and so on.
• Characters are stored as 16-bit Unicode
characters.
String Literals
• A combination of characters is a string.
• Strings in Java are instances of the class
String.
• String literals consist of a series of
characters inside double quotes:
– "Hi, I'm a string literal."
– "" // an empty string
• Strings can contain character constants
such as newline, tab, etc..
• "A string with a \t tab in it“
Expressions &Operators
What are Operators?
• 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
Arithmetic Operators
• Java has 5 basic arithmetic operators
+ add
- subtract
* multiply
/ divide
% modulo
(remainder)

• Order of operations (or precedence) when


evaluating an expression is the same as you
learned in school (PEMDAS).
Order of Operations
• 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
Integer Division

• 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.
Integer Division Example
• 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 result type of most arithmetic
operations involving integers is an int
regardless of the original type of the
operands (shorts and bytes are both
automatically converted to int).

• If either or both operands is of type long,


the result is of type long.
• If one operand is an integer and another is
a floating-point number, the result is a
floating point.
Assignment Operator
• 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;
Increment/Decrement Operators
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 (Comparison) Operators
• 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
a < b a is less than 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)
Conditional Operators
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.
Truth Table for Conditional Operators
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.
Short-Circuit Evaluations
(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.
Bitwise Operators
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise complement

Used to perform operations on individual bits


in integers.
Operator Precedence
• Operator precedence determines the order
in which expressions are evaluated. This,
in some cases, can determine the overall
value of the expression.
• Order of Operations (PEMDAS)
1. Parentheses
2. Exponents
3. Multiplication and Division from left to right
4. Addition and Subtraction from left to right
Table 3.7. Operator precedence.

Operator Notes

++ --

*/% Multiplication, division, modulus

+- Addition, subtraction

< > <= >= Relational comparison tests

== != Equality

& AND

^ XOR

| OR

&& Logical AND

|| Logical OR

?: Shorthand for if...then...else

= += -= *= /= %= ^= Various assignments
POP QUIZ
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


boolean 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;
String Arithmetic
• One special expression in Java is the use
of the addition operator (+) to create and
concatenate strings.
• System.out.println(name + " is a " + color + " beetle");

• The output of this line (to the standard output)


is a single string, with the values of the
variables (name and color), inserted in the
appropriate spots in the string.

• So what's going on here?


• The + operator, when used with strings
and other objects, creates a single string
that contains the concatenation of all its
operands.
• If any of the operands in string
concatenation is not a string, it is
automatically converted to a string,
making it easy to create these sorts of
output lines.
• String concatenation makes lines such as
the previous one especially easy to
construct.
• The += operator, which you learned about
earlier, also works for strings.
• For example, take the following
expression: myName += " Jr.";
• This expression is equivalent to this:
myName = myName + " Jr.";
• In this case, it changes the value of
myName, which might be something like
John Smith to have a Jr. at the end (John
Smith Jr.).
Control Structures
Program Flow
• Java will execute the a more sophisticated program
statements in your code in a statement
specific sequence, or "flow".
• The "flow" of the program statement
and can be described
through a "flow diagram":
statement statement
a simple program

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 Statement Flow Diagram
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-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.
If-Else Flow Diagram
The if-else decision
statement executes a is
statement if an expression yes
“expression” no
is true and a different true?
statement if it is not true.

execute execute
if (expression){
statement1 statement2
statement1;
} else {
statement2;
} execute
rest_of_program rest_of_program
Chained If-Else Statements

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.");
Switch Statements
• 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


or int, 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
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 (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
Remember the Chained If-Else . . .

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
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
3. do-while loops (not discussed in this course)
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.
• 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
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
• 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
• 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;
}
Nested Loops
• 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) { 3
break; 3
} 2
System.out.println(--i);
1
}
System.out.println(i);
}
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 to the next iteration of a loop. continue

4. Write a for loop that outputs 100-1 in


reverse sequence.

5. Write a for loop that outputs all numbers


that are divisible by 3 between 0-50.
Arrays

A way to organize data


What are Arrays?

• 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
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

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
Array Indexes

• 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
Accessing Array Elements

• 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
Filling an Array

• Assign values to compartments:

prices[0] = 6.75;
prices[1] = 80.43;
prices[2] = 10.02;
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


0 1
thought of as a single row of values.
0 8 4
• A 2-dimensional array can be thought
1 9 7
of as a grid (or matrix) of values
2 3 6
• Each element of the 2-D array is
accessed by providing two indexes: value at row index 2,
column index 0 is 3
a row index and a column index

• (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]
Methods
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 is 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
Exceptions

Handling Errors with Exceptions


Attack of the Exception
public static int average(int[] a) {
int total = 0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}
return total / a.length;
}

• What happens when this method is used to


take the average of an array of length zero?
• Program throws an Exception and fails
java.lang.ArithmeticException: / by zero
What is an Exception?
• An error event that disrupts the program
flow and may cause a program to fail.
• Some examples:
– Performing illegal arithmetic
– Illegal arguments to methods
– Accessing an out-of-bounds array element
– Hardware failures
– Writing to a read-only file
• "An exception was thrown" is the proper Java terminology
for "an error happened."
Another Exception Example

• What is the output of this program?


public class ExceptionExample {
public static void main(String args[]) {
String[] greek = {"Alpha", "Beta"};
System.out.println(greek[2]);
}
}

Output:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)
Exception Message Details
Exception message format:
[exception class]: [additional description of exception]
at [class].[method]([file]:[line number])

Example:
java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)

• What exception class? ArrayIndexOutOfBoundsException


• Which array index is out of bounds? 2
• What method throws the exception? main
• What file contains the method? ExceptionExample.java

• What line of the file throws the exception? 4


• A Java exception is an object that describes an
exceptional (that is ‘error’) condition that has
occurred in a piece of code at runtime.
• When an exceptional condition arises, an object
representing that exception is created and
thrown in the method that caused the error.
• That method may handle the exception itself, or
pass it on.
• Java exception handling is managed by 5
keywords: try, catch, throw, throws and
finally.
Exception Types
Throwable

Exception Error
Runtime Exception
• Exception class is used for exceptional conditions
that user programs should catch.
• Exception of type RuntimeException are
automatically defined for the programs that you
write.
• Error class defines exceptions that are not
expected to be caught under normal
circumstances.
Uncaught Exceptions
• When Java runtime system detects an
exception
– It throws this exception.
– Once thrown it must be caught by an exception
handler and dealt with immediately.
– If exception handling code is not written in the
program , default handler of java catch the
exception.
– The default handler displays a string describing
the exception & terminates the program.
• Handling exceptions by ourselves
provides 2 benefits.

– First it allows you to fix the error.

– Second it prevents the program from


automatically terminating.
Exception Handling

1. Use a try-catch block to handle


exceptions that are thrown

try {
// code that might throw exception
}
catch ([Type of Exception] e) {
// what to do if exception is thrown
}
Exception Handling Example
class example{
public static void main(String args[])
int d,a;
try
{
d=0;
a=42/d;
}catch (ArithmeticException e) {
System.out.println(“Division by
zero.");
}
}
• Once an exception is thrown program
control transfers to the try block from a
catch.

• Once the catch statement has executed,


program control Continues with the next
line in the program following the
entire try/catch mechanism.
Exception Handling Example
Public int average(int[] a) {
int total = 0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}
return total / a.length;
}

Public void printAverage(int[] a) {


try {
int avg = average(a);
System.out.println("the average is: " + avg);
}
catch (ArithmeticException e) {
System.out.println("error calculating average");
}
}
• A try and its catch statement form a unit.

• You cannot use try on a single statement.

• The goal of most well-constructed catch


clause should be to resolve the exceptional
condition and then continue on as if the error
had never happened.
Catching Multiple Exceptions
• Handle multiple possible exceptions by multiple
successive catch blocks
try {
// code that might throw multiple exception
}catch (IOException e) {
// handle IOException and all subclasses
}catch (ClassNotFoundException e2) {
// handle ClassNotFoundException
}
When an exception is thrown, each catch statement
is inspected inorder and the first one whose type
matches that of the exception is executed. After
One catch statement executes, the others are
bypassed,and execution continues after the try/catch
block.
Exceptions Terminology

• When an exception happens we


say it was thrown or raised

• When an exception is dealt with,


we say the exception is was
handled or caught
Unchecked Exceptions
• All the exceptions we've seen so far
have been Unchecked Exceptions, or
Runtime Exceptions

• Usually occur because of


programming errors, when code is not
robust enough to prevent them

• They are numerous and can be


ignored by the programmer
Common Unchecked Exceptions

• NullPointerException
reference is null and should not be

• IllegalArgumentException
method argument is improper is some way
Checked Exceptions

• There are also Checked Exceptions

• Usually occur because of errors


programmer cannot control:
examples: hardware failures, unreadable files

• They are less frequent and they cannot


be ignored by the programmer . . .
Exception Class Hierarchy
 All exceptions are instances of classes
that are subclasses of Exception

Exception

RuntimeException IOException SQLException

ArrayIndexOutofBounds FileNotFoundException

NullPointerException MalformedURLException

llegalArgumentException SocketException

etc. etc.

Unchecked Exceptions Checked Exceptions


Dealing With Checked
Exceptions
• Every method must catch (handle) checked
exceptions or specify that it may throw them
• Specify with the throws keyword
void readFile(String filename) {
try {
FileReader reader = new FileReader("myfile.txt");
// read from file . . .
} catch (FileNotFoundException e) {
System.out.println("file was not found");
}
}
o
r
void readFile(String filename) throws FileNotFoundException {
FileReader reader = new FileReader("myfile.txt");
// read from file . . .
}
The throws clause
• When you write a method that can throw
exceptions to its caller, it is useful to document
that fact for other programmers who use your
code.
• This provides them with the opportunity to deal
with those exceptions.
• And also it will let you know which exceptions
can be thrown from code written by others.
• We do this by including a throws clause in
the method’s declaration.
• A throws clause lists the types of
exceptions that a method might throw.
• This is necessary for all exceptions except
Error or RuntimeException.
Checked and Unchecked Exceptions

Checked Exception Unchecked Exception


not subclass of subclass of
RuntimeException RuntimeException
if not caught, method if not caught, method
must specify it to be may specify it to be
thrown thrown
for errors that the for errors that the
programmer cannot programmer can directly
directly prevent from prevent from occurring,
occurring
IOException, NullPointerException,
FileNotFoundException, IllegalArgumentExceptio
Throwing Exceptions

• Throw exception with the throw keyword

public static int average(int[] a) {


if (a.length == 0) {
throw new IllegalArgumentException("array is empty");
}
int total = 0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}
return total / a.length;
}
Summary

• try and catch – used to handle exceptions that may be thrown


• throws – to specify which exceptions a method throws in method declaration
• throw – to throw an exception
• 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