Arrays and Strings in Java


"This is a string\n";

"This\tis\ta\tstring\twith\tlots\tof\ttabs\tin\tit\n";

"The + sign " + "conctenates two strings\n";

Arrays and Objects

Arrays are non-primitive types. Objects and arrays are passed into methods by reference and primitive types are passed by value. This means that an int type would actually pass its value whereas an object or an array would be passed using its memory address reference only. The whole object or array is not passed into a method. Thus both objects and arrays are referred to as reference data types since they refer to something. Reference data types point to something which contains the actual literal values. Obviously those literal values would be primitive types. Like objects, arrays are automatically garbage collected by Java.

Two steps to using arrays involve declaration and allocation. Thus arrays are declared as being of a particular type. Then space is allocated for those array elements.

int arrayOfIntegers[] = new int[10]; (Dynamically declares an array of 10 integers)
int listOfNumbers[] = { 10, 5, 42, 34, 32 }; (Static array declaration)

The Java compiler automatically creates memory space for arrays. Memory leakage is a common source of bugs in C. This is one of the Java restrictions which helps to limit potential bugs. The first element of an array is indexed as 0.

listOfNumbers[0] = 10;
listOfNumbers[1] = 5;

Multi-dimensional arrays are also possible. The three dimensional array below contains 10 arrays of 5 arrays of 2 integers.

int float3D[][][] = new int [10][5][2];

Java will also allow triangular arrays, ie. arrays of different sizes.

int mixedArray[][] =
{
	{ 1, 2, 3, 4, 5 },
	{ 1, 2 },
	{ 1, 2, 3, 4, 5, 6, 7 }
};

Arrays elements can be accessed using any valid integer expression. Java will throw an ArrayOutOfBoundsException if a subscript is too low or high for the number of elements in an array. The number of elements for an array can be found using the length method.

for ( int i = 0; i < intArray.length; i++ ) { ... }

Strings

Strings are implemented using the Strings class in the java.lang package. Thus strings are not null terminated character arrays as they are in C.

Convert integers to strings using the valueOf method. Booleans, characters, integers and floating-point numbers can be converted using the valueOf method.

String outputLine = new String ( String.valueOf ( 12335 ) );
System.out.println ( outputLine );

Note that there is no way to change the contents of a string once it is initialised. Strings are immutable. Changeable strings require the StringBuffer class. Bounds checking takes place at runtime as with arrays. Exceptions are thrown if the bounds of the StringBuffer are exceeded.

Strings can be initialised using double quotes and concatenated using the + operator.

String String1 = "This is a string";
String String2 = "This is " + "another string";