How do I fill array with non-default value?

This code snippet will show you how to create array variable and initialized it with a non-default value. By default, when we create an array of something in Java all entries will have its default value. For primitive types like int, long, float the default value are zero (0 or 0.0). For reference types (anything that holds an object in it) will have null as the default value. For boolean variable it will be false.

If you want to initialize the array to different value you can use the Arrays.fill() method. This method will help you to set the value for every elements of the array.

Let see the following code snippet as an example:

package org.kodejava.example.util;

import java.util.Arrays;

public class ArraysFillExample {
    public static void main(String[] args) {
        // Assign -1 to each elements of numbers array
        int[] numbers = new int[5];
        Arrays.fill(numbers, -1);
        System.out.println("Numbers: " + Arrays.toString(numbers));

        // Assign 1.0f to each elements of prices array
        float[] prices = new float[5];
        Arrays.fill(prices, 1.0f);
        System.out.println("Prices : " + Arrays.toString(prices));

        // Assign empty string to each elements of words array
        String[] words = new String[5];
        Arrays.fill(words, "");
        System.out.println("Words  : " + Arrays.toString(words));

        // Assign 9 to each elements of the multi array
        int[][] multi = new int[3][3];
        for (int[] array : multi) {
            Arrays.fill(array, 9);
        }
        System.out.println("Multi  : " + Arrays.deepToString(multi));
    }
}

In the code snippet above we utilize the Arrays.fill() utility method to assign value for each elements of the int, float and String array. To change the default value of multi dimensional array we can’t directly call the Arrays.fill() method. In the example we use for-loop to set each elements of the sub-array using the Arrays.fill() method.

The output of the code snippet above are:

Numbers: [-1, -1, -1, -1, -1]
Prices : [1.0, 1.0, 1.0, 1.0, 1.0]
Words  : [, , , , ]
Multi  : [[9, 9, 9], [9, 9, 9], [9, 9, 9]]

How can I insert an element in array at a given position?

As we know an array in Java is a fixed-size object, once it created its size cannot be changed. So if you want to have a resizable array-like object where you can insert an element at a given position you can use a java.util.List object type instead.

This example will show you how you can achieve array insert using the java.util.List and java.util.ArrayList object. Let see the code snippet below.

package org.kodejava.example.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayInsert {
    public static void main(String[] args) {
        // Creates an array of integer value and prints the 
        // original values.
        Integer[] numbers = new Integer[]{1, 2, 3, 8, 13, 21};
        System.out.println("Original numbers: " + 
                Arrays.toString(numbers));

        // Creates an ArrayList object and add the entire content
        // of numbers array into the list. We use the 
        // add(index, element) method to add element=5 at index=3.
        List<Integer> list = new ArrayList<>();
        list.addAll(Arrays.asList(numbers));
        list.add(3, 5);

        // Converts back the list into array object and prints 
        // the new values.
        numbers = list.toArray(new Integer[list.size()]);
        System.out.println("After insert    : " + Arrays.toString(numbers));
    }
}

In the code snippet above the original array of Integer numbers will be converted into a List, in this case we use an ArrayList, by adding all elements of the array into the list using the List.addAll() method. The Arrays.asList() can be use to convert an array into a collection type object.

Next we insert a new element into the List using the add(int index, E element) method. Where index is the insert / add position and element is the element to be inserted. After the new element inserted we convert the List back to the original array.

Below is the result of the code snippet above:

Original numbers: [1, 2, 3, 8, 13, 21]
After insert    : [1, 2, 3, 5, 8, 13, 21]

How do I split a string?

Prior to Java 1.4 we use StringTokenizer to split a tokenized string, for example a comma separated string. In Java 1.4 or later the String class introduce a String.split(String regex) method that simplify this process.

Below is a code sample how to do it.

package org.kodejava.example.lang;

import java.util.Arrays;

public class StringSplit {
    public static void main(String[] args) {
        String data = "1,Diego Maradona,Footballer,Argentina";
        String[] items = data.split(",");

        // Iterates the array to print it out.
        for (String item : items) {
            System.out.println("item = " + item);
        }

        // Or simply use Arrays.toString() when print it out.
        System.out.println("item = " + Arrays.toString(items));
    }
}

The result of the code snippet:

item = 1
item = Diego Maradona
item = Footballer
item = Argentina
item = [1, Diego Maradona, Footballer, Argentina]

How do I sort an array of objects?

In this example we are going to learn how to sort an array of objects. We start by using an array of String objects as can be seen in the code snippet below. We sort the contents of the array using Arrays.sort() method and print the sorted result. It was really simple.

String names[] = {"Wayan", "Made", "Nyoman", "Ketut"};
Arrays.sort(names);
System.out.println("Names = " + Arrays.toString(names));

Next, we will sort an array of our own object. It is a bit different compared to sorting an array of primitives. The first rule is we need our object to implements the Comparable interface. This interface have one contract we need to implement, the compareTo() contract.

The basic rule of the compareTo() method is to return 0 when objects value are equals, 1 if this object value is greater and -1 if this object value is smaller. In the Person class below we simply call the String object compareTo() method. See the Person class below for more details.

package org.kodejava.example.util.support;

public class Person implements Comparable {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public int compareTo(Object o) {
        Person p = (Person) o;
        return this.name.compareTo(p.name);
    }

    public String toString() {
        return name;
    }
}

In the snippet below we create four Person objects. We sort the Person object based on their name using the Arrays.sort() method and print out the array values.

Person persons[] = new Person[4];
persons[0] = new Person("Wayan");
persons[1] = new Person("Made");
persons[2] = new Person("Nyoman");
persons[3] = new Person("Ketut");
Arrays.sort(persons);
System.out.println("Persons = " + Arrays.toString(persons));

This is the main class where you can run all the snippet above:

package org.kodejava.example.util;

import org.kodejava.example.util.support.Person;

import java.util.Arrays;

public class ObjectSortExample {
    public static void main(String[] args) {
        String names[] = {"Wayan", "Made", "Nyoman", "Ketut"};
        Arrays.sort(names);
        System.out.println("Names = " + Arrays.toString(names));

        Person persons[] = new Person[4];
        persons[0] = new Person("Wayan");
        persons[1] = new Person("Made");
        persons[2] = new Person("Nyoman");
        persons[3] = new Person("Ketut");
        Arrays.sort(persons);
        System.out.println("Persons = " + Arrays.toString(persons));
    }
}

This snippet will print the following output:

Names = [Ketut, Made, Nyoman, Wayan]
Persons = [Ketut, Made, Nyoman, Wayan]

How do I search specific value in an array?

package org.kodejava.example.util;

import java.util.Arrays;

public class ArraySearchExample {
    public static void main(String[] args) {
        // We create an array of ints where the search will be done.
        int items[] = {9, 5, 14, 6, 11, 28, 9, 16, 37, 3, 2};

        // The Arrays.binarySearch() require us to sort the array
        // items before we call the method. We can utilize the
        // Arrays.sort() method to do this. If we did not sort the
        // array the result will be undefined, the search process
        // will return a negative result.
        Arrays.sort(items);

        // To search we use Arrays.binarySearch() methods which accept
        // parameters of any array type. To search we passed the array
        // to be searched and the key to be searched for.
        //
        // When the search item exist more than one in the array, this
        // method gives no guarantee which one will be returned.
        int needle = 9;
        int index = Arrays.binarySearch(items, needle);

        // Print out where the 9 number is located in the array.
        System.out.println("Items: " + Arrays.toString(items));
        System.out.println("Item " + needle + " is at index " + index);
    }
}

There result of the code snippet:

Items: [2, 3, 5, 6, 9, 9, 11, 14, 16, 28, 37]
Item 9 is at index 5

How do I sort elements of an array?

package org.kodejava.example.util;

import java.util.Arrays;

public class ArraySortExample {
    public static void main(String[] args) {
        // An array of random numbers
        int numbers[] = {3, 1, 8, 34, 1, 2, 13, 89, 5, 21, 55};
        System.out.println("Before: " + Arrays.toString(numbers));

        // We need to sort these array elements into a correct order
        // from the smallest to the greatest. We will use the Arrays
        // class on java.utils package to do the sort. The sort
        // method of this class are overloaded, so they can take
        // other type of array as well such as byte[], long[],
        // float[], Object[].
        Arrays.sort(numbers);
        System.out.println("After : " + Arrays.toString(numbers));

        // We can also do the sort only for the specified range of
        // array elements.
        float money[] = {1.05f, 99.8f, 3f, 4.55f, 7.23f, 6.50f};
        Arrays.sort(money, 3, money.length);

        // Here we display the sort result, the first and the second
        // element of the array is not included in the sort process.
        System.out.println("Money : " + Arrays.toString(money));
    }
}

And here are the results:

Before: [3, 1, 8, 34, 1, 2, 13, 89, 5, 21, 55]
After : [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Money : [1.05, 99.8, 3.0, 4.55, 6.5, 7.23]

How do I convert an array into a collection object?

To convert array based data into List / Collection based we can use java.util.Arrays class. This class provide a static method asList(T... a) that converts array into List / Collection.

package org.kodejava.example.util;

import java.util.Arrays;
import java.util.List;

public class ArraysExample {
    public static void main(String[] args) {
        String[] words = {"Happy", "New", "Year", "2006"};
        List<String> list = Arrays.asList(words);

        for (String word : list) {
            System.out.println(word);
        }
    }
}

The results of our code are:

Happy
New
Year
2006

How do I compare if two arrays are equal?

Using Arrays.equals() methods we can compare if two arrays are equal. Two arrays are considered to be equal if their length, each element in both arrays are equal and in the same order to one another.

package org.kodejava.example.util;

import java.util.Arrays;

public class CompareArrayExample {
    public static void main(String[] args) {
        String[] abc = {"Kode", "Java", "Dot", "Org"};
        String[] xyz = {"Kode", "Java", "Dot", "Org"};
        String[] java = {"Java", "Dot", "Com"};

        System.out.println(Arrays.equals(abc, xyz));
        System.out.println(Arrays.equals(abc, java));
    }
}

The Arrays.equals() can be used to compare array of any primitive data type and array of Object. If you run this example you will have a result as follow:

true
false

How do I create a repeated sequence of character?

This example show you how to create a repeated sequence of characters. To do this we use the Arrays.fill() method. This method fills an array of char with a character.

package org.kodejava.example.util;

import java.util.Arrays;

public class RepeatCharacterExample {
    public static void main(String[] args) {
        char c = 'x';
        int length = 10;

        // creates char array with 10 elements
        char[] chars = new char[length];

        // fill each element of chars array with 'x'
        Arrays.fill(chars, c);

        // print out the repeated 'x'
        System.out.println(String.valueOf(chars));
    }
}

As the result you get the x character repeated 10 times.

xxxxxxxxxx

How do I use ArrayList class?

In this example we will learn how to use the java.util.ArrayList class. An ArrayList is part of the Java Collection Framework. By using this class we can create a dynamic size array of data, which means we can add or remove elements from the array dynamically.

In the code below we will see the demonstration on how to create an instance of ArrayList, add some elements, remove elements and iterate through the entire ArrayList elements either using a for-loop or using the for-each syntax.

We can also see how to convert the ArrayList into an array object using the toArray() method. And we use the Arrays.toString() utility method when we want to print the content of an array.

When creating a class instance it is a good practice to use the interface as the type of variable instead of the concrete type directly. This can make us easily update our code if we don’t want to use ArrayList anymore sometime in the future.

And here is the code snippet:

package org.kodejava.example.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayListExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        // Add items into ArrayList
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");

        // Remove the third item from ArrayList, first index = 0
        list.remove(2);

        // Iterate ArrayList item using for loop statement
        for (int i = 0; i < list.size(); i++) {
            String item = list.get(i);
            System.out.println("Item = " + item);
        }

        // Iterate ArrayList item using for-each statement
        for (String item : list) {
            System.out.println("Item = " + item);
        }

        // Convert ArrayList into array of object
        String[] array = list.toArray(new String[list.size()]);
        System.out.println("Items = " + Arrays.toString(array));
    }
}

Executing the program will give us the following output printed in our console.

Item = Item 1
Item = Item 2
Item = Item 1
Item = Item 2
Items = [Item 1, Item 2]