Date post: | 26-Mar-2015 |
Category: |
Documents |
Upload: | aiden-bell |
View: | 221 times |
Download: | 1 times |
1001ICT Programming 11001ICT Programming 1Semester 1, 2011Semester 1, 2011
Lecture 8Lecture 8
Course ReviewCourse Review
1
2
Java Review TopicsJava Review TopicsPrimitive Data TypesExtended Data TypesVariablesArithmetic ExpressionsBoolean ExpressionsAssignmentData Conversion Input / OutputFlow of ControlArrays (revisited)MethodsClass Libraries
Java Primitive Data TypesJava Primitive Data Types
There are eight primitive data types in Java
Four of them represent integers◦byte, short, int, long
Two of them represent floating point numbers◦float, double
One of them represents characters◦char
And one of them represents boolean values◦boolean
1-3
Java Primitive Data Types - NumericJava Primitive Data Types - Numeric
The difference between the various numeric primitive types is their size, and therefore the values they can store:Type
byteshortintlong
floatdouble
Storage
8 bits16 bits32 bits64 bits
32 bits64 bits
Min Value
-128-32,768-2,147,483,648< -9 x 1018
+/- 3.4 x 1038 with 7 significant digits+/- 1.7 x 10308 with 15 significant digits
Max Value
12732,7672,147,483,647> 9 x 1018
1-4
Java Primitive Data Types - Java Primitive Data Types - charchar
A char variable stores a single characterCharacter literals are delimited by
single quotes:'a' 'X' '7' '$' ',' '\n'
Example declarationschar topGrade = 'A';
char terminator = ';',
separator = ' ';Note the distinction between a
primitive character variable, which holds only one character, and a String object, which can hold multiple characters
1-5
Java Primitive Data Types - Java Primitive Data Types - booleanboolean
A boolean value represents a true or false condition
The reserved words true and false are the only valid values for a boolean type
boolean done = false;
A boolean variable can also be used to represent any two states, such as a light bulb being on or off
1-6
7
Java Review TopicsJava Review TopicsPrimitive Data TypesExtended Data TypesVariablesArithmetic ExpressionsBoolean ExpressionsAssignmentData Conversion Input / OutputFlow of ControlArrays (revisited)MethodsClass Libraries
Java Extended Data Types - Java Extended Data Types - StringString
A string of characters can be represented as a string literal by putting double quotes around the text
Examples
"This is a string literal.""123 Main Street""X"
Every character string is an object in Java, defined by the String class
Every string literal represents a String object
1-8
Java Extended Data Types - Java Extended Data Types - StringString
The string concatenation operator (+) is used to append one string to the end of another
"Peanut butter " + "and jelly"
It can also be used to append a number to a string
A string literal cannot be broken across two lines in a program
1-9
Java Extended Data Types - Java Extended Data Types - StringStringThe + operator is also used for arithmetic
addition
The function that it performs depends on the type of the information on which it operates
If both operands are strings, or if one is a string and one is a number, it performs string concatenation
If both operands are numeric, it adds them
The + operator is evaluated left to right, but parentheses can be used to force the order
1-10
1-11
Java Extended Data Types - Java Extended Data Types - StringString
Because strings are so common, we don't have to use the new operator to create a String object
title = "Java Software Solutions";
This is special syntax that works only for strings
Each string literal (enclosed in double quotes) represents a String object
1-12
Java Extended Data Types - Java Extended Data Types - StringString
It is occasionally helpful to refer to a particular character within a string
This can be done by specifying the character's numeric index
The indexes begin at zero in each string
In the string "Hello", the character 'H' is at index 0 and the 'o' is at index 4
1-13
Java Extended Data Types - Java Extended Data Types - StringString
Once a String object has been created, neither its value nor its length can be changed
Thus we say that an object of the String class is immutable
However, several methods of the String class return new String objects that are modified versions of the original
Java Extended Data Types - Java Extended Data Types - StringStringSome Java String methods
1-14
Method Use
char charAt(int index) s.charAt(3);
boolean equals (String str) s.equals(“abcd”);
int length() s.length();
String trim() s.trim();
String substring(int offset, int endIndex) s.substring(2,10);
String replace(char oldChar, char newChar) s.replace(‘a’, ‘x’);
String toLowerCase() s.toLowerCase();
Java Extended Data Types - Java Extended Data Types - StringString
What if we wanted to print a the quote character?
The following line would confuse the compiler because it would interpret the second quote as the end of the string
System.out.println ("I said "Hello" to you.");
An escape sequence is a series of characters that represents a special character
An escape sequence begins with a backslash character (\)System.out.println ("I said \"Hello\" to you.");
1-15
Java Extended Data Types - Java Extended Data Types - StringString
Some Java escape sequencesEscape Sequence
\b\t\n\r\"\'\\
Meaning
backspacetabnewlinecarriage returndouble quotesingle quotebackslash
1-16
Java Extended Data Types - ArraysJava Extended Data Types - Arrays
An array is an ordered list of values
0 1 2 3 4 5 6 7 8 9
79 87 94 82 67 98 87 81 74 91
An array of size N is indexed from zero to N-1
scores
The entire array
has a single nameEach value has a numeric index
This array holds 10 values that are indexed from 0 to 9
1-17
18
Java Review TopicsJava Review TopicsPrimitive Data TypesExtended Data TypesVariablesArithmetic ExpressionsBoolean ExpressionsAssignmentData Conversion Input / OutputFlow of ControlArrays (revisited)MethodsClass Libraries
Java VariablesJava Variables
A variable is a name for a location in memory
A variable must be declared by specifying the variable's name and the type of information that it will hold
int total;
int count, temp, result;
Multiple variables can be created in one declaration
data type variable name
1-19
Java VariablesJava Variables
A variable can be given an initial value in the declaration
• When a variable is referenced in a program, its current value is used
int sum = 0;int base = 32, max = 149;
1-20
Java Variables - Java Variables - finalfinal
A constant is an identifier that is similar to a variable except that it holds the same value during its entire existence
As the name implies, it is constant, not variable
The compiler will issue an error if you try to change the value of a constant
In Java, we use the final modifier to declare a constant
final int MIN_HEIGHT = 69;
1-21
Java Variables - Java Variables - finalfinal
Constants are useful for three important reasons◦First, they give meaning to otherwise
unclear literal values For example, MAX_LOAD means more than the
literal 250
◦Second, they facilitate program maintenance If a constant is used in multiple places, its
value need only be updated in one place
◦Third, they formally establish that a value should not change, avoiding inadvertent errors by other programmers
1-22
23
Java Review TopicsJava Review TopicsPrimitive Data TypesExtended Data TypesVariablesArithmetic ExpressionsBoolean ExpressionsAssignmentData Conversion Input / OutputFlow of ControlArrays (revisited)MethodsClass Libraries
Java Arithmetic ExpressionsJava Arithmetic Expressions
An expression is a combination of one or more operators and operands
Arithmetic expressions compute numeric results and make use of the arithmetic operators
• If either or both operands used by an arithmetic operator are floating point, then the result is a floating point
AdditionSubtractionMultiplicationDivisionRemainder
+-*/%
1-24
Java Arithmetic Expressions - Java Arithmetic Expressions - // and and %%
If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded)
• The remainder operator (%) returns the remainder after dividing the second operand into the first
14 / 3 equals
8 / 12 equals
4
0
14 % 3 equals
8 % 12 equals
2
8
1-25
Java Arithmetic Expressions - Operator Java Arithmetic Expressions - Operator PrecedencePrecedence
Operators can be combined into complex expressionsresult = total + count / max - offset;
Operators have a well-defined precedence which determines the order in which they are evaluated
Multiplication, division, and remainder are evaluated prior to addition, subtraction, and string concatenation
Arithmetic operators with the same precedence are evaluated from left to right, but parentheses can be used to force the evaluation order
1-26
Java Arithmetic Expressions - Operator Java Arithmetic Expressions - Operator PrecedencePrecedence
What is the order of evaluation in the following expressions?a + b + c + d + e
1 432a + b * c - d / e
3 241
a / (b + c) - d % e2 341
a / (b * (c + (d - e)))4 123
1-27
28
Java Review TopicsJava Review TopicsPrimitive Data TypesExtended Data TypesVariablesArithmetic ExpressionsBoolean ExpressionsAssignmentData Conversion Input / OutputFlow of ControlArrays (revisited)MethodsClass Libraries
Java Boolean ExpressionsJava Boolean Expressions
A condition often uses one of Java's equality operators or relational operators, which all return boolean results
== equal to!= not equal to< less than> greater than<= less than or equal to>= greater than or equal to
Note the difference between the equality operator (==) and the assignment operator (=)
1-29
Java Boolean ExpressionsJava Boolean Expressions
Boolean expressions can also use the following logical operators
! Logical NOT&& Logical AND|| Logical OR
They all take boolean operands and produce boolean results
Logical NOT is a unary operator (it operates on one operand)
Logical AND and logical OR are binary operators (each operates on two operands)
1-30
Java Boolean ExpressionsJava Boolean Expressions
The logical NOT operation is also called logical negation or logical complement
If some boolean condition a is true, then !a is false; if a is false, then !a is true
Logical expressions can be shown using a truth table
a !a
true false
false true
1-31
Java Boolean ExpressionsJava Boolean Expressions
The logical AND expression
a && b
is true if both a and b are true, and false otherwise
The logical OR expression
a || b
is true if a or b or both are true, and false otherwise
1-32
Java Boolean ExpressionsJava Boolean Expressions
Expressions that use logical operators can form complex conditions
1-33
if (total < MAX+5 && !found)
System.out.println ("Processing…");• All logical operators have lower
precedence than the relational operators
• Logical NOT has higher precedence than logical AND and logical OR
Java Boolean ExpressionsJava Boolean Expressions
A truth table shows all possible true-false combinations of the terms
Since && and || each have two operands, there are four possible combinations of conditions a and b
a b a && b a || b
true true true true
true false false true
false true false true
false false false false
1-34
Java Boolean ExpressionsJava Boolean Expressions
Specific expressions can be evaluated using truth tables
total < MAX found !found total < MAX && !found
false false true false
false true false false
true false true true
true true false false
1-35
Java Boolean ExpressionsJava Boolean Expressions
The processing of logical AND and logical OR is short-circuited
If the left operand is sufficient to determine the result, the right operand is not evaluated
•This type of processing must be used carefully
if (count != 0 && total/count > MAX)
System.out.println ("Testing…");
1-36
37
Java Review TopicsJava Review TopicsPrimitive Data TypesExtended Data TypesVariablesArithmetic ExpressionsBoolean ExpressionsAssignmentData Conversion Input / OutputFlow of ControlArrays (revisited)MethodsClass Libraries
Java AssignmentJava Assignment
An assignment statement changes the value of a variable
The assignment operator is the = sign
total = 55;
• The expression on the right is evaluated and the result is stored in the variable on the left
• The value that was in total is overwritten
• You can only assign a value to a variable that is consistent with the variable's declared type
1-38
Java AssignmentJava Assignment
The assignment operator has a lower precedence than the arithmetic operators
First the expression on the right handside of the = operator is evaluated
Then the result is stored in thevariable on the left hand side
answer = sum / 4 + MAX * lowest;
14 3 2
1-39
Java AssignmentJava Assignment
The right and left hand sides of an assignment statement can contain the same variable
First, one is added to theoriginal value of count
Then the result is stored back into count(overwriting the original value)
count = count + 1;
1-40
Java Assignment - OperatorsJava Assignment - Operators
Often we perform an operation on a variable, and then store the result back into that variable
Java provides assignment operators to simplify that process
For example, the statementnum += count;
is equivalent tonum = num + count;
1-41
Java Assignment - OperatorsJava Assignment - Operators
There are many assignment operators in Java, including the following
1-42
Operator
+=-=*=/=%=
Example
x += yx -= yx *= yx /= yx %= y
Equivalent To
x = x + yx = x - yx = x * yx = x / yx = x % y
Java Assignment - OperatorsJava Assignment - Operators
The right hand side of an assignment operator can be a complex expression
The entire right-hand expression is evaluated first, then the result is combined with the original variable
Thereforeresult /= (total-MIN) % num;
is equivalent toresult = result / ((total-MIN) % num);
1-43
Java Assignment - OperatorsJava Assignment - Operators
The behavior of some assignment operators depends on the types of the operands
If the operands to the += operator are strings, the assignment operator performs string concatenation
The behavior of an assignment operator (+=) is always consistent with the behavior of the corresponding operator (+)
1-44
Java Assignment - Increment and Java Assignment - Increment and DecrementDecrement
The increment and decrement operators use only one operand
The increment operator (++) adds one to its operand
The decrement operator (--) subtracts one from its operand
The statementcount++;
is functionally equivalent tocount = count + 1;
1-45
Java Assignment - Increment and Java Assignment - Increment and DecrementDecrement
The increment and decrement operators can be applied in postfix form
count++
or prefix form
++count
When used as part of a larger expression, the two forms can have different effects
Because of their subtleties, the increment and decrement operators should be used with care
1-46
47
Java Review TopicsJava Review TopicsPrimitive Data TypesExtended Data TypesVariablesArithmetic ExpressionsBoolean ExpressionsAssignmentData Conversion Input / OutputFlow of ControlArrays (revisited)MethodsClass Libraries
Java Data ConversionJava Data Conversion
Sometimes it is convenient to convert data from one type to another
For example, in a particular situation we may want to treat an integer as a floating point value
These conversions do not change the type of a variable or the value that's stored in it – they only convert a value as part of a computation
1-48
Java Data ConversionJava Data Conversion
Conversions must be handled carefully to avoid losing information
Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int)
Narrowing conversions can lose information because they tend to go from a large data type to a smaller one.
In Java, data conversions can occur in three ways◦assignment conversion◦promotion◦casting
1-49
Java Data ConversionJava Data Conversion
Assignment conversion occurs when a value of one type is assigned to a variable of another
If money is a float variable and dollars is an int variable, the following assignment converts the value in dollars to a float
money = dollars
Only widening conversions can happen via assignment
Note that the value or type of dollars did not change
1-50
Java Data ConversionJava Data Conversion
Promotion happens automatically when operators in expressions convert their operands
For example, if sum is a float and count is an int, the value of count is converted to a floating point value to perform the following calculation
result = sum / count;
1-51
Java Data ConversionJava Data ConversionCasting is the most powerful, and
dangerous, technique for conversion
Both widening and narrowing conversions can be accomplished by explicitly casting a value
To cast, the type is put in parentheses in front of the value being converted
For example, if total and count are integers, but we want a floating point result when dividing them, we can cast total
result = (float) total / count;1-52
53
Java Review TopicsJava Review TopicsPrimitive Data TypesExtended Data TypesVariablesArithmetic ExpressionsBoolean ExpressionsAssignmentData Conversion Input / OutputFlow of ControlArrays (revisited)MethodsClass Libraries
Java Input / OutputJava Input / Output
The Scanner class provides convenient methods for reading input values of various types
A Scanner object can be set up to read input from various sources, including the user typing values on the keyboard
Keyboard input is represented by the System.in object
1-54
Java Input / OutputJava Input / Output
The following line creates a Scanner object that reads from the keyboard
Scanner scan = new Scanner (System.in);
The new operator creates the Scanner object
Once created, the Scanner object can be used to invoke various input methods, such as
answer = scan.nextLine();
1-55
Java Input / OutputJava Input / Output
The Scanner class is part of the java.util class library, and must be imported into a program to be used
The nextLine method reads all of the input until the end of the line is found
1-56
Java Input / OutputJava Input / Output
Unless specified otherwise, white space is used to separate the elements (called tokens) of the input
White space includes space characters, tabs, new line characters
The next method of the Scanner class reads the next input token and returns it as a string
Methods such as nextInt and nextDouble read data of particular types
1-57
Java Input / OutputJava Input / Output
The System.out object represents a destination (the monitor screen) to which we can send output
System.out.println ("Whatever you are, be a good one.");
object methodname
information provided to the method(parameters)
1-58
Java Input / OutputJava Input / Output
The System.out object provides another service as well
The print method is similar to the println method, except that it does not advance to the next line
Therefore anything printed after a print statement will appear on the same line
1-59
60
Java Review TopicsJava Review TopicsPrimitive Data TypesExtended Data TypesVariablesArithmetic ExpressionsBoolean ExpressionsAssignmentData Conversion Input / OutputFlow of ControlArrays (revisited)MethodsClass Libraries
Java Flow of ControlJava Flow of Control
Unless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequence
Some programming statements allow us to◦ decide whether or not to execute a particular
statement
◦ execute a statement over and over, repetitivelyThese decisions are based on boolean
expressions (or conditions) that evaluate to true or false
The order of statement execution is called the flow of control
1-61
Java Flow of ControlJava Flow of Control
A conditional statement lets us choose which statement will be executed next
Therefore they are sometimes called selection statements
Conditional statements give us the power to make basic decisions
The Java conditional statements are the◦ if statement
◦ if-else statement
◦ switch statement
1-62
Java Flow of Control - Java Flow of Control - ifif
The if statement has the following syntax
1-63
if ( condition )
statement;
if is a Java
reserved word
The condition must be a
boolean expression. It must
evaluate to either true or false.
If the condition is true, the statement is executed.
If it is false, the statement is skipped.
Java Flow of Control - Java Flow of Control - ififAn example of an if statement:
if (sum > MAX)
delta = sum - MAX;
System.out.println ("The sum is " + sum);• First the condition is evaluated -- the
value of sum is either greater than the value of MAX, or it is not
• If the condition is true, the assignment statement is executed -- if it isn’t, it is skipped.
• Either way, the call to println is executed next
1-64
Java Flow of Control - Java Flow of Control - ifif
condition
evaluated
statement
truefalse
1-65
Java Flow of Control - Java Flow of Control - ifif
What do the following statements do?
if (top >= MAXIMUM)
top = 0;Sets top to zero if the current value of top is greater
than or equal to the value of MAXIMUMif (total != stock + warehouse)
inventoryError = true;
Sets a flag to true if the value of total is not equal to
the sum of stock and warehouse• The precedence of the arithmetic operators is higher than the precedence of the equality and relational operators
1-66
Java Flow of Control – Java Flow of Control – if-elseif-else
An else clause can be added to an if statement to make an if-else statement
1-67
if ( condition )
statement1;
else
statement2;• If the condition is true, statement1 is executed; if the condition is false, statement2 is executed
• One or the other will be executed, but not both
Java Flow of Control – Java Flow of Control – if-elseif-else
condition
evaluated
statement1
true false
statement2
1-68
Java Flow of Control – Java Flow of Control – block block statementsstatements
Several statements can be grouped together into a block statement delimited by braces
A block statement can be used wherever a statement is called for in the Java syntax rules
1-69
if (total > MAX)
{
System.out.println ("Error!!");
errorCount++;
}
Java Flow of Control – Java Flow of Control – block block statementsstatements
In an if-else statement, the if portion, or the else portion, or both, could be block statements
1-70
if (total > MAX)
{
System.out.println ("Error!!");
errorCount++;
}
else
{
System.out.println ("Total: " + total);
current = total*2;
}
Java Flow of Control – Java Flow of Control – nested ifnested if
The statement executed as a result of an if statement or else clause could be another if statement
These are called nested if statements
An else clause is matched to the last unmatched if (no matter what the indentation implies)
Braces can be used to specify the if statement to which an else clause belongs
1-71
Java Flow of Control – Java Flow of Control – switchswitch
The switch statement provides another way to decide which statement to execute next
The switch statement evaluates an expression, then attempts to match the result to one of several possible cases
Each case contains a value and a list of statements
The flow of control transfers to statement associated with the first case value that matches
1-72
Java Flow of Control – Java Flow of Control – switchswitch
The general syntax of a switch statement is
switch ( expression )
{
case value1 :
statement-list1
case value2 :
statement-list2
case value3 :
statement-list3
case ...
}
switch
and
case
are
reserved
words
If expression
matches value2,
control jumps
to here
Java Flow of Control – Java Flow of Control – switchswitch
Often a break statement is used as the last statement in each case's statement list
A break statement causes control to transfer to the end of the switch statement
If a break statement is not used, the flow of control will continue into the next case
Sometimes this may be appropriate, but often we want to execute only the statements associated with one case
Java Flow of Control – Java Flow of Control – switchswitch
An example of a switch statementswitch (option)
{
case 'A':
aCount++;
break;
case 'B':
bCount++;
break;
case 'C':
cCount++;
break;
}
Java Flow of Control – Java Flow of Control – switchswitch
A switch statement can have an optional default case
The default case has no associated value and simply uses the reserved word default
If the default case is present, control will transfer to it if no other case value matches
If there is no default case, and no other value matches, control falls through to the statement after the switch
Java Flow of Control – Java Flow of Control – switchswitch
The expression of a switch statement must result in an integral type, meaning an integer (byte, short, int, long) or a char
It cannot be a boolean value or a floating point value (float or double)
The implicit boolean condition in a switch statement is equality
You cannot perform relational checks with a switch statement
Java Flow of Control – Repetition Java Flow of Control – Repetition StatementsStatements
Repetition statements allow us to execute a statement multiple times
Often they are referred to as loopsLike conditional statements, they are
controlled by boolean expressionsJava has three kinds of repetition
statements:◦ the while loop◦ the do loop◦ the for loop
The programmer should choose the right kind of loop for the situation
1-78
Java Flow of Control – Java Flow of Control – whilewhile
A while statement has the following syntax
1-79
while ( condition )
statement;
If the condition is true, the statement is executed
Then the condition is evaluated again, and if it is still true, the statement is executed again
The statement is executed repeatedly until the condition becomes false
Java Flow of Control – Java Flow of Control – whilewhile
statement
true false
condition
evaluated
1-80
Java Flow of Control – Java Flow of Control – whilewhile
The body of a while loop eventually must make the condition false
If not, it is called an infinite loop, which will execute until the user interrupts the program
This is a common logical error
You should always double check the logic of a program to ensure that your loops will terminate normally
1-81
Java Flow of Control – Nested LoopsJava Flow of Control – Nested Loops
Similar to nested if statements, loops can be nested as well
That is, the body of a loop can contain another loop
For each iteration of the outer loop, the inner loop iterates completely
1-82
Java Flow of Control – Java Flow of Control – dodo
A do statement has the following syntaxdo
{
statement;
}
while ( condition )• The statement is executed once initially, and then the condition is evaluated
• The statement is executed repeatedly until the condition becomes false
1-83
Java Flow of Control – Java Flow of Control – dodo
true
condition
evaluated
statement
false
1-84
Java Flow of Control – Java Flow of Control – while while andand dodo
statement
true false
condition
evaluated
The while Loop
true
condition
evaluated
statement
false
The do Loop
1-85
Java Flow of Control – Java Flow of Control – forfor
A for statement has the following syntax
for ( initialization ; condition ; increment )
statement;
The initialization
is executed once
before the loop begins
The statement is
executed until the
condition becomes false
The increment portion is executed at the
end of each iteration
1-86
Java Flow of Control – Java Flow of Control – forfor
statement
true
condition
evaluated
false
increment
initialization
1-87
Java Flow of Control – Java Flow of Control – forfor
A for loop is functionally equivalent to the following while loop structureinitialization;
while ( condition )
{
statement;
increment;
}
1-88
Java Flow of Control – Java Flow of Control – forfor
Each expression in the header of a for loop is optional
If the initialization is left out, no initialization is performed
If the condition is left out, it is always considered to be true, and therefore creates an infinite loop
If the increment is left out, no increment operation is performed
1-89
90
Java Review TopicsJava Review TopicsPrimitive Data TypesExtended Data TypesVariablesArithmetic ExpressionsBoolean ExpressionsAssignmentData Conversion Input / OutputFlow of ControlArrays (revisited)MethodsClass Libraries
Java ArraysJava Arrays
A particular value in an array is referenced using the array name followed by the index in brackets
For example, the expression
scores[2]
refers to the value 94 (the 3rd value in the array)
That expression represents a place to store a single integer and can be used wherever an integer variable can be used
1-91
Java ArraysJava Arrays
For example, an array element can be assigned a value, printed, or used in a calculation
scores[2] = 89;
scores[first] = scores[first] + 2;
mean = (scores[0] + scores[1])/2;
System.out.println ("Top = " + scores[5]);
1-92
Java ArraysJava ArraysThe values held in an array are called
array elementsAn array stores multiple values of the
same type – the element typeThe element type can be a primitive
type or an object referenceTherefore, we can create an array of
integers, an array of characters, an array of String objects, an array of Coin objects, etc.
In Java, the array itself is an object that must be instantiated
1-93
Java ArraysJava Arrays
Another way to depict the scores array
scores 79
87
94
82
67
98
87
81
74
91
1-94
Java ArraysJava Arrays
The scores array could be declared as follows
int[] scores = new int[10];
The type of the variable scores is int[] (an array of integers)
Note that the array type does not specify its size, but each object of that type has a specific size
The reference variable scores is set to a new array object that can hold 10 integers
1-95
Java ArraysJava Arrays
Some other examples of array declarations
float[] prices = new float[500];
boolean[] flags;
flags = new boolean[20];
char[] codes = new char[1750];
1-96
Java ArraysJava Arrays
Once an array is created, it has a fixed size
An index used in an array reference must specify a valid element
That is, the index value must be in range 0 to N-1
The Java interpreter throws an ArrayIndexOutOfBoundsException if an array index is out of bounds
This is called automatic bounds checking
1-97
Java ArraysJava Arrays
For example, if the array codes can hold 100 values, it can be indexed using only the numbers 0 to 99
If the value of count is 100, then the following reference will cause an exception to be thrown
System.out.println (codes[count]);
It’s common to introduce off-by-one errors when using arrays
for (int index=0; index <= 100; index++)codes[index] = index*50 + epsilon;
problem
1-98
Java ArraysJava Arrays
Each array object has a public constant called length that stores the size of the array
It is referenced using the array name
scores.length
Note that length holds the number of elements, not the largest index
1-99
Java ArraysJava Arrays
The brackets of the array type can be associated with the element type or with the name of the array
Therefore the following two declarations are equivalent
float[] prices;float prices[];
The first format generally is more readable and should be used
1-100
Java ArraysJava Arrays
An initializer list can be used to instantiate and fill an array in one step
The values are delimited by braces and separated by commas
Examples
int[] units = {147, 323, 89, 933, 540,
269, 97, 114, 298, 476};
char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};
1-101
Java ArraysJava Arrays
Note that when an initializer list is used
◦ the new operator is not used
◦ no size value is specifiedThe size of the array is determined by
the number of items in the initializer list
An initializer list can be used only in the array declaration
1-102
Java ArraysJava Arrays
An entire array can be passed as a parameter to a method
Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other
Therefore, changing an array element within the method changes the original
An individual array element can be passed to a method as well, in which case the type of the formal parameter is the same as the element type
1-103
Java ArraysJava Arrays
A one-dimensional array stores a list of elements
A two-dimensional array can be thought of as a table of elements, with rows and columns
one
dimension
two
dimensions
1-104
Java ArraysJava ArraysTo be precise, in Java a two-dimensional
array is an array of arraysA two-dimensional array is declared by
specifying the size of each dimension separately
int[][] scores = new int[12][50];A array element is referenced using two
index valuesvalue = scores[3][6]
The array stored in one row can be specified using one index
1-105
Java ArraysJava Arrays
Expression Type Descriptiontable int[][] 2D array of integers, or
array of integer arrays
table[5] int[] array of integers
table[5][12] int integer
1-106
Java ArraysJava Arrays
An array can have many dimensions – if it has more than one dimension, it is called a multidimensional array
Each dimension subdivides the previous one into the specified number of elements
Each dimension has its own length constant
Because each dimension is an array of array references, the arrays within one dimension can be of different lengths
◦ these are sometimes called ragged arrays
1-107
108
Java Review TopicsJava Review TopicsPrimitive Data TypesExtended Data TypesVariablesArithmetic ExpressionsBoolean ExpressionsAssignmentData Conversion Input / OutputFlow of ControlArrays (revisited)MethodsClass Libraries
Java MethodsJava Methods
Let’s now examine method declarations in more detail
A method declaration specifies the code that will be executed when the method is invoked (called)
When a method is invoked, the flow of control jumps to the method and executes its code
When complete, the flow returns to the place where the method was called and continues
The invocation may or may not return a value, depending on how the method is defined
1-109
myMethod();
myMethodcompute
Java MethodsJava MethodsIf the called method is in the same class,
only the method name is needed
1-110
Java MethodsJava MethodsWe will only use static methodsA method declaration begins with a method header
static char calc (int num1, int num2, String msg)
method
name
return
type
parameter list
The parameter list specifies the type
and name of each parameter
The name of a parameter in the method
declaration is called a formal parameter
1-111
Java MethodsJava Methods
The method header is followed by the method body
static char calc (int num1, int num2, String msg)
{
int sum = num1 + num2;
char result = msg.charAt (sum);
return result;
} The return expression
must be consistent with
the return type
sum and result
are local data
They are created each time the
method is called, and are
destroyed when it finishes
executing
1-112
Java Methods - Java Methods - returnreturn
The return type of a method indicates the type of value that the method sends back to the calling location
A method that does not return a value has a void return type
A return statement specifies the value that will be returned
return expression;
Its expression must conform to the return type
1-113
Java Methods – ParametersJava Methods – Parameters
When a method is called, the actual parameters in the invocation are copied into the formal parameters in the method header
char calc (int num1, int num2, String message)
{
int sum = num1 + num2;
char result = message.charAt (sum);
return result;
}
ch = obj.calc (25, count, "Hello");
1-114
Java Methods – Local DataJava Methods – Local Data
As we’ve seen, local variables can be declared inside a method
The formal parameters of a method create automatic local variables when the method is invoked
When the method finishes, all local variables are destroyed (including the formal parameters)
1-115
116
Java Review TopicsJava Review TopicsPrimitive Data TypesExtended Data TypesVariablesArithmetic ExpressionsBoolean ExpressionsAssignmentData Conversion Input / OutputFlow of ControlArrays (revisited)MethodsClass Libraries
1-117
Java Class LibrariesJava Class LibrariesA class library is a collection of classes that
we can use when developing programs
The Java standard class library is part of any Java development environment
Its classes are not part of the Java language per se, but we rely on them heavily
Various classes we've already used (System , Scanner, String) are part of the Java standard class library
Other class libraries can be obtained through third party vendors, or you can create them yourself
1-118
Java Class LibrariesJava Class Libraries
The classes of the Java standard class library are organized into packages
Some of the packages in the standard class library are
Package
java.langjava.appletjava.awtjavax.swingjava.netjava.utiljavax.xml.parsers
Purpose
General supportCreating applets for the webGraphics and graphical user interfacesAdditional graphics capabilitiesNetwork communicationUtilitiesXML document processing
1-119
Java Class LibrariesJava Class Libraries
When you want to use a class from a package, you could use its fully qualified name
java.util.Scanner
Or you can import the class, and then use just the class name
import java.util.Scanner;
To import all classes in a particular package, you can use the * wildcard character
import java.util.*;
1-120
Java Class LibrariesJava Class Libraries
All classes of the java.lang package are imported automatically into all programs
It's as if all programs contain the following line
import java.lang.*;
That's why we didn't have to import the System or String classes explicitly in earlier programs
The Scanner class, on the other hand, is part of the java.util package, and therefore must be imported