Welcome!

Server Monitoring Authors: Yeshim Deniz, Liz McMillan, Pat Romanski, Carmen Gonzalez, Ken Schwaber

Blog Feed Post

Java: Passing by Reference With a Twist

Currently I’m teaching a Java class online, and Vitaly O., one of my students, ran into an interesting situation. He sent me the program below, which, to his surprise, printed 1.

public class Main {

    public static void main(String[] args) {
        Integer t = new Integer(0);
        t=1;
        test(t);
        System.out.println(t);
    }

    public static void test(Integer t) {
    	t=2;
    }

}

The topic of passing by value vs by reference is one of the difficult topics to understand for Java beginners. The code above can confuse junior Java developers, because the author of the program above ran into a bouquet of Java features, which I’ll explain (slowly) in this blog.

All Java textbooks (mine included) will tell you that objects are being passed by reference and primitives by value. That’s fine and understandable – nobody wants to copy large objects in memory . But what about the variables that point at an object and are being passed to a method as arguments like in test(t) line above?
First, let’s take care of a simpler case. Let’s replace the Integer with the class Car that looks like this:

public class Car {
   int salesmanWhoHasKeys;
} 

Imagine a tiny car dealership with two salesmen that has a room only for one car. When a customer pops in, one of the salesmen takes the car keys to test drive THE car. The class TestCar will look similar to the class Main, but is not exactly the same.

public class TestCar {

    public static void main(String[] args) {
        Car t = new Car();
        t.salesmanWhoHasKeys=1;

        test(t);
        System.out.println(t.salesmanWhoHasKeys);
    }

    public static void test(Car t) {
    	t.salesmanWhoHasKeys=2;
    }
}

The program TestCar prints 2. Why? What makes it different from the program Main? Just bear with me for a moment. Let’s completely understand what the phrase “objects are passed by reference” means. There is only one car, remember? And Java doesn’t create a copy of the one and only instance of the object Car just to pass it to the method test(). But it does create a copy of the original pointer t inside the method test for method argument, which (to add to the confusion) is also named t.

Get used to the fact that we have one object in memory with two different pointers to it (t and ttt). To make things easier to understand, modify the method test() to look as follow:

   public static void test(Car ttt) {
    	ttt.salesmanWhoHasKeys=2;
    }

The program still prints 2. So what’s the difference between dealing with the instance of a Car vs Integer? The wrapper class Integer is immutable. This means that you can’t change its value once it was assigned, which is not the case with the Car.
To make things worse for comprehension, the Java feature called autoboxing kicks in and the original program quietly creates instances of new wrapper Integer objects when it sees something like t=2. This line gets converted into t=new Integer(2)! Got it? So the value 2 has been assigned to a different Integer object via a different variable t.

And just to make sure that you clearly understand the whole confusion of the program Main, please answer my final question, “How many instances of the class Integer were created during the lifespan of the program Main?”

Who said two? Mary? Wrong! The right answer is three! The first one had the value of zero, the next line caused the creation of the another instance if Integer with the value of 1, and the third instance was created by the method test() with the value of 2. Don’t believe me? Step through the Main program in a debugger, and you’ll see three different ids assigned to the variable t.

Don’t you love Java? I do.


Read the original blog entry...

More Stories By Yakov Fain

Yakov Fain is a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs (http://yakovfain.com) and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain

IoT & Smart Cities Stories
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
Whenever a new technology hits the high points of hype, everyone starts talking about it like it will solve all their business problems. Blockchain is one of those technologies. According to Gartner's latest report on the hype cycle of emerging technologies, blockchain has just passed the peak of their hype cycle curve. If you read the news articles about it, one would think it has taken over the technology world. No disruptive technology is without its challenges and potential impediments t...
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...