This Q&A is a bit different in that I'm going to tackle four quick questions in one swoop. We'll look at green versus native threads,
Class.forName(), returning multiple values from a method, and shallow copying. So, let's get to it.
Green and native threads -- what's the difference?.
What does Class.forName(); do?.
In the case of JDBC, the
Class.forName() loads the JDBC driver into the JVM.
Return multiple values from a method
Question: How can I return more than one value from a method in Java?
Answer: Two easy ways exist to return multiple values from a function:
Precondition: Method 1 works only if the return values are all of the same type -- all values must be integers or booleans, and so on.
If your return values meet the precondition, simply return an array of values.
If your values are of different types, you could cast them all down to object and return them as an array of object. However, this proves dangerous work and requires your method's caller to possess too much knowledge of how the array is filled in.
No precondition: With method 2, simply create a high-level wrapper object. For example, if you would like to return an int, a float, and a boolean, create the following wrapper:
public class SimpleWrapper { public SimpleWrapper(int I, float f, boolean b) { _anInt = I; _aFloat = f; _aBoolean = b; } public int getInt() { return _anInt; } public float getFloat() { return _aFloat; } public boolean getBoolean() { return _aBoolean; } private int _anInt; private float _aFloat; private boolean _aBoolean; }
Of course, the class and method names should make more sense in your context.
Shallow vs. deep copy
Question: I have questions about shallow copy and deep copy. Consider the following code:
Vector v = new Vector(); Vector v2 = v;
Is this the only way to make a shallow copy?
Answer: Actually, you have not done a shallow copy at all. Rather, by creating
v and
v2, you have created a second reference to the same object. A shallow copy will make a complete copy of the object and any primitive attribute. It will not, however, make copies of any high-level object attributes. Instead, it points those attributes at the reference in the original object.
For a good introduction to how Java treats references, read: "Does Java pass by reference or pass by value?" (JavaWorld, May 26, 2000).
Learn more about this topic
- For more articles on Java threads, visit the Threads section of our Topical Index
- "Does Java Pass by Reference or Pass by Value?" Tony Sintes (JavaWorld, May 26, 2000)
- Want more? See the Java Q&A index for the full Q&A catalog
- For over a hundred insightful Java tips from some of the best minds in the business, visit JavaWorld's Java Tips index