Lanky Dan Blog

Is this the correct object?

March 02, 2017

java

This is something I came across at work that wasn’t working as I expected. After a little playing around it seemed pretty obvious but even after a few years of working with Java this wasn’t a situation I came across before.

Now what happened? Its way easier to show you an example first.

public class AssigningObjects {
  public static void main(String[] args) {
    Integer a = 1;
    Integer b = a;
    Integer c = 2;
    a = 3;
    a = c;
    System.out.println("a = " + a); // prints 2
    System.out.println("b = " + b); // prints 1
    System.out.println("c = " + c); // prints 2

    c = 4;
    System.out.println("a = " + a); // prints 2
    System.out.println("c = " + c); // prints 4

    c = null;
    System.out.println("a = " + a); // prints 2
    System.out.println("c = " + c); // prints null
  }
}

So the problem I had… I thought that if b = a and a = c then b = c, so by changing c’s value b will also change. But this is not the case. What actually happens is a refers to an underlying object (which is the Integer 1) and by assigning b to a, b now also refers to the same object. When a is assigned to c the underlying object a refers to has now changed, but this does not affect b which will still have the value 1 as the object it is pointing to has not changed.

Anyway this is just something small that I found interesting as I never actually ran into this situation before and when I told my colleague I wanted to tell him something interesting he told me to go away… so I told you instead!


Dan Newton

Saving transactions where only a subset of parties are signers

July 05, 2019
cordakotlindltdistributed ledger technologyblockchain

It took a while for me to think of a title that could summarise the contents of this post without becoming a full sentence itself. I think I…

Kotlin primitive and object arrays

June 21, 2019
kotlinjavabeginner

I initially set out to write this post because I was playing around with some reflection code and thought I found something interesting…

Preventing invalid spending of broadcasted states

June 12, 2019
cordakotlindltdistributed ledger technologyblockchain

Corda is super flexible and will allow you to put together the code needed to write many complex workflows. This flexibility does come with…

Broadcasting a transaction to external organisations

May 31, 2019
cordakotlindltdistributed ledger technologyblockchain

There is a misconception that Corda cannot broadcast data across a network. This is simply wrong. In fact, Corda can send anything between…

Running a Kotlin class as a subprocess

May 25, 2019
kotlin

Last week I wrote a post on running a Java class as a subprocess . That post was triggered by my need to run a class from within a test…