Search this site

 Home  Howto index  Getting started with Java  Java for C programmers  Java for BASIC programmers

From C to Java: an introduction to Java for C programmers

(Continued from our introduction to Java for C programmers.)

Look, no pointers!

In C, it is common to refer to structures by pointer to avoid passing a copy of the entire structure, and to allow modifications made to the structure to be seen by the caller. In some cases, a pointer is useful simply to manipulate "raw memory". And in C, arrays are effectively pointers to an area of memory assumed to have space for a given number of elements (with infamous consequences when this assumption is not correct).

Java doesn't have pointers, strictly speaking. However, in Java, all objects are accessed and passed by reference. Arrays are also objects in Java. A reference to an object shares some similarities with a pointer in C. But:

  • A Java reference must refer to an object of its given type, or else be null. There is no other possibility.
  • Java object references cannot be manipulated in any other way, except to assign or read which object that reference refers to, and to access fields and methods of that object.
  • Java object references are not memory addresses, and you can't treat them as such.

It is therefore not possible in Java to assign some random value to a pointer and "pretend" that it points to a data structure, as it is in C. Nor is it possible to perform arithmetic on object references (whereas in C, you can, for example, do ptr++, which will advance the pointer's value by the number of bytes occupied by the variable type to which ptr is declared to point). Java basically does not provide a means to access memory directly without plugging in native code1.

Pointers are sometimes used to pass a buffer that will be filled by some function. This is especially useful when a function needs to effectively return more than one value. A common situation is that the return value is used as an error condition, whilst a buffer passed in is filled with the actual value. In Java, this situation actually arises less often because, as we'll see on the next page, error handling is managed differently. But when necessary, the nearest equivalent is to pass an array for the method to fill.

On the next page, we look at differences in error handling between Java and C.

1. The Java Native Interface framework provides a means to write plugin methods to Java in native code, such as a Windows DLL. JNI provides a means to create a Java ByteBuffer object which wraps round a particular portion of memory. Thus to a limited extent, accessing memory directly from Java is actually possible. From within Java itself, it is also possible to create a ByteBuffer that accesses "raw" memory, but allocated at some arbitrary memory location.

comments powered by Disqus

Written by Neil Coffey. Copyright © Javamex UK 2012. All rights reserved.