Prev Next

Java / Arrays

Could not find what you were looking for? send us the question and we would be happy to answer your question.

How do I initialize a String array?

String myFruits[];
myFruits = new String[] { "Apple", "Pineapple", "Strawberry"  };

or just in one line,

String myFruits[] = new String[] { "Apple", "Pineapple", "Strawberry"  };

more simpler,

String[] myFruits = { "Apple", "Pineapple", "Strawberry" };

when passing as an argument to a method,

methodName(new String[] { "Apple", "Pineapple", "Strawberry" });

Is arrays are considered as primitive data types?
Posted on Apr 1, 2016 by Senthil Kumar.

No, Arrays are objects in Java.


asList method takes an array/vararg argument and returns a fixed-size list backed by the specified array. Any modification or overwrite applied on the list will reflect on the original array and like wise.

Remember that asList is fixed size so we can not add/remove new elements to the List.

Rearranging the elements in array or the list reflects in both.

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

public class ArraysAsListExample {

	public static void main(String[] args) {
		String[] myFruits = { "Apple", "Pineapple", "Strawberry" };

		System.out.println("The fruits available in my original Array:");

		for (String fruit : myFruits) {
			System.out.println("* " + fruit);

		List<String> fruitList = Arrays.asList(myFruits);
		System.out.println("The fruits in my fixed size List:");
		for (String fruit : fruitList) {
			System.out.println("* " + fruit);

		// The below lines (add and remove operation) will throw runtime
		// Exception (java.lang.UnsupportedOperationException) on the fixed
		// length list. so commented the line.
		// fruitList.add("Cherry");
		// fruitList.remove(2);

		// overwriting Apple with Cherry through the List which will be
		// reflected in the original Array.
		fruitList.set(0, "Cherry");
		// overwriting Pineapple with Banana through the original Array which
		// will be reflected in the list.
		myFruits[1] = "Banana";

		System.out.println("The fruits available in my original Array:");
		for (String fruit : myFruits) {
			System.out.println("* " + fruit);

		System.out.println("The fruits in my fixed size List:");
		for (String fruit : fruitList) {
			System.out.println("* " + fruit);

Note that asList produces unexpected results with primitive arrays since List does not support primitive datatypes and it does not get autoboxed to its corresponding wrapper class.

How do I create a list from Array which is completely independent of the original array?

The fixed length list returned by asList method is used as an argument to create a new ArrayList which is later garbage collected.

The new ArrayList is independent of the original array and the changes to the list does not reflect on the array and vice versa.

Adding/removing elements could be performed in this list.

String[] myFruits1 = { "Apple", "Pineapple", "Strawberry" };
List<String> myFruitsList = new ArrayList<String>(Arrays.asList(myFruits1));      

What is the index of the first element in an array?

The index value of the first element is 0 in an Array.

How do you print the content of an array in Java?

In Java, arrays do not override toString() method, so the content cannot be printed just by specifying the array reference as illustrated below.

int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(intArray);     // prints something like '[I@1732a4df'
char[] charArray = new char[] {'J', 'a', 'v', 'a', 'p','e','d','i','a','.','n','e','t'};
System.out.println(charArray);     // prints ,wow

One of the approach is that iterating through all the array elements, retrieve each element and print it to the console as shown below.

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

for (int element : intArray) {

Since Java 5, we have inbuilt API Arrays.toString(arr) and Arrays.deepToString(arr) to print the contents of the single dimensional array.

The difference between Arrays.toString and Arrays.deepToString is that Arrays.toString accepts primitive type arrays as well as object arrays where as deepToString accepts only object arrays.

The below example shows how to use the Arrays API to print the content of an array.

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


Byte[] byteArray = new Byte[] { 1, 2, 3, 4, 5 };


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

How do you print the content of a multi dimensional array in Java?

java.util.Arrays.deepToString(Object[]) method returns a string representation of the content of the single (or) multi dimensioned array.

The below example illustrates how the deepToString method could be used to print the content of a multi dimensional array.

// initializing an object array
 Object[][] ob={{"Welcome "," to "}, {"javapedia", ".net"}};
 System.out.println("The string content of array is:");


The string representation of array is:
[[Welcome ,  to ], [javapedia, .net]]

Why is it a good practice to store sensitive information like password, SSN into a character Array rather than String?

The String objects are immutable and are stored in String pool in memory until garbage collected. So Although a string object is processed and no longer required, for an indeterminate period of time the string object remains in the memory until garbage collected. Even this can not be controlled programmatically. By accessing the memory dump, the hackers could extract sensitive information from the string object hence String is insecure.

Character Array is a mutable object, and when it is no longer required, nullifying the reference guarantees that the object in memory cannot be accessed until garbage collected. Hence character array is prefered for storing sensitive information.

What is the tradeoff between using an unordered array versus an ordered array?

The major advantage of an ordered array is that the search times have time complexity of O(log n), compared to that of an unordered array, which is O (n). The disadvantage of an ordered array is that the insertion operation has a time complexity of O(n), because the elements with higher values must be moved to make room for the new element. Instead, the insertion operation for an unordered array takes constant time of O(1).

Which algorithm does Arrays.sort use in Java?

Arrays.sort implementation uses merge sort or tim sort.

Difference between Arrays.sort and Arrays.parallelSort in Java 8.

Arrays.parallelSort is introduced in Java 1.8 and uses multi threading.


Comments & Discussions