Welcome!

Server Monitoring Authors: Carmen Gonzalez, AppDynamics Blog, Yeshim Deniz, Liz McMillan, Pat Romanski

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
The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.
The Jevons Paradox suggests that when technological advances increase efficiency of a resource, it results in an overall increase in consumption. Writing on the increased use of coal as a result of technological improvements, 19th-century economist William Stanley Jevons found that these improvements led to the development of new ways to utilize coal. In his session at 19th Cloud Expo, Mark Thiele, Chief Strategy Officer for Apcera, compared the Jevons Paradox to modern-day enterprise IT, examin...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
DSR is a supplier of project management, consultancy services and IT solutions that increase effectiveness of a company's operations in the production sector. The company combines in-depth knowledge of international companies with expert knowledge utilising IT tools that support manufacturing and distribution processes. DSR ensures optimization and integration of internal processes which is necessary for companies to grow rapidly. The rapid growth is possible thanks, to specialized services an...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...