toString()

Hello

According to the Java reference (http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#toString ()) and many other sources (for example: http://www.ntu.edu.sg/home/ehchua/programming/java/J3a_OOPBasics.html), it is recommended to override the toString() method.
All well designed Java classes should have a public method called toString() that returns a string describing the object.
Could you please clarify why is this so important?
Why such a method is not so important in other languages such as C++ OO?

Thank you in advance.

Kind regards
Apostolis

Good Java itself uses toString() in some cases. Take this as an example:

Integer i = new Integer(5);
System.out.println("Value: " + i);

Java, will call the method toString() of integer here to be able to operate the concatenation of strings.

Its not 'important' to implement toString() for EACH class that you write, but in most cases it can still be practical to do, especially with the record in mind of debugging. You can simply connect the object instead of having to deal with its properties. Goes the same for the display of an IDE debugger, your debugging experience will be much more pleasant when your objects have representations of useful toString().

Tags: Java

Similar Questions

  • Why do I get this error:? Permission denied for my {URL} call the UnnamedClass.toString method on.

    When I click on links to external sites on my site, I get the following error, like 5 times, and yet, it always opens the other site after clicking the OKs. For example, click on "Host Hotel' on the left NAV.

    Error: Permission denied to call method UnnamedClass.toString on.

    URL of affected sites

    http://www.TGIF-classic.org

    Norton Toolbar is the culprit. I work with Norton to get addressed.

  • ShapeStyle.ToString)

    Hello

    in my application, I want to save the settings of an annotation. When to use the annotation. Method ShapeStyle.ToString () it provides only "ShapeStyle. I think so

    they should give the name of the actual shape, use the Shape.Parse () function to get the saved state.

    Best regards

    Gerald

    Hello

    You are absolutely right about the fact that the ShapeStyle returns the string "ShapeStyle" for different forms.

    Note: ShapeStyle and ArrowStyle are not related to the hiararchy class. ArrowStyle is not a subclass of ShapeStyle (and vice versa).

    For your use case, you can create a method that would check the style of the form and returns you the correct string.
    Something like the following,

    public string GetStyleName(Object style)
    {
        if(style is ShapeStyle)
        {
            if(style == ShapeStyle.None)
            {
                return "None";
            }
            else if(style == ShapeStyle.Oval)
            {
                return "Oval";
            }
            .
            .
            .
        }
        else if(style is ArrowStyle)
        {
            return style.ToString();
        }
    }
    

    For loading, you could create a (factory) method to actually compare the strings and return the value.

    public Object GetMyStyleByName(string name, Type type)
    {
        if(type == typeof(ShapeStyle))
        {
            if(name == "None")
            {
                return ShapeStyle.None;
            }
            .
            .
            .
        } }
    

    I hope this helps.

    Concerning

    Habim stone

    National Instruments

  • Method 'toString' with signature "() Ljava/lang/String"; is not applicable on this object

    Feature: bold 9780

    OS: 6.0

    When the app to debug with actual device, get problem like this:

    Method 'toString' with signature "() Ljava/lang/String"; is not applicable on this object

    Tel: String tmp = "http:/ /...". "always see the string tmp = null;

    What is the problem, how to fix?

    In the Simulator, the app works!

    Thank you

    its 'only' a debugger issue.
    Maybe the version of the software of the device does not match that your debugger uses.
    You can work around the problem by using DD

  • HttpDateParse and Date.toString problem...

    I'm parsing a string by using the HttpDateParser and check when I create a date from the long value object and get a string the day of the week always rest Saturday...

    String defaultResponse = kill Jan 10 05:20:20 2009;

    long date = HttpDateParser.parse (defaultResponse);

    String s = new Date (date) m:System.NET.SocketAddress.ToString ();

    I have values of s like Sat Jan 10 12:20:20 GMT 2009

    Why am I sitting and not kill ... .Please help

    Kind regards

    kaddy

    Probably because on January 10, 2009 is in fact a Saturday

  • Link text toString in ChoiceBox

    Hello

    When I add items to a ChoiceBox, their ToString() - method is used to determine the text of the label. However, the ChoiceBox is not aware of the changes. The same problem arises with ListView and make, but in this case, I can write my own cell implementations that support of the update. ChoiceBox, toString () - calls seem to be hard-coded.

    Is it possible to link the ChoiceBox items so that they change dyamically? I have an ObservableValue < String > (in fact even a property < String >) on my ChoiceBox items that I want to appear on the label. The only way I see currently is completely rewrite ChoiceBox skin (which is not a good idea, because it impacts portability and will probably break on JavaFX 8).

    In general: Y at - it something like toStringProperty() or toStringObservable() in JavaFX (maybe in future releases) which would see the value of an object's toString?

    Thanks for any help!

    Philipp

    You can use a ComboBox instead of a ChoiceBox? Like ListView, ComboBox allows you to define a cell factory, so you would be able to write your own implementation of the cell.

  • toString, method why it is not called implicitly for objects

    class building {}
    public class Example
    {
    Public Shared Sub main()
    {
    Building b = new Building();
    String s = (String) b;
    }
    }

    in the 5th line it shows error that cannot cast building type in string...
    but all classes have the toString method that is called whenever we give the object argument in System.out.println ();

    the following code compiles

    class building {}
    Class Example
    {
    Public Shared Sub main()
    {
    Building b = new Building();
    System.out.println (b);
    }
    }
    can someone explain this?

    is the tostring method implicitly called only in println where he expects a string?

    It is not called implicitly anywhere. It is explicitly called by println (Object).

  • ToString of the element must be declared

    Hi there, I try this code in form of Oracle and got the message 'toString of the element must be declared'.tx.
    ex                  ora_java.jexception;
    
    ex := ORA_JAVA.LAST_EXCEPTION;
    message(Exception_.toString(ex));

    And how this problem is related to the languages of server database called SQL and PL/SQL - the purpose of this forum?

  • Problems with toString()

    This is probably a strange question, but how do this program to return the result using toString()? This is a duty...

    import java.util.Scanner;
    
    public class LED_Digit {
         
         private int myTop, myTopBothSides, myTopLeft, myTopRight, myMiddle, myBottomBothSides, myBottomLeft, myBottomRight, myBottom;
         
         public void drawLED_Digit(int top, int topBothSides, int topLeft, int topRight, int middle, int bottomBothSides, int bottomLeft,
                   int bottomRight, int bottom) {
         for (int t = 1; t <= top; t++) {
              System.out.print(" - "); }
              System.out.println();
         for (int tbth = 1; tbth <= topBothSides; tbth++) {
              System.out.println("|   |");}
         for (int tl =1; tl <= topLeft; tl++) {
                   System.out.println("|   "); }
         for (int tr = 1; tr <= topRight; tr++) {
                   System.out.println("    |"); }
         for (int m = 1; m <= middle; m++) {
                   System.out.print(" - "); }
         for (int bbth = 1; bbth <= bottomBothSides; bbth++) {
                   System.out.println();
                   System.out.println("|   |");}
         for (int bl = 1; bl <= bottomLeft; bl++) {
                   System.out.println();
                   System.out.println("|   "); }
         for (int br = 1; br <= bottomRight; br++) {
                   System.out.println();
                   System.out.println("    |"); }
         for (int b = 1; b <= bottom; b++) {
                   System.out.print(" - "); }
         
         myTop = top;
         myTopBothSides = topBothSides;
         myTopLeft = topLeft;
         myTopRight = topRight;
         myMiddle = middle;
         myBottomBothSides = bottomBothSides;
         myBottomLeft = bottomLeft;
         myBottomRight = bottomRight;
         myBottom = bottom;
         
         }
          
         
         public static void main(String[] args) {
              Scanner keyboard = new Scanner(System.in);
              System.out.print("What is the number? " );
              int num = keyboard.nextInt();
              findDig(num);
              
         }
              
         public static void findDig(int num) {
         if (num == 0) {
              LED_Digit zero = new LED_Digit();
              zero.drawLED_Digit(2, 3, 0, 0, 0, 0, 0, 0, 2);
              System.out.println(); }
         else if (num == 1){
              LED_Digit one = new LED_Digit();
              one.drawLED_Digit(0, 0, 0, 4, 0, 0, 0, 0, 0);
              System.out.println(); }
         else if (num == 2) {
              LED_Digit two = new LED_Digit();
              two.drawLED_Digit(2, 0, 0, 1, 2, 0, 1, 0, 2);
              System.out.println(); }
         else if (num == 3) {
              LED_Digit three = new LED_Digit();
              three.drawLED_Digit(2, 0, 0, 1, 2, 0, 0, 1, 2);
              System.out.println(); }
         else if (num == 4) {
              LED_Digit four = new LED_Digit();
              four.drawLED_Digit(0, 1, 0, 0, 2, 0, 0, 1, 0);
              System.out.println(); }
         else if (num == 5) {
              LED_Digit five = new LED_Digit();
              five.drawLED_Digit(2, 0, 1, 0, 2, 0, 0, 1, 2);
              System.out.println(); }
         else if (num == 6) {
              LED_Digit six = new LED_Digit();
              six.drawLED_Digit(2, 0, 1, 0, 2, 1, 0, 0, 2);
              System.out.println(); }
         else if (num == 7) {
              LED_Digit seven = new LED_Digit();
              seven.drawLED_Digit(2, 0, 0, 1, 0, 0, 0, 1, 0);
              System.out.println(); }
         else if (num == 8) {
              LED_Digit eight = new LED_Digit();
              eight.drawLED_Digit(2, 1, 0, 0, 2, 1, 0, 0, 2);
              System.out.println(); }
         else if (num == 9) {
              LED_Digit nine = new LED_Digit();
              nine.drawLED_Digit(2, 1, 0, 0, 2, 0, 0, 1, 2); }
         else {
              System.err.println("Not a valid digit"); }
         }
    }

    It does not appear that understand how something back from a method. Your OE is the result of this. Consider the following simple example:

    class SomeClass {
       int a;
       String b;
    
       public String toString() {
          String returnValue = "a=" + a + ", b=" + b;
          return returnValue;
       }
    
       public static void main( String[] args )
       {
          SomeClass sc = new SomeClass();
          sc.a = 5;
          sc.b = "Test";
          System.out.println( sc );
       }
    }
    

    Using a StringBuilder or StringBuffer would also apply in this case, but the concept is the same.

    Also, I suggest looking at the use of a switch statement in your code.

  • What is the difference between String() - as String - toString();

    Hello

    I wonder what is the difference between these 3 ways of getting around.

    There is no difference between run using an object as a string:

    String (Something)

    and

    something as a string.

    If on the same object, you apply the toString() method, you can use any of the foregoing, there is no difference between the 3.

  • String (int_myInt) &amp; int_myInt.toString)

    Are they the same?

    String (int_myInt);

    and

    int_myInt.ToString ();

    Which one should I use to optimize the coding?

    -Zainuu

    they do the same thing but casting a string is much faster:

    String (Integer)

  • sendLV.img = compressArray (PixelAF (bmp)) m:System.NET.SocketAddress.ToString ();

    I'm trying to convert a mc into a jpg. But the images seems to be empty.

    Frame1

    import flash.display.BitmapData;

    var itemA:Array = [holder1, case];

    function bitmap2F(mc:MovieClip) {}

    itemA.push (mc);

    }

    go.onRelase = function () {}

    bitmap2F (holderX);

    Stop (5);

    }

    Frame5

    import flash.display.BitmapData;

    to import flash.geom.Matrix;

    var sendLV:LoadVars = new LoadVars();

    var receiveLV:LoadVars = new LoadVars();

    function saveBitmap2F(mc:MovieClip) {}

    sendLV.imageName = 'itemN_' + itemNIndex + '_' + imageIndentifier;

    mc.cacheAsBitmap = true;

    sendLV.img = compressArray (PixelAF (bmp)) m:System.NET.SocketAddress.ToString ();

    sendLV.height = bmp.height;

    sendLV.width = bmp.width;

    sendLV.sendAndLoad("/saveImage.php",receiveLV,"POST");

    }

    function PixelAF(bmp:BitmapData):Array {}

    var h = bmp.height;

    var l = bmp.width;

    var pixelA:Array = new Array();

    for (var a = 0; a < = w; a ++) {}

    for (var b = 0; b < = h; b ++) {}

    tmp = bmp.getPixel (a, b) var m:System.NET.SocketAddress.ToString (16);

    pixelA.push (tmp);

    }

    }

    return of pixelA;

    }

    function compressArray(orig:Array):Array {}

    var compressedA:Array = [];

    var lei: Number = 0;

    for (var i = 0; i < orig.length; i ++) {}

    {If (orig [i]! = {compressedA [lei])}

    compressedA [i] = orig [i];

    Lei = i;

    } else {}

    compressedA [i] = "";

    }

    }

    Return compressedA;

    }

    Add an our to receiveLV (see below), download everything to your server and display the url.  also, make sure your echoes something php.

    Frame1

    import flash.display.BitmapData;

    var itemA:Array = [holder1, case];

    function bitmap2F(mc:MovieClip) {}

    itemA.push (mc);

    }

    go.onRelase = function () {}

    bitmap2F (holderX);

    Stop (5);

    }

    Frame5

    import flash.display.BitmapData;

    to import flash.geom.Matrix;

    var sendLV:LoadVars = new LoadVars();

    var receiveLV:LoadVars = new LoadVars();

    {receiveLV.onData = function (src)}

    trace (SRC);

    }

    function saveBitmap2F(mc:MovieClip) {}

    sendLV.imageName = 'itemN_' + itemNIndex + '_' + imageIndentifier;

    mc.cacheAsBitmap = true;

    sendLV.img = compressArray (PixelAF (bmp)) m:System.NET.SocketAddress.ToString ();

    sendLV.height = bmp.height;

    sendLV.width = bmp.width;

    sendLV.sendAndLoad("/saveImage.php",receiveLV,"POST");

    }

    function PixelAF(bmp:BitmapData):Array {}

    var h = bmp.height;

    var l = bmp.width;

    var pixelA:Array = new Array();

    for (var a = 0;<=w; a++)="">

    for (var b = 0; b)<=h; b++)="">

    tmp = bmp.getPixel (a, b) var m:System.NET.SocketAddress.ToString (16);

    pixelA.push (tmp);

    }

    }

    return of pixelA;

    }

    function compressArray(orig:Array):Array {}

    var compressedA:Array = [];

    var lei: Number = 0;

    for (var i = 0; i)

    {If (orig [i]! = {compressedA [lei])}

    compressedA [i] = orig [i];

    Lei = i;

    } else {}

    compressedA [i] = "";

    }

    }

    Return compressedA;

    }

  • How to add the zero using the toString() function?

    Hello

    I looked in the manual and I can't find any reference to toString() for syntax information.  Is there a setting to use me to specify the length of the string?  And to add zeros or not?

    Here is the code that I need to add zeros:

    p laybutt.addEventListener (MouseEvent.CLICK, playSound);

    function playSound(e:Event)
    {
    SoundMixer.stopAll ();
    var num:Number = Math.ceil (Math.random () * 43);
    bigNum.text = num.toString ();
    var path: String = "Track number" + bigNum.text + ".mp3".
    trace (Path);
    var s:Sound = new Sound (new URLRequest (path));
    s.Play ();
    }

    The I am trying to open the files begins to "Track No01.

    Any ideas?

    Ron

    Try using:

    bigNum.text = num< 10="" "0"+string(num)="" :="">

    instead of bigNum.text = num.toString ();

  • toString then split() do not work!

    Hello!

    I applied to an array, the toString method and the method of allocation for the result achieved.
    It does not work.
    What is the best process use?
    I want to get the result of the split as html to the format of strings I can display in an active html text field element.

    Thank you in advance for any help!

    Best regards
    Gerry

    And of course, it would be more efficient

  • using toString

    Hello

    If I am a sendandLoad to an asp program and I do a m:System.NET.SocketAddress.ToString on the returned data what should I expect to see? I seem to be getting any display asp document. I don't know if it's okay. If it is not correct that this means that IIS does not work correctly or I need to set the encoding to something else? No interaction with asp work properly by doing TestMovie?

    Any help appreciated.



    Hello

    He is finally solved!

    I don't know why, but about sending and load the asp file must be an absolute reference to it, IE http://localhost/...getGroup.asp and then it works!

    Thanks for your help and stick to the post.

Maybe you are looking for

  • Configurator can deploy more apps?

    Hello You can use configurator to deploy applications more once you have all your iPads travel configurator to prepare them for the students? I know that you can add that app and re deal throughout the Configurator, but since its manual and we 100...

  • HP Pavilion usb does not work with Windows 7

    I have HP Pavilion dv9910us. I've updated from Vista to Windows 7 Ultimate 32 as soon as he was released. It worked fine until a couple of weeks. My two side usb drives stop working. When I plug something in them their power led lights, but they do n

  • Bistre using Photosmart Premium AIO

    When I print on my HP C309 Photosmart Premium new all-in-one using iPhoto ' 09 running Mac OS 10.6.2 (Snow Leopard), the prints look as I applied sepia effect. In other words, my black and white photos have a light yellow background pink or clear. I

  • How can I send a mail stored in the drafts folder?

    I prepared an e-mail, stored in the drafts folder, and now want to send.  What should I do?

  • Remote VPN access without end

    Hi all. I have a 5510 I use for tunneling ipsec l2l as remote access. I've been watching this thing so long as I'm goofy. My tunnel l2l is up and happy. Hosts can talk to each other. My RA is happy that I can connect with a vpn client. Unfortunately,