Tuesday, March 9, 2010

[Java] A Solution to Pass by Reference problem in Java

 

Hi All

I  faced the following problem in Java:

public class PassByReference
{

    public static void main(String[] args)
    {
        String s1 = "one";
        alter(s1);
        String s2 = s1;
        System.out.println(s2); // ouput is one

// my solution
        AString as = new  AString("one");
        alter(as);
        String s3 = as.s1;
        System.out.println(s3);   // output is one two

/*
try
{
AResultSet ars=new AResultSet();

int rowsCount = getUsers(ars);

ars.rs.getString(1); and so on
}
catch(SQLException ex)
{
}

*/

    }

    static void alter(String str)
    {
        str += " two";

    }

    static void alter(AString astr)
    {
        astr.s1 += " two";

    }

}

class AString
{

    public AString(String s1)
    {
        this.s1 = s1;
    }

    String s1;
}

// also with this solution we can pass by references any object reference without //initialization

// such as ResultSet

/*

class AResultSet
{
ResultSet rs;
}

*/

[Non-text portions of this message have been removed]

__._,_.___
Recent Activity:
Visit http://aiaiai.com or http://jgame.org for more groups to join.
Java Official Group is created for the following topics: Java 2 Enterprise Edition - J2EE, Java 2 Standard Edition - J2SE, Java 2 Micro Edition - J2ME, XML, XSL, XSD, XPATH, Web Services, Jini, JXTA for all type of Java Geeks.
Whoever posts spam / ads / job related message will be BANNED IMMEDIATELY
.

__,_._,___

No comments:

Post a Comment