In this Tutorial, we will Discuss the Java Arrays with Different Data Types of Elements with Examples:
In our previous tutorials, we discussed that array is a collection of elements of the same data type in a contiguous fashion. You can have array declared with most of the primitive data types and use them in your program.
Some arrays like character arrays or string arrays behave little differently than the rest of the data types. In this tutorial, we will walk you through arrays with different data types and discuss their usage in Java programs by giving examples.
=> Visit Here To Learn Java From Scratch.
Table of Contents:
Java Array Data Types
Integer Array
You can use an array with elements of the numeric data type. The most common one is the integer data type (int array in Java).
The following program illustrates the usage of the array with the int data type.
import java.util.*; public class Main { public static void main(String[] args) { int[] oddArray = {1,3,5,7,9}; //array of integers System.out.println("Array of odd elements:" + Arrays.toString(oddArray)); int[] intArray = new int[10]; for(int i=0;i<10;i++){ //assign values to array intArray[i] = i+2; } System.out.println("Array of Integer elements:" + Arrays.toString(intArray)); } }
Output:
The above program defines an array with initial values and another array in which the values are assigned in a For Loop.
Java Double Array
An array having elements of type double is another numeric array.
The example given below demonstrates the double array in Java.
import java.util.*; public class Main { public static void main(String[] args) { double[] d_Array = new double[10]; //array of doubles for(int i=0;i<10;i++){ d_Array[i] = i+1.0; //assign values to double array } //print the array System.out.println("Array of double elements:" + Arrays.toString(d_Array)); } }
Output:
In the above program, we initialize the double array through for loop and display its contents.
Byte Array
A byte in Java is the binary data having a 8-bit size. The byte array consists of elements of type ‘byte’ and is mostly used to store binary data.
The shortcoming of byte array is that you should always load the byte data into the memory. Though you should refrain from converting byte data, it might become necessary sometimes to convert the byte data to string and vice-versa.
The below example program shows a byte array that is converted to a string using a string constructor.
import java.util.*; public class Main { public static void main(String[] args) { byte[] bytes = "Hello World!!".getBytes(); //initialize the bytes array //Convert byte[] to String String s = new String(bytes); System.out.println(s); } }
Output:
The above program defines a byte array and then passes it on to the String constructor to convert it to String.
You can also convert byte array to string using Base64 encoding method available from Java 8 onwards. The program is left to the readers for implementation.
Boolean Array
Boolean array in Java only stores Boolean type values i.e. either true or false. The default value stored in the Boolean array is ‘false’.
Suggested reading =>> What is a Boolean in Java
Given below is an example of a Boolean array.
import java.util.*; public class Main { public static void main(String args[]) { //declare and allocate memory boolean bool_array[] = new boolean[5]; //assign values to first 4 elements bool_array[0] = true; bool_array[1] = false; bool_array[2] = true; bool_array[3] = false; //print the array System.out.println("Java boolean Array Example:" + Arrays.toString(bool_array)); } }
Output:
Note that in the above program only the first four elements are assigned explicit values. When the array is printed, the last element has default value false.
Character Array
Character arrays or Char arrays in Java contain single characters as its elements. Character arrays act as character buffers and can easily be altered, unlike Strings. Character arrays do not need allocations and are faster and efficient.
The program below shows the implementation of the character array.
import java.util.*; public class Main { public static void main(String[] args) { char[] vowel_Array = {'a', 'e', 'i', 'o', 'u'}; //character array of vowels System.out.println("Character array containing vowels:"); //print the array for (int i=0; i<vowel_Array.length; i++) { System.out.print(vowel_Array[i] + " "); } }
Output:
The above program declares a character array consisting of English vowels. These vowels are then printed by iterating the character array using for loop.
Java Array Of Strings
A string in Java is a sequence of characters. For example, “hello” is a string in Java. An array of a string is a collection of strings. When the array of strings is not initialized or assigned values, the default is null.
The following program exhibits the usage of an array of strings in Java.
import java.util.*; public class Main { public static void main(String[] args) { String[] num_Array = {"one", "two", "three", "four", "five"}; //string array System.out.println("String array with number names:"); System.out.print(Arrays.toString(num_Array)); } }
Output:
In the above code, we have a string array consisting of number names till five. Then using the Arrays class, we have printed the string array with the toString method.
You can also use enhanced for loop (for-each) or for loop to iterate through the array of strings.
Empty Array In Java
You can have empty arrays in Java i.e. you can define an array in Java with 0 as dimension.
Consider the following array declarations.
int[] myArray = new int[]; //compiler error
int[] intArray = new int[0]; //compiles fine
The difference between the above array declarations is that the first declaration has not specified any dimension. Such a declaration will not compile.
The second declaration, however, declares an array with dimension as 0 i.e. this array cannot store any elements in it. This declaration will compile fine. The second declaration is for the empty array. Empty array is basically an array with 0 dimensions so that no elements are stored in this array.
Then, why do we need empty arrays in our programs? One use is when you are passing an array between functions and you have a certain case when you don’t want to pass any array parameters. Thus instead of assigning null values to array parameters, you could just pass an empty array directly.
The example given below demonstrates the use of an empty array.
import java.util.*; public class Main { public static String appendMessage(String msg, String[] msg_params) { for ( int i = 0; i <msg_params.length; i++ ) { //appends the incoming message with array parameters int index = msg.indexOf("{" + i + "}"); while ( index != -1 ) { msg = (new StringBuffer(msg)).replace(index, index+3, msg_params[i]).toString(); index = msg.indexOf("{" + i + "}"); } } return msg; } public static void main(String[] args) throws Exception { String[] msgParam_1 = {"Java"}; //empty array String[] msgParam_2 = new String[0]; System.out.println(appendMessage("Learn {0}!", msgParam_1)); //pass empty array System.out.println(appendMessage("Start Programming", msgParam_2)); } }
Output:
In the above program, you can see that there are two calls made to function ‘appendMessage’. In the first call, an array having one element is passed. In the second call, there is no need to pass an array but as the prototype of the function demands the second parameter, an empty array is passed.
Frequently Asked Questions
Q #1) What is a Primitive Array in Java?
Answer: Arrays having Primitive or built-in Data Types of elements are primitive arrays. An array can be declared as either having elements of primitive type or reference type.
Q #2) What is Byte Array in Java?
Answer: An array consisting of elements of type byte is the byte array. A byte is 8 bit in size and is usually used to represent binary data.
Q #3) What is a Boolean Array in Java?
Answer: An array that stores only Boolean type values i.e. true or false. If not explicitly assigned values, the default value of the Boolean array element is false.
Q #4) Is a String a Char Array Java?
Answer: No. The string is a class in Java that holds a sequence of characters. The string is immutable i.e. its contents cannot be changed once defined and it also has its own methods that operate on its contents.
Q #5) What is String [] args?
Answer: In Java, the command line arguments to the program are supplied through args which is a string of array. You can just perform operations on this array just like any other array.
Conclusion
In this tutorial, we learned that the arrays which are contiguous sequences of homogenous elements can be defined for various Java primitive data types as well as reference types. We mainly discussed the arrays of primitive data types and their examples.
We will discuss the array of objects which is a reference type in a separate tutorial.
=> Watch Out The Simple Java Training Series Here.