Arrays in Squirrel
Our first example demonstrates the use of arrays in Java. In Java, an array is a fixed-size container that holds elements of the same type. Unlike some other languages, Java arrays have a fixed length that is set when the array is created.
public class ArraysExample {
public static void main(String[] args) {
// Here we create an array 'a' that will hold exactly 5 integers.
// By default, an array is initialized with zeros for numeric types.
int[] a = new int[5];
System.out.println("emp: " + java.util.Arrays.toString(a));
// We can set a value at an index using the array[index] = value syntax,
// and get a value with array[index].
a[4] = 100;
System.out.println("set: " + java.util.Arrays.toString(a));
System.out.println("get: " + a[4]);
// The length property returns the length of an array.
System.out.println("len: " + a.length);
// Use this syntax to declare and initialize an array in one line.
int[] b = {1, 2, 3, 4, 5};
System.out.println("dcl: " + java.util.Arrays.toString(b));
// In Java, we don't have the '...' syntax for array initialization.
// Instead, we can use the Arrays.copyOf method to create a new array
// with the same elements.
b = java.util.Arrays.copyOf(new int[]{1, 2, 3, 4, 5}, 5);
System.out.println("cpy: " + java.util.Arrays.toString(b));
// Java doesn't have a direct equivalent to Go's index-based initialization.
// We can achieve a similar result by creating an array and then setting values.
b = new int[5];
b[0] = 100;
b[3] = 400;
b[4] = 500;
System.out.println("idx: " + java.util.Arrays.toString(b));
// Array types are one-dimensional, but you can create multi-dimensional arrays.
int[][] twoD = new int[2][3];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
twoD[i][j] = i + j;
}
}
System.out.println("2d: " + java.util.Arrays.deepToString(twoD));
// You can create and initialize multi-dimensional arrays at once too.
twoD = new int[][]{
{1, 2, 3},
{1, 2, 3}
};
System.out.println("2d: " + java.util.Arrays.deepToString(twoD));
}
}
Note that arrays in Java are printed using Arrays.toString()
for one-dimensional arrays and Arrays.deepToString()
for multi-dimensional arrays.
When you run this program, you should see output similar to this:
emp: [0, 0, 0, 0, 0]
set: [0, 0, 0, 0, 100]
get: 100
len: 5
dcl: [1, 2, 3, 4, 5]
cpy: [1, 2, 3, 4, 5]
idx: [100, 0, 0, 400, 500]
2d: [[0, 1, 2], [1, 2, 3]]
2d: [[1, 2, 3], [1, 2, 3]]
This example demonstrates the basics of working with arrays in Java, including creation, initialization, accessing elements, and working with multi-dimensional arrays. Remember that Java arrays have a fixed size once created, which is different from some other languages that allow dynamic resizing.