Passing references to a method

i hv declared and defined a method whose parameters are two int which are manipulated during the course and are required to b returned to the callin method(take example of swapping integers)
How do I do it?
problems faced are:
1. cant return more than 1 value
2. cant return in anyother form(like array...etc)
plz suggest

This is a duplicate of
http://forum.java.sun.com/thread.jsp?forum=31&thread=379031&tstart=0&trange=15

Similar Messages

  • How to pass Method Inner Class reference to other method?

    Hi All,
    I am trying to pass the reference of "method inner class".
    Can any one explain me how to pass the reference and where other method will sit in the class, I mean either in Outer Class or in Inner Class ?
    Thanks in advance for ur reply :)
    package methosInnerClass;
    public class MethodLocalInnerClass {
         private String outerName;
         private static String statOuterName;
         public MethodLocalInnerClass(String name, String statName) {
              outerName = name;
              statOuterName = statName;
         public void methodWithLocallClass() {
              class MethodInnerClass {
                   String innerName;
                   MethodInnerClass(String name) {
                        innerName = name;
                   public void displayOuterInner() {
                        System.out.println("Outer Name: " + outerName + "\nOuter StatName: " + MethodLocalInnerClass.statOuterName + "\nInner Name: " + innerName);
              MethodInnerClass methodInner = new MethodInnerClass("Harish");
              methodInner.displayOuterInner();
                    *Pass above reference to other method*
         public static void staticMethodWithLocallClass() {
              class MethodInnerClass {
                   String innerName;
                   MethodInnerClass(String name) {
                        innerName = name;
                   public void displayOuterInner() {
                        // We can not access the non-static instance variable since this method is a static method
                        //System.out.println("Outer Name: " + outerName + "\nOuter StatName: " + MethodLocalInnerClass.statOuterName + "\nInner Name: " + innerName);
                        System.out.println("Outer StatName: " + MethodLocalInnerClass.statOuterName + "\nInner Name: " + innerName);
              new MethodInnerClass("Shakshi").displayOuterInner();
         public static void main(String[] args) {
              new MethodLocalInnerClass("Abhishek","Neeshu").methodWithLocallClass();
              System.out.println("Calling innerClass within static method !!!");
              staticMethodWithLocallClass();
    }

    package donald.test.inner_class;
    public class OutterClass {
         private String outerName;
         private final OutterClass outterClass;
         public OutterClass() {
              outterClass = this;
         public void methodWithInnerClass(final String strValueToPassToInnerClass) {
              class InnerClass {
                   private InnerClass innerClass;
                   private String innerName;
                   InnerClass(String name) {
                        innerName = name;
                   public void displayOuterInner() {
                        System.out.println("Non-Static:\tOuter Name: " + outerName + "\tInner Name: " + innerName);
                        System.out.println("");
                        System.out.println("final String strValueToPassToInnerClass = " + strValueToPassToInnerClass);
                    * @return the innerClass
                   public InnerClass getInnerClass() {
                        return innerClass;
                    * @param innerClass the innerClass to set
                   public void setInnerClass(InnerClass innerClass) {
                        this.innerClass = innerClass;
                    * @return the innerName
                   public String getInnerName() {
                        return innerName;
                    * @param innerName the innerName to set
                   public void setInnerName(String innerName) {
                        this.innerName = innerName;
              InnerClass methodInner = new InnerClass("Inner.Donald");
              methodInner.displayOuterInner();
              System.out.println("My OutterClass " + outterClass.getOuterName());
        // Unknown "MethodInnerClass "
         public void passReferenceOfInnerClassToOtherMethod(     ) {
          * @param args
         public static void main(String[] args) {
              OutterClass outterClass = new OutterClass();
              outterClass.setOuterName("Outter.Donald");
              outterClass.methodWithInnerClass("This Donald is so very cool...!!!  Yeah...!!!");
          * @return the outerName
         public String getOuterName() {
              return outerName;
          * @param outerName the outerName to set
         public void setOuterName(String outerName) {
              this.outerName = outerName;
          * @return the outterClass
         public OutterClass getOutterClass() {
              return outterClass;
    }

  • How to get caller object reference from a method

    Hi,
    I am working a already existing Java Swing project, now I got a problem, in a method I need to get the caller object reference otherwise, I can't succeed this operation. So please tell me a way how to get the caller object reference from a method. that method would be static or regular method anything will do for me.
    Edited by: navaneeth.j on Jan 29, 2010 11:20 PM

    navaneeth.j wrote:
    Actually my doubt is, I have a method "addition" method, which is using by many classes so my requirement is in the addition method I want to write a code snippet which will identify and get the the caller object. Actually I tried Reflection.getcallerclass but there I am getting "CLASS" object not the actual object reference, but I want object reference.
    Actually we have a huge project which is writen plain JAVA, so in this project the authors written the Database connection package for single database transaction. so now we are using this project source code for JSF application in this web application the DB package has serve based on the dynamic db connection parameters, so if we want to change this package fully means need to solve the dependency problem in hundreds of classes, so my point is if I can access the caller object in the DB package when ever it gets called by any class from any where of the project. So actually I liked Reflection.getcallerclass, the way of implementation perfectly works for me but it is not giving caller object reference, if something gives the caller object then I can get the DB connection parameters then there is no need to pass the parameters in the hierarchy.You can add a parameter (of type Object) to your addition() method
    and everywhere you call the addition() method also pass this (which from the POW of the addition() method will be a reference to the calling class instance).
    There may be alternative solutions
    but none that require less effort.

  • Passing paramaters to a method

    I am passing objects to another method.
    I do some changes to them and expect the changed objects to be available in the calling method ( since they are supposedely passed by reference) when the execution is returned to it. However, I don't get the changed objects but rather the old ones, before the method execution.
    Can someone explain?
    Thanks,
    Boris.

    This is an extremely common question. A search through this forum would be very useful to you.
    Java does not pass-by-reference in the same way C/C++ do. When you pass an object to a method, you can change the contents of the object using its methods and see the changes after the method completes in the calling method. In this way Java is similar to C/C++.
    However, you cannot change an object to equal another object or a new object inside a method and expect the changes to be visible after the method completes in the calling method.
    Here is an example.
    This will show changes and the line "String" would be printed.
      StringBuffer sb = new StringBuffer();
      method(sb);
      System.out.println(sb);
      public void method(StringBuffer buf) {
        buf.append("String");
      }However, this would not show changes and the line "Old String would be printed:
      String string = "Old String";
      method(string);
      System.out.println(string);
      public void method(String string) {
        string = "New String";
        // string.concat("New String) would also fail to work

  • Passing parameters to a method

    I am passing objects to another method.
    I do some changes to them and expect the changed objects to be available in the calling method ( since they are supposedely passed by reference) when the execution is returned to it. However, I don't get the changed objects but rather the old ones, before the method execution.
    Can someone explain?
    Thanks,
    Boris.

    I do some changes to them and expect the changed
    objects to be available in the calling methodIf you modify an object passed to a method, then the changes made to that object will be visible as soon as they are made.
    If you change the parameter so that it references some other object, this will NOT be seen in the calling method.
    You can "fake" it by putting the object in question in an array and passing the array. Better though is to just not expect methods to be able to change references they are passed to point at some other object.

  • Passing information to a method

    Im going through the java tutorial about passing information to a method
    and i am presented with this code.
    class RGBColor {
        public int red, green, blue;
    class Pen {
        int redValue, greenValue, blueValue;
        void getRGBColor(RGBColor aColor) {// is aColor a reference for RGBColor ?
            aColor.red = redValue; //is aColor then used to access the variables of RGBColor ?
            aColor.green = greenValue;// Are these values being initialised here
            aColor.blue = blueValue;
    RGBColor penColor = new RGBColor();// we are creating an instance of RGBColor called penColor
    pen.getRGBColor(penColor);// this is the bit i dont understand where the heck did pen.getRGBColor come from, i cant see anywhere where pen has been declared ..... or instantiated
    System.out.println("red = " + penColor.red +
                       ", green = " + penColor.green +
                       ", blue = " + penColor.blue);The follwoing is what it says in the java tutorial about the code
    The modifications made to the RGBColor object within the getRGBColor method affect the object created in the calling sequence because the names penColor (in the calling sequence) and aColor (in the getRGBColor method) refer to the same object.
    any guidance would be great

    Directly above the code that you don't understand is
    o A definition for a class Pen.
    o something called "pen" is probably declared somewhere like this:
    Pen pen;
    or
    Pen pen = new Pen(....);
    or
    Pen pen = something.getPen();
    So pen is an instance of Pen, and you can invoke the methods defined in class Pen, thus
    pen.getRGBColor(....);

  • Is it possible in java to pass reference of object in Java?

    Hello,
    I'm relativily new to Java but I have "solid" knowledge in C+ and C# .NET+.
    Is it possible in java to pass reference of object in Java? I read some articles about weakreferences, softreferences, etc. but it seems that it's not what I'm looking for.
    Here is a little piece of code I wrote:
    package Software;
    import java.util.Random;
    * @author Rodrigue
    public class RandomText
        private Random rand = new Random();
        private Thread t;
        private String rText = "Rodrigue";
        public RandomText()
            t = new Thread()
                @Override
                public void run()
                    try
                        while(true)
                            UpdateText();
                            sleep(100);
                    catch(InterruptedException ex)
            t.start();
        private void UpdateText()
            int i = rand.nextInt();
            synchronized (rText)
                rText = String.valueOf(i);
        public String GetText()
            return rText;
    }It's just a class which start a thread. This class updates a text with a random integer 10 times per second.
    I would like to get a reference on the String rText (like in C++ ;) yes I know, I must think in Java :D). So, like that, I could get one time the reference, thanks to the GetText function, and update the text when my application will repaint. Otherwise, I always have to call the GetText method ... which is slow, no?
    Are objects passed by reference in java? Or, my string is duplicated each time?
    Thank you very much in advance!
    Rodrigue

    disturbedRod wrote:
    Ok, "Everything in Java is passed by value. Objects, however, are never passed at all.". Reference of object is passed by value too.
    But, how to solve my problem in Java_? I have an object which is continually modified in a thread. From an another side, this object is continually repainted in a form.I'm not sure I totally understand your problem. If you pass a reference to an object, then both the caller and the method point to the same object. Changing the internal state of the object (e.g. by calling a setter method) through one reference will be observed through both references, since they both point to the same object.
    No, calling a method is not particularly slow. Especially if it's just a simple getter method that returns the value of a member variable.
    If this is happening in a multithreaded context, you'll have to use proper synchronization to ensure that each thread sees the others' changes.

  • Reference on a method

    i have a object obj with an method test() and i want to create a reference to this method ( type x = obj.test ). but i don't know what i must do.
    i hope you know what i mean - my english is not so good.

    mh - ok. i thought the method-reference points to the
    method that will be execute und so 'invoke' knows what
    method it must exactly execute.No, and this is pretty important. Objects encapsulate data and methods. Methods (ignoring static methods for the moment) are not just procedural functions like you would have in C. Suppose for example you wanted to call the getHeight() method of the java.awt.Rectangle class. You need to invoke this method on a certain Rectangle instance, right? Each instance has a different height.
    That's why you must pass in a target object when you call invoke() on an instance of Method.
    But again, you shouldn't do this (use reflection) if you can avoid it. Is there some reason that you can't simply code the method call in the usual way?

  • Pass Table to Class Methods

    Hi.
    I want to pass the Standard and Hashed Table to Methods of CLass.
    Can anyone please provide a code snippet ?
    Currently it only has string as passed by value
    My Class code is :
    class ZCL_SHM definition
      public
      final
      create public .
    public section.
        data STRING_ATTR type STRING .
    Theses Statements does not work :
    data z_Table type any table.
    data z_Table type Hashed Table.

    You can't use generic types in the way you want to.  But there's a way round - pass references.  So in your class, you want an attribute to be a table that can be any kind of table and any structure.  What you do is instead have a class attribute my_table_ref TYPE REF TO DATA.
    Now you need to work out how to set the class attribute my_table_ref.  One way is to use a setter method, like SET_TABLE_REF, which has one importing parameter i_ref TYPE REF TO DATA.  Body is me->my_table_ref = i_ref.
    From the program using the class, assuming you've defined a table somewhere "t_my_table", you can set the attribute like this.
    DATA: io TYPE REF TO myclass.
    GET REFERENCE OF t_my_table INTO io->my_table_ref.
    When you want to access the table within the class, you dereference to a field-symbol in the method.
    FIELD-SYMBOLS: <my_table> TYPE ANY TABLE.
    ASSIGN my_table_ref->* TO <my_table>.
    You can then access <my_table> as you would any other dynamic table.
    ( Note - you can use generic table as IMPORTING and EXPORTING parameters of method.  Just not as attributes or RETURNING parameters - for those, you just need to pass the reference instead ).
    matt

  • Passing Parameters via Post Method from Webdynpro Java to a web application

    Hello Experts,
    I want to pass few parameters from a web dynpro application to an external web application.
    In order to achieve this, I am referring to the below thread:
    HTTP Post
    As mentioned in the thread, I am trying to create an additional Suspend Plug parameter (besides 'Url' of type String) with name 'postParams' and of type Map.
    But when I build my DC, I am getting the same error which most of the people in the thread have mentioned:
    Controller XXXCompInterfaceView [Suspend]: Outbound plug (of type 'Suspend') 'Suspend' may have at most two parameters: 'Url' of type 'string' and 'postParams' of type 'Map'.
    I am using SAP NetWeaver Developer Studio Version: 7.01.00
    Kindly suggest if this is the NWDS version issue or is it something else that I am missing out.
    Also, if it is the NWDS version issue please let me know the NWDS version that I can use to avoid this error.
    Any other suggestion/alternative approach to pass the parameters via POST method from webdynpro java to an external web application apart from the one which is mentioned in the above thread is most welcome.
    Thanks & Regards,
    Anurag

    Hi,
    This is purely a java approach, even you can try this for your requirement.
    There are two types of http calls synchronous call or Asynchronous call. So you have to choose the way to pass parameters in post method based on the http call.
    if it is synchronous means, collect all the values from users/parameters using UI element eg: form and pass all the values via form to the next page is nothing but your web application url.
    If it is Asynchronous  means, write a http client in java and integrate the same with your custom code and you can find an option for sending parameters in post method.
    here you go and find the way to implement Asynchronous  scenario,
    http://www.theserverside.com/news/1365153/HttpClient-and-FileUpload
    http://download.oracle.com/javase/tutorial/networking/urls/readingWriting.html
    http://digiassn.blogspot.com/2008/10/java-simple-httpurlconnection-example.html
    Thanks & Regards
    Rajesh A

  • Passing parameter in a method

    hi i have a situation where i have to pass parameter to my method i don't what to pass the parameter define from the viewO because am not using parameter to query from the view,i just what to pass it to my procedure,my method is
                    public void submit_agr(String par_id,String dref_id,String tas_id,String agr_id){
                        ViewObject sub = this.findViewObject("AGR1");
                      i don't what to use this-> sub.setNamedWhereClauseParam("tas_id", tas_id); the tas_id is not in AGR1 VIEWO
                      // sub.
                        sub.executeQuery();
                        Row row = sub.first();
                        par_id = (String)row.getAttribute("par_id");
                        agr_id = (String)row.getAttribute("id");
                        callPerformSdmsLogon("SMS_FORM_TO_ADf.delete_agr(?)", new  Object[] {par_id,dref_id,tas_id,agr_id});
                    }

    i try this AM IN jDEVELOPER 11.1.2.1.0
                    public void submit_agr(String par_id,String dref_id,String tas_id,String agr_id){
                        ViewObject sub = this.findViewObject("AGR1");                 
                        Row row = sub.first();
                        sub.setNamedWhereClauseParam("tas_id", new Number(10));-how will i pass this to my procedure
                        sub.setNamedWhereClauseParam("dref_id", new Number(10));-how will i pass this to my procedure
                        par_id = (String)row.getAttribute("par_id");
                        agr_id = (String)row.getAttribute("id");
                        sub.executeQuery();
                        callPerformSdmsLogon("SMS_FORM_TO_ADf.delete_agr(?)", new  Object[] {par_id,dref_id,tas_id,agr_id});
                    }how will i pass the two prameter to my procedure
    Edited by: Tshifhiwa on 2012/07/01 3:14 PM

  • Can we pass Reference cursor using dblink

    Can we pass reference cursor from one DB to another DB using DBlink?
    I feel like it is not possible because the memory structure of same will be available in other DB.
    Could you please let me know whether we can give a work around which will solve the issue.
    Regards,
    Balu

    Balu, cursor is a memory area which contains parsed SQL statement and everything needed for
    the execution of the SQL command. That, of course, is instance specific and carrying it over to another DB using db-link would make no sense whatsoever.

  • Passing output to a method, I'm lost!

    I want to put all of my "output" including the returns on the three Temp functions in my method DisplayTemperatures, but I'm stuck and don't know how to do this. Please help
    import javax.swing.*;
    import java.text.DecimalFormat;
    public class Temp {
         public static void main(String[] args) {
              int Hourly_Temperatures[];
              String output;
              Hourly_Temperatures = new int[24];
              DecimalFormat twoDigits = new DecimalFormat ("00");     
              for (int i = 0;i < Hourly_Temperatures.length;i++) { //inputs temps               
                   Hourly_Temperatures[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter temperature between -50 & 130\nHour: " + twoDigits.format(i) + ":00"));
                   while (Hourly_Temperatures[i] < -50|| Hourly_Temperatures[i] > 130) {
                        Hourly_Temperatures[i] = Integer.parseInt(JOptionPane.showInputDialog(null,"Invalid Entry!\nEnter temperature"));
              output = "Hour\tTemperature\n"; // build output string
              for (int counter = 0; counter < Hourly_Temperatures.length; counter++)
              output += twoDigits.format(counter) + ":00" + "\t" + Hourly_Temperatures[counter] + "\n";
              JTextArea outputArea = new JTextArea();
              outputArea.setText(output);
              JOptionPane.showMessageDialog(null,outputArea,"24 hour Temperature",JOptionPane.INFORMATION_MESSAGE);
              //System.exit(0);
         } //end main
         public int High_Temp(int Temperatures[]){
              int highTemp = Temperatures[0];
              for (int counter =0; counter < Temperatures.length; counter++)
              if (Temperatures[counter]>highTemp)
              highTemp = Temperatures[counter];
              return highTemp;
         }//end method High_Temp
         public int Low_Temp(int Temperatures[]){
                   int lowTemp = Temperatures[0];
                   for (int counter =0; counter < Temperatures.length; counter++)
                   if (Temperatures[counter]<lowTemp)
                   lowTemp = Temperatures[counter];
                   return lowTemp;
         }//end method Low_temp
         public int Average_Temp(int Temperatures[]){
              int total = 0;
              for (int counter =0; counter < Temperatures.length; counter++)
              total += Temperatures[counter];
              return total / Temperatures.length;
         }// end method Average_Temp
         public void Display_Temperatures(int Temperatues[], int Average_Temp){
        }// end method Display_Temperatures
    } //end class

    I am not sure I understand what problem you are having in passing output to the method. However, I'll guess:
    If you want to pass output to Display_Temperatures() then:
    1. change Display_Temperatures to accept a String
    2. move display code from main to Display_Temperatures.
    3. pass output to Display_Temperatures()
    Display_Temperatures(output)If you want to do all the calculations also in Display_Temperatures:
    1. change Display_Temperatures to accept only 1 arg - int[]
    2. move all the calculations & display code from main to Display_Temperatures
    3. pass Hourly_Temperatures to Display_Temperatures()
    Display_Temperatures(Hourly_Temperatures)If you make these changes then you will encounter some compilation errors. Post them here only after you've first tried to understand and fix them.
    If it is something else you want to do, then you will have to explain it better; at least I've not understood your problem.
    The naming standards that almost all jave professionals follow is:
    1. not to use underscore char ( _ ) in method names; so Display_Temperatures shd be DisplayTemperatures
    2. var names don't have _ char within the name and begin with a lower case; so Hourly_Temperatures shd be hourlyTemperatures
    It is generally a good practice to create an instance of the class in the main() method and write the process code in the instance methods instead of putting all that code in main() itself. Read the [url http://java.sun.com/docs/books/tutorial/]tutorials for this starting from the "Your First Cup of Java".

  • Passing objects to a method.

    Hi,
    I was reading this from a book and puzzled by this suggestion:
    for example:
    public Employee findEmployee(String employeeID);
    This method takes a String specifying a unique employee id and returns the Employee object with that id, null otherwise. Don't pass un-necessary objects to methods, and return the appropriate results.
    Why not passing objects to methods, I found it is convenient to pass objects to methods, why ?
    Thanks in advance !
    Tee

    Of course you can pass objects to methods. A String is also an object.
    The author doesn't say to not pass any objects to methods, only no unnecessary objects. He propably means that you don't need a method likepublic Employee findEmployee(String employeeID, String country)to retrieve the Employee if the employee ID by itself is unique or you don't use the country in the method, to give you an example.

  • Passing hashtable to a method

    Can anyone show me the syntax to pass Hashtable to a method???
    c.buildHT(cal, ht); //where ht is the hashtable...
    buildHT(Calendar cal, Hashtable ht) {
    Is this OK? I tried....but I am getting errors...Can anyone clarify me about this?????

    I guess, instead of passing the entire HashTable, why dont you try passing only the keys of the hashtable, and accessing the values of the hashtable, thro' their respective keys

Maybe you are looking for

  • Get data in a subreport based on a shared variable from the main report.

    Goodd morning, My question/problem is how to manage this scenario. I am transfering 2 shared variables (pereiod from /period To, ) from the main report to a subreport and now  i would like to get data in this subreport based on these 2 variables... T

  • ITunes 11.1.3 Store crashes the program when I attempt to access it

    I posted this over a month ago and no one answered then, so I'll see if I can get some sort of advice now. I am currently running Windows 7 64bit, and realize I am running an older version of itunes, due to all the recent upgrade issues, including it

  • Cost center assignment of GRIR clearing account

    Hello Expert, There is a purchase order assigned to an asset.  the cost center K8071 is maintained in the asset. Later, the cost center is changed to K8410. Normally this cost center will always be determined from the asset. But in goods receipt (MIG

  • XCP connection problem

    Hello everybody, I have a very similar problem as mentioned in the link below: http://forums.ni.com/ni/board/message?board.id=30&message.id=3202&query.id=250743#M3202  Since i dont see any solution to the above problem i shall put forth the exact nat

  • Number range for local PO

    Hi experts I have the the following scenario For shopping carts fron catalogs and with material number assigned my scenario is ECS, so if the shopping carts is complete after aproval a Po is created and replicated to R/3, if the shopping cart is inco