Arrays:
The first obvious difference is that Java doesn't use the same declaration syntax for arrays as C. In C, the array subscript is part of the declarator, whereas in Java it's part of the type specification:
int[] arr; // Java, arr is null until array object is instantiated
int arr[]; // C, incomplete declaration
Note that, in Java, arr
exists but is null-valued. In C, arr
doesn't exist until a complete declaration appears.
int[][] 2Darr; // Java, arr is null until array object is instantiated
int 2Darr[][]; // Illegal declaration in C; size must be specified for at least
// the outer dimension
Array objects in Java must be instantiated with a new
operation, and it's there that the array size is specified:
int[] arr = new int [10];
int[][] 2Darr = new int[10][20];
If the array is not of a primitive type, each individual array element must be separately instantiated:
String[] strs = new String[10];
for (int i = 0; i < strs.length; i++)
strs[i] = new String("some value");
Array expressions in Java do not have their types "decay" to pointer types like array expressions in C (which is handy, since Java doesn't have pointer types per se); array types in Java are "first class" objects, meaning they retain all their type characteristics in any context. When you pass an array object to a method, the method receives an array object, not a pointer.
Java arrays know how big they are (given by the .length
attribute).
Strings:
Unlike C, Java supplies a distinct String data type. Do not think of Java strings as 0-terminated arrays of char; they are something different.
Java String objects are immutable; you cannot modify the contents of a String object. You can create a new String object from the modified contents of an existing String object. There are also classes like StringBuilder and StringBuffer that allow you to manipulate character data directly and create new String objects.
Hope that helps.