How do I convert varargs to an array?

Varargs can be seen as a simplification of array when we need to pass a multiple value as a method parameter. Varargs itself is an array that automatically created, for these reason you will be enabled to do things you can do with array to varargs.

In the example below you can see the messages parameter can be assigned to the String array variables, we can call the length method to the messages parameter as we do with the array. So actually you don’t need to convert varargs to array because varargs is array.

package org.kodejava.lang;

public class VarargsToArray {
    public static void main(String[] args) {
        printMessage("Hello ", "there", ", ", "how ", "are ", "you", "?");
    }

    public static void printMessage(String... messages) {
        String[] copiedMessage = messages;
        for (int i = 0; i < messages.length; i++) {
            System.out.print(copiedMessage[i]);
        }
    }
}

How do I create a method that accept varargs in Java?

Varargs (variable arguments) is a new feature in Java 1.5 which allows us to pass multiple values in a single variable name when calling a method. Of course, it can be done easily using array but the varargs add another power to the language.

The varargs can be created by using three periods (...) after the parameter type. If a method accept others parameter than the varargs, the varargs parameter should be the last parameter to the method. And please be aware that overloading a varargs method can make harder to figure out which method is called in the code.

package org.kodejava.lang;

import java.util.Arrays;

public class VarArgsExample {
    public static void main(String[] args) {
        VarArgsExample e = new VarArgsExample();
        e.printParams(1, 2, 3);
        e.printParams(10, 20, 30, 40, 50);
        e.printParams(100, 200, 300, 400, 500);
    }

    public void printParams(int... numbers) {
        System.out.println(Arrays.toString(numbers));
    }
}

Running the code snippet give you the following output:

[1, 2, 3]
[10, 20, 30, 40, 50]
[100, 200, 300, 400, 500]

How do I copy char array to string?

package org.kodejava.lang;

public class CharArrayCopyExample {
    public static void main(String[] args) {
        char[] data = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};

        // Copy all value in the char array and create a new string out of it.
        String text = String.valueOf(data);
        System.out.println(text);

        // Copy a sub array from the char array and create a new string. The
        // following line will just copy 5 characters starting from array index
        // of 3. If the element copied is outside the array index an
        // IndexOutOfBoundsException will be thrown.
        text = String.copyValueOf(data, 3, 5);
        System.out.println(text);
    }
}

The result:

abcdefghij
defgh

How do I shuffle elements of an array?

package org.kodejava.util;

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

public class ArrayShuffle {
    public static void main(String[] args) {
        // Initialize the contents of our array
        String[] alphabets = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};

        // As the Collections.shuffle() method need a list for the parameter
        // we convert our array into List using the Arrays class.
        List<String> list = Arrays.asList(alphabets);

        // Here we just simply used the shuffle method of Collections class
        // to shuffle out defined array.
        Collections.shuffle(list);

        // Run the code again and again, then you'll see how simple we do
        // shuffling
        for (String alpha : list) {
            System.out.print(alpha + " ");
        }
    }
}

An example of the generated results are:

F H E A B I G J D C  

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.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<>();
        names.add("Musk");
        names.add("Nakamoto");
        names.add("Einstein");

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

The result of the code snippet:

Number: 10
Number: 100
Number: 1000
Number: 10000
Number: 100000
Number: 1000000
Name: Musk
Name: Nakamoto
Name: Einstein