When and why do we override toString() method

public class BobTest {
        public static void main (String[] args) {
          Bob f = new Bob("GoBobGo", 19);
          System.out.println(f); // if i put s.o.p("hello"); the overridden toString doesnt get called, y so ?
     class Bob {
        int shoeSize;
        String nickName;
        Bob(String nickName, int shoeSize) {
          this.shoeSize = shoeSize;
          this.nickName = nickName;
        public String toString() {
           return ("I am a Bob, but you can call me " + nickName +
                   ". My shoe size is " + shoeSize);
     }

masijade. wrote:
To get a meaningful String representation of your Object.And just to further the point
@OP: In answer to your original question: almost always.
I generally don't regard a class as complete until I've implemented toString() -- or, at the very least, displayed it with println() and determined that the default representation is fine.
Same goes for equals() and hashCode().
Winston

Similar Messages

  • Overriding toString method of entrySet() in LinkedHashMap

    Hi all,
    I got a LinkedHashMap which return a Set by entrySet() method. When I print the String represantation of the returned Set, I receive something like [key=value, key=value, key= value]. I, however, would like to override toString method so that I can implement my own representation of the Set class which is returned by entrySet() method. How can I do that if it's possible?

    i believe what Peter was saying was to overrider the Set (in your case...the concrete LinkedhashSet class)
    you're not implementing the add, get, contains, etc..function..you're extending it.
    after extending it..you can overide any public and protected method...any other method not overide is still there for you to use.
    so you would have something like this
    public class MyLinkHashSet extends LinkHashSet{
        public String toString(){
             return a String representation you want 
        public Object getMyObject(){ return myObject; }  // your own method
       // you still have all of the other LinkHashSet methods to use
    }

  • How  to override toString() method ?

    class  Test
    String x[];
    int c;
    Test(int size)
    x=new String[size];
    c=-1;
    public void addString(String str)
    x=new String
    x[++c]=str;
    public void String toString()
    //  i want to override toString method to view the strings existing in the x[]...
    //   how do i view the strings ?
    //  probabily i should NOT use println() here (..as it is inside tostring() method ..right? )
    //   so i should  RETURN   x[] as an array...but the  toString() method return  type is String not the String array!.
    //   so i am in trouble.
    so in a simple way my question is how do i override toString() method to view the Strings stored in the array ?
    i am avoiding println() bcoz of bad design.
    }

    AS you said, the toString method returns a String - this String is supposed to be a representation of the current instance of your class's state. In your case, your class's state is a String array, so you just pick a format for that and make a String that fits that format. Maybe you want it to spit out something like:
    Test[1] = "some string"
    Test[2] = "some other String"If so, code something like:public String toString() {
        StringBuffer returnValue = new StringBuffer();
        for (int i = 0; i < x.length; i++) {
            returnValue.append("Test[" + i + "] = \"" + x[i] + "\"";
        return returnValue.toString();
    } If you don't mind the formatting of the toString method that Lists get, you could just do something like:public String toString() {
        return java.util.Arrays.asList(this).toString();
    } and call it good. That will print out something like:
    [Some String, another String, null]Depending on what's in your array.
    Good Luck
    Lee

  • Vectors gone?  When and why?

    I have read in a couple of posts that Vectors are "legacy" and may not be around forever. Can anyone shed light on the when and why of this? I am relatively new to JAVA programming but I do have a bunch of applications out there that use Vectors. I personally found them very easy to work with.
    Thoughts?

    Wow! I can't wait for Java 2.0! (Please read heavy sarcasm.)
    Speaking of rumors, let's not start spreading any rumors that the Java group at Sun has actually started to talk about -- let alone publicly announced -- that a 2.0 version is in the works; 1.5 sounds right to me.
    I know that you can get almost the same functionality out of a List that is returned from the Collections.synchronizedList(List) method as you can out of a Vector, but Vector is by no means a deprecated class. (We should try to be careful about the casual use of meaning-laden words.) pengjuc is right that a lot of Swing (and non-Swing) classes such as JTable rely on Vector; the mere rewrite to replace all the Vectors with ArrayLists would probably require a Java release all on its own (and whose to say that ArrayLists are really all that, anyway?). Moreover, Vector is part of the public API of many classes and to deprecate it would throw a lot of developers into a tizzy because it would potentially break the ability of their applications to upgrade to a new version of Java. There is nothing inherently wrong with Vector -- it performs as advertised -- and pengjuc is right again that the performance differentials are minute over small object collections.
    In response, again, to dubwai, there's a difference between using Vectors as a developer and having them included in the J2SDK. If you don't like them don't use them, and if you don't like them in other classes, rewrite those classes to your taste. Personally, I think you either have to take what you're given, do it yourself, or get involved in the process.
    Good luck, All!
    Shaun

  • When and Why do we need to build a CUSTOM CUBE

    Hello Experts, Could some please explain with a scenerio ..
    "When and Why do we need to build a CUSTOM CUBE"
    Thanks in advance
    Bhalout

    When and Why:
    Custom cube should be think of when the constent cube is either not suitable nor available for a subject area.
    If there is a content cube and but does not meet your reporting needs, then the better thing will be to adopt the content one and make changes.
    Ravi Thothadri

  • When and Why Do We Need to Create 2 Diff iTunes Libraries?

    Hi,
    When and Why Do We Need to Create 2 Diff iTunes Libraries?
    Thanks.
    Ed

    There's no fast rule sayng you must, and I suspect most people only use one.
    You might want to set up a second library if your first one is so huge that it is slow to operate.  Split your media. For example, I don't listen to classical and rock music at the same time and could restart iTunes ffrom a different library when the time came to switch.
    I have a few extra libraries. One's for music I organized for a special occasion but don't really listen to myself and don't want it cluttering mine. I also have a special library for my mp3 player (not an Apple model) with its own set of files which match some in my main library but they are tagged differently to be compatible with the player's quirks.
    I could also see having a different library for files on an external drive if you have some on your internal drive too.  You might, for example, have a bunch of movie files on an external drive that you don't normally need to have plugged in all the time and don't want iTunes giving you a bunch of exclamation marks if are using it to play your music media on your internal drive.

  • When and why "Never Shared" ??

    when and why we use "Never Shared" in Essbase ??
    Give an real life example which explore it detail ??
    Thanks in advance ....

    Here is an example of lots of reading for you :- Never Share memer
    Cheers
    John
    http://john-goodwin.blogspot.com/

  • When and why (how) use the exit RSR00003 (EXIT_SAPLRRS2_001)

    Boa tarde, expert´s ...
    I tried to find documentation about exit RSR00003, but I didn´t found ...
    I want know when and why a have to use this exit ...
    Muito obrigado,

    Hello,
    The exit is only for Internal SAP use this is why you don't find any documentation for it. So you don't need
    to use it, see the information in the SAP note 153562.
    Best Regards,
    Des

  • Overriding toString() method

    hello all,
    in the following class how toString() is overriding?
    class Box {
        public Box(){
        public String toString(){
            return "Hello";
        public static void main(String args[]){
            System.out.println(new Box());
    }even though i am not extending anything.
    how the toString() method of String class is overriding here?
    is it due to Object class?
    thanks
    daya

    even though i am not extending anything.
    how the toString() method of String class is
    overriding here?
    is it due to Object class?Yes, thats it exactly. Even when you do not extend and class, by default every class inherits from the Object class. Since toString is defined in the Object class, you override it when you defing toString with the same signature.

  • How to enforce developers to override toString() method

    Hi,
    Right now we are in design stage of our application. I want that all our BO classes should override toString(), equals() and hashCode() methods.
    We expect that our application would be running for next 5 to 10 years, and so looking for ways to enforce these rules to developers.
    One way to do is let ant script handle such validations. Another way could be using PMD to enforce rules.
    These could be good ways of doing this, but my manager doesnot quite like to depend on external tools like these ... as 5 years down the line you donot know state of these tools.
    Can someone suggest if java provides any such provision ...
    If someone has some smart solution do let me know ... your help is much appreciated ... and thanks in advance.
    Regards,
    Rana Biswas

    This is interesting.
    toString() method is already implemented in class Object, which is inherited by all other class.
    What happens if we make toString() method abstract. I tried it and compiler allows to do it ... was wondering if it would have any side effect.
    Regards,
    Rana Biswas

  • When and Why Did Apple Drop The 160GB Classic Ipod

    Hi
    I was going to go and finally buy a 160GB Ipod tomrrow.I see they don't even list it anymore on Apples site and Future-shop doesn't even list it on the site.
    They only make a 120GB Now
    When Did they Drop this and why???
    Also Do any stores still have them in Stock???
    I won't be spending the money on only a 120GB if thats all they make now
    I've had my Ipod Mini 4GB since 2005 and thought it was time for a upgrade.
    Please do tell me if Apple still makes the 160GB Ipod
    thanks

    Apple has discontinued the 160GB. You can buy one online still, but not from Apple. Or buy a used one off Craig's List.
    P.S. Actually Apple is still selling refurbished 160GB on it's site, if you want to go that route. I also found some new ones on Amazon. Buy.com may have some too.
    Message was edited by: iPodDiva

  • HTMLDB trimming - when and why?

    Hi, I recentrly found that I couldn't delete one row that I entered within my htmldb app.
    It turned out that when I was inserting this row I've entered a value (varchar2) beginning with space. However on displaying the space was trimmed. And my delete process did not even fail (It gave something like "Process concluded successfully!") which was a pure lie. :-)
    The proces is "DELETE FROM MYTABLE WHERE MYFIELD = :P99_MYITEM";
    I am using version 1.6
    Please tell me is this a bug and why am forced to use trim on every insert process.
    Please don't tell me to use numeric ID for a key because am not the designer of this table.
    If there is an automatic trim, why isn't it used when the value is inserted or why is this trim used at all if this space is part of the value?
    10x.

    Sounds like this has very little to do with HTMLDB. The VARCHAR2 datatype will contain exactly what you put in it (if you insert a value with a leading space, that's what you'll get). Also, your delete did not really fail (which would indicate a error of some kind), it merely resulted in zero rows deleted.
    There is no automatic trim, but you can code this functionality into a trigger or stored procedure.

  • When and why did they decide to lobotomize Siri

    Siri used to amuse me when I was bored. She sang, she told jokes. It was fun to look for the easter eggs. not anymore. Which doofus came up with this plan and why.

    None of us here would know, we are users like you. If you would like to provide feedback to Apple about your concerns, you may do so at www.apple.com/feedback and click on the appropriate link.

  • Which partition type option i use and when and why?

    hi
    i really confused with the types of partition available with essbase, i really want to know which partitioning option i use and in which situation and why should i use that partion type.
    ok

    Hi This kinda question is already answered in this forum many times.
    See the below threads, you will get a better idea of using partitions.
    Re: using partition in real time
    Re: Partition between Essbase and Hyperion Planning Cube
    Re: Transparent Partition - REQUEST HELP
    Re: partition aso to bso error

  • When and why do i have to use a Network-Path?

    Hello,
    i'm wondering when i why i have to use a Network-Path in KM.
    I'm able to connect to a File-System Repository, even if i have no Network-Path defined.
    - both run on W2K Server
    - EP runs on host EP (not an Domain-member)
    - Filesystem is provided by host FS (Domain-member)
    - EP is started with the default local-user SAPServiceEP6
    - on the FS host, i have defined also a local-user SAPServiceEP6 (because EP always wants to logon with these credentials, i have checked this in the windows securitylog of host FS)
    - no network-path defined
    So regarding the fact, that everything is working, can anybody tell me when i have to use a Network-Path?
    Thanks in advance
    Frank

    Hi,
    for example if you want to access a share that only access is granted for a given user. The idea is having a superuser with privileges on the other computer to do things like checking ACLS.
    Another example, how can you access windows shares when running the portal in Unix? Using a network path.
    REgards,
    Miguel

Maybe you are looking for

  • Issue in Registered Server Program RFC in ERP

    Hello Experts, I need suggestion on one problem we are facing. From ERP we have 3 application which uses Synchronous message call to PI system from where the call is sent to a mainframe system and returned. All these 3 applications uses a registered

  • Creating a business object using bapi

    can some one tell me how to create a business object using a bapi and is it possible to create bapi using business object.which is dependent on which one.

  • Move from one application to another without Logging in again

    Hi, I have two standalone applications app1 and app2. When the user clicks on a particular link in app1, He would be directed to another page in app2. Is there a way to avoid the second login that is currently being requested when moving to app2? Bot

  • Interval paritioning based on Integer

    Oracle 11.0.1.7: Can I create interval based partitioning on integer column. We have a integer column that basically is a sequence. I need to create partition dynamically every 10Million rows, how can I do that in interval based partitioning scheme?

  • ZAC PROBLEM........URGENT PLEASE!!!!!!

    HI!!! First of all I'm sorry if this is the wrong place to post for I couldn't figure out where exactly to post ZAC problems. I am trying to create a bootstrap application using ZAC for a client application. As mentioned in the docs, I created a ZAC