Sign In
Sign In

How to Create an Array in Java

How to Create an Array in Java
Hostman Team
Technical writer
Java
28.03.2024
Reading time: 9 min

In Java programming, arrays, as a fundamental data structure, provide efficient storage and manipulation of multiple values. Due to their advantages in managing big data, they are commonly used in various programming tasks. Without arrays, separate variables for each value would have to be declared, which is time-consuming and prone to errors.

The arrays can be resized to meet various programming requirements. The dynamic of arrays is a solution when the number of elements is unknown or may change. It is essential to master techniques such as looping through the array to perform specific tasks on each item, or using built-in functions to sort or search for specific values within the array.

We'll delve into the concept of arrays in Java, starting with the fundamentals of their structure and how to create an array in Java. We'll cover the different types of arrays and their initialization methods. You will gain a thorough comprehension of arrays in Java, empowering you to confidently incorporate them into your programming endeavors.

The syntax of array creation in Java

To confidently deal with arrays in Java, it is necessary to understand the syntax of array creation. To create an array, use the new keyword, followed by the data type of the elements and the number of elements enclosed in square brackets.

To create an array of integers with ten elements, use the syntax:

int[] arrayName = new int[10];

This tells the Java compiler to allocate memory for an array of 10 integers and assign it to the variable arrayName.

The indicated data type in an array declaration determines the type of data to store within the array. Both data types should match. An integer array cannot store strings or floating point numbers. Mixing different data types within an array results in errors and unpredictable outcomes.

For an array creation in Java, indicate its size or the number of elements it will contain. Once an array is created, its size is fixed and cannot be changed by adding or removing items. It is important to determine the appropriate size of the array before creating it.

To access an element at an index that is outside the array's size, get an ArrayIndexOutOfBoundsException to eliminate the program crash.

The memory usage of an array depends on its size. The bigger the array, the greater amount of memory it will require. When declaring an array, it is crucial to take into account its size, especially when dealing with big data. Remember that the size of an array is a positive integer value.

How to create an array in Java

To create a simple array in Java, declare the array, indicate its data type, and initialize it with values.

To create an array for storing weekly temperatures, declare it as follows:

int[] temperatures;

Next, indicate the size of the array, which determines the number of elements it contains. To store the temperatures for seven days, initialize the array in Java with a size of seven as follows:

temperatures = new int[7];

Now, assign values to each element in the array using a for loop to iterate through the array and assign a value to each element.

This can be achieved as follows:

for (int i = 0; i < temperatures.length; i++) {
temperatures[i] = i + 1;
}

In this case, a temperature value is assigned to each element, starting from 1 for day 1 and increasing by 1 for every next day. Once all the values ​​are assigned, the array will look like this:

[1, 2, 3, 4, 5, 6, 7]

Access each element of the array through its index, starting from 0. So, the first element of the array has index 0, the second element has index 1, and so on.

To print the temperature for day 7, access the element at index 6 as follows:

System.out.println('Temperature for day 7: ' + temperatures[6])

Arrays are used to store different data types, such as strings, doubles, and booleans. 

To create an array for storing the names of months, declare and initialize it as follows:

String[] months = {'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', December'};

Arrays deal with large datasets and perform tasks on them. To find the average month temperature, use a for loop to iterate through the array and sum all temperatures, divided by the number of items in the array.

This can be achieved as follows:

int sum = 0;
for (int i = 0; i < temperatures.length; i++) {
sum += temperatures[i];
}
double average = sum/temperatures.length;
System.out.println('Average temperature for the month: ' + average);

This will output: Average temperature for the month: 12.

Managed solution for Backend development

How to declare and initialize an array in Java

To work correctly, you should learn how to declare an array in Java. Start by specifying any primitive data type of the elements it will contain, such as int, double, char, or string.

To create an array of integers, use the syntax:

int[] myArray;

A variable named myArray of type int[] may contain multiple integer values.

Next, you should know how to initialize an array in Java. To do this, specify an array size in square brackets after the data type indicating the number of elements the array contains.

To store 10 integers within the array, write:

int[] myArray = new int[10];

A new array object with a length of 10 is assigned to the variable myArray.

To assign values, use the assignment operator (=) and enclose the values in curly braces, separated by commas.

To assign values 1, 2, 3, 4, and 5 to an array, use the following code:

myArray = {1, 2, 3, 4, 5};

Alternatively, you can assign values to the array in a separate statement:

myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
myArray[3] = 4;
myArray[4] = 5;

There are also other methods to initialize arrays in Java. The first one is by using the fill method from the Arrays class to fill an array with a specific value or a range of values.

For instance:

int[] numbers = new int[5]; Arrays.fill(numbers, 1);

This initializes the numbers array with 5 elements, all assigned the value of 1. 

Java also provides the copyOf method for initializing arrays to copy an existing array and specify the desired length of the new array.

For instance:

int[] copy = Arrays.copyOf(numbers, 3);

It creates a new array named copy with 3 elements, copying the first three elements from the numbers array.

To access elements of the array, use the index number enclosed in square brackets. In Java, arrays are zero-based with the first element of the array being at index 0, the second element at index 1, and so on.

To access the first element of our array, use the following code:

int firstElement = myArray[0];

To access the second element, use the following code:

int secondElement = myArray[1];

Use a for loop to iterate through all the elements of an array and interact with them. The for loop takes the size of the array as a condition and uses the index variable to access each element of the array, as shown below:

for (int i = 0; i < myArray.length; i++) {
//perform operations on each element of the array
}

To see the values stored in an array, use the System.out.println() method to print them to the console. Print each element individually or use a loop to print all the elements, as shown below:

System.out.println(myArray[0]);
System.out.println(myArray[1]);
System.out.println(myArray[2]);
System.out.println(myArray[3]);
System.out.println(myArray[4]);

Use a loop to print all the elements at once:

for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}

One-dimensional arrays in Java

One-dimensional arrays store and organize a collection of elements of the same data type. They consist of a fixed number of elements of the same data type, such as integers, strings, or characters. The array elements are indexed, starting from 0, allowing each element to be accessed at its appropriate index.

To declare an array, use the square brackets notation after the data type. To declare an array of integers, write int[], followed by the name of the array and an equal sign to assign values to the array.

To initialize an array, use the keyword new, followed by the data type and the number of elements in the array.

For instance:

int[] numbers = new int[5] 

This code will create an array named numbers with 5 elements of type integer.

Multi-dimensional arrays in Java

Multi-dimensional arrays store and manipulate data in a table or spreadsheet format. Unlike traditional one-dimensional arrays, which are limited to a single row or column of data, these ones appear as a grid or matrix with rows and columns.

To create a multi-dimensional array in Java, use square brackets to indicate the dimensions of the array. To create a 2D array with 3 rows and 4 columns, use the following syntax:

int[][] arr = new int[3][4]

To access and modify elements in the array, use row and column indices, such as arr[0][0] to access the first element in the first row.

Simple and fully managed app deployment

The use of array literals and anonymous arrays in Java

Typically, arrays are declared with a fixed size and are initialized with specific values ​​at declaration time. The introduction of array literals and anonymous arrays led to better versatility and ease of manipulation. Array literals stand for creating arrays without explicitly declaring and initializing them. Instead of writing multiple code lines to declare and assign values to an array, use a single code line with the curly braces.

For instance, instead of writing this:

int[] numbers = new int[]{1, 2, 3, 4, 5};

Simply write:

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

This makes the code easier to read and understand.

Array literals allow you to create multi-dimensional arrays. While previously creating them required nested square brackets, now with array literals you can use a comma-separated list of arrays within curly braces.

For instance:

int[][] numbers = {{1, 2}, {3, 4}, {5, 6}};

will create a 2D array with 3 rows and 2 columns.

This shortens the code when working with large arrays.

Java supports anonymous arrays created without a variable name for one-time use. To sort an array of integers, use them as the argument for the sorting method rather than declaring or initializing a named array.

Anonymous arrays are used in cases where the size of the array is unknown by omitting it in the declaration and using curly braces.

For instance, this: 

int[] numbers = new int[]{1, 2, 3, 4, 5};

Can be rewritten as this, using an anonymous array:

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

Conclusion

Arrays play a crucial role in Java programming as they serve as a fundamental data structure for organizing and modifying a set of elements with the same data type. Proficiency in the proper syntax for creating, declaring and initializing arrays is essential, as it forms the foundation for commonly used algorithms and data structures. With a solid understanding of the core concepts, you can efficiently utilize arrays in your code and effectively manipulate data. And in case you missed it, servers can be started on Hostman for only $4 per month.

Java
28.03.2024
Reading time: 9 min

Similar

Java

Java main() Method

The main method in Java is a fundamental component for any standalone application. It serves as the entry point where the program begins execution. Understanding the syntax and functionality of this method is crucial for every Java programmer. This article delves into the specifics of the main method, explaining its syntax, the role of command-line arguments, and providing practical examples to illustrate its use. Syntax Explanation: public static void main(String[] args) The Java main method is defined as: public static void main(String[] args) Breaking down the syntax: public: This is an access modifier, meaning the method is accessible from anywhere. static: This keyword means the method belongs to the class rather than an instance of the class. It can be invoked without creating an object of the class. void: This signifies that the method does not return any value. main: This is the name of the method. The Java runtime environment looks for this specific method signature to start execution. String[] args: This parameter is an array of String objects, which stores command-line arguments passed to the program. Understanding the String[] args Parameter The String[] args parameter in the main method is crucial for passing information to the program at runtime. Each element in this array is a command-line argument provided when the program is executed. For example, if a program is run with java MyClass arg1 arg2, args[0] would be arg1 and args[1] would be arg2. public class MyClass { public static void main(String[] args) { for (String arg : args) { System.out.println(arg); } } In the above code, each command-line argument passed to the program is printed to the console. How to Use Command-Line Arguments Command-line arguments allow users to pass data into a Java program at the time of execution, making the program more flexible and dynamic. Here's a simple example of how to use command-line arguments in a Java program: public class SumArgs { public static void main(String[] args) { int sum = 0; for (String arg : args) { sum += Integer.parseInt(arg); } System.out.println("Sum: " + sum); } } If this program is run with java SumArgs 10 20 30, it will output Sum: 60. This demonstrates how command-line arguments can be used to input data without modifying the program's source code. Typical Use Cases and Examples Configuration Parameters: Command-line arguments are often used to pass configuration settings to a program. For example, specifying the path to a configuration file or setting a debug mode. public class ConfigLoader { public static void main(String[] args) { if (args.length > 0) { String configFilePath = args[0]; System.out.println("Loading configuration from: " + configFilePath); // Load and process the configuration file } else { System.out.println("No configuration file path provided."); } } } File Processing: Programs that perform operations on files often accept file paths as command-line arguments. public class FilePrinter { public static void main(String[] args) { if (args.length > 0) { String filePath = args[0]; // Code to read and print file content } else { System.out.println("Please provide a file path."); } } } Testing and Debugging: Command-line arguments can be used to quickly test and debug different scenarios by changing the input parameters without altering the source code. Conclusion The public static void main(String[] args) method is an essential part of any Java application. Its syntax and functionality are designed to provide a standardized entry point for program execution. Understanding how to leverage String[] args for command-line arguments can significantly enhance the flexibility and utility of your programs. By mastering the main method, Java developers can build more dynamic and configurable applications, making their code more versatile and easier to manage.
31 July 2024 · 4 min to read
Java

Installing Java Using apt on Ubuntu

Java and the JVM (Java Virtual Machine) are often used in various applications. Therefore, it's important to know how to install free packages and alternative releases from Oracle, including JRE (Java Runtime Environment) and JDK (Java Development Kit).  This tutorial will guide you through installing Java on Ubuntu using apt and selecting the preferred version. Prerequisites You will need a system (your local machine or a cloud server) with Ubuntu 20.04 pre-installed, with root and sudo accounts, and a configured firewall. Installing JRE/JDK The simplest way to get started is to use the release included in the standard Ubuntu package. Ubuntu 22.04 comes with OpenJDK 11, which includes open-source JRE and JDK packages. First, download updates to the package index: sudo apt update Before installing Java on Ubuntu, check if it has already been installed: java -version If Java is not installed, you will see: Command 'java' not found, but can be installed with:apt install openjdk-11-jre-headless  # version 11.0.20.1+1-0ubuntu1~22.04, orapt install default-jre              # version 2:1.11-72build2apt install openjdk-17-jre-headless  # version 17.0.8.1+1~us1-0ubuntu1~22.04apt install openjdk-18-jre-headless  # version 18.0.2+9-2~22.04apt install openjdk-19-jre-headless  # version 19.0.2+7-0ubuntu3~22.04apt install openjdk-8-jre-headless   # version 8u382-ga-1~22.04.1 Now, install the OpenJDK package: sudo apt install default-jre After installation, verify the JRE presence: java -version You should see: openjdk version "11.0.23" 2024-04-16OpenJDK Runtime Environment (build 11.0.23+9-post-Ubuntu-1ubuntu122.04.1)OpenJDK 64-Bit Server VM (build 11.0.23+9-post-Ubuntu-1ubuntu122.04.1, mixed mode, sharing) To compile and run even specific applications, you will also need the JDK package: sudo apt install default-jdk Verify the compiler version: javac -version You should see: javac 11.0.23 Installing Oracle JDK In some cases, you may need the Oracle JDK package. This installation of Java on Ubuntu will differ from the methods described above, as it requires manual installation. You cannot install it from Ubuntu repositories using apt-get install, but the process is still relatively easy. The latest version is Java 22. However, Java 21 has the longest support. We will install Java 21 in Ubuntu using wget and a download link copied from the Downloads section on the Oracle website. Run: wget https://download.oracle.com/java/21/latest/jdk-21_linux-x64_bin.deb Now install: sudo apt install ./jdk-21_linux-x64_bin.deb Check the Java version: java -version You should see: java version "21.0.3" 2024-04-16 LTSJava(TM) SE Runtime Environment (build 21.0.3+7-LTS-152)Java HotSpot(TM) 64-Bit Server VM (build 21.0.3+7-LTS-152, mixed mode, sharing) Managing Java Versions You can install multiple versions of Java on a single machine. To see the default version, use: sudo update-alternatives --config java If you've installed the previously mentioned versions, you will see: Enter the desired version number or press Enter to keep the current settings (indicated by an asterisk). This also applies to other modules like the compiler javac, keytool, javadoc, jarsigner, etc.: sudo update-alternatives --config javac Setting the JAVA_HOME Variable Most Java applications use the JAVA_HOME environment variable to determine the installation directory.  In the previous chapter, we run this command: sudo update-alternatives --config java Check the paths in its output. In our case, the directories are: OpenJDK 11: /usr/lib/jvm/java-11-openjdk-amd64/bin/java OpenJDK 8: /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java Oracle Java 21: /usr/lib/jvm/java-8-oracle/jre/bin/java Copy the desired path and edit the /etc/environment file with nano: sudo nano /etc/environment Add a new line with the copied path: JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64/bin/" This sets the JAVA_HOME variable for all user accounts. Save and exit the file, then reload the environment variables: source /etc/environment Check if the changes were applied: echo $JAVA_HOME You should see: /usr/lib/jvm/java-11-openjdk-amd64/bin/ This change applies to the current user, while others need to restart the system. Conclusion We have covered the installation of Java in Ubuntu, including standard JRE/JDK versions and official Oracle releases. After installing the platform, you can use Java applications and dependencies without restrictions.
09 July 2024 · 4 min to read
Java

Method Overloading and Overriding in Java

A method in Java is a function that defines what an object of a class can do. One of the main tasks of a method is to perform actions on the object's data. They can change values, transform data, and print to the console. Methods can be overloaded and overridden. In this article, we'll explore how to do this and the differences between these two mechanisms. Method Overloading Method overloading in Java means using one method name with different parameters. To understand this mechanism, let's start with a simple example - creating a helper to greet users. public class Assistant { public void sayHello(String name) { System.out.println("Good day, " + name + "!"); } public static void main(String[] args) { Assistant assistant = new Assistant(); assistant.sayHello("Michael"); } } The console will display the phrase "Good day, Michael!". Suppose Michael didn't come alone but with his friend Victor. The current implementation of the method greets only Michael and ignores Victor. To fix this, we'll implement two methods in the class with the same name but different parameters. public class Assistant { public void sayHello(String firstGuest) { System.out.println("Good evening, " + firstGuest + "!"); } public void sayHello(String firstGuest, String secondGuest) { System.out.println("Good day, " + firstGuest + " and " + secondGuest + "!"); } public static void main(String[] args) { Assistant assistant = new Assistant(); assistant.sayHello("Michael", "Victor"); } } Now the console will display "Good day, Michael and Victor!". We have overloaded sayHello(). The program is now more flexible - the assistant can greet two guests at once. But what happens if three, four, or five guests arrive? Let's check: public class Assistant { public void sayHello(String firstGuest) { System.out.println("Good evening, " + firstGuest + "!"); } public void sayHello(String firstGuest, String secondGuest) { System.out.println("Good day, " + firstGuest + " and " + secondGuest + "!"); } public static void main(String[] args) { Assistant assistant = new Assistant(); assistant.sayHello("Michael", "Victor", "Mary"); } } We will get an error because sayHello() is ready to accept only two arguments. A straightforward solution is to continue overloading it to accept three, four, five, or more guests. However, this isn't flexible programming. We would constantly need to add more code. We would constantly need to add more code. A more flexible solution is to pass a variable-length argument (String... names). This allows sayHello() to accept any number of strings. To print a greeting for each guest to the console, we can use a loop. public class Assistant { public void sayHello(String firstGuest) { System.out.println("Good evening, " + firstGuest + "!"); } public void sayHello(String... names) { for (String name : names) { System.out.println("Good evening, " + name + "!"); } } public static void main(String[] args) { Assistant assistant = new Assistant(); assistant.sayHello("Michael", "Victor", "Mary", "Andrew", "Anna"); } } The console will display a greeting for each guest: Good evening, Michael! Good evening, Victor! Good evening, Mary! Good evening, Andrew! Good evening, Anna! Managed solution for Backend development Argument Order In the example above, we didn't think about the order of arguments because they were all strings. It doesn't matter whether we greet Michael or Anna first. But the order of arguments matters if the method takes, for example, a string and a number. Look at this: public class User { public static void sayYourAge(String greeting, int age) { System.out.println(greeting + " " + age); } public static void main(String[] args) { sayYourAge(20, "My age is - "); //error! } } A compilation error occurs because we defined sayYourAge() to accept a string first and then a number, but we passed the arguments in the opposite order. To fix the error, pass the arguments in the correct order: public class User { public static void sayYourAge(String greeting, int age) { System.out.println(greeting + " " + age); } public static void main(String[] args) { sayYourAge("My age is - ", 20); } } To avoid errors, you can overload by the order of parameters. For example: public class User { public static void sayYourAge(String greeting, int age) { System.out.println(greeting + " " + age); } public static void sayYourAge(int age, String greeting) { System.out.println(greeting + " " + age); } public static void main(String[] args) { sayYourAge("My age is - ", 20); sayYourAge(20, "My age is - "); } } Now it doesn't matter in which order the arguments are passed—the program will understand both options. Variations of Overloading From the examples above, we can identify three variations of overloading Java methods. By the number of parameters: public class Calculator {    void calculate(int number1, int number2) { }    void calculate(int number1, int number2, int number3) { }} By parameter types: public class Calculator {    void calculate(int number1, int number2) { }    void calculate(double number1, double number2) { }} By parameter order: public class Calculator {    void calculate(double number1, int number2) { }    void calculate(int number1, double number2) { }} Finally, let's reiterate what method overloading in Java means. It is a language mechanism that allows the creation of multiple methods with the same name but different parameters. This is not possible in all languages. Overloading is part of polymorphism, one of the key components of object-oriented programming. The main advantage of overloading in Java is the ability to use similar methods with the same names. Method Overriding Method overriding in Java allows you to take a method from a parent class and create a specific implementation in a subclass. To understand this better, let's look at an example. Suppose you create a class Animal with a method voice(). It allows the animal to make a sound: public class Animal { public void voice() { System.out.println("Speak!"); } } The problem immediately arises - all animals make different sounds. You could create a separate method for each. For example, for a cat, it would be voiceCat(), and for a dog, it would be voiceDog(). But imagine how many lines of code you would have to write to allow all animals to make a sound. This is where the overriding mechanism in Java comes in handy. It allows you to replace the implementation in the subclass. Let's look at examples with a cat and a dog: public class Cat extends Animal { @Override public void voice() { System.out.println("Meow!"); } } public class Dog extends Animal { @Override public void voice() { System.out.println("Woof!"); } } The output will first display "Meow" and then "Woof". To achieve this result, you need to: Create a method in the subclass with the same name as in the parent class. Add the @Override annotation before it. This annotation tells the compiler it is not a mistake; you intentionally override the method. Note that the annotation is not mandatory. Creating a method in the subclass with the same signature as the parent class will still override the method. However, it is recommended that you always use the annotation, as it improves code readability and ensures the compiler checks at compile time that such a method exists in the parent class. You write a custom implementation for each subclass. If you don't do this, the parent class's implementation will be used. Even after overriding, you can refer to the parent class's method as long as it is not defined with the private modifier. To do this, use the super keyword: super.method(); Simple and fully managed app deployment Overriding Restrictions Overriding class methods in Java has several restrictions. The method name must be identical to the parent's method (i.e., the method signature must be identical). The arguments must remain the same as the parent's method. The return type must be the same as the parent's method. The access modifier must be the same as the parent's method. Final methods cannot be overridden. One way to prevent overriding is to declare the method using the final keyword. For example: class Parent { final void show() {} } class Child extends Parent { void show() {} // Error! } This code will return an error because the parent class used the final keyword. Static methods cannot be overridden. If you define the same method signature in the subclass as in the parent class, you will perform hiding. More details can be found in the documentation. Private methods cannot be overridden as they are bound at compile time, not runtime. You cannot narrow the access modifier, for example, from public to private. Widening the access level is possible. You cannot change the return type, but you can narrow it if they are compatible. Overriding a method in Java adheres to the rules listed above, which must be followed. Some methods have their own overriding rules, such as equals() and hashCode(). The most important condition is that if you override equals(), you must also override hashCode(). Otherwise, classes and methods that rely on the contracts of these two methods' standard implementation might work incorrectly. We discussed this in detail in another article. Conclusion Method overriding and overloading in Java are important parts of polymorphism but are different mechanisms. When overloading, you create multiple methods within one class with the same name but different parameters. When overriding, you take the same method and make it do different things depending on which class it is called in. However, Java overloading and overriding share some characteristics. Both mechanisms help make code cleaner and more readable and reduce the number of errors during program execution.
08 July 2024 · 8 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support