Re: Java

From: James Rogers (jimmaureenrogers_at_att.net)
Date: 04/09/04


Date: Fri, 09 Apr 2004 12:32:01 GMT

Thomas Stegen <tstegen@cis.strath.ac.uk> wrote in
news:407693be$1@nntphost.cis.strath.ac.uk:

> Java:
>
> public class Test
> {
> public static void main(String args[])
> {
> String a = "abc";
> System.out.println("main1 " + a);
> func(a);
> System.out.println("main2 " + a);
> }
>
> static void func(String s)
> {
> System.out.println("func1 " + s);
> s = "def";
> System.out.println("func2 " + s);
> }
> }
>
> Java output:
>
> main1 abc
> func1 abc
> func2 def
> main2 abc

I do not think you demonstrated what you think you demonstrated.
The Java String class is immutable.

Within func the parameter 's' is a local copy of the reference
to the actual string parameter from the call. Assigning a value
to 's' creates a new String object. It does not modify the
existing String object.

>
>
> C++:
>
> #include <string>
> #include <iostream>
>
> void func(std::string &s)
> {
> std::cout << "func1 " << s << std::endl;
> s = "def";
> std::cout << "func2 " << s << std::endl;
> }
>
> int main()
> {
> std::string a = "abc";
> std::cout << "main1 " << a << std::endl;
> func(a);
> std::cout << "main2 " << a << std::endl;
> return 0;
> }
>
> C++ output:
>
> main1 abc
> func1 abc
> func2 def
> main2 def

In C++ the parameter 's' is a reference to a string object.
That reference is a local value assigned by copying the
address of the actual parameter.

Within func the assignment 's = "def"' modifies the object
referenced by 's'. It does not create a new object.

The difference is not in the parameter passing mechanism. It is
in the different definitions of a string class between Java and
C++.

Jim Rogers



Relevant Pages

  • Re: Universal Programming Lanaguage
    ... While Java does have a substringcall, ... ABC abc = new ABC; ... DEF def = new DEF; ... declaring an object to implement Comparable, ...
    (sci.logic)
  • Java and abc enhanced tv and MSN Today
    ... I get the java one for abc enhanced tv and its perfect says sun.com I think ... To get MSN working you need to install JAVA. ...
    (microsoft.public.windows.mediacenter)
  • Re: same old question: interface Vs. Abstract class
    ... Then I think I should use ABC only over ... > interface for speed optimization. ... methods in each of the subclasses. ... I'm not 100% what you mean by, "How will one phrase the same in JAVA;" ...
    (comp.lang.java.help)
  • Re: Is "String s = "abc";" equal to "String s = new String("abc")
    ... Some String objects are in that pool, ... reference to it when executing that code. ... then the JVM still arranges for "abc" to be in that pool, ... It's that second String object which ends up ...
    (comp.lang.java.programmer)
  • Re: subet algo, hash table
    ... someguy wrote: ... > I'm trying to write a function in Java that takes in a string and ... A B C AB AC BC ABC). ...
    (comp.lang.java.help)