0% found this document useful (0 votes)
4 views13 pages

Java Arrays: Basics and Examples

This document is a lesson on Java arrays, covering their definition, initialization, and manipulation through loops, sorting, and multi-dimensional arrays. It also introduces ArrayLists as a dynamic alternative to static arrays, detailing how to add and remove items. The lesson includes code examples to illustrate these concepts in practice.

Uploaded by

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

Java Arrays: Basics and Examples

This document is a lesson on Java arrays, covering their definition, initialization, and manipulation through loops, sorting, and multi-dimensional arrays. It also introduces ArrayLists as a dynamic alternative to static arrays, detailing how to add and remove items. The lesson includes code examples to illustrate these concepts in practice.

Uploaded by

ronnelbalcita23
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Republic of the Philippines

PAMPANGA STATE UNIVERSITY


(former Don Honorio Ventura State

University) Sto. Tomas Campus

Lesson 6: Java Arrays

Course Code: ITELEC 1


Course Title: Object-Oriented Programming (Java)
Prepared by: Alvin Herrera, Instructor 1

Lesson Content:
1. Understanding Java Arrays
2. Arrays and Loops
3. Sorting Arrays
4. Arrays and Strings
5. Multi-Dimensional Arrays
6. Array Lists
7. Java for-each loops

1. Understanding Java Arrays


An array is an important linear data structure that allows us to
store multiple values of the same type. It's like a list of items.
Think of an array as the columns in a spreadsheet.

You can have a spreadsheet with only one column, or lots of


columns. The data held in a single-list array might look like
this:
Array_Value
s

0 10

1 14

2 36

3 27

4 43

5 18

Like a spreadsheet, arrays have a position number for each row.


The positions in an array start at 0 and go up sequentially. Each
position in the array can then hold a value. In the table above,
array position 0 is holding a value of 10, array position 1 is
holding a value of 14, position 2 has a value of 36, and so on.

How to initialize Array?


You have to tell Java what kind of data is going in to your array
(integers, strings, boolean values, etc). You then need to say how
many positions the array has.

This is called Initializing an Array in Java.

You do it like this:


int[] aryNums = new int[6];

To assign values to the various positions in an array, you do it


in the normal way:

BACOLOR (MAIN) • MEXICO • PORAC • STO. TOMAS • LUBAO • CANDABA • APALIT • SAN FERNANDO
Office Address | Moras dela Paz, Sto. Tomas, Pampanga, Philippines Email Address |
santotomascampus@[Link] • Contact No. | (0921) 373 0913 Website |
[Link]
Republic of the Philippines

PAMPANGA STATE UNIVERSITY


(former Don Honorio Ventura State University)

Sto. Tomas Campus

aryNums[0] = 10;

If you know what values are going to be in the array, you can set
them up like this instead:

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

Note that you still need the square brackets after int, but not
the new keyword, or the repetition of the data type and square
brackets.
For String types:

String[] aryStrings = {"Autumn", "Spring", "Summer", "Winter" };

For Booleans:
boolean[ ] aryBools = {false, true, false, true};

To get at the values held in your array, you type the name of the
array followed by an array position in square brackets.

Like this:
[Link]( aryNums[2] );

Example:
Code Output

class Main{ 3
public static void
main(String[]args){

int[] aryNums = new


int[6]; aryNums[0] = 10;

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

String[] aryStrings =
{"Autumn", "Spring",
"Summer", "Winter" };

boolean[ ] aryBools = {false,


true, false, true};

[Link](
aryNums[2] );

}
}
BACOLOR (MAIN) • MEXICO • PORAC • STO. TOMAS • LUBAO • CANDABA • APALIT • SAN FERNANDO
Office Address | Moras dela Paz, Sto. Tomas, Pampanga, Philippines
Email Address | santotomascampus@[Link] • Contact No. | (0921) 373 0913
Website | [Link]
Republic of the Philippines

PAMPANGA STATE UNIVERSITY


(former Don Honorio Ventura State University)

Sto. Tomas Campus

2. Arrays and Loops


Arrays come into their own with loops. You have seen that to
assign values to array positions, you did this:

aryNums[0] = 10;

But that's not terribly practical if you have a lot of numbers to


assign to an array. So we set up an array to hold 49 integer
values. Then comes the loop code. Notice the end condition of the
loop:

i < [Link]

Length is a property of array objects that you can use to get the
size of the array (how many positions it has). So this loop will
keep going round and round while the value in the variable i is
less than the size of the array.

To assign values to each position in the array, we have this

line: numbers[i] = i + 1;

Instead of a hard-code value between the square brackets of the


array name, we have the variable called i. This increases by 1
each time round the loop, remember. Each array position can then
be accessed just by using the loop value. The value that is being
assigned to each position is i + 1. So again, it's just the
incremented loop value, this time with 1 added to it. Because the
loop value is starting at 0, this will give you the numbers 1 to
n.

The other line in the loop just prints out whatever value is in
each array position.

Example:
Code Output

class Main{ 1 2 3 4 5
public static void
main(String[]args){

int[] aryNums = new int[5];

for(int i=0; i <


[Link];i++ ){
aryNums[i] = i+1;
}

for(int i=0; i <


[Link];i++ ){
BACOLOR (MAIN) • MEXICO • PORAC • STO. TOMAS • LUBAO • CANDABA • APALIT • SAN FERNANDO
Office Address | Moras dela Paz, Sto. Tomas, Pampanga, Philippines
Email Address | santotomascampus@[Link] • Contact No. | (0921) 373 0913
Website | [Link]
Republic of the Philippines

PAMPANGA STATE UNIVERSITY


(former Don Honorio Ventura State University)

Sto. Tomas Campus


[Link](aryNums[i]
+ “ ”);
}

}
}

3. Sorting Arrays
Other inbuilt java methods allow you to sort your arrays. To use
the sort method of arrays, you first need to reference a Java
library called Arrays. You do this with the import statement.

import [Link];

Now that you have imported the Arrays library, you can use the
sort method. It's quite easy:

[Link]( aryNums );

Example:
Code Output

import [Link]; 1 5 7 7 8 9 11 15

class Main{
public static void
main(String[]args){

int[] aryNums = {7, 15, 11,


1, 7, 5, 8, 9};

[Link](aryNums);

for(int i=0; i <


[Link];i++ ){

[Link](aryNums[i] +
" ");
}
}
}

Sorting in descending order, however, is only possible either by


writing your own sorting code, or converting your array to Integer
objects then importing from the Collections library. If you need
to a descending sort, here's some code that does just that.
BACOLOR (MAIN) • MEXICO • PORAC • STO. TOMAS • LUBAO • CANDABA • APALIT • SAN FERNANDO
Office Address | Moras dela Paz, Sto. Tomas, Pampanga, Philippines Email Address |
santotomascampus@[Link] • Contact No. | (0921) 373 0913 Website |
[Link]
Republic of the Philippines

PAMPANGA STATE UNIVERSITY


(former Don Honorio Ventura State

University) Sto. Tomas Campus

Example:
Code Output

import [Link]; 15 11 9 8 7 7 5 1

class Main{
public static void
main(String[]args){

int[] aryNums = {7, 15, 11,


1, 7, 5, 8, 9};

Integer[] integerArr =
new
Integer[[Link]];
for (int i = 0; i <
[Link]; i++) {
integerArr[i] = new
Integer(aryNums[i]);
}

[Link](integerArr,
[Link]()
);
for (int i = 0; i <
[Link]; i++) {

[Link](integerArr[i
] + " ");
}
}
}

4. Arrays and Strings


You can place strings of text into your Java arrays. This is done
in the same way as for integers:

String[] aryString = new String[5];

aryString[0] = "This";
aryString[1] = "is";
aryString[2] = "a";
aryString[3] = "string";
aryString[4] = "array";

The code above sets up a string array with 5 positions. Text is


then assigned to each position in the array.
BACOLOR (MAIN) • MEXICO • PORAC • STO. TOMAS • LUBAO • CANDABA • APALIT • SAN FERNANDO
Office Address | Moras dela Paz, Sto. Tomas, Pampanga, Philippines Email Address |
santotomascampus@[Link] • Contact No. | (0921) 373 0913 Website |
[Link]
Republic of the Philippines

PAMPANGA STATE UNIVERSITY


(former Don Honorio Ventura State

University) Sto. Tomas Campus

Here's a loop that goes round all the positions in the array,
printing out whatever is at each position:

int i;
for ( i=0; i < [Link]; i++ ) {
[Link]( aryString[i] );
}

Example:
Code Output

import [Link]; This


is
class Main{ a
public static void string
main(String[]args){ array

String[] aryString =
new String[5] ;

aryString[0] = "This";
aryString[1] = "is";
aryString[2] = "a";
aryString[3] =
"string"; aryString[4]
= "array";

int i;

for ( i=0; i <


[Link]; i++ )
{ [Link](
aryString[i] );

}
}
}

5. Multi-Dimensional Arrays
The arrays you have been using so far have only held one column of
data. But you can set up an array to hold more than one column.
These are called multi-dimensional arrays. As an example, think of
a spreadsheet with rows and columns. If you have 6 rows and 5
columns then your spreadsheet can hold 30 numbers. It might look
like this:
BACOLOR (MAIN) • MEXICO • PORAC • STO. TOMAS • LUBAO • CANDABA • APALIT • SAN FERNANDO
Office Address | Moras dela Paz, Sto. Tomas, Pampanga, Philippines Email Address |
santotomascampus@[Link] • Contact No. | (0921) 373 0913 Website |
[Link]
Republic of the Philippines

PAMPANGA STATE UNIVERSITY


(former Don Honorio Ventura State University)

Sto. Tomas Campus

A multi dimensional array is one that can hold all the values
above. You set them up like
this:

int[][] aryNumbers = new int[6][5];

To assign values:

aryNumbers[0][0] = 10;
aryNumbers[0][1] = 12;
aryNumbers[0][2] = 43;
aryNumbers[0][3] = 11;
aryNumbers[0][4] = 22;

Example:
Code Output

class Main{ 10 12
public static void 43 11
main(String[]args){

int[][] aryNumbers = new


int[2][2];

aryNumbers[0][0] = 10;
aryNumbers[0][1] = 12;
aryNumbers[1][0] = 43;
aryNumbers[1][1] = 11;

for (int i = 0; i <


[Link]; i++) {
for (int j = 0; j <
[Link]; j++) {

[Link](aryNumbers[i]
[j] + " ");
}

[Link]("");
}

BACOLOR (MAIN) • MEXICO • PORAC • STO. TOMAS • LUBAO • CANDABA • APALIT • SAN FERNANDO
Office Address | Moras dela Paz, Sto. Tomas, Pampanga, Philippines
Email Address | santotomascampus@[Link] • Contact No. | (0921) 373 0913
Website | [Link]
Republic of the Philippines

PAMPANGA STATE UNIVERSITY


(former Don Honorio Ventura State University)

Sto. Tomas Campus


}
}
}

6. Array Lists
If you don't know how many items are going to be held in your
array, you may be better off using something called an ArrayList.
An ArrayList is a dynamic data structure, meaning items can be
added and removed from the list. A normal array in Java is a
static data structure, because you stuck with the initial size of
your array.

To set up an ArrayList, you first have to import the package from


the [Link] library:

import [Link];

You can then create a new ArrayList object:

ArrayList<String> listTest = new ArrayList<>();

Once you have a new ArrayList objects, you can add elements to it
with the add method:

[Link]( "first item" );


[Link]( "second item" );
[Link]( "third item" );

In between the round brackets of add you put what it is you want
to add to the ArrayList.

Items in the list can be referenced by an Index number, and by


using the get method:

[Link]( 3 )

This line will get the item at Index position 3 on the list. Index
numbers start counting at
zero, so this will be the fourth item.

You can also remove items from an ArrayList. You can either use
the Index number:

[Link](2);

Or you can use the value on the list:

[Link]( "second item" );

BACOLOR (MAIN) • MEXICO • PORAC • STO. TOMAS • LUBAO • CANDABA • APALIT • SAN FERNANDO
Office Address | Moras dela Paz, Sto. Tomas, Pampanga, Philippines Email Address |
santotomascampus@[Link] • Contact No. | (0921) 373 0913 Website |
[Link]
Republic of the Philippines

PAMPANGA STATE UNIVERSITY


(former Don Honorio Ventura State University)

Sto. Tomas Campus

Other methods are clear() and contains().


Removing an item will resize the ArrayList, so you have to be
careful when trying to get an item on the list when using its
Index number. If we've removed item number 2, then our list above
will contain only 3 items. Trying to get the item with the Index
number 3 would then result in an error.

To go through each item in your ArrayList you can set up something


called an Iterator. This class can also be found in the [Link]
library:

import [Link];

You can then attach your ArrayList to a new Iterator

object: Iterator it = [Link]( );

This sets up a new Iterator object called it that can be used to


go through the items in the ArrayList called listTest. The reason
for using an Iterator object is because it has methods called next
and hasNext. You can use these in a loop:

while ( [Link]( ) ) {
[Link]( [Link]( ) );
}

The method hasNext returns a Boolean value. The value will be


false if there are no more items in the ArrayList. The next
method can be used to go through all the items in the list.

A quick way to see which items are on your list, if it gets a bit
too long is calling the Array List:

[Link]( "Whole list=" + listTest );

Example:
Code Output

class Main{ first item


public static void second item
main(String[]args){ third item

ArrayList<String> listTest
= new ArrayList<>();

[Link]( "first
item" );
[Link]( "second
item" );
[Link]( "third
item" );
BACOLOR (MAIN) • MEXICO • PORAC • STO. TOMAS • LUBAO • CANDABA • APALIT • SAN FERNANDO
Office Address | Moras dela Paz, Sto. Tomas, Pampanga, Philippines
Email Address | santotomascampus@[Link] • Contact No. | (0921) 373 0913
Website | [Link]
Republic of the Philippines

PAMPANGA STATE UNIVERSITY


(former Don Honorio Ventura State University)

Sto. Tomas Campus


Iterator it =
[Link]();

while ([Link]()) {
[Link]([Link]()
); }
}}
}

7. Java for-each loops


You can use the for-each loop in Java. It looks like this:

for (Variable Type variable_name : your_arrayname)


{
//CODE HERE
}

You start with the word for. In between round brackets, you need a
variable type (like String, int, Object). After a space, you type
a name for your variable. Next comes a colon (:). After the colon,
you need the name of your array or collection. Add this to test it
out:

for ( Object order : listOrder ) {


[Link](order + " " + "\r\n");
}

The whole thing reads, 'for each order in listOrder, print


something out'. (Because we have mixed values in our array list,
we've used Object as the variable type.) You can use for-each with
ordinary arrays, as well, not just Array Lists. Here's an example
to try out.

String[] months = {"Jan", "Feb", "March", "April"};

for (String singleMonth : months) {


[Link](singleMonth);
}

Or you can have all numbers:

int[] Numbers = {2, 5, 7, 18, 45, 46};


for (int num : Numbers) {
[Link](num);
}

BACOLOR (MAIN) • MEXICO • PORAC • STO. TOMAS • LUBAO • CANDABA • APALIT • SAN FERNANDO
Office Address | Moras dela Paz, Sto. Tomas, Pampanga, Philippines Email Address |
santotomascampus@[Link] • Contact No. | (0921) 373 0913 Website |
[Link]
Republic of the Philippines

PAMPANGA STATE UNIVERSITY


(former Don Honorio Ventura State

University) Sto. Tomas Campus

The for-each loop in Java is a lot easier to use than iterators.


They are perfect for when you don't much care about loop index
numbers.

Example:
Code Output

class Main{ 2
public static void 5
main(String[]args){ 7
int[] Numbers = {2, 5, 7, 18
18, 45, 46}; 45
for (int num : Numbers) 46
{ [Link](nu
m); }
}
}

Review Questions and their answers

1. What is an array in Java?

Ans. An array is a linear data structure that stores multiple values of


the same type in fixed-size memory blocks. Each element is accessed
using an index starting from 0.

2. How do you initialize an integer array in Java with 6


elements? Ans. You can use: int[] aryNums = new int[6];

This creates an array with 6 positions, all initially set to


0. 3. What is the purpose of the .length property in arrays?

Ans. The .length property tells you how many elements are in the array.
It’s often used in loops to avoid accessing out-of-bounds indexes.

4. How can you initialize an array with known values directly? Ans.
By using curly braces: int[] aryNums = {1, 2, 3, 4}; This
automatically sets the array size and assigns the values. 5. How do
you sort an array in ascending order in Java? Ans. You must import the
Arrays class and use: [Link](arrayName); This sorts the elements
from smallest to largest.

6. What is the difference between a standard array and an ArrayList in


Java?

BACOLOR (MAIN) • MEXICO • PORAC • STO. TOMAS • LUBAO • CANDABA • APALIT • SAN FERNANDO
Office Address | Moras dela Paz, Sto. Tomas, Pampanga, Philippines Email Address |
santotomascampus@[Link] • Contact No. | (0921) 373 0913 Website |
[Link]
Republic of the Philippines

PAMPANGA STATE UNIVERSITY


(former Don Honorio Ventura State

University) Sto. Tomas Campus

Ans. A standard array has a fixed size, while an ArrayList is dynamic


and can grow or shrink. ArrayLists also offer built-in methods
like .add() and .remove().

7. How do you create and use a multi-dimensional array in


Java? Ans. You declare it like: int[][] table = new int[2][3];
You can access elements using two indices, like table[1][2]. 8.
How can you loop through an array without using an index? Ans.
Using a for-each loop:

for (int num : aryNums) {

[Link](num);

It automatically goes through each element.

9. What is the purpose of an Iterator with an ArrayList?

Ans. An Iterator allows you to loop through the list using .hasNext()
and .next() methods. It's helpful when you want more control or to
remove items while looping.

10. How do you remove an element from an ArrayList by value and by


index?

Ans. Use [Link]("value") to remove by value, or [Link](index)


to remove by position.

This resizes the ArrayList automatically.


BACOLOR (MAIN) • MEXICO • PORAC • STO. TOMAS • LUBAO • CANDABA • APALIT • SAN FERNANDO
Office Address | Moras dela Paz, Sto. Tomas, Pampanga, Philippines Email Address |
santotomascampus@[Link] • Contact No. | (0921) 373 0913 Website |
[Link]

You might also like