javaScriptIsTheSameAsJava = false; Part 3: Arrays
In the first entry of this series, we began by taking a look at the structure of a basic output task, declaration and assignment of variables, and mathematic operations. In the second entry, we discussed value comparison and conditionals. In this entry, we’ll take a look at how arrays are created and modified in Java and JavaScript.
Array Creation and Terminology
Let’s begin with the various options for creating a new array in both languages:
In JavaScript:
newArray.js
--------------------
// Method 1 of Array Declaration
let emptyArrayOne = [];
let filledArrayOne = [1, 2, 3, 4, 5];
let mixedArrayOne = [1, “two”, 3.0, “four”, true];// Method Two of Array Declaration
let emptyArrayTwo = new Array();
let filledArrayTwo = new Array(1, 2, 3, 4, 5);
let mixedArrayTwo = new Array(1, “two”, 3.0, “four”, true)
In Java:
NewArray.java
--------------------
public class NewArray {
public static void main(String[] args) {
// Method 1 of Array Declaration
int[] emptyArrayOne = {};
int[] filledArrayOne = {1, 2, 3, 4, 5};
// Array of mixed data types not possible // Method 2 of Array Declaration
int[] emptyArrayTwo = new int[0];
int[] filledArrayTwo = new int[5];
filledArrayTwo[0] = 1;
filledArrayTwo[1] = 2;
filledArrayTwo[2] = 3;
filledArrayTwo[3] = 4;
filledArrayTwo[4] = 5;
// Array of mixed data types not possible
}
}
Notice the differences in the above example:
First and foremost, in JavaScript, arrays can contain elements of differing data types. This is not the case in Java. Arrays of mixed data types are not allowed.
Secondly, when utilizing the second method above in Java, the length of the array must be set. This is because in Java, an array’s size cannot be changed after it’s declared, so Java must know what the size of the array is upon initial declaration. In JavaScript, an array’s size can change as it’s modified.
Notice also that JavaScript utilizes []
when declaring the array and its contents. Java utilizes this when the array is initially declared (after the data type of the array’s elements are declared), and when referencing the indices, but not to encapsulate the values if they are set at the same time as the declaration. Instead, {}
are used.
Two terms that work similarly regarding arrays in the two languages are index
and length
. For arrays in both languages, the index
refers to the nth element of the array, and for both languages, the index
count begins at 0, so the first element of each array is at index
0, the second is at index
1 and so on.
In addition, length
refers to the number of elements in a given array and can be accessed in the same way in both languages.
In JavaScript:
newArray.js
--------------------
console.log(emptyArrayOne.length);//=> 0console.log(filledArrayOne.length);//=> 5
In Java:
NewArray.java
--------------------
System.out.println(emptyArrayOne.length);//=> 0System.out.println(filledArrayOne.length);//=> 5
Let’s now try to print out our arrays:
In JavaScript:
newArray.js
--------------------
console.log(emptyArrayOne);console.log(filledArrayOne);console.log(mixedArrayOne);//=> [];//=> [1, 2, 3, 4, 5];//=> [1, “two”, 3.0, “four”, true];
In Java:
NewArray.java
--------------------
System.out.println(emptyArrayOne);System.out.println(filledArrayOne);//=> [I@5a07e868//=> [I@76ed5528
This output seems clear with JavaScript, but what happened in the Java file?
What you see above is a memory address, which doesn’t really give the content of the array.
It IS possible to see the content of our arrays, but it will require the first of two Java packages we’ll be looking at in this blog. The Arrays package
in Java gives us access to a method called toString()
, which we can use to print out the contents of our array:
NewArray.java
--------------------
import java.util.Arrays;public class NewArray {
public static void main(String[] args) {
int[] emptyArrayOne = {};
int[] filledArrayOne = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(emptyArrayOne));
System.out.println(Arrays.toString(filledArrayOne));
}
}//=> []//=> [1, 2, 3, 4, 5]
Changing the Contents of An Array
As mentioned earlier, the length of arrays in Java cannot be changed, so the following methods in JavaScript don’t have a direct equivalent in Java.
modifiedArray.js
--------------------
let arrayToModify = [1, 2, 3, 4, 5]//=> pop() removes the last element of the arrayarrayToModify.pop()
console.log(arrayToModify)//=> [1, 2, 3, 4]//=> shift() removes the first element of the arrayarrayToModify.shift()
console.log(arrayToModify)//=> [2, 3, 4]//=> unshift(value) adds the given value to the front of the arrayarrayToModify.unshift(“new value”)
console.log(arrayToModify)//=> [“new value”, 2, 3, 4]//=> push(value) add the given value to the back of the arrayarrayToModify.push(“end value”)
console.log(arrayToModify)//=> [“new value”, 2, 3, 4, “end value”]//=> splice(indexToStartRemoval, numberOfItemsToRemove, itemsToAdd) uses the passed in variables to modify the arrayarrayToModify.splice(2, 1)
console.log(arrayToModify)//=> [“new value”, 2, 4, “end value”]
However, the individual values of an array in Java can be modified.
ModifiedArray.java
--------------------
import java.util.Arrays;public class ModifiedArray {
public static void main(String[] args) {
int[] arrayToModify = {1, 2, 3, 4, 5};
System.out.println(arrayToModify[2]);
System.out.println(Arrays.toString(arrayToModify); // => 3
//=> [1, 2, 3, 4, 5] arrayToModify[2] = 6;
System.out.println(arrayToModify[2]);
System.out.println(Arrays.toString(arrayToModify); // => 6
//=> [1, 2, 6, 4, 5]
}
}
So while arrays in JavaScript are much more malleable, arrays in Java ensure for consistency in the number of entries of data in the array.
A Note on Array Lists
Given the fact that a major difference between the basic type of arrays in JavaScript and Java is this component of the arrays in Java not being malleable length-wise, the concept of ArrayLists
should be mentioned.
ArrayLists
are utilized for listing items in a collection that can have their length modified. It also requires a Java package. Let’s see how this works with our previous example.
NewArrayList.java
--------------------import java.util.ArrayList;public class NewArrayList {
public static void main(String[] args) {
ArrayList<Integer> myArrayList = new ArrayList<Integer>();
System.out.println(myArrayList);
//=> [] myArrayList.add(1);
System.out.println(myArrayList);
//=> [1] myArrayList.add(2);
System.out.println(myArrayList);
//=> [1, 2] myArrayList.add(3);
System.out.println(myArrayList);
//=> [1, 2, 3] System.out.println(myArrayList.size())
//=> 3 System.out.println(myArrayList.get(1));
//=> 2 myArrayList.set(0, 5);
System.out.println(myArrayList);
//=> [5, 2, 3] myArrayList.remove(1);
System.out.println(myArrayList);
//=> [5, 3]
}
}
To declare a new ArrayList
, you’ll have to declare the data type in angle brackets <>
. However, the data has to be declared as what’s known as a generic, which is why you see <Integer>
instead of int
in the above example.
Here are some operations to be aware of with ArrayLists
:
add(value)
— adds the specified value to the end of the ArrayList
size()
— gives the length
of the ArrayList
get(index)
— gives the value at the given index
of the ArrayList
set(index, newValue)
— sets the value at the given index
of the ArrayList
to newValue
remove(index)
— removes the item at the specified index
Happy coding in whatever language you use!