Lanky Dan Blog

Is this the correct object?

March 02, 2017


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

Augmenting a Spring Data repository through delegation

September 14, 2019
springspring datakotlinjavar2dbcspring data r2dbcreactivereactive streamsspring boot

I have recently written several posts about Kotlin’s delegation. In doing so, I realised a useful way to apply it to Spring Data…

Implementing multiple interfaces through delegation

September 05, 2019

In Kotlin, a class can implement multiple interfaces. This is common knowledge. A class can also use delegation to implement numerous…

Streaming live updates from a reactive Spring Data repository

August 29, 2019
springspring datakotlinjavar2dbcspring data r2dbcreactivereactive streams

This post details a naive implementation of streaming updates from a database to any other components that are interested in that data…

The potential traps in Kotlin's Data Classes

August 17, 2019

The aim of this post is not to point out some massive flaws in Kotlin’s design of data classes and show you how to get passed them. Actually…

Connecting a Ktor web server to a Corda node

August 12, 2019
cordakotlindltdistributed ledger technologyblockchain

The preparation for this blog post began several weeks ago (probably over a month by now). Before I could write about melding Corda and Ktor…