Java

Pointers In Java

Somesh

--

A confusing topic got demystified…

In my dev role, as a fresher and being new to java , I found pointers very confusing.

Points to be clear

In Java there is no pointers concept, which means we cannot perform any pointer arithmetic operations in java as we tend to do in c++ or c. The main reason I feel is because in java memory is garbage collected, we don’t need to allocate and free memory as we do in c++.

But but but, we use pointers a lot in java not explicitly but implicitly. Lets get it demystified.

Demystification

When we pass primitive types to a method, then it is pass by value. Which means an exact copy of the value is passed and altering it inside that method won’t change the exact value.

public class PassByValueExample {
public static void main(String[] args) {
int number = 10;
System.out.println("Before calling the method: " + number);
modifyValue(number);
System.out.println("After calling the method: " + number);
}

public static void modifyValue(int value) {
value = 20;
System.out.println("Inside the method: " + value);
}
}
Before calling the method: 10
Inside the method: 20
After calling the method: 10

Like wise when we pass an object to a method, then an exact copy of the reference to the object location in memory is passed to the method as pass by value. So any modification to the passed object will directly affect the original value.

But when a new object is assigned to the object reference then it won’t affect the original value.

public class PassByReferenceExample {
public static void main(String[] args) {
StringBuilder name = new StringBuilder("John");
System.out.println("Before calling the method: " + name);
modifyReference(name);
System.out.println("After calling the method: " + name);
}

public static void modifyReference(StringBuilder value) {
value.append(" Doe");
System.out.println("Inside the method: " + value);
value = new StringBuilder("Jane"); // Assigning a new object
System.out.println("Inside the method (after reassignment): " + value);
}
}
Before calling the method: John
Inside the method: John Doe
Inside the method (after reassignment): Jane
After calling the method: John Doe

I hope this article finds useful to someone…

--

--

Somesh

Software Developer | Loves writing about technology.