How to code a method that returns string for class object

I have a class named Address.
public class Addresss{   
private String street;   
private String city;            // instance variables  
private String zipcode;}I have been asked to write a method that returns a string for Address object. I dont understand how to create address object.Can anyone pls help me understand.
do I have to write (for creating object)
Address addressObject  = new Address(); ( coding method that returns a string for address object) ---> I really dont understand this part.

looks almost right. The problem is that your method name AddressBookEntry does not match the name of your class AddressBook and therefore is not a constructor.
Furthermore, you probably need to make a distinction between a single entry into the address book which consists of a single name and a single address, (which is just what you have done) and an address book itself which is probably a list of AddressBookEntries
So for your code I would change the class that you called "AddressBook" to "AddressBookEntry" and have a third class that represents the collection of AddressBookEntries.
Now to be honest, I don't know why you keep the name split apart from the street address portion of the address. I would be more inclined to keep the name as a field of the address itself, but it's your code, you carve it up the way you like.

Similar Messages

  • Methods that return more than one object.

    Hello everyone,
    I don't know if this has ever been proposed or if there's an actual solution to this in any programming language. I just think it would be very interesting and would like to see it someday.
    This is the thing: why isn't it possible for a method to return more than one object. They can receive as many parameters as wanted (I don't know if there's a limit), but they can return only 1 object. So, if you need to return more than one, you have to use an auxiliary class...
    public class Person {
       private String name;
       private String lastName;
       public Person(String name, String lastName) {
          this.name = name;
          this.lastName= lastName;
       public String getName() {
           return name;
       public String getLastName() {
           return lastName;
    }So if you want to get the name of somebody you have to do this, assuming "person" is an instance of the object Person:
    String name = person.getName();And you need a whole new method (getLastName) for getting the person's last name:
    String lastName = person.getLastName();Anyway, what if we were able to have just one method that would return both. My idea is as follows:
    public class Person {
       private String name;
       private String lastName;
       public Person(String name, String lastName) {
          this.name = name;
          this.lastName= lastName;
       public String name, String lastName getName() {
           return this.name as name;
           return this.lastName as lastName;
    }And you would be able to do something like:
    String name = person.getName().name;and for the last name you would use the same method:
    String lastName = person.getName().lastName;It may not seem like a big deal in this example, but as things get more complicated simplicity becomes very useful.
    Imagine for example that you were trying to get information from a database with a very complex query. If you only need to return 1 column you have no problem, since your object can be an array of Strings (or whatever type is necessary). But if you need to retrieve all columns, you have three options:
    - Create 1 method per column --> Not so good idea since you're duplicating code (the query).
    - Create and auxiliary object to store the information --> Maybe you won't ever use that class again. So, too much code.
    - Concatenate the results and then parse them where you get them. --> Too much work.
    What do you think of my idea? Very simple, very straight-forward.
    I think it should be native to the language and Java seems like a great option to implement it in the future.
    Please leave your comments.
    Juan Carlos García Naranjo

    It's pretty simple. In OO, a method should do one thing. If that thing is to produce an object that contains multiple values as part of its state, and that object makes sense as an entity in its own right in the problem domain--as opposed to just being a way to wrap up multiple values that the programmer finds it convenient to return together--then great, define the class as such and return an instance. But if you're returning multiple values that have nothing to do with each other outside of the fact that it's convenient to return them together, then your method is probably doing too much and should be refactored.
    As for the "if it increases productivity, why not add it?" argument, there are lots of things that would "increase productivity" or have some benefit or other, but it's not worth having them in the language because the value they add is so small as to no be worth the increase in complexity, risk, etc. MI of implementation is one great example of something that a lot of people want because it's convenient, but that has real, valid utility only in very rare cases. This feature is another one--at least in the domain that Java is targetting, AFAICT.

  • Calling a method that returns values in a map - using JSTL

    Hi I have a method within an object that returns a List for a particular category
    public List<String> getFieldsInCategory(String categoryName){
        return _categoryFieldsMap.get(categoryName); //This is a map that returns a list                                                             
      }Trying to call the above function in jsp, the object is available as "document",
    how do i pass a key to the above function to return a List.
       <c:forEach items="${document.fieldsInCategory('ABSTRACT')}" var="temp">How do i get the list by passing a string key to my method,
    please let me know how to go about this.
    Thanks

    JSTL can not directly call methods that take parameters.
    All it can do is access javabean properties - ie via the revealed get/set methods.
    You can fudge it by having a seperate variable to set:
    Map  _categoryFieldsMap;
    String category = null;
    public void setCategory(String category){
      this.category = category;
    public String getCategory(String category){
      return category;
    public List<String> getFieldsInCategory(){
        return _categoryFieldsMap.get(categoryName); //This is a map that returns a list                          
      }You would then do it like this in your JSP:
    <c:set target="document.category" value="ABSTRACT"/>
    <c:forEach items="${document.fieldsInCategory}" var="temp">
    ...The other alternative is to return the entire map to the page.
    EL accesses maps quite handily.
    so given a method that returns the map:
    public Map getCategoryFieldsMap(){
    return _categoryFieldsMap;
    then the expression: ${document.categoryFieldsMap.ABSTRACT} returns what you are after.
    Hope this helps,
    evnafets

  • Web Service Method that returns an ArrayList

    Hi guys,
    I have to create a web service method that returns an ArrayList, but it's not working. My problem is:
    With the "@XmlSeeAlso" annotation, my client prints the result, but the ArryaList is not from java.util, it's from org.me.calculator so I can't use it.
    If I remove this annotation, I get no result, with this error message on Tomcat 6:
    [javax.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context.]
    I'm a newbie, and trying to understand web services (I read some posts here, but didn't get the point, from its answers), but this problem I just can't figure out how to solve....
    WEb Service
    package org.me.calculator;
    import java.io.Serializable;
    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    import java.util.*;
    import java.util.ArrayList;
    import javax.xml.bind.annotation.XmlSeeAlso;
    * @author eduardo.domanski
    @WebService()
    @XmlSeeAlso({java.util.ArrayList.class}) // With this, I can see the result on client, but, the ArrayList is an org.me.calculator.ArrayList class.... Strange...
    public class CalculatorWS {
        @WebMethod(operationName = "valores")
        public ArrayList valores(@WebParam(name = "a") int a,
                           @WebParam(name = "b") int b) {
            ArrayList teste = new ArrayList();
            ArrayList a1 = new ArrayList();
            a1.add(a);
            a1.add(b);
            ArrayList a2 = new ArrayList();
            a2.add(a+b);
            a2.add(a-b);
            teste.add(a1);
            teste.add(a2);
            return  teste; 
    }CLient
    package org.me.calculator.client;
    import java.io.*;
    import java.net.*;
    import java.util.ArrayList;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class ClientServlet extends HttpServlet {
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ClientServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet ClientServlet at " + request.getContextPath() + "</h1>");
            try { // Call Web Service Operation
                org.me.calculator.CalculatorWSService service = new org.me.calculator.CalculatorWSService();
                org.me.calculator.CalculatorWS port = service.getCalculatorWSPort();
                // TODO initialize WS operation arguments here
                int i = 8;
                int j = -6;
                // TODO process result here
                ArrayList result = (ArrayList) port.valores(i, j);
                out.println("Result = " + result);
            } catch (Exception ex) {
                System.out.println(ex);
            // TODO handle custom exceptions here
            out.println("</body>");
            out.println("</html>");
            out.close();
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            processRequest(request, response);
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            processRequest(request, response);
    }THank you all,
    Eduardo
    Edited by: EduardoDomanski on Apr 23, 2008 4:40 AM

    I forgot to say that, when I try to return an ArrayList of an object, for example, ClassA, which is on the package org.me.classes, on my Server App, the ArrayList is returned, but the objects are from type org.me.calculator.ClassA. It should be from org.me.classes.ClassA, right?
    This package also exists on my client App, to use the object, but as the returned type is from another package, I can't even cast it. I tried some annotations @Xml... but it failed.
    Packages
    ServerApp
    org.me.calculator
    CalcWS.java
    org.me.classes
    ClassA.java
    Client App
    org.me.classes
    ClassA.java
    The return from my method should be an ArrayList of org.me.classes.ClassA, but when I print it, on client, it's from org.me.calculator.ClassA.
    Does anybody knows, or had the same problem?
    Thanks,
    Eduardo

  • F5 Big IP 4000 Send /Return String for Exchange 2013

    Hi,
    I need to Implement F5 Big IP 4000 and need to set send / return string for Exchange 2013 server for OWA monitoring... Can anyone help me with Exact output String.
    Amit

    Hi,
    In the Send String box enter in GET /owa/healthcheck.htm.  In the
    Receive String box, enter in 200 OK.
    Here is a related article for your reference.
    http://port25guy.com/2013/07/24/how-to-use-managed-availability-in-exchange-2013-with-your-load-balancer/
    Note: Microsoft is providing this information as a convenience to you. The sites are not controlled by Microsoft. Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. Please make
    sure that you completely understand the risk before retrieving any suggestions from the above link.
    Hope this is helpful to you.
    Best regards,
    Belinda Ma
    TechNet Community Support

  • How to find the TCODE that is created for the table maintanance generator

    Hi ,
    How to find the TCODE that is created for the table maintanance generator of particular table,if we only know the table name.
    Regards
    Ramakrishna L

    Hello,
    I try it this way
    1. Goto SE16 --> enter table TSTCP.
    2. In the selection-screen displayed, enter
    PARAM = *<ZTABNAME>*
    You will get the t-code for the TMG.
    BR,
    Suhas
    PS: Are you sure a t-code has been created for this TMG ?

  • How can I transfer products that were purchased for me by our IT vendor to our own Adobe account

    How can I transfer products that were purchased for our company by our IT vendor to our own Adobe account? - we are no longer using this IT vendor.

    There's no way at all except to delete them and then buy them from your Apple ID.
    (97379)

  • Interfaces declare methods that one or more classes may or may not implemen

    Interfaces declare methods that one or more classes may or may not implement.
    true or false?

    Encephalopathic wrote:
    If you want to appear to be more than just someone scrounging for someone else to do their homeworkHe/she is what they is
    [http://forum.java.sun.com/thread.jspa?threadID=5292343]
    [http://forum.java.sun.com/thread.jspa?threadID=5283461]
    [http://forum.java.sun.com/thread.jspa?threadID=5283412]
    [http://forum.java.sun.com/thread.jspa?threadID=5279385]

  • Method "equals" not implemented for class "Pan1"

    Method "equals" not implemented for class "Pan1" -- this is the error I'm getting while running one static Analyzer. Can anybody say, what is this error , and how to rectify it ?

    The static analyzer may have noticed that either you may invoke .equals() on instances of this class (possibly through polymorphism) and you have not implemented the method in your class. This is most likely a warning since many times lack of an implemented .equals() method in such cicumstances will lead to Object.equals() being executed and that simply checks to see if the object references are the same - quite a bit stronger than what one would probably expect from .equals();
    it is also possible that you did implement an equals() method but that you used the wrong argument type. This is a common mistake:
    public boolean equals(MyClass other) {
       return /* something */;
    }This type of warning may be ignored, or if it troubles you and there is no way to disable it for the classes that you know you have implemented correctly, you might consider adding an equals method of the form:
    public boolean equals(Object other) {
       return super.equals(other);
    }Chuck

  • How can i have a refrence of a java class object instance in my c++ project

    Hi!
    How can i have a refrence of a java class object instance in my c++ project. Is there a way?

    hahaxia wrote:
    The second question is the big one. The first question is half of the problem of "c++ to java" invocation and access. But the other half which is "java to c++ " invocation and access is still not solved. jni only provide the "java to c++ " DLL invocation Wrong,
    Using JNI your java classes can have methods implemented in C/C++.
    Using JNI you can call java classes.
    There is no other possible interaction between C++ and java, so it does it all.

  • How to set user preferred timezone in OBIEE for all objects.

    How to set user preferred timezone in OBIEE for all objects based on users TZ(may be from @{session.timeZone}). without changing My Account -> Preferences

    Check
    Time Zone Specification from http://docs.oracle.com/cd/E12844_01/doc/bip.1013/e12187/T421739T481157.htm#4535403
    just in case https://blogs.oracle.com/xmlpublisher/entry/how_to_keep_your_dates_from_go

  • How to execute external scripts that returns error code

    Hi,
    What is the best approach to execute a unix shell scripts in ODI thats return a code e.g. 1- found , 2 - not found. The return code needs to assigned to a ODI variable. I have gone through some posts that explained how to refresh odi variable from file. well in that case i have to write the error code to a file and then read to a ODI variable. Is there any direct approach available ? Is there any other way I can assign values to ODI variable other than its refresh methods ( select from <source>) for e.g. Inside odi procedure ?
    Thanks you all for answering this
    -Mansa

    In order to reduce the steps we need to do that using java itself. It will be something like this .
    Step 1. ODI procedure - Technology Java Bean shell .
    <@
    JAVA OS COMMOND CODE TO TRIGGER THE PEARL SCRIPT.
    GET THE RETURN INTO JAVA VARIABLE ( SAY FOR EX result )
    @>
    Step 2. Creating the variable.
    select any oracle schema
    select '<@=result@>' from dual
    and call this variable in refresh mode in package.
    Step 3. processing with variable what ever you wish to do .
    Personally i have not tried the java os command to get the return code . I will look into this and let you know sooner or later. If you want you can explore the code or google the code and see if what you are planning to achive is possible ,else the other way can be using the file as you know.

  • How to invoke AM method that accepts parameter other than string

    Hi
    I need to pass 2 date parameters to my AM method.
    I checked the jdev doc and found the below method that can be used for any of the parameter other than String
    public Serializable invokeMethod(String methodName,
    Serializable[] methodParams,
    Class[] methodParamTypes)
    one thing i am not able to understand is how to pass multiple dates in a single Class parameter.
    can anyone tell me the invoke method syntax for passing 2 dates.

    Hi,
    Suppose you have a string and two date parameters
    String test;
    Date date1;
    Date date2;
    then pass it like this
    OAApplicationModule am = pageContext.getApplicationModule(webBean);
    Serializable parameters[] = {test,date1,date2};
    Class paramTypes[] = {String.class,Date.class,Date.class};
    am.invokeMethod("initSummary", parameters, paramTypes);
    Thanks,
    Gaurav

  • How Do I Call PL/SQL Stored Procedure That Returns String Array??

    I Have Problem Calling An Oracle(8i) Stored Procedure That Returns Array Type (Multi Rows)
    (As Good As String Array Type..)
    In This Fourm, I Can't Find Out Example Source.
    (Question is Exist.. But No Answer..)
    I Want An Example,, Because I'm A Beginner...
    (I Wonder...)
    If It Is Impossible, Please Told Me.. "Impossible"
    Then, I'll Give Up to Resolve This Way.....
    Please Help Me !!!
    Thanks in advance,

    // Try the following, I appologize that I have not compiled and run this ... but it is headed in the right direction
    import java.sql.*;
    class RunStoredProc
    public static void main(String args[])
    throws SQLException
    try
    Class.forName("oracle.jdbc.driver.OracleDriver");
    catch(Exception ex)
    ex.printStackTrace();
    java.util.Properties props = new java.util.Properties();
    props.put("user", "********"); // you need to replace stars with db userid
    props.put("password", "********"); // you need to replace stars with userid db password
              // below replace machine.domain.com and DBNAME, and port address if different than 1521
    Connection conn =
    DriverManager.getConnection("jdbc:oracle:thin:@machine.domain.com:1521:DBNAME", props);
    // replace "Your Stored Procedure" with your stored procedure
    CallableStatement stmt = conn.prepareCall("Your Stored Procedure");
    ResultSet rset = stmt.execute();
    while(rset.next())
    System.out.println(rset.getString(1));

  • How to map the method action return value directly into screen using variables?

    Hi,
    My JDev version is 11.1.1.6.3.
    I have a 'MethodAction' defined in PageDef file, that goes to model layer and return String value. As this needs to be executed during initializing of pageDef, I have also added an 'InvokeAction' for that.
    <executables>
               <invokeAction id="invokeSayHelloId" Refresh="ifNeeded"
                                    Binds="sayHello"/>
               <variableIterator id="variables">
                    <variable Name="Name" Type="java.lang.String"/>
               </variableIterator>
    </executables>
    <bindings>
              <methodAction id="sayHello" InstanceName="HrAMDataControl.dataProvider"
                                     DataControl="HrAMDataControl" RequiresUpdateModel="true"
                                     Action="invokeMethod" MethodName="sayHello"
                                     IsViewObjectMethod="false"
                                     ReturnName="data.HrAMDataControl.methodResults.sayHello_HrAMDataControl_dataProvider_sayHello_result">
                                        <NamedData NDName="pName" NDValue="Michael John" NDType="java.lang.String"/>
             </methodAction>
    </bindings?
    Requirement:
    I want to map the return value of this method action directly into screen by making use of PageDef variables.
    Question:
    I. I need to know how to map this return value direcly as exprssion against PageDef variable.
    2. If Question 1 is achievable, assuming the method action returls List instead of String (I know well it returns 2 items), can I map the 1st Item against Variable 1 and 2nd Item against Variable 2 directly?
    Thanks in Advance.
    Ragu

    Thanks Frank, but If I directly map the MethodAction's result to UI, there are chances where it might get executed whenever I refresh the UIComponent (UIComponent to which the methodAction result is mapped. Isn't so??). Instead, If I invoke the MethodAction using InvokeAction, I can get the control on when it should get invoked (using RefreshCondition). If I assign the variable to UIComponent (Assume I've mapped the method action result to variable using expression), refreshing of UIComponent will not cause any performance issue I feel.
    Correct me If I am wrong.

Maybe you are looking for

  • Media Browser PP CC does not display all folders

    Using Premiere Pro CC. Windows 7. 980x, 16 Gb RAM, 2x Radeon 5800 I have one very large folder for documents that I back up regularly on my secondary D: drive keeping as much as I can off the C: drive which is an SSD. The folder does not show up in t

  • RFC Lookup error after moving to Quality from Development

    Hi All, For a scenario,I am using the RFC Lookup in message mapping. I am not using it in a UDF but for directly for an target element.... The scenario was wrkng properly in development... but in quality it's not wrkng giving the following error....

  • How to see which programs are attached to which desktop?

    I have used the option to attache software programs to different desktops in Mountain Lion.  When I hava not used a specific program in a while and then need to, I cannot always remember which desktop I anchored it to.  I know I can go to the launch

  • Cisco Prime 1.3

    I did an opps and deployed the latest IOS image to all of our switches, I have looked and looked for a way to stop the deployment. Right now I have stopped the the service but I need to find out a way to stop the deployment when I turn Prime back on?

  • Problems with Quicktime

    I recently finished an interactive tutorial that was published to DVD. I had no problems and the dvd played perfectly. Once the project was complete, I had some computer issues and was forced to reformat my HD. Ever since re-installing Director MX 20