|
-
Nov 25th, 2001, 02:02 PM
#1
Thread Starter
Addicted Member
I though String was an object (scope question)
I wrote these two little classes:
class ScopeExplorer {
private static String m_objective[] = {"initial", "value"};
private static String m_objective2 = "initial value";
public static void main(String[] args) {
System.out.println("Before 1: " + m_objective[0] + ", " + m_objective[1]);
System.out.println("Before 2: " + m_objective2);
Scoper scoper = new Scoper(m_objective, m_objective2);
System.out.println("After: 1 " + m_objective[0] + ", " + m_objective[1]);
System.out.println("After 2: " + m_objective2);
}
}
and
class Scoper {
Scoper(String[] objective, String objective2) {
objective[0] = "Hello";
objective[1] = "World";
objective2 = "Hello World";
}
}
The first class calls the second class and passes two arguments that both get changed in the constructor. When control passes back to main, only one gets changed, the other doesn't. Here's the output:
Before 1: initial, value
Before 2: initial value
After: 1 Hello, World
After 2: initial value
I thought that String was an object and as an object would be passed by reference, not value! Can anybody shed any light on this?
(Quick vbforum newbie question: how do you indent code? <pre> didn't work)
Marlin
-
Nov 25th, 2001, 03:33 PM
#2
Since String is a final class, new memory is allocated and the pointer is changed every time you change its value. So, in a sense, Strings are passed by value, not reference.
Laugh, and the world laughs with you. Cry, and you just water down your vodka.
Take credit, not responsibility
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|