Skip to main content

How to create an array in Java

How to use arrays in Java

An array in Java is a type of variable that can store multiple values. It stores these values based on a key that can be used to subsequently look up that information.

Arrays can be useful for developers to store, arrange, and retrieve large data sets. Whether you are keeping track of high scores in a computer game, or storing information about clients in a database, an array is often the best choice.

Also read: How to use arrays in Python

So, how do you create an array in Java? That all depends on the type of array you want to use!

How to create an array in Java

The word “array” is defined as a data structure, consisting of a collection of elements. These elements must be identified by at least one “index” or “key.”

There are multiple data objects in Java that we could describe as arrays, therefore. We refer to the first as the “Java array.” Though making matters a little more confusing, this is actually most similar to what we would call a “list” in many other programming languages!

This is the easiest way to think about a Java array: as a list of sequential values. Here, a key is automatically assigned to each value in the sequence based on its relative position. The first index is always “0” and from there, the number will increase incrementally with each new item.

Unlike a list in say Python, however, Java arrays are of a fixed size. There is no way to remove elements or to add to the array at run time. This restriction is great for optimized code but of course does have some limitations.

To create this type of array in Java, simply create a new variable of your chosen data type with square brackets to indicate that it is indeed an array. We then enter each value inside curly brackets, separated by commas. Values are subsequently accessed by using the index based on the order of this list.

String listOfFruit[] = {"apple", "orange", "lemon", "pear", "grape"};
System.out.println(listOfFruit[2]);

While it’s not possible to change the size of a Java array, we can change specific values:

listOfFruit[3] = “melon”;

ArrayLists

If you need to use arrays in Java that can be resized, then you might opt for the ArrayList. An ArrayList is not as fast, but it will give you more flexibility at runtime.

To build an array list, you need to initialize it using our chosen data type, and then we can add each element individually using the add method. We also need to import ArrayList from the Java.util package.

import java.util.ArrayList;

class Main {

  public static void main(String[] args) {

    ArrayList<String> arrayListOfFruit = new ArrayList<String>();
    arrayListOfFruit.add("Apple");
    arrayListOfFruit.add("Orange");
    arrayListOfFruit.add("Mango");
    arrayListOfFruit.add("Banana");
    System.out.println(arrayListOfFruit);

  }

}

Now, at any point in our code, we will be able to add and remove elements. But keep in mind that doing so will alter the positions of all the other values and their respective keys. Thus, were I to do this:

System.out.println(arrayListOfFruit.get(3));
arrayListOfFruit.add(2, "Lemon");
System.out.println(arrayListOfFruit.get(3));

I would get a different output each time I printed. Note that we use “get” in order to return values at specific indexes, and that I can add values at different positions by passing my index as the first argument.

How to create an array in Java using maps

Another type of array in Java is the map. A map is an associative array that uses key/value pairs that do not change.

This is a perfect way to store phone numbers, for example. Here, you might use the numbers as the values and the names of the contacts as the index. So “197701289321” could be given the key “Jeff.” This makes it much easier for us to quickly find the data we need, even as we add and remove data from our list!

We do this like so:

import java.util.HashMap;
import java.util.Map;

    Map<String, String> phoneBook = new HashMap<String, String>();
    phoneBook.put("Adam", "229901239");
    phoneBook.put("Fred", "981231999");
    phoneBook.put("Dave", "123879122");
    System.out.println("Adam's Number: " + phoneBook.get("Adam"));

As you can see then, a Java Array is always an array, but an array is not always a Java Array!

How to use the multidimensional array in Java

Head not spinning enough yet? Then take a look at the multidimensional array in Java!

This is a type of Java Array that has two “columns.”

Imagine that your typical Java array is an Excel spreadsheet. Were that the case, you’d have created a table with just a single column. We might consider it a “one dimensional” database, in that the data only changes from top to bottom. We have as many rows as we like (1st dimension) but only one column (the hypothetical 2nd dimension).

To add more columns, we simply add a second set of square brackets. We then populate the rows and columns. The resulting data structure can be thought of as an “array of arrays,” wherein each element is an entire array itself!

In this example, we are using integers (whole numbers):

int[][] twoDimensions = {
      {1, 2, 3, 4},
      {5, 6, 7, 8},
      {9, 10, 11, 12},
};

But we can actually take this idea even further by creating a three dimensional array! This would be an array of 2D arrays. You would build it like this:

int[][][] threeDimensions = {
        {
          {1, 2, 3},
          {4, 5, 6}
        },
        {
          {-1, -2, -3},
          {-4, -5. -61},
        }
};

Although this idea is tricky to conceptualize, try to imagine a database that has three axes, with cells that move in each direction.

So that is how you create an array in Java! While many people reading this will never need to concern themselves with three-dimensional arrays, it just goes to show how powerful and adaptable Java really is.

In fact, the list of things you can accomplish with Java is limitless. As is the Array List. Why not continue your education with one of the best resources to learn Java?



source https://www.androidauthority.com/how-to-create-an-array-in-java-1151277/

Comments

Popular posts from this blog

5 tips to Voice Speech Recognition in Android Marshmallow

Android Marshmallow landed on our Android devices. The opportunity for us to offer a small compilation of tricks to try immediately. The latest version of the Google OS starts (very gently, unhurriedly) to be offered on other devices as Nexus. You will find on Android TM, in the coming weeks, a compilation of the best tips for Android 6.0 Marshmallow. It starts slowly with a video featuring the 10 essential tips & tricks of this new version of the little green robot OS. To continue, we offer a selection of five "tricks" on the management of the battery on Android 6.0 Marshmallow. To enjoy longer your newly updated mobile. Follow the guide. then continue with 5 tips to tame the super-assistant Google Now on Tap. Here you will find 5 "tips" to manage in the best way your applications. We then discuss the quick tips to navigate more easily on this version of the Google OS. We enchanters with features focused on safety and the protection of personal data. We co...

Energy Android TV Play turns your TV into a Smart TV

ENERGY SISTEM Android Energy TV Play, you have a smart TV with Android operating system allows you to convert any traditional TV has announced the launch of a new product. Energy Android TV Play can be connected to the TV to enjoy f the size of a flash drive, a smart phone, a tablet and a computer unconsolidated is a lightweight device. System 1.6 GHz, DDR3 1GB of RAM and a dual-core processor can be expanded using external USB devices, which is the internal memory of 8 GB. It also integrates WiFi and a USB port for connecting external devices. One of its outstanding features, it is easily connected to the TV screen by screen cast application to display the contents of any terminal, making any phone or tablet is synchronized with iOS or Android. All ENERGY SISTEM products one click In addition, through streaming media service applications, images, video or other multimedia content, and game play is the ability to share. With integrated WiFi, the device you want from t...

How to run Python apps on any platform

Credit: Adam Sinicki / Android Authority Want to know how to run Python? It sounds simple, but it can actually be tricky to figure this out. In this post, we’ll discuss how to test your Python code, as well as how to run Python in other contexts: online for example, or as a packaged app. Sometimes, the thing holding you back from learning to code can be extremely simple. I remember wanting to learn to program when I was younger – or learning to take what I’d learned from BASIC on the ZX Spectrum and apply that to a modern environment. My problem? I didn’t know “where” to program. Once I understood C# or Java, where would I enter the code and how would I run it? And whenever I asked someone, they would look at me blankly. What kind of a question is that? Thing is, I had never needed an IDE or an interpreter before. Machines like the ZX Spectrum and Tatung Einstein (any other Einstein users out there?) simply booted up with a prompt to code into! Many people have a similar iss...