Java does not have explicit pointers; in a sense, all variables that refer to objects are pointers. When you assign between two objects of the same type, you actually assign a reference to the object on the right-hand side. To create a new instance of an object, you need to call one of its constructors:
myObject a, b;
a = b; // reference
a = new myObject(b); // create a new object
In Java, the + operator can concatenate strings together. A sequence such as the following
is legal. Because the original String that greeting points to cannot be modified, the concatenation actually involves the creation of a new String, which greeting is then set to point to. Therefore, the reference to the original "Hello" string is removed, which eventually causes it to be destroyed.
The concatenation statement also involves some more behind-the-scenes magic by the compiler. It creates a temporary StringBuffer, then calls the StringBuffer.append() method for each expression separated by a + sign, then calls StringBuffer.toString() to convert it back to the result String. As with the automatic creation of String objects from constant strings, this is a special case on the part of Java, but is there because string concatenation is so useful.
Arrays can also hold objects, so you can declare the following:
MyObject[] objarray;
This would then be created as follows (this could be combined with the declaration):
objarray = new MyObject[ 5 ];It is important to note that this creates only the array. You still need to create the five objects:
for (k = 0 ; k < 5 ; k ++ ) {
objarray[k] = new MyObject();
}
To create subarrays, create an array where each element is an array. The first array can be declared and created in one step
int [][] bigArray = new int [ 6 ][];and then each subarray needs to be created (each one can be a different length, in fact):
for (m = 0 ; m < 6 ; m ++ ) {You can initialize arrays when they are declared:
bigArray[m] = new int[20];
}
short [][] shortArray = { { 1, 2, 3 }, { 4 }, { 5 , 6 } } ;
After that, shortArray[0] would be an array of three elements,
shortArray[1] would be an array of one element,
and shortArray[2] would be an array of two elements.