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)

Addressing app review rejections for auto-renewing subscription in-app purchase (iOS)

The ability to know what the weather is like while planning your day is a feature of  My Day To-Do  Pro and as of the last update it’s also a part of the  Lite version . Unlike the Pro version it’s an auto-renewing subscription based  in-app purchase (IAP)  in the Lite version. What means is that when a user purchases it, the user only pays for the subscription duration after which the user will be automatically charged for the next period. Adding an  auto-renewing  subscription based IAP proved to be somewhat challenging in terms of the app store review i.e. the app update was rejected by the App Review team thrice because of missing information about the IAP. Therefore in this post I will share my experiences and knowledge of adding auto-renewing IAP in hopes to save someone else the time that I had to spend on this problem. In-App purchase This year I started adding IAPs to My Day To-Do Lite which lead to learning about different types of IAP...

Serving HTML content in an iOS app that works in iOS 7 and later (using Swift)

As I have mentioned in an earlier post , I really enjoying coding in Swift. Now what am I doing with it? Well I am trying to build an HTML5 app that must work on devices with iOS 7. So in iOS8 apple has introduced a whole bunch of features that facilitate easy communication between web content and lets just call it back-end Swift code, but those features are not in iOS 7. So why do I want to build something that would work in an older OS? well I do not expect existing iOS users to upgrade to iOS 8 straight away and i also know a couple of people who would be very reluctant to upgrade their iPhones to iOS 8. Now in case you do not, you can have a read of the "Working with WebViews" section of this post , to know how to serve HTML content with WebViews. So when I started building my app, I wanted to know: How do I invoke some Swift code from my HTML content? Well the solution to this may feel a little bit "hacky" but it is a solution to achieve this.  The followi...