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
Early Bird Registration Discount Expires on August 31, 2018 Conference Registration Link ▸ HERE. Pick from all 200 sessions in all 10 tracks, plus 22 Keynotes & General Sessions! Lunch is served two days. EXPIRES AUGUST 31, 2018. Ticket prices: ($1,295-Aug 31) ($1,495-Oct 31) ($1,995-Nov 12) ($2,500-Walk-in)
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...
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
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.
Machine learning has taken residence at our cities' cores and now we can finally have "smart cities." Cities are a collection of buildings made to provide the structure and safety necessary for people to function, create and survive. Buildings are a pool of ever-changing performance data from large automated systems such as heating and cooling to the people that live and work within them. Through machine learning, buildings can optimize performance, reduce costs, and improve occupant comfort by ...
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...
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...