Java Reference
In-Depth Information
as predator or herbivore). Making multiple classes and interfaces greatly aids debugging because you
can see which piece holds the problem spot. In other words, granularity makes it easier to create error-
free programs.
Real programs need granularity, and good programmers work to achieve it.
Pass-by-Reference and Pass-by-Value
Pass-by-reference and pass-by-value refer to how information is passed from one object to another.
Nearly all of the passing of information in Java goes through methods, but information can also go
through fields within an object.
Strictly speaking, Java uses only pass-by-value. However, the values it passes differ greatly based on
what is passed. For primitives, Java passes a copy of the primitive. So, if you pass an int to a method, the
method receives a copy of the int , not the original int . For objects, Java passes a pointer. A pointer is the
address of an object in memory. This subtle difference trips up many novice Java developers. A few
examples clarify (I hope) the issue (see Listing 6-16). I say, “I hope,” because this topic gives even
seasoned developers fits.
Listing 6-16. Pass-by-reference and pass-by-value
package com.apress.java7forabsolutebeginners .examples.hello;
public class IntegerWrapper {
public int objectInt = 0;
}
package com.apress.java7forabsolutebeginners .examples.hello;
public class Hello {
static int primitiveInt = 0;
static IntegerWrapper intWrapper = new IntegerWrapper();
public static void main(String[] args) throws Exception {
passBy(primitiveInt, intWrapper);
System.out.println("primitiveInt = " + primitiveInt +
"; intWrapper.objectInt = " + intWrapper.objectInt);
}
public static void passBy(int primitiveInt, IntegerWrapper intWrapper) {
primitiveInt++;
intWrapper.objectInt++;
}
}
As you can see, this program has two classes, IntegerWrapper and PassByTest . IntegerWrapper is a
way to turn a primitive into an object (and don't ever write objects like this for real, by the way—it's bad
form, but it makes sense to keep this illustration as simple as possible). PassByTest demonstrates pass-
by-reference and pass-by-value. When we run PassByTest, its output is primitiveInt = 0;
intWrapper.objectInt = 1 .
Search WWH ::




Custom Search