Java for
Beginners
Arrays and Loops
A beginner-friendly introduction to
fundamental Java concepts
Today's Topics
In this presentation, we'll cover two
fundamental concepts in Java
programming:
Arrays - A way to store
multiple values of the same
type
Loops - Code structures that
let us repeat actions
By the end of this presentation,
you'll understand:
How to create and use arrays
How to work with different
types of loops
When to use each type of
loop
Note: These concepts are building
blocks for all Java programs you'll
write!
What are Arrays?
An array is a container that holds
multiple values of the same type.
Think of an array as a row of
boxes, where:
Each box can hold one value
All boxes must hold the same
type of value (all ints, all
Strings, etc.)
Each box has a number
(called an index) starting
from 0
Array visualization showing boxes
with indexes
Important: In Java, array indexes
start at 0, not 1. So the first
element is at position 0.
Creating Arrays
There are two ways to create
arrays in Java:
Method 1: Declare and
initialize in separate
steps
// Step 1: Declare the array
int[] numbers;
// Step 2: Initialize the ar
numbers = new int[5]; // Cr
// Step 3: Assign values to
numbers[0] = 10; // First e
numbers[1] = 20; // Second
numbers[2] = 30; // Third e
numbers[3] = 40; // Fourth
numbers[4] = 50; // Fifth e
Method 2: Declare and
initialize in one step
// Method 2a: With size
int[] numbers = new int[5];
// Method 2b: With initial v
int[] scores = {95, 87, 98,
Warning: Once an array is
created, its size cannot be
changed!
Accessing Array
Elements
We use the index (position
number) to access array elements:
int[] scores = {95, 87, 98,
// Reading values
int firstScore = scores[0];
int thirdScore = scores[2];
// Changing values
scores[1] = 92; // Changes
scores[4] = 80; // Changes
// Printing a value
System.out.println("First sc
First score: 95
Remember: The last element's
index is always (array length - 1)
For the array scores which has 5
elements:
First element: scores[0]
Last element: scores[4]
Array Length and
Common
Mistakes
To find out how many elements an
array has, use the length
property:
int[] scores = {95, 87, 98,
int numberOfScores = scores
System.out.println("The arra
The array has 5 elements.
Common Array Mistakes
IndexOutOfBoundsException:
Happens when you try to access
an index that doesn't exist
int[] numbers = {10, 20, 30
// WRONG: This will cause an
System.out.println(numbers[3
Always remember:
Array indexes start at 0
The last valid index is
(length - 1)
Array size cannot be
changed after creation
Array Exercises
Exercise 1: Create and
Access an Array
Create an array of 5 favorite
foods. Then print the first and
last food in the array.
Show Solution
Exercise 2: Modify Array
Elements
Create an array of 3 test
scores: 85, 90, and 78. Then:
1. Change the last score to
95
2. Calculate and print the
average of all scores
Show Solution
Introduction to
Loops
Loops are programming structures
that allow us to repeat a block of
code multiple times.
Why Do We Need
Loops?
Imagine you need to print numbers
from 1 to 100. Without loops:
System.out.println(1);
System.out.println(2);
System.out.println(3);
// ... and so on for 100 lin
With loops, we can do this in just a
few lines of code!
Types of Loops in Java
for loop - When you know
exactly how many times to
loop
while loop - When you want
to loop until a condition is
false
do-while loop - Like while,
but always executes at least
once
for-each loop - Specially
designed for collections like
arrays
For Loop
The for loop is ideal when you
know exactly how many times you
want to repeat something.
For Loop Syntax
for (initialization; conditi
// Code to repeat
}
initialization: Executed once
before the loop starts
condition: Checked before
each iteration; loop continues
if true
update: Executed after each
iteration
Example: Printing
Numbers 1-5
for (int i = 1; i <= 5; i++)
System.out.println("Numb
}
Number: 1 Number: 2
Number: 3 Number: 4
Number: 5
How it works:
1. Initialize i = 1
2. Check if i <= 5 (true)
3. Execute the code block (print
number)
4. Update i (i++, which means
i = i + 1)
5. Repeat steps 2-4 until
condition is false
While Loop
The while loop repeats a block of
code as long as a specified
condition is true.
While Loop Syntax
while (condition) {
// Code to repeat
}
The condition is checked
before each iteration. If it's true,
the loop continues; if false, the
loop ends.
Example: Counting
Down from 5
int countdown = 5;
while (countdown > 0) {
System.out.println("Coun
countdown--; // Same as
}
System.out.println("Blast of
Countdown: 5 Countdown: 4
Countdown: 3 Countdown: 2
Countdown: 1 Blast off!
Important: Make sure your
condition will eventually become
false, or you'll create an infinite
loop!
Do-While Loop
The do-while loop is similar to the
while loop, but it guarantees that
the code block executes at least
once.
Do-While Loop Syntax
do {
// Code to repeat
} while (condition);
The key difference is that the
condition is checked after each
iteration, not before.
Example: Menu
Selection
import java.util.Scanner;
public class MenuExample {
public static void main
Scanner scanner = ne
int choice;
do {
System.out.print
System.out.print
System.out.print
System.out.print
System.out.print
choice = scanner
// Process the u
System.out.print
} while (choice != 3
System.out.println("
}
When to use do-while: When you
need to execute the code at least
once before checking the
condition (like showing a menu).
10
For-Each Loop
The for-each loop (also called
enhanced for loop) is specially
designed for iterating through
arrays and collections.
For-Each Loop Syntax
for (elementType element : a
// Code using element
}
This loop automatically iterates
through each element of the array
without needing an index variable.
Example: Iterating
Through an Array
String[] fruits = {"Apple",
// Using for-each loop to pr
for (String fruit : fruits)
System.out.println("I li
}
I like Apple I like
Banana I like Orange I
like Mango I like
Strawberry
Advantage: Simpler, cleaner code
when you need to process all
elements in an array.
Limitation: You can't easily track
the element's position or modify
the array.
11
Using Loops with
Arrays
Loops and arrays work great
together! Here's how to use
different loops with arrays:
1. Using a for loop (with
index)
int[] numbers = {10, 20, 30,
// Print all elements with t
for (int i = 0; i < numbers
System.out.println("Inde
}
Index 0: 10 Index 1: 20
Index 2: 30 Index 3: 40
Index 4: 50
2. Using a for-each loop
(without index)
int[] numbers = {10, 20, 30,
// Print all elements withou
for (int number : numbers)
System.out.println("Valu
}
Value: 10 Value: 20
Value: 30 Value: 40
Value: 50
Tip: Use the regular for loop when
you need the index, and the for-
each loop when you just need the
values.
12
Loop Control
Statements
Sometimes we need to control the
flow of our loops beyond the basic
conditions.
The break Statement
The break statement exits a loop
completely, skipping any remaining
iterations.
// Search for the number 30
int[] numbers = {10, 25, 30,
boolean found = false;
for (int i = 0; i < numbers
if (numbers[i] == 30) {
System.out.println("
found = true;
break; // Exit the
}
}
if (!found) {
System.out.println("30 w
}
The continue
Statement
The continue statement skips
the current iteration and continues
with the next one.
// Print only odd numbers fr
for (int i = 1; i <= 10; i++
if (i % 2 == 0) { // If
continue; // Skip t
}
System.out.println(i + "
}
1 is odd 3 is odd 5 is
odd 7 is odd 9 is odd
13
Loop and Array
Exercises
Exercise 1: Sum of Array
Elements
Write a program that calculates
the sum of all elements in an
integer array.
Use this array: int[]
numbers = {5, 10, 15,
20, 25};
Use a loop to go through each
element and add it to a sum
variable.
Show Solution
Exercise 2: Finding
Maximum Value
Write a program that finds the
largest number in an array.
Use this array: int[]
values = {42, 17, 93,
64, 58};
Start by assuming the first
element is the maximum, then
compare with each element.
Show Solution
Exercise 3: Count Even
Numbers
Write a program that counts
how many even numbers are
in an array.
Use this array: int[]
numbers = {7, 4, 11,
23, 8, 16, 5, 36};
A number is even if dividing
by 2 gives a remainder of 0
(use the % operator).
Show Solution
14
Nested Loops
A nested loop is a loop inside
another loop. The inner loop runs
completely for each iteration of the
outer loop.
Example: Printing a
Pattern
// Print a rectangle pattern
for (int row = 1; row <= 4;
for (int col = 1; col <=
System.out.print("*
}
System.out.println(); /
}
* * * * * * * * * * * * *
* * * * * * *
Nested Loops with
Arrays
Nested loops are great for working
with multi-dimensional arrays
(arrays of arrays):
// A 2D array representing a
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Print all elements with t
for (int row = 0; row < 3; r
for (int col = 0; col <
System.out.println("
}
}
Tip: Nested loops are commonly
used for:
Working with 2D arrays
(matrices, grids, tables)
Creating patterns
Comparing each element
of one array with each
element of another
15
Common Loop
Patterns
Here are some common patterns
you'll use when working with loops:
1. Looping Through
Array in Reverse
int[] numbers = {10, 20, 30,
// Print array in reverse or
for (int i = numbers.length
System.out.println(numbe
}
50 40 30 20 10
2. Looping with Multiple
Variables
// Countdown with two counte
for (int i = 1, j = 10; i <=
System.out.println("i: "
}
3. Processing Every
Other Element
int[] values = {1, 2, 3, 4,
// Process every other eleme
for (int i = 0; i < values.l
System.out.println("Inde
}
16
Choosing the
Right Loop
Each type of loop has its strengths.
Here's when to use each one:
Loop Example
Best For
Type Use Case
When you
know Iterating
exactly how through an
for
many array with
iterations an index
you need
Reading
When you
values from
need to
an array
for- process
(when
each every
index
element in a
doesn't
collection
matter)
When the
loop
Reading
condition
input until a
depends on
while specific
something
value is
other than a
entered
simple
counter
When you
Displaying
need to
do- a menu and
execute the
while getting user
loop at least
input
once
Remember: Often, multiple loop
types can solve the same
problem. Choose the one that
makes your code clearest and
most maintainable.
17
Advanced
Exercises
Exercise 1: Reverse an Array
Write a program that creates a
new array with the elements of
the original array in reverse
order.
Original array: int[]
original = {1, 2, 3, 4,
5};
Expected result: [5, 4, 3,
2, 1]
Show Solution
Exercise 2: Find Duplicates
Write a program that finds and
prints any duplicate values in
an array.
Use this array: int[]
numbers = {4, 2, 7, 4,
8, 3, 7, 1};
Show Solution
18
Summary
Arrays
An array is a collection of
elements of the same type
Array indexes start at 0
Arrays have a fixed size that
cannot be changed after
creation
We can access elements
using their index:
array[index]
The length of an array can be
found using: array.length
Loops
for: For a specific number of
iterations
while: Continue while a
condition is true
do-while: Like while, but
executes at least once
for-each: For iterating
through all elements of an
array
Loop Control
break: Exit a loop early
continue: Skip to the next
iteration
Next steps: Continue practicing
with different array sizes, types,
and loop structures!
19
Thank You!
Keep practicing arrays
and loops
They are building blocks for more
advanced Java programming!