0% found this document useful (0 votes)
16 views251 pages

Module - 2

Uploaded by

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

Module - 2

Uploaded by

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

BCSE103E

Computer Programming: JAVA


Module - II

Dr. R.BHARANIDARAN
Associate Professor


School of Mechanical Engineering
Course Content
Conditional Control Statements in Java
Conditional control statements in java
Relational Operators
One-way if Statements
if (radius >= 0) {
area = radius * radius * PI;
if (boolean-expression) { System.out.println("The area"
statement(s);
}
+ " for the circle of radius "
+ radius + " is " + area);
}
Note
Example
Write a program that prompts the user to enter an integer. If the
number is a multiple of 5, print HiFive. If the number is divisible
by 2, print HiEven.
The Two-way if Statement
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
if-else Example
if (radius >= 0) {
area = radius * radius * 3.14159;

System.out.println("The area for the “


+ “circle of radius " + radius +
" is " + area);
}
else {
System.out.println("Negative input");
}
Multiple Alternative if Statements
Multi-Way if-else Statements
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
Trace if-else statement
Suppose score is 70.0 The condition is true

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
Trace if-else statement
Suppose score is 70.0 grade is C

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
Trace if-else statement
Suppose score is 70.0 Exit the if statement

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
Note
The else clause matches the most recent if clause in the
same block.
Note, cont.
Nothing is printed from the preceding statement. To force
the else clause to match the first if clause, you must add a
pair of braces:
int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");
This statement prints B.
Common Errors
Adding a semicolon at the end of an if clause is a common
mistake.
if (radius >= 0);
Wrong
{
area = radius*radius*PI;
System.out.println(
"The area for the circle of radius " +
radius + " is " + area);
}
This mistake is hard to find, because it is not a compilation error
or a runtime error, it is a logic error.
This error often occurs when you use the next-line block style.
TIP
CAUTION
Problem: An Improved Math Learning Tool
This example creates a program to teach a
first grade child how to learn subtractions.
The program randomly generates two single-
digit integers number1 and number2 with
number1 >= number2 and displays a question
such as “What is 9 – 2?” to the student. After
the student types the answer, the program
displays whether the answer is correct.
Problem: Body Mass Index

Body Mass Index (BMI) is a measure of health on weight. It can


be calculated by taking your weight in kilograms and dividing by
the square of your height in meters. The interpretation of BMI for
people 16 years or older is as follows:
Problem: Computing Taxes
The US federal personal income tax is calculated based on the
filing status and taxable income. There are four filing statuses:
single filers, married filing jointly, married filing separately, and
head of household. The tax rates for 2009 are shown below.
Problem: Computing Taxes, cont.
if (status == 0) {
// Compute tax for single filers
}
else if (status == 1) {
// Compute tax for married file jointly
// or qualifying widow(er)
}
else if (status == 2) {
// Compute tax for married file separately
}
else if (status == 3) {
// Compute tax for head of household
}
else {
// Display wrong status
}
Logical Operators
Operator Name Description

! not logical negation

&& and logical conjunction

|| or logical disjunction

^ exclusive or logical exclusion


Truth Table for Operator !

p !p Example (assume age = 24, weight = 140)

true false !(age > 18) is false, because (age > 18) is true.

false true !(weight == 150) is true, because (weight == 150) is false.


Truth Table for Operator &&
p1 p2 p1 && p2 Example (assume age = 24, weight = 140)

false false false (age <= 18) && (weight < 140) is false, because both

conditions are both false.

false true false  

false
true false (age > 18) && (weight > 140) is false, because (weight

> 140) is false.

true
true true  (age > 18) && (weight >= 140) is true, because both

(age > 18) and (weight >= 140) are true.


Truth Table for Operator ||

p1 p2 p1 || p2 Example (assume age = 24, weihgt = 140)

false false false

false true true  (age > 34) || (weight <= 140) is true, because (age > 34)
is false, but (weight <= 140) is true.

true
true false (age > 14) || (weight >= 150) is false, because

(age > 14) is true.

true
true true  
Truth Table for Operator ^
p1 p2 p1 ^ p2 Example (assume age = 24, weight = 140)

false false false (age > 34) ^ (weight > 140) is true, because (age > 34) is false

and (weight > 140) is false.

false true true  (age > 34) ^ (weight >= 140) is true, because (age > 34) is false

but (weight >= 140) is true.

true
true false (age > 14) ^ (weight > 140) is true, because (age > 14) is

true and (weight > 140) is false.

false
true true  
Examples
Here is a program that checks whether a number is divisible by 2
and 3, whether a number is divisible by 2 or 3, and whether a
number is divisible by 2 or 3 but not both:
Examples
System.out.println("Is " + number + " divisible by 2 and 3? " +
((number % 2 == 0) && (number % 3 == 0)));
  
System.out.println("Is " + number + " divisible by 2 or 3? " +
((number % 2 == 0) || (number % 3 == 0)));
 
System.out.println("Is " + number +
" divisible by 2 or 3, but not both? " + TestBooleanOperators
((number % 2 == 0) ^ (number % 3 == 0))); Run
Companion
Website
The & and | Operators

Supplement III.B, “The & and | Operators”


Companion
Website
The & and | Operators
If x is 1, what is x after this
expression?
(x > 1) & (x++ < 10)

If x is 1, what is x after this


expression?
(1 > x) && ( 1 > x++)

How about (1 == x) | (10 > x++)?


(1 == x) || (10 > x++)?
Problem: Determining Leap Year?
This program first prompts the user to enter a year as
an int value and checks if it is a leap year.
A year is a leap year if it is divisible by 4 but not by
100, or it is divisible by 400.
(year % 4 == 0 && year % 100 != 0) || ( year % 400 == 0)
Problem: Lottery

Write a program that randomly generates a lottery of a


two-digit number, prompts the user to enter a two-digit
number, and determines whether the user wins
according to the following rule:
 If the user input matches the lottery in exact order,
the award is $10,000.
 If the user input matches the lottery, the award is
$3,000.
 If one digit in the user input matches a digit in the
lottery, the award is $1,000.
switch (status) {
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file
jointly;
break;
case 2: compute taxes for married file
switch separately;

Statements break;
case 3: compute taxes for head of
household;
break;
default: System.out.println("Errors: invalid
status");
System.exit(1);
}
switch Statement Flow Chart
switch Statement Rules
The switch-expression
must yield a value of char, switch (switch-expression) {
byte, short, or int type and
must always be enclosed case value1: statement(s)1;
in parentheses. break;
case value2: statement(s)2;
The value1, ..., and valueN must break;
have the same data type as the …
value of the switch-expression.
case valueN: statement(s)N;
The resulting statements in the
case statement are executed when break;
the value in the case statement default: statement(s)-for-default;
matches the value of the switch- }
expression. Note that value1, ...,
and valueN are constant
expressions, meaning that they
cannot contain variables in the
expression, such as 1 + x.
switch Statement Rules
The keyword break is optional, switch (switch-expression) {
but it should be used at the end
of each case in order to terminate case value1: statement(s)1;
the remainder of the switch break;
statement. If the break statement
is not present, the next case case value2: statement(s)2;
statement will be executed. break;

case valueN: statement(s)N;
The default case, which is
break;
optional, can be used to perform default: statement(s)-for-default;
actions when none of the }
specified cases matches the
switch-expression.
When the value in a case statement matches the value
of the switch-expression, the statements starting from
this case are executed until either a break statement or
the end of the switch statement is reached.
animation
Trace switch statement
Suppose day is 2:

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation
Trace switch statement
Match case 2

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation
Trace switch statement
Fall through case 3

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation
Trace switch statement
Fall through case 4

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation
Trace switch statement
Fall through case 5

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation
Trace switch statement
Encounter break

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation
Trace switch statement
Exit the statement

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
Sample
public class Main {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}
}
}
Problem: Chinese Zodiac

Write a program that prompts the user to enter a year and


displays the animal for the year.

ChineseZodiac Run
Conditional Expressions
if (x > 0)
y=1
else
y = -1;

is equivalent to

y = (x > 0) ? 1 : -1;
(boolean-expression) ? expression1 : expression2

Ternary operator
Binary operator
Unary operator
Conditional Operator
if (num % 2 == 0)
System.out.println(num + “is even”);
else
System.out.println(num + “is odd”);

System.out.println(
(num % 2 == 0)? num + “is even” :
num + “is odd”);
Conditional Operator, cont.
boolean-expression ? exp1 : exp2
Operator Precedence
• ()
• var++, var--
• +, - (Unary plus and minus), ++var,--var
• (type) Casting
• ! (Not)
• *, /, % (Multiplication, division, and remainder)
• +, - (Binary addition and subtraction)
• <, <=, >, >= (Relational operators)
• ==, !=; (Equality)
• ^ (Exclusive OR)
• && (Conditional AND) Short-circuit AND
• || (Conditional OR) Short-circuit OR
• =, +=, -=, *=, /=, %= (Assignment operator)
Operator Precedence and Associativity
The expression in the parentheses is evaluated first.
(Parentheses can be nested, in which case the expression
in the inner parentheses is executed first.) When
evaluating an expression without parentheses, the
operators are applied according to the precedence rule
and the associativity rule.

If operators with the same precedence are next to each


other, their associativity determines the order of
evaluation. All binary operators except assignment
operators are left-associative.
Operator Associativity
When two operators with the same precedence
are evaluated, the associativity of the operators
determines the order of evaluation. All binary
operators except assignment operators are left-
associative.
a – b + c – d is equivalent to  ((a – b) + c) – d
Assignment operators are right-associative.
Therefore, the expression
a = b += c = 5 is equivalent to a = (b += (c = 5))
Example
Applying the operator precedence and associativity
rule, the expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is
evaluated as follows:
Debugging
Logic errors are called bugs. The process of finding and
correcting errors is called debugging. A common approach
to debugging is to use a combination of methods to
narrow down to the part of the program where the bug is
located. You can hand-trace the program (i.e., catch errors
by reading the program), or you can insert print
statements in order to show the values of the variables or
the execution flow of the program. This approach might
work for a short, simple program. But for a large, complex
program, the most effective approach for debugging is to
use a debugger utility.
Debugger
Debugger is a program that facilitates debugging.
You can use a debugger to

•Execute a single statement at a time.


•Trace into or stepping over a method.
•Set breakpoints.
•Display variables.
•Display call stack.
•Modify variables.
while Loop Flow Chart
int count = 0;
while (loop-continuation-condition) {
while (count < 100) {
// loop-body;
System.out.println("Welcome to Java!");
Statement(s); count++;
} }
animation

Trace while Loop


Initialize count
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation

Trace while Loop, cont.


(count < 2) is true
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation

Trace while Loop, cont.


Print Welcome to Java
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation

Trace while Loop, cont.


Increase count by 1
int count = 0; count is 1 now
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation

Trace while Loop, cont.


(count < 2) is still true since count
int count = 0; is 1
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation

Trace while Loop, cont.


Print Welcome to Java
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation

Trace while Loop, cont.


Increase count by 1
int count = 0; count is 2 now
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation

Trace while Loop, cont.


(count < 2) is false since count is 2
int count = 0; now
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation

Trace while Loop


The loop exits. Execute the next
int count = 0; statement after the loop.

while (count < 2) {


System.out.println("Welcome to Java!");
count++;
}
Problem: Repeat Addition Until Correct

Recall that Listing 3.1 AdditionQuiz.java gives a program


that prompts the user to enter an answer for a question
on addition of two single digits. Using a loop, you can
now rewrite the program to let the user enter a new
answer until it is correct.

IMPORTANT NOTE: If you cannot run the buttons,


see www.cs.armstrong.edu/liang/javaslidenote.doc.

RepeatAdditionQuiz Run
Problem: Guessing Numbers
Write a program that randomly generates an integer
between 0 and 100, inclusive. The program prompts the
user to enter a number continuously until the number
matches the randomly generated number. For each user
input, the program tells the user whether the input is too
low or too high, so the user can choose the next input
intelligently. Here is a sample run:

GuessNumberOneTime Run

GuessNumber Run
Problem: An Advanced Math Learning Tool

The Math subtraction learning tool program generates


just one question for each run. You can use a loop to
generate questions repeatedly. This example gives a
program that generates five questions and reports the
number of the correct answers after a student answers all
five questions.

SubtractionQuizLoop Run
Ending a Loop with a Sentinel Value
Often the number of times a loop is executed is not
predetermined. You may use an input value to signify the
end of the loop. Such a value is known as a sentinel value.

Write a program that reads and calculates the sum of an


unspecified number of integers. The input 0 signifies the
end of the input.

SentinelValue Run
Caution
Don’t use floating-point values for equality checking in a
loop control. Since floating-point values are
approximations for some values, using them could result
in imprecise counter values and inaccurate results.
Consider the following code for computing 1 + 0.9 + 0.8
+ ... + 0.1:
double item = 1; double sum = 0;
while (item != 0) { // No guarantee item will be 0
sum += item;
item -= 0.1;
}
System.out.println(sum);
do-while Loop

do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
for Loops
for (initial-action; loop- int i;
continuation-condition; action- for (i = 0; i < 100; i++) {
after-each-iteration) {
System.out.println(
// loop body;
Statement(s); "Welcome to Java!");
} }
animation

Trace for Loop


Declare i
int i;
for (i = 0; i < 2; i++) {
System.out.println(
"Welcome to Java!");
}
animation

Trace for Loop, cont.


Execute initializer
int i; i is now 0
for (i = 0; i < 2; i++) {
System.out.println(
"Welcome to Java!");
}
animation

Trace for Loop, cont.


(i < 2) is true
int i; since i is 0
for (i = 0; i < 2; i++) {
System.out.println( "Welcome to Java!");
}
animation

Trace for Loop, cont.


Print Welcome to Java
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
animation

Trace for Loop, cont.


Execute adjustment statement
int i; i now is 1
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
animation

Trace for Loop, cont.


(i < 2) is still true
int i; since i is 1
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
animation

Trace for Loop, cont.


Print Welcome to Java
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
animation

Trace for Loop, cont.


Execute adjustment statement
int i; i now is 2
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
animation

Trace for Loop, cont.


(i < 2) is false
int i; since i is 2
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
animation

Trace for Loop, cont.


Exit the loop. Execute the next
int i; statement after the loop
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
Note
The initial-action in a for loop can be a list of zero or more
comma-separated expressions. The action-after-each-
iteration in a for loop can be a list of zero or more comma-
separated statements. Therefore, the following two for
loops are correct. They are rarely used in practice,
however.
for (int i = 1; i < 100; System.out.println(i++));
 
for (int i = 0, j = 0; (i + j < 10); i++, j++) {
// Do something
}
Note
If the loop-continuation-condition in a for loop is omitted,
it is implicitly true. Thus the statement given below in (a),
which is an infinite loop, is correct. Nevertheless, it is
better to use the equivalent loop in (b) to avoid confusion:
Caution
Adding a semicolon at the end of the for clause before
the loop body is a common mistake, as shown below:
Logic
Error

for (int i=0; i<10; i++);


{
System.out.println("i is " + i);
}
Caution, cont.
Similarly, the following loop is also wrong:
int i=0;
while (i < 10); Logic Error
{
System.out.println("i is " + i);
i++;
}
In the case of the do loop, the following semicolon is
needed to end the loop.
int i=0;
do {
System.out.println("i is " + i);
i++;
} while (i<10); Correct
Which Loop to Use?
The three forms of loop statements, while, do-while, and for, are
expressively equivalent; that is, you can write a loop in any of these
three forms. For example, a while loop in (a) in the following figure
can always be converted into the following for loop in (b):

A for loop in (a) in the following figure can generally be converted into the
following while loop in (b) except in certain special cases (see Review Question
3.19 for one of them):
Recommendations
Use the one that is most intuitive and comfortable for
you. In general, a for loop may be used if the number of
repetitions is known, as, for example, when you need to
print a message 100 times. A while loop may be used if
the number of repetitions is not known, as in the case of
reading the numbers until the input is 0. A do-while loop
can be used to replace a while loop if the loop body has to
be executed before testing the continuation condition.
Nested Loops
Problem: Write a program that uses nested for
loops to print a multiplication table.

MultiplicationTable Run
Minimizing Numerical Errors

Numeric errors involving floating-point


numbers are inevitable. This section discusses
how to minimize such errors through an
example.

Here is an example that sums a series that


starts with 0.01 and ends with 1.0. The
numbers in the series will increment by 0.01,
as follows: 0.01 + 0.02 + 0.03 and so on.
TestSum Run
Problem:
Finding the Greatest Common Divisor
Problem: Write a program that prompts the user to enter two
positive integers and finds their greatest common divisor.
Solution: Suppose you enter two integers 4 and 2, their greatest
common divisor is 2. Suppose you enter two integers 16 and 24,
their greatest common divisor is 8. So, how do you find the
greatest common divisor? Let the two input integers be n1 and n2.
You know number 1 is a common divisor, but it may not be the
greatest commons divisor. So you can check whether k (for k = 2,
3, 4, and so on) is a common divisor for n1 and n2, until k is
greater than n1 or n2.
Problem: Predicting the Future Tuition
Problem: Suppose that the tuition for a university is $10,000 this year
and tuition increases 7% every year. In how many years will the
tuition be doubled?

FutureTuition Run
Problem: Predicating the Future Tuition
double tuition = 10000; int year = 0 // Year 0
tuition = tuition * 1.07; year++; // Year 1
tuition = tuition * 1.07; year++; // Year 2
tuition = tuition * 1.07; year++; // Year 3
...
Case Study: Converting Decimals to
Hexadecimals
Hexadecimals are often used in computer systems programming (see
Appendix F for an introduction to number systems). How do you
convert a decimal number to a hexadecimal number? To convert a
decimal number d to a hexadecimal number is to find the
hexadecimal digits hn, hn-1, hn-2, ... , h2, h1, and h0 such that

These hexadecimal digits can be found by successively dividing d by


16 until the quotient is 0. The remainders are h0, h1, h2, ... , hn-2, hn-1,
and hn.
Dec2Hex Run
Companion Website

Problem: Monte Carlo Simulation


The Monte Carlo simulation refers to a technique that uses random
numbers and probability to solve problems. This method has a wide
range of applications in computational mathematics, physics,
chemistry, and finance. This section gives an example of using the
Monto Carlo simulation for estimating .

circleArea / squareArea =  / 4.

 can be approximated as 4 *
numberOfHits / numberOfTrials

MonteCarloSimulation Run
Using break and continue
Examples for using the break and continue
keywords:

 TestBreak.java
TestBreak Run

 TestContinue.java
TestContinue Run
break
continue
Guessing Number Problem Revisited

Here is a program for guessing a number. You can rewrite


it using a break statement.

GuessNumberUsingBreak Run
Problem: Checking Palindrome
A string is a palindrome if it reads the same forward and backward.
The words “mom,” “dad,” and “noon,” for instance, are all
palindromes.
The problem is to write a program that prompts the user to enter a
string and reports whether the string is a palindrome. One solution is
to check whether the first character in the string is the same as the last
character. If so, check whether the second character is the same as the
second-to-last character. This process continues until a mismatch is
found or all the characters in the string are checked, except for the
middle character if the string has an odd number of characters.

Palindrome Run
Problem: Displaying Prime Numbers
Problem: Write a program that displays the first 50 prime numbers in
five lines, each of which contains 10 numbers. An integer greater
than 1 is prime if its only positive divisor is 1 or itself. For example,
2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not.
Solution: The problem can be broken into the following tasks:
• For number = 2, 3, 4, 5, 6, ..., test whether the number is prime.
• Determine whether a given number is prime.
• Count the prime numbers.
• Print each prime number, and print 10 numbers per line.

PrimeNumber Run
Single-Dimensional Arrays
Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
Declaring Array Variables
• datatype[] arrayRefVar;
Example:
double[] myList;

• datatype arrayRefVar[]; // This style is


allowed, but not preferred
Example:
double myList[];
Creating Arrays
arrayRefVar = new datatype[arraySize];

Example:
myList = new double[10];

myList[0] references the first element in the array.


myList[9] references the last element in the array.
Declaring and Creating
in One Step
• datatype[] arrayRefVar = new
datatype[arraySize];
double[] myList = new double[10];

• datatype arrayRefVar[] = new


datatype[arraySize];
double myList[] = new double[10];
The Length of an Array
Once an array is created, its size is fixed. It cannot be
changed. You can find its size using

arrayRefVar.length

For example,

myList.length returns 10
Default Values
When an array is created, its elements are
assigned the default value of

0 for the numeric primitive data types,


'\u0000' for char types, and
false for boolean types.
Indexed Variables
The array elements are accessed through the index.
The array indices are 0-based, i.e., it starts from 0 to
arrayRefVar.length-1. example, myList holds ten double
values and the indices are from 0 to 9.

Each element in the array is represented using the


following syntax, known as an indexed variable:

arrayRefVar[index];
Using Indexed Variables
After an array is created, an indexed variable
can be used in the same way as a regular
variable. For example, the following code adds
the value in myList[0] and myList[1] to myList[2].

myList[2] = myList[0] + myList[1];


Array Initializers
• Declaring, creating, initializing in one step:
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand syntax must be in one
statement.
Declaring, creating, initializing Using the
Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the following
statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
CAUTION
Using the shorthand notation, you have to declare, create,
and initialize the array all in one statement. Splitting it
would cause a syntax error. For example, the following is
wrong:
double[] myList;

myList = {1.9, 2.9, 3.4, 3.5};


animation
Trace Program with Arrays
Declare array variable values, create an
array, and assign its reference to values

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
animation
Trace Program with Arrays
i becomes 1

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
animation
Trace Program with Arrays
i (=1) is less than 5

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
animation
Trace Program with Arrays
After this line is executed, value[1] is 1

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
animation
Trace Program with Arrays
After i++, i becomes 2

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
animation
Trace Program with Arrays

i (= 2) is less than 5
public class Test {
public static void main(String[]
args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
animation
Trace Program with Arrays
After this line is executed,
values[2] is 3 (2 + 1)

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
animation
Trace Program with Arrays
After this, i becomes 3.

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
animation
Trace Program with Arrays

i (=3) is still less than 5.

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
animation
Trace Program with Arrays

After this line, values[3] becomes 6 (3 + 3)

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
animation
Trace Program with Arrays
After this, i becomes 4

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
animation
Trace Program with Arrays
i (=4) is still less than 5

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
animation
Trace Program with Arrays
After this, values[4] becomes 10 (4 + 6)

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
animation
Trace Program with Arrays
After i++, i becomes 5

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
animation

Trace Program with Arrays


i ( =5) < 5 is false. Exit the loop

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
animation
Trace Program with Arrays
After this line, values[0] is 11 (1 + 10)

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
Processing Arrays
See the examples in the text.
1. (Initializing arrays with input values)
2. (Initializing arrays with random values)
3. (Printing arrays)
4. (Summing all elements)
5. (Finding the largest element)
6. (Finding the smallest index of the largest element)
7. (Random shuffling)
8. (Shifting elements)
Initializing arrays with input values
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + myList.length + " values: ");
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble();
Initializing arrays with random values

for (int i = 0; i < myList.length; i++) {


myList[i] = Math.random() * 100;
}
Printing arrays

for (int i = 0; i < myList.length; i++) {


System.out.print(myList[i] + " ");
}
Summing all elements

double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
Finding the largest element

double max = myList[0];


for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
Random shuffling
Shifting Elements
Enhanced for Loop (for-each loop)
JDK 1.5 introduced a new for loop that enables you to traverse the complete array
sequentially without using an index variable. For example, the following code
displays all elements in the array myList:
 
for (double value: myList)
System.out.println(value);
 
In general, the syntax is
 
for (elementType value: arrayRefVar) {
// Process the value
}
 
You still have to use an index variable if you wish to traverse the array in a
different order or change the elements in the array.
Analyze Numbers
Read numbers from users, compute their average, and
find out how many numbers are above the average.
Problem: Deck of Cards
The problem is to write a program that picks four cards
randomly from a deck of 52 cards. All the cards can be
represented using an array named deck, filled with initial
values 0 to 51, as follows:

int[] deck = new int[52];


// Initialize cards
for (int i = 0; i < deck.length; i++)
deck[i] = i;
Problem: Deck of Cards, cont.
Problem: Deck of Cards, cont.
Problem: Deck of Cards
This problem builds a foundation for future more interesting and
realistic applications:
http://www.cs.armstrong.edu/liang/animation/web/
24Point.html
See Exercise 20.15.
Problem: Lotto Numbers
Suppose you play the Pick-10 lotto. Each ticket has 10
unique numbers ranging from 1 to 99. You buy a lot of
tickets. You like to have your tickets to cover all numbers
from 1 to 99. Write a program that reads the ticket
numbers from a file and checks whether all numbers are
covered. Assume the last number in the file is 0.

Lotto Numbers Sample Data LottoNumbers Run


Problem: Lotto Numbers
Copying Arrays
Often, in a program, you need to duplicate an array or a part of an array. In
such cases you could attempt to use the assignment statement (=), as
follows:
 
list2 = list1;
 
Copying Arrays
Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new
int[sourceArray.length];

for (int i = 0; i < sourceArrays.length; i++)


targetArray[i] = sourceArray[i];
The arraycopy Utility
arraycopy(sourceArray, src_pos,
targetArray, tar_pos, length);

Example:
System.arraycopy(sourceArray, 0,
targetArray, 0, sourceArray.length);
Passing Arrays to Methods
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}

Invoke the method

int[] list = {3, 1, 2, 6, 4, 2};


printArray(list);

Invoke the method


printArray(new int[]{3, 1, 2, 6, 4, 2});

Anonymous array
Anonymous Array
The statement
printArray(new int[]{3, 1, 2, 6, 4, 2});
creates an array using the following syntax:
new dataType[]{literal0, literal1, ..., literalk};
There is no explicit reference variable for the array.
Such array is called an anonymous array.
Pass By Value
Java uses pass by value to pass arguments to a method. There are
important differences between passing a value of variables of
primitive data types and passing arrays.

• For a parameter of a primitive type value, the actual value is


passed. Changing the value of the local parameter inside the
method does not affect the value of the variable outside the
method.

• For a parameter of an array type, the value of the parameter


contains a reference to an array; this reference is passed to the
method. Any changes to the array that occur inside the method
body will affect the original array that was passed as the
argument.
Simple Example

public class Test {


public static void main(String[] args) {
int x = 1; // x represents an int value
int[] y = new int[10]; // y represents an array of int values
 
m(x, y); // Invoke m with arguments x and y
 
System.out.println("x is " + x);
System.out.println("y[0] is " + y[0]);
}
 
public static void m(int number, int[] numbers) {
number = 1001; // Assign a new value to number
numbers[0] = 5555; // Assign a new value to numbers[0]
}
}
Call Stack

When invoking m(x, y), the values of x and y are passed


to number and numbers. Since y contains the reference
value to the array, numbers now contains the same
reference value to the same array.
Call Stack

When invoking m(x, y), the values of x and y are


passed to number and numbers. Since y contains the
reference value to the array, numbers now contains
the same reference value to the same array.
Heap

The JVM stores the array in an area of memory,


called heap, which is used for dynamic memory
allocation where blocks of memory are allocated and
freed in an arbitrary order.
Passing Arrays as Arguments

• Objective: Demonstrate differences of


passing primitive data type variables and
array variables.

TestPassArray Run
Example, cont.
Returning an Array from a Method
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
list
return result;
} result

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


int[] list2 = reverse(list1);
animation
Trace the reverse Method
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
Declare result and create array
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 0
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 0 and j = 5
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 0
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (= 0) is less than 6
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 0
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 0 and j = 5
public static int[] reverse(int[] list) { Assign list[0] to result[5]
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

After this, i becomes 1 and j


public static int[] reverse(int[] list) { becomes 4
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i (=1) is less than 6


public static int[] reverse(int[] list) {
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 1 and j = 4
public static int[] reverse(int[] list) { Assign list[1] to result[4]
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
After this, i becomes 2 and
public static int[] reverse(int[] list) { j becomes 3
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (=2) is still less than 6
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 2 and j = 3
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
After this, i becomes 3 and
public static int[] reverse(int[] list) { j becomes 2
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (=3) is still less than 6
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 3 and j = 2
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
After this, i becomes 4 and
public static int[] reverse(int[] list) { j becomes 1
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (=4) is still less than 6
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 4 and j = 1
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 5 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
After this, i becomes 5 and
public static int[] reverse(int[] list) { j becomes 0
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 5 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (=5) is still less than 6
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 5 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 5 and j = 0
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 6 5 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
After this, i becomes 6 and
public static int[] reverse(int[] list) { j becomes -1
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 6 5 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (=6) < 6 is false. So exit
public static int[] reverse(int[] list) { the loop.
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 6 5 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
Return result
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

list2
result 6 5 4 3 2 1
Problem: Counting Occurrence of Each
Letter
• Generate 100 lowercase letters randomly and assign to an array of
characters.
• Count the occurrence of each letter in the array.

CountLettersInArray Run
Variable-Length Arguments
You can pass a variable number of arguments of the same
type to a method.

VarArgsDemo Run
Searching Arrays
Searching is the process of looking for a specific element in
an array; for example, discovering whether a certain score is
included in a list of scores. Searching is a common task in
computer programming. There are many algorithms and
data structures devoted to searching. In this section, two
commonly used approaches are discussed, linear search
and binary search.
Linear Search
The linear search approach compares the key
element, key, sequentially with each element in the
array list. The method continues to do so until the key
matches an element in the list or the list is exhausted
without a match being found. If a match is made, the
linear search returns the index of the element in the
array that matches the key. If no match is found, the
search returns -1.
animation

Linear Search Animation


Key List
3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8
animation
Linear Search Animation

http://www.cs.armstrong.edu/liang/animation/web/
LinearSearch.html
From Idea to Solution
/** The method for finding a key in the list */
public static int linearSearch(int[] list, int key) {
for (int i = 0; i < list.length; i++)
if (key == list[i])
return i;
return -1;
}

Trace the method


int[] list = {1, 4, 4, 2, 5, -3, 6, 2};
int i = linearSearch(list, 4); // returns 1
int j = linearSearch(list, -4); // returns -1
int k = linearSearch(list, -3); // returns 5
Binary Search
For binary search to work, the elements in the array
must already be ordered. Without loss of generality,
assume that the array is in ascending order.
e.g., 2 4 7 10 11 45 50 59 60 66 69 70 79
The binary search first compares the key with the
element in the middle of the array.
Binary Search, cont.
Consider the following three cases:
• If the key is less than the middle element, you
only need to search the key in the first half of the
array.
• If the key is equal to the middle element, the
search ends with a match.
• If the key is greater than the middle element, you
only need to search the key in the second half of
the array.
animation

Binary Search

Key List

8 1 2 3 4 6 7 8 9

8 1 2 3 4 6 7 8 9

8 1 2 3 4 6 7 8 9
animation
Binary Search Animation

http://www.cs.armstrong.edu/liang/animation/web/
BinarySearch.html
Binary Search, cont.
Binary Search, cont.
Binary Search, cont.
The binarySearch method returns the index of the
element in the list that matches the search key if it is
contained in the list. Otherwise, it returns

-insertion point - 1.

The insertion point is the point at which the key would be


inserted into the list.
From Idea to Soluton
/** Use binary search to find the key in the list */
public static int binarySearch(int[] list, int key) {
int low = 0;
int high = list.length - 1;
 
while (high >= low) {
int mid = (low + high) / 2;
if (key < list[mid])
high = mid - 1;
else if (key == list[mid])
return mid;
else
low = mid + 1;
}
 
return -1 - low;
}
The Arrays.binarySearch Method
Since binary search is frequently used in programming, Java provides several
overloaded binarySearch methods for searching a key in an array of int, double,
char, short, long, and float in the java.util.Arrays class. For example, the following
code searches the keys in an array of numbers and an array of characters.

int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
System.out.println("Index is " +
java.util.Arrays.binarySearch(list, 11));
  Return is 4
char[] chars = {'a', 'c', 'g', 'x', 'y', 'z'};
System.out.println("Index is " +
java.util.Arrays.binarySearch(chars, 't')); Return is –4 (insertion point
  is 3, so return is -3-1)
For the binarySearch method to work, the array must be pre-sorted in increasing
order.
Sorting Arrays
Sorting, like searching, is also a common task in computer
programming. Many different algorithms have been
developed for sorting. This section introduces a simple,
intuitive sorting algorithms: selection sort.
Selection Sort
Selection sort finds the smallest number in the list and places it first. It then finds
the smallest number remaining and places it second, and so on until the list
contains only a single number.
animation
Selection Sort Animation

http://www.cs.armstrong.edu/liang/animation/web/
SelectionSort.html
From Idea to Solution
for (int i = 0; i < list.length; i++) {
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i+1..listSize-1]
}

list[0] list[1] list[2] list[3] ... list[10]

list[0] list[1] list[2] list[3] ... list[10]

list[0] list[1] list[2] list[3] ... list[10]

list[0] list[1] list[2] list[3] ... list[10]

list[0] list[1] list[2] list[3] ... list[10]

...

list[0] list[1] list[2] list[3] ... list[10]


for (int i = 0; i < listSize; i++) {
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}

Expand
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i+1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
for (int i = 0; i < listSize; i++) {
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}

Expand
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
for (int i = 0; i < listSize; i++) {
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}

Expand

if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
Wrap it in a Method
/** The method for sorting the numbers */
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length; i++) {
// Find the minimum in the list[i..list.length-1]
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}

// Swap list[i] with list[currentMinIndex] if necessary;


if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin; Invoke it
}
} selectionSort(yourList)
}
The Arrays.sort Method

Since sorting is frequently used in programming, Java provides several


overloaded sort methods for sorting an array of int, double, char, short,
long, and float in the java.util.Arrays class. For example, the following
code sorts an array of numbers and an array of characters.

double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5};


java.util.Arrays.sort(numbers);
 
char[] chars = {'a', 'A', '4', 'F', 'D', 'P'};
java.util.Arrays.sort(chars);
Java 8 now provides Arrays.parallelSort(list) that utilizes the multicore
for fast sorting.
The Arrays.toString(list) Method
The Arrays.toString(list) method can be used to return a string
representation for the list.
Main Method Is Just a Regular Method
You can call a regular method by passing actual
parameters. Can you pass arguments to main? Of course,
yes. For example, the main method in class B is invoked
by a method in A, as shown below:
Command-Line Parameters
class TestMain {
public static void main(String[] args) {
...
}
}

java TestMain arg0 arg1 arg2 ... argn


Processing
Command-Line Parameters

In the main method, get the arguments from


args[0], args[1], ..., args[n], which
corresponds to arg0, arg1, ..., argn in
the command line.
Problem: Calculator
• Objective: Write a program that will perform
binary operations on integers. The program
receives three parameters: an operator and two
integers.

java Calculator 2 + 3
java Calculator 2 - 3
Calculator java Calculator 2 / 3
Run java Calculator 2 . 3
Declare/Create Two-dimensional Arrays
// Declare array ref var
dataType[][] refVar;

// Create array and assign its reference to variable


refVar = new dataType[10][10];

// Combine declaration and creation in one statement


dataType[][] refVar = new dataType[10][10];

// Alternative syntax
dataType refVar[][] = new dataType[10][10];

222
Declaring Variables of Two-dimensional Arrays
and Creating Two-dimensional Arrays

int[][] matrix = new int[10][10];


or
int matrix[][] = new int[10][10];
matrix[0][0] = 3;

for (int i = 0; i < matrix.length; i++)


for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = (int)(Math.random() * 1000);

double[][] x;
223
Two-dimensional Array Illustration

matrix.length? 5 array.length? 4
matrix[0].length? 5 array[0].length? 3

224
Declaring, Creating, and Initializing Using Shorthand Notations

You can also use an array initializer to declare, create and


initialize a two-dimensional array. For example,

int[][] array = { int[][] array = new int[4][3];


{1, 2, 3}, array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;
{4, 5, 6}, Same as array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;
{7, 8, 9}, array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;
{10, 11, 12} array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
};

225
Lengths of Two-dimensional Arrays

int[][] x = new int[3][4];

226
Lengths of Two-dimensional Arrays, cont.

int[][] array = { array.length


{1, 2, 3}, array[0].length
{4, 5, 6}, array[1].length
{7, 8, 9}, array[2].length
{10, 11, 12} array[3].length
};

array[4].length ArrayIndexOutOfBoundsException

227
Ragged Arrays
Each row in a two-dimensional array is itself an array. So,
the rows can have different lengths. Such an array is
known as a ragged array. For example,
int[][] matrix = {
{1, 2, 3, 4, 5},
matrix.length is 5
{2, 3, 4, 5}, matrix[0].length is 5
{3, 4, 5}, matrix[1].length is 4
matrix[2].length is 3
{4, 5}, matrix[3].length is 2
{5} matrix[4].length is 1
};
228
Ragged Arrays, cont.

229
Processing Two-Dimensional Arrays
See the examples in the text.
1. (Initializing arrays with input values)
2. (Printing arrays)
3. (Summing all elements)
4. (Summing all elements by column)
5. (Which row has the largest sum)
6. (Finding the smallest index of the largest element)
7. (Random shuffling)

230
Initializing arrays with input values
java.util.Scanner input = new Scanner(System.in);
System.out.println("Enter " + matrix.length + " rows and " +
matrix[0].length + " columns: ");
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = input.nextInt();
}
}

231
Initializing arrays with random values

for (int row = 0; row < matrix.length; row++) {


for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = (int)(Math.random() * 100);
}
}

232
Printing arrays
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}

System.out.println();
}

233
Summing all elements
int total = 0;
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
total += matrix[row][column];
}
}

234
Summing elements by column
for (int column = 0; column < matrix[0].length; column++) {
int total = 0;
for (int row = 0; row < matrix.length; row++)
total += matrix[row][column];
System.out.println("Sum for column " + column + " is "
+ total);
}

235
Random shuffling
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
int i1 = (int)(Math.random() * matrix.length);
int j1 = (int)(Math.random() * matrix[i].length);
// Swap matrix[i][j] with matrix[i1][j1]
int temp = matrix[i][j];
matrix[i][j] = matrix[i1][j1];
matrix[i1][j1] = temp;
}
}

236
Problem: Grading Multiple-Choice Test

Students’ answer Objective: write a


program that grades
multiple-choice test.

237
Problem: Finding Two Points Nearest to Each Other

238
What is Sudoku?

http://www.cs.armstrong.edu/
liang/animation/web/Sudoku.html

239
Every row contains the numbers 1 to 9

240
Every column contains the numbers 1 to 9
5 3 4 6 7 8 9 1 2
6 7 2 1 9 5 3 4 8
1 9 8 3 4 2 5 6 7
8 5 9 7 6 1 4 2 3
4 2 6 8 5 3 7 9 1
7 1 3 9 2 4 8 5 6
9 6 1 5 3 7 2 8 4
2 8 7 4 1 9 6 3 5
3 4 5 2 8 6 1 7 9

241
Every 3×3 box contains the numbers 1 to 9

5 3 4 6 7 8 9 1 2
6 7 2 1 9 5 3 4 8
1 9 8 3 4 2 5 6 7
8 5 9 7 6 1 4 2 3
4 2 6 8 5 3 7 9 1
7 1 3 9 2 4 8 5 6
9 6 1 5 3 7 2 8 4
2 8 7 4 1 9 6 3 5
3 4 5 2 8 6 1 7 9

242
Checking Whether a Solution Is Correct

PassTwoDimensionalArray Run

243
Multidimensional Arrays
Occasionally, you will need to represent n-dimensional
data structures. In Java, you can create n-dimensional
arrays for any integer n.
 
The way to declare two-dimensional array variables and
create two-dimensional arrays can be generalized to
declare n-dimensional array variables and create n-
dimensional arrays for n >= 3.

244
Multidimensional Arrays
double[][][] scores = {
{{7.5, 20.5}, {9.0, 22.5}, {15, 33.5}, {13, 21.5}, {15, 2.5}},
{{4.5, 21.5}, {9.0, 22.5}, {15, 34.5}, {12, 20.5}, {14, 9.5}},
{{6.5, 30.5}, {9.4, 10.5}, {11, 33.5}, {11, 23.5}, {10, 2.5}},
{{6.5, 23.5}, {9.4, 32.5}, {13, 34.5}, {11, 20.5}, {16, 7.5}},
{{8.5, 26.5}, {9.4, 52.5}, {13, 36.5}, {13, 24.5}, {16, 2.5}},
{{9.5, 20.5}, {9.4, 42.5}, {13, 31.5}, {12, 20.5}, {16, 6.5}}
};

245
Problem: Calculating Total Scores
Objective: write a program that calculates the total score for
students in a class. Suppose the scores are stored in a three-
dimensional array named scores. The first index in scores refers
to a student, the second refers to an exam, and the third refers
to the part of the exam. Suppose there are 7 students, 5 exams,
and each exam has two parts--the multiple-choice part and the
programming part. So, scores[i][j][0] represents the score on the
multiple-choice part for the i’s student on the j’s exam. Your
program displays the total score for each student.

246
Problem: Weather Information
Suppose a meteorology station records the temperature
and humidity at each hour of every day and stores the data
for the past ten days in a text file named weather.txt. Each
line of the file consists of four numbers that indicate the
day, hour, temperature, and humidity. Your task is to write
a program that calculates the average daily temperature
and humidity for the 10 days.

247
Problem: Guessing Birthday
Listing 4.3, GuessBirthday.java, gives a program that
guesses a birthday. The program can be simplified by
storing the numbers in five sets in a three-dimensional
array, and it prompts the user for the answers using a
loop.

248
Problem:
References:
• https://www.javatpoint.com/
• https://www.geeksforgeeks.org/
• https://www.w3schools.com/
• https://www.educba.com/
• Y. Daniel Liang, Intro to Java Programming, Pearson
Education India
Thank You All

You might also like