0% found this document useful (0 votes)
18 views39 pages

Array Ni Lee

Uploaded by

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

Array Ni Lee

Uploaded by

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

Programming (Java) NCIII

UC1.1-5: Creating and


Using Arrays
JOHN LOUIS MERCARAL, MIS
ICT313359
Perform object-oriented
analysis and design in Java
technology
❑ Apply Basics of Java language

UC1
❑ Work with Methods and Encapsulation
❑ Work with Inheritance and Handling
Exceptions
❑ Examine Object-Oriented Concepts and
Terminology
❑ Explain Modeling and Software
Development Process
❑ Create Use Case Diagrams and Use Case
Scenarios
❑ Transition Analysis to Design using
Interaction Diagrams
❑ Introduce Architectural Concepts and
Architecture Tiers Diagrams
UC1.1: Apply Basics
of Java Language
1.1.1 Executable Java applications are created in accordance with
Java framework
1.1.2 Java packages are imported to make them accessible in the
code
1.1.3 Working with Java Data types is demonstrated in
accordance with Java framework
1.1.4 Using Operators and Decision Constructs is demonstrated
in accordance with Java framework
1.1.5 Creating and Using Arrays is demonstrated in
accordance with Java framework
1.1.6 Using Loop Constructs is demonstrated in accordance with
Java framework
UC1.1.5: Creating and Using
Arrays is demonstrated in
accordance with Java framework

• Declare, initialize, and use a


one-dimensional array
• Declare, initialize, and use a
multi-dimensional array
• Declare and use an ArrayList
Java Arrays
Arrays are defined as the collection of similar types of data items stored at
contiguous memory locations.

For example, if we want to store the names of 100 people then we can create an
array of the string type that can store 100 names.

String[] array = new String[100];

Here, the above array cannot store more than 100 names. The number of values in a
Java array is always fixed.
Representation of an array
We can represent an array in various ways in different programming languages.

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

As per the above example, there are some of the following important points:
• An element is an individual item or value stored in an array. In the array, the
elements are "Volvo", "BMW", "Ford", and "Mazda".
• The length of an array is the total number of elements it can hold. The array's
length is 4, which means we can store 4 elements.
• Index is the position number of an element in the array. Indices in Java
arrays start at 0 and go up to the array’s length minus 1.
Declare an Array
In Java, here is how we can declare an array:
datatype[] arrayName;
• datatype - it can be primitive data types like int, char, double,
byte, etc. or Java objects
• arrayName - it is an identifier

But, how many elements can array this hold?


To define the number of elements that an array can hold, we have to
allocate memory for the array in Java. For example,
// declare an array
double[] data;

// allocate memory
data = new double[10];
Initialize an Array
initialize arrays during declaration

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

Here, we have created an array named cars and initialized it with the
values inside the curly brackets.

Note that we have not provided the size of the array. In this case, the
Java compiler automatically specifies the size by counting the
number of elements in the array (i.e. 4).

In the Java array, each memory location is associated with a number.


The number is known as an index.
Initialize an Array
initialize arrays using the index number

String[] cars = new String[4];


cars[0] = "Volvo";
cars[1] = "BMW";
cars[2] = "Ford";
cars[3] = "Mazda";

Here, we can also initialize arrays in Java, using the index number.
Access the Elements of an
Array
You can access an array element by referring to the index number.
This statement accesses the value of the first element in cars:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


System.out.println(cars[0]);
// Outputs Volvo
Change an Array Element
To change the value of a specific element, refer to the index number:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


cars[0] = ”Audi"; // Changing index 0 element

System.out.println(cars[0]);
// Now outputs Audi instead of Volvo
Array Length
To find out how many elements an array has, use the length
property:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

System.out.println(cars.length);
// Outputs 4
Loop
Through
an Array
For Loop
You can loop through the array elements with the for loop, and use the length
property to specify how many times the loop should run. The following example
outputs all elements in the cars array:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


for (int i = 0; i < cars.length; i++)
{
System.out.println(cars[i]);
}
Foreach Loop
There is also a "for-each" loop, which is used exclusively to loop through elements in
arrays:

for (type variable : arrayname) { ... }

The following example outputs all elements in the cars array, using a "for-each" loop:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


for (String i : cars) {
System.out.println(i);
}

The example above can be read like this: for each String element (called i - as in index)
in cars, print out the value of i.
Example 1: Using For Loop
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5};
// loop through the array

// using for loop


System.out.println("Using for Loop:");
for(int i = 0; i < age.length; i++)
{
System.out.println(age[i]);
}
}
}
Example 2: Using the for-each Loop
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5};
// loop through the array // using for loop
System.out.println("Using for-each Loop:");
for(int a : age)
{
System.out.println(a);
}
}
}
Creating and Iterating Over a Simple
Java Array

Activity 1. You need to declare an array of String type that


contains the names of the days of the week.
“Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"

1.1.5.a
2. Update the "Saturday" and "Sunday" to "Sat" and
"Sun".
3. Iterate Using a for Loop: The traditional for loop
allows you to access each element in the array by its
index.
4. Iterate Using a for-each Loop: The for-each loop
provides a simplified way to iterate through all the
elements in the array without needing to reference
the index.
Java Multidimensional
Arrays
A multidimensional array is an array of arrays. Each element of a
multidimensional array is an array itself. For example,

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

Here, we have created a multidimensional array named a. It is a


2-dimensional array, that can hold a maximum of 12 elements.

Let's take another example of the multidimensional array. This time we will
be creating a 3-dimensional array. For example,

String[][][] data = new String[3][4][2];

Here, data is a 3d array that can hold a maximum of 24 (3*4*2) elements of


type String.
Initialize a 2D Array
Here is how we can initialize a 2-dimensional array in Java.
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7}
};
Example 3: Print all elements of 2d
array Using Loop
class Main {
public static void main(String[] args) {
int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7}
};

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


{
for(int j = 0; j < a[i].length; ++j) { System.out.println(a[i][j]);
}
}
}
Example 4: Print all elements of 2d
array Using For-each
class Main {
public static void main(String[] args) {
int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7}
};

for (int[] innerArray: a) {


for(int data: innerArray) {
System.out.println(data);
}
}
}
Initialize a 3D Array
Let's see how we can use a 3d array in Java. We can initialize a 3d
array similar to the 2d array. For example,
int[][][] test = {
{
{1, -2, 3},
{2, 3, 4}
},
{
{-4, -5, 6, 9},
{1},
{2, 3}
}
};

Basically, a 3d array is an array of 2d arrays. The rows of a 3d array


can also vary in length just like in a 2d array.
Example 5: 3-dimensional Array
class Main {
public static void main(String[] args) {
int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7}
};

for (int[][] array2D: test) {


for (int[] array1D: array2D) {
for(int item: array1D) {
System.out.println(item);
}
}
}
}
Java
ArrayList
In Java, we use the ArrayList class to implement the
functionality of resizable-arrays. It implements the List
interface of the collections framework.

In Java, the List interface is an ordered collection that


allows us to store and access elements sequentially. It
extends the Collection interface.
Java ArrayList Vs Array
In Java, we need to declare the size of an array before we can use it.
Once the size of an array is declared, it's hard to change it.

To handle this issue, we can use the ArrayList class. It allows us to


create resizable arrays.

Unlike arrays, arraylists can automatically adjust their capacity when


we add or remove elements from them. Hence, arraylists are also
known as dynamic arrays.
Creating an ArrayList
Before using ArrayList, we need to import the java.util.ArrayList
package first. Here is how we can create arraylists in Java:
ArrayList<Type> arrayList= new ArrayList<>();

Here, Type indicates the type of an arraylist. For example,


// create Integer type arraylist
ArrayList<Integer> arrayList = new ArrayList<>();

// create String type arraylist


ArrayList<String> arrayList = new ArrayList<>();
Example 6: Create ArrayList in Java
import java.util.ArrayList;

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

// create ArrayList
ArrayList<String> languages = new ArrayList<>();
}
Basic Operations
on ArrayList
The ArrayList class provides various methods to
perform different operations on arraylists. We will look
at some commonly used arraylist operations in this
tutorial:
• Add elements
• Access elements
• Change elements
• Remove elements
Add Elements to
an ArrayList
To add a single element to the arraylist, we use the add() method of
the ArrayList class. For example,

import java.util.ArrayList;
class Main {
public static void main(String[] args){
// create ArrayList
ArrayList<String> languages = new ArrayList<>();

// add() method without the index parameter languages.add("Java");


languages.add("C");
languages.add("Python");
System.out.println("ArrayList: " + languages);
}
}
Access ArrayList
Elements
To access an element from the arraylist, we use the get() method of
the ArrayList class.For example,

import java.util.ArrayList;
class Main {
public static void main(String[] args){
// create ArrayList
ArrayList<String> languages = new ArrayList<>();
// add() method without the index parameter languages.add("Java");
languages.add("C");
languages.add("Python");

// get the element from the arraylist


String str = languages.get(1);
System.out.print("Element at index 1: " + str);
}
}
Change ArrayList
Elements
To change elements of the arraylist, we use the set() method of the
ArrayList class. For example,

import java.util.ArrayList;
class Main {
public static void main(String[] args){
ArrayList<String> languages = new ArrayList<>();

languages.add("Java");
languages.add("C");
languages.add("Python");

System.out.println("ArrayList: " + languages);


// change the element of the array list
languages.set(2, "JavaScript");
System.out.println("Modified ArrayList: " + languages);
}
}
Iterate through an
ArrayList
We can use the Java for-each loop to loop through each element of
the arraylist. For example,

import java.util.ArrayList;
class Main {
public static void main(String[] args){
ArrayList<String> languages = new ArrayList<>();

languages.add("Java");
languages.add("C");
languages.add("Python");

for (String language : languages) {


System.out.print(language);
System.out.print(", ");
}
}
}
Remove ArrayList
Elements
To remove an element from the arraylist, we can use the remove()
method of the ArrayList class. For example,
import java.util.ArrayList;
class Main {
public static void main(String[] args){
ArrayList<String> languages = new ArrayList<>();

languages.add("Java");
languages.add("C");
languages.add("Python");

// remove element from index 2


languages.remove(2);
System.out.println("Updated ArrayList: " + languages);
}
}
Remove All ArrayList
Elements
To remove all elements from the arraylist, we can use the
removeAll() method of the ArrayList class. For example,
import java.util.ArrayList;
class Main {
public static void main(String[] args){
ArrayList<String> languages = new ArrayList<>();

languages.add("Java");
languages.add("C");
languages.add("Python");

// remove all elements from arraylist languages.removeAll(languages);


System.out.println("ArrayList after removeAll(): " + languages);
}
}
ArrayList of days
of a week
Activity 1. You need to declare an ArrayList that contains the
names of the days of the week. "Sunday", "Monday",
"Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday"

1.1.5.b
2. Update the "Saturday" and "Sunday" to "Sat" and
"Sun".
3. Use a for-each loop to iterate through the ArrayList
and print each day.
4. Remove "Friday”
5. Repeat step 3
Other ArrayList Operations
Method Description Example
size() Returns the length of the arraylist. int size = languages.size();

contains() Searches the arraylist for the specified boolean isTrue =


element and returns a boolean result. languages.contains("Java");

isEmpty() Checks if the arraylist is empty. boolean result =


languages.isEmpty();
indexOf() Searches a specified element in an arraylist int position =
and returns the index of the element. The languages.indexOf("Java");
method returns -1 if the element doesn't
exist in the arraylist.
ArrayList of days
of a week
Activity 1. Based on Activity 1.1.5.b, get the following.
• Ge the total number of elements using size()
• Check if "Thursday" exist using contains()
• Using indexOf(), get the index of "Thursday"

1.1.5.c
2. Remove all elements.
3. Check if ArrayList is empty using isEmpty()
Thank You

You might also like