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.

1. 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" });

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

No, Arrays are objects in Java.

3. Arrays.asList(arrayIdentifier)

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.

4. 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));      

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

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

6. 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 javapedia.net ,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) {
	System.out.println(element);
}

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 };

System.out.println(Arrays.toString(intArray));

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

System.out.println(Arrays.deepToString(byteArray));

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

7. 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:");
 System.out.println(Arrays.deepToString(ob));

Output:

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

8. 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.

9. 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).

10. Which algorithm does Arrays.sort use in Java?

Arrays.sort implementation uses merge sort or tim sort.

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

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

12. On which memory arrays are created in Java?

Arrays are created on dynamic memory by JVM.

13. Can we declare array size as negative?

No, it is not possible to declare array size as negative. We won't get any compile-time error however we will encounter NegativeArraySizeException at run-time.

14. Difference between int array[] and int[] array.

There is no difference between array[] and []array. Both array[] and []array are the ways to declare an array. The only difference between them is that if we are declaring more than one array in a line, we should use prefix []. If we are declaring a single array in a line, we should use postfix []. For example, consider the following declaration

int array1[], var1;   //array1[] is an array while var1 is just a variable of type int  
int[] arr1, arr2;  //both arr1 and arr2 are arrays of int type  

15. The default value of the array in Java.

When we create a new array, it is always initialized with the default values. The default values of the array are:

Array data-typeDefault value
byte, short, int, and long0
float and double0
Booleanfalse
Object null

16. Define jagged array.

A jagged array is a multidimensional array in which member arrays are of different sizes. For example, int array[][]=new int[3][]. The statement creates a two-dimensional jagged array.

17. How to copy an array in Java?

We can create a copy of an array in two ways, the first one is manually by iterating over the array and the second one is by using the arrayCopy() method. Using the arrayCopy() method of the System class is the fastest way to copy an array and also allows us to copy a part of the array.

You may also copy array by using the Arrays.copyOf() method and using clone() method.

18. Is it possible to make an array volatile?

Yes, we can make an array volatile in Java. But we only make the variable that is pointing to array volatile. If an array is changed by replacing individual elements that happen before the guarantee provided by volatile variables will not hold.

19. When ArrayIndexOutOfBoundsException occurs?

The ArrayIndexOutOfBoundsException occurs when the program tries to access the index of an array. The exception also occurs when the index is higher than the size of the array or the index is negative.

20. How to check an array contains values or not?

Java Arrays class provides two methods isExists() and contains() to check an array has elements or not. Both the methods return true if an array has elements else returns false.

«
»
Strings

Comments & Discussions