It depends on your definition of the dangling pointer.
If you take the Wikipedia definition for a dangling pointer, then no, you cannot have it in Java. Since the language is garbage collection, a link always points to a valid object, unless you explicitly assign the link "null" to the link.
However, you might consider a more semantic version of a dangling pointer. "Semantic chatty link" if you want. Using this definition, you are referring to a physically valid object, but semantically the object is no longer valid.
String source = "my string"; String copy = source; if (true == true) { // Invalidate the data, because why not source = null; // We forgot to set 'copy' to null! } // Only print data if it hasn't been invalidated if (copy) { System.out.println("Result: " + copy) }
In this example, "copy" is a physically valid object reference, but semantically it is a chatty reference, since we wanted to set it to null, but forgot. As a result, code using the "copy" variable will execute without problems, even if we want to make it invalid.
source share