O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Passing Values

Problem

You need to pass a number like an int into a routine, and get back the routine’s updated version of that value in addition to the routine’s return value.

This often comes up in working through strings; the routine may need to return a boolean, say, or the number of characters transferred, but also needs to increment an integer array or string index in the calling class.

It is also useful in constructors, which can’t return a value but may need to indicate that they have “consumed” or processed a certain number of characters from within a string, such as when the string will be further processed in a subsequent call.

Solution

Use a specialized class such as the one presented here.

Discussion

The Integer class is one of Java’s predefined Number subclasses, mentioned in the Introduction to Chapter 5. It serves as a wrapper for an int value, and also has static methods for parsing and formatting integers.

It’s fine as it is, but you may want something simpler.

Here is a class I wrote, called MutableInteger , that is like an Integer but specialized by omitting the overhead of Number and providing only the set, get, and incr operations, the latter overloaded to provide a no-argument version that performs the increment (++) operator on its value, and also a one-integer version that adds that increment into the value (analogous to the += operator). Since Java doesn’t support operator overloading, the calling class has to call these methods instead of invoking the operations ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required