In this article, we will take a look at the comparison of Java Pointers (References ) with C++ Pointers. Java has four types of references which are strong, weak, soft, and phantom references. In C++, you can use references and java pointer.
2. Java Pointers (References)
2.1 Prerequisites
Java 8 is required on the Linux, windows or mac operating system. Eclipse Oxygen can be used for this example. Eclipse C++ is necessary on the operating system in which you want to execute the code.
2.2 Download
You can download Java 8 from the Oracle web site . Eclipse Oxygen can be downloaded from the eclipse web site. Eclipse C++ is available at this link.
The ‘eclipse-java-oxygen-2-macosx-cocoa-x86_64.tar’ can be downloaded from the eclipse website. The tar file is opened by double click. The tar file is unzipped by using the archive utility. After unzipping, you will find the eclipse icon in the folder. You can move the eclipse icon from the folder to applications by dragging the icon.
The ‘eclipse-cpp-2019-06-R-macosx-cocoa-x86_64.dmg’ can be downloaded from the eclipse C/C++ website. After installing the application on macos, you will find the eclipse icon in the folder. You can move the eclipse icon from the folder to applications by dragging the icon.
2.5 Launching IDE
2.5.1 Eclipse Java
Eclipse has features related to language support, customization, and extension. You can click on the eclipse icon to launch eclipse. The eclipse screen pops up as shown in the screen shot below:
You can select the workspace from the screen which pops up. The attached image shows how it can be selected.
You can see the eclipse workbench on the screen. The attached screen shot shows the Eclipse project screen. Java Hello World class prints the greetings. The screenshot below is added to show the class and execution on eclipse.
2.5.1 Eclipse C++
C++ code is created to print “Hello World” and executed on Eclipse C++. The screenshot below shows the Hello World in C++ and the printed output.
2.6 What is a reference in Java?
In java, Objects can be modified by references. The properties of the object are references. Sample code is shown for a Location class whose properties are x coordinate xcoord and y coordinate ycoord . Java Reference
/** * */ /** * @author bhagvan.kommadi * */ public class Location < public int xcoord; public int ycoord; public Location(int x, int y) < this.xcoord = x; this.ycoord = y; >public static void setLocations(Location loc1, Location loc2) < loc1.xcoord = 30; loc1.ycoord = 40; Location buf = loc1; loc1 = loc2; loc2 = buf; >/** * @param args */ public static void main(String[] args) < Location loc1 = new Location(20,10); Location loc2 = new Location(10,50); System.out.println("Location 1 X Coordinate: " + loc1.xcoord + " Y Coordinate: " +loc1.ycoord); System.out.println("Location 2 X Coorodinate: " + loc2.xcoord + " Y Coordinate: " +loc2.ycoord); System.out.println(" "); setLocations(loc1,loc2); System.out.println("Location 1 X Coordinate: " + loc1.xcoord + " Y Coordinate: " +loc1.ycoord); System.out.println("Location 2 X Coorodinate: " + loc2.xcoord + " Y Coordinate: " +loc2.ycoord); System.out.println(" "); >>
The Location class has a constructor to set the x and y coordinates. The static method setLocations method which sets the properties of loc1 and tries to swap the loc1 and loc2 objects. The references are used to modify the properties. loc1 object will have the properties changed. loc2 does not change after the call on setLocations method.
2.7 Comparison between java reference and c++ pointer
In C++, pointers are used for executing tasks and managing the memory dynamically. A pointer to a variable is related to the memory address.’ &’ operator is used for accessing the memory address of the pointer. ‘*’ operator is used for getting the value of the variable at the pointer location. C++ Pointer
#include using namespace std; int main(int argc, char **argv)
Let us look at another example where you can see pointers and references in C++. C++ Pointers And Refrences
/* * References.cpp * * Created on: Dec 22, 2019 * Author: bhagvan.kommadi */ #include using namespace std; int main(int argc, char **argv)
In the above example, you can see the pointer intpointer defined and set to an integer variable. Similarly, a reference is defined intref pointing to intval. The output of the above code when executed in eclipse is shown below:
In java, let us look at Flower object and how references are used to modify the properties of the Flower . The code example below shows the properties are changed using the references. Java Reference
In the sections below, different types of references are shown in the examples.
2.8.1 Strong References
Strong references are the default type of References. Objects which are strong references are not candidates for garbage collection. If the object is set to null, it is garbage collected. The code sample below shows how strong references are used.Strong Reference
public class StrongReference < /** * @param args */ public static void main(String[] args) < // TODO Auto-generated method stub StrongReference reference = new StrongReference(); reference = null; >>
2.8.2 Weak References
Weak references are used in WeakHashMap for referencing the entries. java.lang.ref.WeakReference class is used to create this type of reference. Weak objects are marked for garbage collection. Weak Reference
import java.lang.ref.WeakReference; /** * @author bhagvan.kommadi * */ public class WeakReferenceExample < /** * @param args */ public static void main(String[] args) < // TODO Auto-generated method stub WeakReferenceExample reference = new WeakReferenceExample(); WeakReference weakReference = new WeakReference(reference); reference = weakReference.get(); >>
2.8.3 Soft References
java.lang.ref.SoftReference class is used to create soft references. This type of objects are not garbage collected, even if they are free. Soft Reference
/** * */ import java.lang.ref.SoftReference; /** * @author bhagvan.kommadi * */ public class SoftReferenceExample < /** * @param args */ public static void main(String[] args) < SoftReferenceExample reference = new SoftReferenceExample(); SoftReference softReference = new SoftReference(reference); reference = softReference.get(); >>
2.8.4 Phantom References
java.lang.ref.PhantomReference class is used for creating phantom references. They are good candidates for garbage collection. Phantom Reference
import java.lang.ref.PhantomReference; import java.lang.ref.ReferenceQueue; /** * */ /** * @author bhagvan.kommadi * */ public class PhantomReferenceExample < /** * @param args */ public static void main(String[] args) < PhantomReferenceExample reference = new PhantomReferenceExample(); ReferenceQueue queue = new ReferenceQueue(); PhantomReference phantomReference = new PhantomReference(reference,queue); reference = phantomReference.get(); >>
3. Summary
Java references are useful to modify the properties of the class. Java pointers have better benefits compared to C++ pointers. In C++, pointers can be modified which is not a good practice. In Java, references can be pointed to an object or null but cannot be modified. Types can be changed in C++ for pointers. In java, types cannot be changed or reinterpreted. Pointers in C++ might cause issues related to security.
4. More articles
5. Download the Source Code
Download You can download the full source code of this example here: Java Pointers (References) Example
Abstract base class for reference objects. This class defines the operations common to all reference objects. Because reference objects are implemented in close cooperation with the garbage collector, this class may not be subclassed directly.
Method Summary
This method was originally specified to test if a reference object has been cleared and enqueued but was never implemented to do this test.
Ensures that the object referenced by the given reference remains strongly reachable, regardless of any prior actions of the program that might otherwise cause the object to become unreachable; thus, the referenced object is not reclaimable by garbage collection at least until after the invocation of this method.
Methods declared in class java.lang.Object
Method Details
get
Returns this reference object's referent. If this reference object has been cleared, either by the program or by the garbage collector, then this method returns null .
refersTo
Tests if the referent of this reference object is obj . Using a null obj returns true if the reference object has been cleared.
clear
Clears this reference object. Invoking this method will not cause this object to be enqueued. This method is invoked only by Java code; when the garbage collector clears references it does so directly, without invoking this method.
isEnqueued
This method was originally specified to test if a reference object has been cleared and enqueued but was never implemented to do this test. This method could be misused due to the inherent race condition or without an associated ReferenceQueue . An application relying on this method to release critical resources could cause serious performance issue. An application should use ReferenceQueue to reliably determine what reference objects that have been enqueued or refersTo(null) to determine if this reference object has been cleared.
this reference object was registered with a queue when it was created; and
the garbage collector has added this reference object to the queue or enqueue() is called; and
this reference object is not yet removed from the queue.
enqueue
Clears this reference object and adds it to the queue with which it is registered, if any. This method is invoked only by Java code; when the garbage collector enqueues references it does so directly, without invoking this method.
clone
Throws CloneNotSupportedException . A Reference cannot be meaningfully cloned. Construct a new Reference instead.
reachabilityFence
Ensures that the object referenced by the given reference remains strongly reachable, regardless of any prior actions of the program that might otherwise cause the object to become unreachable; thus, the referenced object is not reclaimable by garbage collection at least until after the invocation of this method. Invocation of this method does not itself initiate garbage collection or finalization. This method establishes an ordering for strong reachability with respect to garbage collection. It controls relations that are otherwise only implicit in a program -- the reachability conditions triggering garbage collection. This method is designed for use in uncommon situations of premature finalization where using synchronized blocks or methods, or using other synchronization facilities are not possible or do not provide the desired control. This method is applicable only when reclamation may have visible effects, which is possible for objects with finalizers (See Section 12.6 of The Java Language Specification ) that are implemented in ways that rely on ordering control for correctness.
API Note: Finalization may occur whenever the virtual machine detects that no reference to an object will ever be stored in the heap: The garbage collector may reclaim an object even if the fields of that object are still in use, so long as the object has otherwise become unreachable. This may have surprising and undesirable effects in cases such as the following example in which the bookkeeping associated with a class is managed through array indices. Here, method action uses a reachabilityFence to ensure that the Resource object is not reclaimed before bookkeeping on an associated ExternalResource has been performed; in particular here, to ensure that the array slot holding the ExternalResource is not nulled out in method Object.finalize() , which may otherwise run concurrently.
Here, the invocation of reachabilityFence is nonintuitively placed after the call to update , to ensure that the array slot is not nulled out by Object.finalize() before the update, even if the call to action was the last use of this object. This might be the case if, for example a usage in a user program had the form new Resource().action(); which retains no other reference to this Resource . While probably overkill here, reachabilityFence is placed in a finally block to ensure that it is invoked across all paths in the method. In a method with more complex control paths, you might need further precautions to ensure that reachabilityFence is encountered along all of them. It is sometimes possible to better encapsulate use of reachabilityFence . Continuing the above example, if it were acceptable for the call to method update to proceed even if the finalizer had already executed (nulling out slot), then you could localize use of reachabilityFence :
public void action2() < // . Resource.update(getExternalResource()); >private ExternalResource getExternalResource()