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.

Author

Recent Posts

Apple is developing a doorbell camera equipped with Face ID technology.

Apple is reportedly developing a new smart doorbell camera with Face ID technology to unlock…

15 hours ago

Google Launches Its Own ‘Reasoning’ AI Model to Compete with OpenAI

This month has been packed for Google as it ramps up efforts to outshine OpenAI…

3 days ago

You can now use your phone line to call ChatGPT when cellular data is unavailable.

OpenAI has been rolling out a series of exciting updates and features for ChatGPT, and…

4 days ago

Phishers use fake Google Calendar invites to target victims

A financially motivated phishing campaign has targeted around 300 organizations, with over 4,000 spoofed emails…

5 days ago

Hackers Exploiting Microsoft Teams to Remotely Access Users’ Systems

Hackers are exploiting Microsoft Teams to deceive users into installing remote access tools, granting attackers…

6 days ago

Ethical Hacking Essentials

Data plays an essential role in our lives.  We each consume and produce huge amounts…

1 week ago