Results 1 to 2 of 2

Thread: I though String was an object (scope question)

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Nov 2001
    Location
    Yewston, Texis
    Posts
    240

    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

  2. #2
    The Devil crptcblade's Avatar
    Join Date
    Aug 2000
    Location
    Quetzalshacatenango
    Posts
    9,091
    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
  •  



Click Here to Expand Forum to Full Width