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 convert array into JSON?

In the example below you can see how to convert an array into JSON string. We serialize the array to JSON using the Gson.toJson() method. To deserialize a string of JSON into array we use the Gson.fromJson() method.

package org.kodejava.example.google.gson;

import com.google.gson.Gson;

public class ArrayToJson {
    public static void main(String[] args) {
        int[] numbers = {1, 1, 2, 3, 5, 8, 13};
        String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

        // Create a new instance of Gson
        Gson gson = new Gson();

        // Convert numbers array into JSON string.
        String numbersJson = gson.toJson(numbers);

        // Convert strings array into JSON string
        String daysJson = gson.toJson(days);
        System.out.println("numbersJson = " + numbersJson);
        System.out.println("daysJson = " + daysJson);

        // Convert from JSON string to a primitive array of int.
        int[] fibonacci = gson.fromJson(numbersJson, int[].class);
        for (int number : fibonacci) {
            System.out.print(number + " ");
        }
        System.out.println("");

        // Convert from JSON string to a string array.
        String[] weekDays = gson.fromJson(daysJson, String[].class);
        for (String weekDay : weekDays) {
            System.out.print(weekDay + " ");
        }
        System.out.println("");

        // Converting multidimensional array into JSON
        int[][] data = {{1, 2, 3}, {3, 4, 5}, {4, 5, 6}};
        String json = gson.toJson(data);
        System.out.println("Data = " + json);

        // Convert JSON string into multidimensional array of int.
        int[][] dataMap = gson.fromJson(json, int[][].class);
        for (int[] i : dataMap) {
            for (int j : i) {
                System.out.print(j + " ");
            }
            System.out.println("");
        }
    }
}

Here is our code result:

numbersJson = [1,1,2,3,5,8,13]
daysJson = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
1 1 2 3 5 8 13 
Sun Mon Tue Wed Thu Fri Sat 
Data = [[1,2,3],[3,4,5],[4,5,6]]
1 2 3 
3 4 5 
4 5 6

Maven Dependencies

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.2.2</version>
</dependency>

How do I use for-each in Java?

Using for-each command to iterate arrays or a list can simplified our code. Below is an example how to do it in Java. The first loop is for iterating array and the second for iterating a list containing a some names.

package org.kodejava.example.lang;

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

public class ForEachExample {
    public static void main(String[] args) {
        Integer[] numbers = {10, 100, 1000, 10000, 100000, 1000000};

        for (Integer i : numbers) {
            System.out.println("Number: " + i);
        }

        List<String> names = new ArrayList<String>();
        names.add("James");
        names.add("Joshua");
        names.add("Scott");

        for (String name : names) {
            System.out.println("Name: " + name);
        }
    }
}

How do I know the minimum and maximum number in array?

package org.kodejava.example.util;

import java.util.Arrays;
import java.util.Collections;

public class ArrayMinMax {
    public static void main(String[] args) {
        // Creates an array of integer numbers in it.
        Integer[] numbers = {8, 2, 6, 7, 0, 1, 4, 9, 5, 3};

        // To get the minimum or maximum value from the array we can
        // use the Collections.min() and Collections.max() methods.
        // But as this method requires a list type of data we need
        // to convert the array to list first.
        int min = Collections.min(Arrays.asList(numbers));
        int max = Collections.max(Arrays.asList(numbers));

        // Viola! we get the minimum and the maximum value from the
        // array.
        System.out.println("Min number: " + min);
        System.out.println("Max number: " + max);
    }
}

And here are the results:

Min number: 0
Max number: 9

How do I convert string to char array?

Here we have a small class that convert a string literal into array, a character array.

package org.kodejava.example.lang;

public class StringToArrayExample {
    public static void main(String[] args) {
        // We have a string literal that contains the motto of this website.
        String literal = "Kode Java - Learn Java Programming by Examples";

        // Now we want to convert or divided it into a small array of char.
        // To do this we can simply used String.toCharArray() method. This
        // method splits the string into an array of characters.
        char[] temp = literal.toCharArray();

        // Here we just iterate the char array and print it to our console.
        for (int i = 0; i < temp.length; i++) {
            System.out.print(temp[i]);
        }
    }
}

How do I Convert Array to Collection?

package org.kodejava.example.util;

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

public class ArrayToListExample {
    public static void main(String[] args) {
        // Creates an array of object, in this case we create an
        // Integer array.
        Integer[] numbers = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55};

        // Convert the created array above to collection, in this
        // example we convert it to a List.
        List list = Arrays.asList(numbers);

        // We've got a list of our array here and iterate it.
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i) + ", ");
        }
    }
}

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 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]