Skip to main content

Java and referencing

Given that the last post was all about pointers and references in C++, it is only fair that i do justice to my first love (Java) and talk about parameter passing and referencing in it. Now being a managed language, there is no memory management as such in Java, so no pointers no keeping track of what memory is being used where. So how does that work? well there is the Java garbage collector, which periodically (to my knowledge, there really is no telling exactly when) does the rounds and deletes any objects that are no longer being referenced. To go into the details of the garbage collector (GC) and reference counting and related concepts deserves a post on its own, so i will just skip it here. Anyway so yeah....GC woohhuuuu, we can focus solely on the business logic and not worry about dangling pointers and other memory related grief. Now this is awesome, i mean it really is, however it does have its cons, Java programs run slower because of the GC compared to their well written C++ counterparts. This is precisely why unmanaged code (C++, C) would never go out of style, as it would be used to solve  very different kinds of problems (real-time systems, image processing anyone?) when compared to Java. I mean dont get me wrong, there is stuff out there which is trying to get managed languages to do real-time stuff for example (http://dl.acm.org/citation.cfm?id=1806615).

Anyway the GC makes Java almost 100% leak proof. See i said almost, it is not 100% leak proof, memory leaks can potentially happen in Java, especially when you are doing something with JNI.

Ok moving on, there are a few basic things that one needs to remember when working with Java and that is Objects are passed by reference and primitive types by values. I will make it clear with examples below.

Problem

Parameter passing and Objects in Java.

Solution

ok lets create a simple class with a couple of methods

public class Params{

int val;
public void changeValue(int valuePassed) {
  /* now lets change the value we have passed in this variable */
  valuePassed = 84;
}
/* change object variable */
public void changeObjVar(Params p){
  p.val = 43;
}
public static void main(String []args)
{
    /* lets declare a nice little int variable */
    int ultimateAnswer = 42;
    Params p = new Params();

    System.out.println("Original value of ultimateAnswer:"+ultimateAnswer);  
    /* ok now lets see what happens when we pass the value to a function */
    p.changeValue(ultimateAnswer);
    /* now lets print this */
    System.out.println("changed value of ultimateAnswer:"+ultimateAnswer);  

    /* ok so the value is not changed is it? So the reason for this is
     * that its pass by value i.e. a copy of the value is being sent 
     * through rather than the actual location of memory where the value
     * is being stored */   
     /* ok moving on, lets assign a value to the object variable*/
    p.val = 34;
    System.out.println("initial value:"+ultimateAnswer);  

    /* now lets see what happens if we try to change it */
    p.changeObjVar(p);
    System.out.println("changed value:"+ultimateAnswer);  
    /* great so the value is different now, awesome! the reason why 
     * this is happening is because the object that we created for P 
     * is passed by reference to the method */
  }
}

Constuctors

So i admit the last bit was dry and boring, but it was important to touch on that. Now some fun stuff! Ok so lets create 2 objects of params, the second object will be a copy of the first. So looking at the class above the code would go something like this

Params p1 = new Params();
Params p2 = p1;
p1.val = 34;
print(p1.val);
p2.val = 56;
print(p2.val);
So this code seems harmless enough? well that really depends on what our objective is... Ok say if we are hoping to make changes to p2 without affecting p1, then things are not quite as we may expect them to be. We can find out now when we try to print p1.val, the output would be 56 instead of 34. why? well the reason is simple enough, unlike C++, Java does not have copy constructors by default, so p2 holds a reference to p1 and when we change something in p2,  p1 gets affected as well.

Ohh and another to always remember, using "=="  java means we are comparing the references of 2 objects!

so lets create a copy constructor, which in this case would be something like

public Params(Params p){
    this.val = p.val;
}
Then we can create our p2 object using p1.

Params p2 = new Params(p1);
I know this is a trivial concept, but believe me, mistakes do happen from time to time and one can spend hours debugging their Java code only to find a simple problem like this which may have been overlooked. Actually that is not entirely true, i think this is more relevant in my case, because i am switching between Java and C++ on a daily basis, so i need some form of reference to keep these things in check. Like right now, its nearly 1am and i am using valgrind to find memory leaks in my C++ code, ahh i really hate this.

Variable no of arguments

So this is an awesome way in which we can pass values to a Java method.

If we have a function 

void print_values(int... values)
Those "..." mean that we can pass any number of values of type int when calling this function and whats more awesome about this is that, we can access the values we pass as an array, which means we can traverse using values.length and access the contents just as we would in an array.

we can invoke the above method like 
print_values(1,2,3,4,5,6,7);
and that is totally fine!

Java rocks, not matter what anyone says about it, there are things about it, the verbosity etc etc, but as i said, it is first love and while i may come to appreciate the awesomeness of other languages, my heart will always belong to Java. Here's hoping all those changes Oracle plans on bringing in Java 8, actually work out!

Comments

Popular posts from this blog

Upload to AWS S3 from Java API

In this post, you will see code samples for how to upload a file to AWS S3 bucket from a Java Spring Boot app. The code you will see here is from one of my open-source repositories on Github, called document-sharing. Problem Let’s say you are building a document sharing app where you allow your users to upload the file to a public cloud solution. Now, let’s say you are building the API for your app with Spring Boot and you are using AWS S3 as your public cloud solution. How would you do that? This blog post contains the code that can help you achieve that. Read more below,  Upload to AWS S3 bucket from Java Spring Boot app - My Day To-Do (mydaytodo.com)

Build a Full-Stack Image Upload App with Node.js, Express, React, and Vite (Beginner Tutorial)

 If you’re new to full-stack web development and want a hands-on project to practice React frontend integration with a Node.js + Express backend , this tutorial is for you. In this guide, we’ll walk through a simple but powerful app that lets users upload images, store them on the server, and display them back in the browser. This project is based on my GitHub repo: node-express-react-simple-fileupload . It’s designed to be beginner-friendly, SEO-optimized, and a great starting point for anyone learning JavaScript full-stack development . 🛠️ Technologies Used Here’s the tech stack powering this project: Node.js – JavaScript runtime for the backend. Express.js – Lightweight web framework for building REST APIs. Multer – Middleware for handling file uploads. CORS – Enables cross-origin requests between frontend and backend. React.js – Frontend library for building user interfaces. Vite – Fast development server and build tool for React. Fetch API – For making HTTP requests ...

Html5 based widget for an iOS app: Today extension powered by the Ionic framework

At some point the thought of adding a Widget to my iOS app came to mind which was followed by starting work on adding a widget for my app, My Day Todos . Obviously the first step was to learn how to add a Widget to an iOS app and in that learning process I discovered many things about widgets in iOS first of which was a widget in iOS is a an app extension i.e a  Today Extension . While I am still haven't finished working on the widget for my iOS app, I thought I would take some time out and share what I have learned. In this post, I will share a few important tips and provide an example of how to add a Widget to an iOS app and have the widget UI powered by Html5 via  Ionic framework . I added some code to my Github repo, Html5StarterAppWithSwift in order to show how this can be achieved. There are already too many tutorials out on the Web on how to add a Today extension to an iOS app so I won't be including that here. Instead I will focus on sharing some of the useful tip...