Re: Java
From: James Rogers (jimmaureenrogers_at_att.net)
Date: 04/09/04
- Next message: osmium: "Re: Cutting stock problem"
- Previous message: Thomas Stegen: "Re: Java"
- In reply to: Thomas Stegen: "Re: Java"
- Next in thread: Thomas Stegen: "Re: Java"
- Reply: Thomas Stegen: "Re: Java"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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
- Next message: osmium: "Re: Cutting stock problem"
- Previous message: Thomas Stegen: "Re: Java"
- In reply to: Thomas Stegen: "Re: Java"
- Next in thread: Thomas Stegen: "Re: Java"
- Reply: Thomas Stegen: "Re: Java"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|