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.

Similar Messages

  • Passing object references to methods

    i got the Foo class a few minutes ago from the other forum, despite passing the object reference to the baz method, it prints "2" and not "3" at the end.
    but the Passer3 code seems to be different, "p" is passed to test() , and the changes to "pass" in the test method prints "silver 7".
    so i'm totally confused about the whole call by reference thing, can anyone explain?
    class Foo {
        public int bar = 0;
        public static void main(String[] args) {
                Foo foo = new Foo();
                foo.bar = 1;
                System.out.println(foo.bar);
                baz(foo);
                // if this was pass by reference the following line would print 3
                // but it doesn't, it prints 2
                System.out.println(foo.bar);
        private static void baz(Foo foo) {
            foo.bar = 2;
            foo = new Foo();
            foo.bar = 3;
    class Passer2 {
         String str;
         int i;
         Passer2(String str, int i) {
         this.str = str;
         this.i = i;
         void test(Passer2 pass) {
         pass.str = "silver";
         pass.i = 7;
    class Passer3 {
         public static void main(String[] args) {
         Passer2 p = new Passer2("gold", 5);
         System.out.println(p.str+" "+p.i);  //prints gold 5
         p.test(p);
         System.out.println(p.str+" "+p.i);   //prints silver 7
    }

    private static void baz(Foo foo) {
    foo.bar = 2;
    foo = new Foo();
    foo.bar = 3;This sets the bar variable in the object reference by
    foo to 2.
    It then creates a new Foo and references it by foo
    (foo is a copy of the passed reference and cannot be
    seen outside the method).
    It sets the bar variable of the newly created Foo to
    3 and then exits the method.
    The method's foo variable now no longer exists and
    now there is no longer any reference to the Foo
    created in the method.thanks, i think i followed what you said.
    so when i pass the object reference to the method, the parameter is a copy of that reference, and it can be pointed to a different object.
    is that correct?

  • Passing object references via methods

    Why is the JFrame object not being created in the following code:
    public class Main {
      public static void main(String[] args) {
        Main main = new Main();
        JFrame frame = null;
        main.createFrame(frame);  // <-- does not create the "frame" object
        frame.pack();
        frame.setVisible(true);
      private void createFrame(JFrame frame) {
        frame = new JFrame("createFrame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }Thanks.

    These explanations are great; real eye openers.
    OK. This could be a "way out in left field" question. I am just starting out with Java. But I want to ask:
    Objects are stored in the heap?
    Object references and primitives are stored on the stack?
    Adjusting heap size is straight-forward. A larger heap can store more/larger objects. What about stack sizes?
    C:\Dev\java -Xss1024k Main
    I assume this refers to method's stacks. But, what about object scoped, and class scoped, object references?
    public class Main {
      private static List list = new ArrayList(); // class scoped
      private JFrame frame = new JFrame();  // object scoped
      public static void main(String[] args) { ...... }
      private void createFrame() { .... }
    }How is the reference to list and frame stored, with regard to memory management?
    Do objects have stacks?
    Do classes have stacks?
    If not, how are the list and frame references stored (which helps me understand reference scoping).
    Would the overflow of a method stack (ex. via recurssion) also overflow the method's object and the method's class stacks?
    If these questions are stupid, "out of left field", don't matter, etc. Just ignore them.
    But the knowledge could help me avoid future memory related mistakes, and maybe pass a "Java Certified Developer" exam?
    My original question is already answered, so thanks to all.

  • How do u pass an object into a method

    I want to create a method getData that takes an object of type Helper and returns an object of the same type.
    how do u pass objects into a method and how do u get objects as returns im a bit confused

    That will just allow you to pass a parameter. If you want to return a helper object
    Helper paramHelper = new Helper();
    Helper someHelper = callMethod(paramHelper);
    public Helper callMethod(Helper hobj) {
        //<some code>
        Helper retHelper = new Helper();
        //<blah, blah>
        return retHelper;

  • 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 object as a parameter to a method while dragging it to UI

    Hi
    I am using webservice datacontrol to invoke "Secured webservice". Dragged a method from datacontrol and dropped it into UI, it passes a object(i.e., SOAHeader object) as input parameter and returns "String" as a output. So, here I have created a java class and passing it as an object to the method. When i deployed the app into Android emulator, while clicking that method as a button, its throwing me an error message *"HTTPStatusCode 500: Server encountered an unexpected condition which prevented it from fulfilling the request"*. I tried to configure debugger to get log for remote deployment, after that the application itself not opening in emulator. Then how can i find the exact reason for this error message?
    Here I got few doubts,
    1) Is this the correct way of passing the object as a method input parameter?
    2) How can i invoke secured web service through "Webservice datacontrol" in ADF Mobile. I searched in google and got a link by andrejus "http://andrejusb.blogspot.be/2012/11/adf-mobile-secured-web-service-access.html", but not understanding about "*adfCredentialStoreKey*", what is it? and how can i use it?. I set the security policies as mentioned, is it enough to invoke the secured webservices without giving username/password?. Bit confused, can anyone please tell me more about accessing secured webservices from webservice datacontrol.
    3) I tried to configure debug option(as mentioned in developer's guide) to get log of remote deployment. I changed *"java.debug.enabled=true"* in cvm.properties. After that configuration, unable to open that mobile app through emulator. What could be the reason?
    Regards
    Raj

    Thank you Shay.. you have posted new demo's regarding this for people like us(Newbies in ADF), awesome :) Please keep continuing.. This demo & Andrejus sample helps me a lot to do sample authentication using "**Remote login server**".
    Small doubt, Is it possible to inject user credentials with webservice request without creating *"regular" web ADF application, securing it, and deploying it on a server* . I read it in mobile document that,
    For secured web services, the user credentials are dynamically injected using ADF Mobile uses Oracle Web Services Manager (OWSM) Lite Mobile ADF Application Agent to create and configure proxies, as well as to request services through the proxies. The user credentials are injected into the OWSM enforcement context when proxies are configured.
    I am new with this OWSM, can you please give me some hints like how to proceed further for implementing authentication using OWSM lite mobile ADF Application Agent.
    Thanks in advance

  • Passing Objects to methods, why aren't they changed permanently?

    If an object is passed by reference, and primitive types are passed by value; then why does the following programme not alter the original values of A and B?
    I m trying to pass parameters into a method so that they can be altered and returned, can any one suggest a way to do this.
    Thanks,
    Ben.
    public class Application2 {
    Application2(){ }
         void goProc(){
              Integer A=new Integer(4);
              Integer B=new Integer(6);
              add(A,B);
              System.out.println("A2 " + A);
              System.out.println("B2 " + B);
         void add(Integer A,Integer B){
              System.out.println("A " + A);
              System.out.println("B " + B);
              A=A.valueOf(String.valueOf((A.intValue()+B.intValue())));
              System.out.println("added " + A);
    //Main method
         public static void main(String[] args) {
              Application2 App = new Application2();
              Integer A=new Integer(4);
              Integer B=new Integer(1);
              App.add(A,B);
              System.out.println("A1 " + A);
              System.out.println("B1 " + B);
              App.goProc();
    OUTPUT.
    A 4
    B 1
    added 5
    A1 4
    B1 1
    A 4
    B 6
    added 10
    A2 4
    B2 6

    If an object is passed by reference,It isn't. Instead, a pointer to the object is passed
    by value.That is exactly what passing by reference is.
    Objects passed by reference can be modified and it will affect the caller, but modifying the reference (assiging a new object) won't affect the caller.
    I m trying to pass parameters into a method so that
    they can be altered and returned, can any one
    suggest a way to do this.I think this is bad OO programing, it results in less readable code and may be hard to debug. Better is to make the method return the result and let the caller assign the new value. (This is my personal oppinion at least)

  • Pass object to xslt stylesheet and invoke its methods

    I'd like to pass an external created object to a xslt stylesheet to dynamically modify the xslt file at run time. After searching around for weeks, I'm really desperate.
    I used Xalan transformer's method setParameter(name, obj) to initialize a variable in xslt file with this object. Then the object's method was invoked.
    The class that I want to invoke the method:
    class test{
    private String testString = "abc";
    public String valueOf(){
    return testString;
    xslt file:
    <xsl:param name="myType"></xsl:param>
    <<xsl:variable name="new-pop"
    select="my-class:valueOf($myType)">
    Any help is greatly appreciated.
    Thank you.
    Message was edited by:
    Orbital
    Message was edited by:
    Orbital

    Thank sabre. I have looked through your link.
    The problem is for all the info I knew, we can only
    create a new object inside the stylesheet using new()
    and then invoke this particular object's instance
    method.
    However, I want to pass an already created java
    object into the stylesheet and then invoke its
    method.
    Xalan seems to not allow this. I have tried to pass
    an object as the parameter of
    transformer.setParameter(name, object) but it doesn't
    work.
    Any one know what 3rd party transformer that allow to
    pass object directly into xslt?setParameter will work... in your XSL, you should have
    <xsl:param name="myParam" />set the parameter in your transformer like what you had in your post...
    In your XSL header, you must declare the your Java object namespace and path, such as:
    xml:myJavaObject= "com.MyCompany.MyJavaObject"then in your template or anywhere that you want to use your object, you should have:
    <xsl:variable name="runningMyMethod" select="myJavaObject:myJavaMethod($myParam)" />The XSL will treat $myParam as the instance object, if there is any other method parameters needed to be passed in do:
    <xsl:variable name="runningMyMethod" select="myJavaObject:myJavaMethod($myParam, 'blah', 'blah')" />Good luck.

  • Passing object as parameter in JSF using h:commandLink tag

    Hi ,
    I have a scenario in which i need to pass objects from one jsp to another using h:commandLink. i read balusC article "Communication in JSF" and found a basic idea of achieving it. Thanks to BalusC for the wonderful article. But i am not fully clear on the concepts and the code is giving some error. The code i have is
    My JSP:
    This commandlink is inside a <h:column> tag of <h:dataTable>
    <h:commandLink id="ol3"action="ManageAccount" actionListener="#{admincontroller.action}" >
                   <f:param id="ag" name="account" value="#{admincontroller.account}" />
                   <h:outputText id="ot3" value="Manage Account" rendered="#{adminbean.productList!=null}" />
                   </h:commandLink>
    Also a binding in h:dataTable tag with the  binding="#{admincontroller.dataTable}"
                      My Backing Bean:
    public class CompanyAdminController {
              private HtmlDataTable dataTable;
              private Account account=new Account();
    public HtmlDataTable getDataTable() {
            return dataTable;
    public Account getAccount() {
             return this.account;
    public void setAccount(Account account) {
              this.account = account;
          public void action(){
                account= (Account)this.getDataTable().getRowData();
           } faces-config.xml
    <navigation-rule>
        <from-view-id>/compadmin.jsp</from-view-id>
        <navigation-case>
          <from-outcome>ManageAccount</from-outcome>
          <to-view-id>/manageAccount.jsp</to-view-id>
        </navigation-case>
      </navigation-rule>
    <managed-bean>
              <managed-bean-name>admincontroller</managed-bean-name>
              <managed-bean-class>com.forrester.AdminController</managed-bean-class>
              <managed-bean-scope>request</managed-bean-scope>
              <managed-property>
                   <property-name>account</property-name>
                   <property-class>com.model.Account</property-class>
                   <value>#{param.account}</value>
             </managed-property>
         </managed-bean>My account object:
    public class Account {
    string name;
      public String getName()
        return this.name;
      public void setName(String name)
           this.name=name;
      }I need to display #{admincontroller.account.name} in my forwarded jsp. But I am not sure whether the code i wrote in commandlink is correct. I get an error if i use <f:setActionListener> . No tag "setPropertyActionListener" defined in tag library imported with prefix "f"
    Please advise.
    Edited by: twisai on Oct 18, 2009 11:46 AM
    Edited by: twisai on Oct 18, 2009 11:47 AM
    Edited by: twisai on Oct 18, 2009 11:48 AM

    Yes.. iam removed the managedproperty from faces-config. But still i get the null pointer exception on main jsp itself and i am taken to second jsp manageaccount.jsp. Did you find anything wrong in my navigation case in the action method??
                                     public String loadAccount(){
               Account account = (Account)this.getDataTable().getRowData();
                return "ManageAcct";And also can you please answer this question i have
    The AdminController is the backing bean of 1st JSP and manageAccontController is the backing bean of forwarded JSP .
    Can i put this action method and dataTable binding in a 2nd manageAccontController backing bean instead of AdminController. But if i do that way dataList binding in h:dataTable tag will be in first JSP backing bean and dataTable binding to 2nd JSP. Not sure how to deal with this.
    {                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to create new java objects in native methods?

    Hello,
    Is it possible to create java objects and return the same to the java code from a native method?
    Also is it possible to pass java objects other than String objects (for example, Vector objects) as parameters to native methods and is it possible to return such objects back to the java code?
    If so how can I access those objects (say for example, accessing Vector elements) inside the native code?
    What should I do in order to achieve them?
    Regards,
    Satish

    bschauwe is correct in that constructing Java objects and calling methods on Java objects from native code is tough and takes some study. While you're at it, you might want to check out Jace, http://jace.reyelts.com/jace. It's a free open-source toolkit that really takes the nastiness out of doing this sort of stuff. For example,/**
    * A C++ function that takes a java.util.Vector and plays around with it.
    public void useVector( java::util::Vector& vector ) {
      // Print out all the contents of the vector
      for ( Iterator it = vector.iterator(); it.hasNext(); ) {
        cout << it.next();
      // Add some new elements to the vector
      vector.addElement( "Hello" );
      vector.addElement( "world" );
    } All this code just results in calls to standard JNI functions like FindClass, NewObject, GetMethodID, NewStringUTF, CallObjectMethod, etc...
    God bless,
    -Toby Reyelts

  • 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

  • How to use an object's paint method

    I have created a class imagePanel which extends a jPanel to display an image. When I create a new imagePanel object I pass it an image argument which is used to paint my image on the jPanel, so far so good. I don't wish to have to continuously create new ImamePanels to display new images so I thought I could make a set_Image method that would set a new image in an exising imagePanel object. This is where I run into problems how to use the existing object paint method to replace the image. I tried this without success:
    public Image setMyImage (Image myImage)
    imageX = myImage; // imageX is the image that is painted by the imagePanel object's paint method
    paint(g);
    Something must be wrong on how I access the paint method. Thanks for any help.
    Jack

    Yahoooo, got it. This was the code I needed and thanks for your help:
    public void setImage (Image myImage)
    imageX = myImage;
    repaint(300);
    }

  • Passing text component to methods

    I have a method that reads a file and output puts it to a JTextArea. Everything is working fine but I am wondering if I can pass an object from a class above JTextArea (like TextComponent). Looking for a generic feel with whatever text based component I passed...will this make a difference with lightweight and heavyweigth components (swing vs. awt)? Or even streams for that matter? Will byte and character streams act differently?
    What is the super class of all text based gui components?
    What is the super class of all streams?
    Yes I have read the java api doc on streams and using swing! Thanks

    You have me until
    Everything is working fine but I am wondering if I can pass an object from a class above JTextArea (like TextComponent).What are you asking for here?
    You want to know if you can pass an object to a method? Yes.
    You want to know if you can modify a class further up in JTextArea's hierarchy, so it has a method that passes an object to another method? Yes, by extending it and implementing the functionality you want.
    Looking for a generic feel with whatever text based component I passed...will this make a difference with lightweight and heavyweigth components (swing vs. awt)?Not sure what you were asking for in the first place, so I'm unable to help you with this one.
    Or even streams for that matter? Will byte and character streams act differently?If you're asking, "When I pass a stream through a method, will it act differently when I use it inside that method?", then I can answer no, it will not. You are passing your stream by reference.
    class MyClass {
       private Object anObject;
       public MyClass() {
          anObject = new Object();
          MySecondClass secondClass = new MySecondClass(anObject);
    class MySecondClass {
       private Object theSameObject;
       public MyClass(Object argument) {
          theSameObject = argument;
    }In the above example, anObject was created in MyClass, and passed to the constructor of MySecondClass. The field theSameObject in MySecondClass is set to point to the Object passed into its constructor, which just happens to be the Object anObject created in MyClass. anObject was created in MyClass. theSameObject is essentially the exact same Object in that it references (points to) anObject.
    If I'm wrong feel free to call me on it, java gurus.
    What is the super class of all text based gui components?AWT or Swing?
    If it's AWT, look up the API for an AWT text component, try TextField, and look at the class hierarchy.
    If it's Swing, do the same for JTextField. You can easily do some detective work and figure out the super classes of 'text based gui components'.
    What is the super class of all streams?You can do the same as above for streams as well.
    Yes I have read the java api doc on streams and using swing! ThanksIf you've read the API docs on streams and Swing, then why did you ask the last two questions? Not trying to offend, it just seems kind of wierd.

  • 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(....);

Maybe you are looking for

  • How to go about getting my MBP replaced?

    Okay, so I was on an agonizing wait of 1 month for my MPB to arrive, and I was extremely excited when I got it. After using it for a week or so, I've become really perturbed by the whole EXTREMELY HOT aspect, and screen whine issues. My MBP gets supe

  • BEA ProcMgr and TListen 9.1 (Port 3050)

    Hi On the NT process scheduler i found the above 2 services. Can you please help me understand a. what these services are for b. whether they need to be bounced in a particular order while bouncing the Process Scheduler c. What are the processes on U

  • Quicktime movies will not play if I delete 'media' files

    I have created several Quicktime movies so that I can see the movies after I delete the imported media files which are quite large. But after I delete those files I cannot play the Quicktime movie. I get messages saying that the parts cannot be found

  • Report Scenario of Facts and Dimensions

    Hi All, If the dimensions d1 and d2 are joined to f1 and dimensions d3 and d4 are joined to f2 then the report is expecting the data from the both the fact tables and one dimension table. How can be achieved? Please let me know on this. Thanks in Adv

  • BUG 10.1.3 PageDef

    When you delete a component from a jspx page, it does not delete it from the PageDef.