Pointers and references in java

C/C++ Pointers vs Java References

Java doesn’t have pointers; Java has references.
Reference: A reference is a variable that refers to something else and can be used as an alias for that something else.
Pointer: A pointer is a variable that stores a memory address, for the purpose of acting as an alias to what is stored at that address.
So, a pointer is a reference, but a reference is not necessarily a pointer. Pointers are a particular implementation of the concept of a reference, and the term tends to be used only for languages that give you direct access to the memory address.

Let’s discuss some keypoints about pointers and references in context of C/C++ and Java:

  • C/C++ allows pointer arithmetic but Java Pointers (References) not: The term “pointer” is strongly associated with the C/C++ concept of pointers, which are variables which store memory addresses and can be modified arithmetically to point to arbitrary addresses.
    In Java, pointers only exist as an implementation detail for References. A copy of the reference is copied to the stack of a called function, pointing to the same object as the calling function and allowing you to manipulate that object. However you cannot change the object the calling function refers to.
  • Java doesn’t support pointer explicitly, But java uses pointer implicitly: Java use pointers for manipulations of references but these pointers are not available for outside use. Any operations implicitly done by the language are actually NOT visible.
  • Pointers can do arithmetic, References can’t: Memory access via pointer arithmetic is fundamentally unsafe and for safe guarding, Java has a robust security model and disallows pointer arithmetic for this reason. Users cannot manipulate pointers no matter what may ever is the case.
  • Pointing objects: In C, we can add or subtract address of a pointer to point to things. In Java, a reference points to one thing only. You can make a variable hold a different reference, but such c manipulations to pointers are not possible.
  • References are strongly typed: Type of a reference is much more strictly controlled in Java than the type of a pointer is in C. In C you can have an int* and cast it to a char* and just re-interpret the memory at that location. That re-interpretation doesn’t work in Java: you can only interpret the object at the other end of the reference as something that it already is (i.e. you can cast a Object reference to String reference only if the object pointed to is actually a String).
  • Manipulation of pointers can be dangerous: On one hand, it can be good and flexible to have control over pointers by user but it may also prove to be dangerous. They may turn out to be big source of problems, because if used incorrectly they can easily break assumptions that your code is built around. And it’s pretty easy to use them incorrectly.
Читайте также:  Отправить get запрос html

So overall Java doesn’t have pointers (in the C/C++ sense) because it doesn’t need them for general purpose OOP programming. Furthermore, adding pointers to Java would undermine security and robustness and make the language more complex.

CPP program to illustrate pointer manipulations

Источник

Java Pointers (References) Example

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.

2.3 Setup

2.3.1 Java Setup

JAVA_HOME="/desktop/jdk1.8.0_73" export JAVA_HOME PATH=$JAVA_HOME/bin:$PATH export PATH

2.3.2 C++ Setup

2.4 IDE

2.4.1 Eclipse Oxygen Setup

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.

2.4.2 Eclipse C++ Setup

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:

Java Pointers

You can select the workspace from the screen which pops up. The attached image shows how it can be selected.

Java Pointers

You can see the eclipse workbench on the screen. The attached screen shot shows the Eclipse project screen. Java Pointers - Eclipse WorkbenchJava Hello World class prints the greetings. The screenshot below is added to show the class and execution on eclipse.Java Pointers - Java Hello

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.

Java Pointers - C++ Helloworld

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.

Java Pointers - Java References

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)

Java Pointers - C++ Pointers

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:

Java Pointers - C++ References & Pointers

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

/** * */ /** * @author bhagvan.kommadi * */ public class Flower < private String color; public Flower()<>public Flower(String color) < this.color= color; >public String getColor() < return color; >public void setColor(String color) < this.color = color; >private static void setProperties(Flower flower) < flower.setColor("Red"); flower = new Flower("Green"); flower.setColor("Blue"); >public static void swapObjects(Object obj1, Object obj2) < Object buff = obj1; obj1=obj2; obj2=buff; >/** * @param args */ public static void main(String[] args) < Flower rose = new Flower("Red"); Flower iris = new Flower("Blue"); swapObjects(rose, iris); System.out.println("rose color="+rose.getColor()); System.out.println("iris color="+iris.getColor()); setProperties(iris); System.out.println("iris wp-block-image">
Pointers and references in java
Java References

2.8 Example using Java references

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.

5. Download the Source Code

Download
You can download the full source code of this example here: Java Pointers (References) Example

Last updated on Aug. 10th, 2021

Источник

Оцените статью