java

Working With Arrays in Java

Arrays refer to a sequential collection of elements of the same type. It is used to store a collection of data. Unlike Javascript where an array can hold many elements of different data types, an array in Java holds a fixed number of values of a single type.

Immediately after creating an array, its length is fixed. Each item in an array is referred to as an element, and each element can be accessed by its numerical index.

An array index begins from 0 and begins to increment for the given length of the array.

An array illustration from Oracle

Syntax

dataType [] arrayRefValue; //Preferred way

dataTaype arrayRefValue []; //Not so preferred way

Processing Arrays

public class TestArray {
public static void main(String [] args) {
double [] myList = {1.2, 1.4, 2.5, 4.5, 1.6}
System.out.println(myList[0]) // 1.2
System.out.println(myList[1]) // 1.4
System.out.println(myList[2]) // 2.5
System.out.println(myList[3]) // 4.5
System.out.println(myList[4]) // 1.6
}
}

Summing All Elements in an Array

public class TestArray {
public static void main(String [] args) {
double [] myList = {1.2, 1.4, 2.5, 4.5, 1.6}
double total = 0;
for(int i=0; i<myList.length; i++){
total +=myList[i];
}
System.out.println("Total is "+total); //11.2
}
}

Finding The Largest Element in an Array

public class TestArray {
public static void main(String [] args) {
double [] myList = {1.2, 1.4, 2.5, 4.5, 1.6}
double max = myList[0];
for(int i=0; i<myList.length; i++){
if(myList[i] > max) max = myList[i];
}
System.out.println("Largest value is "+max); //4.5
}
}

See the official Java documentation for Arrays

THE END.

Recent Posts

Google Announces that AI-developed Drug will be in Trials by the End of the Year

Isomorphic Labs, a drug discovery start-up launched four years ago and owned by Google’s parent…

1 hour ago

Instagram Extends Reels Duration to 3 Minutes

Regardless of whether TikTok faces a U.S. ban, Instagram is wasting no time positioning itself…

2 days ago

AWS Expands Payment Options for Nigerian Customers, Introducing Naira (NGN) for Local Transactions

Amazon Web Services (AWS) continues to enhance its customer experience by offering more flexible payment…

6 days ago

Why JavaScript Remains Dominant in 2025

JavaScript, often hailed as the "language of the web," continues to dominate the programming landscape…

1 week ago

Amazon Moves to Upgrade Alexa with Generative AI Technology

Amazon is accelerating efforts to reinvent Alexa as a generative AI-powered “agent” capable of performing…

1 week ago

Smuggled Starlink Devices Allegedly Used to Bypass India’s Internet Shutdown

SpaceX's satellite-based Starlink, which is currently unlicensed for use in India, is reportedly being utilized…

1 week ago