-2

I am trying to figure out what the toString method does. I have looked a lot on youtube and googled a lot. But it's something that I am missing out. Please note that I have done java about 80 hours in total.

I do know that toString is a name on a method (?) that has a built in function. When should I use this? When i mix up string and int/doubles?

And second question that might be answered with the first one. How does it work when I use this toString? Same as usually? No changes?

harpun
  • 4,022
  • 1
  • 36
  • 40
Minivera
  • 17
  • 4
  • 1
    It is used to create a String representation of the state of your object. I usually use it (override it) to display the key object fields and for debugging purposes, and I try to avoid using it for production code. Your question `"how does it work..."` is a bit over-broad and thus hard to answer. What do you mean? – Hovercraft Full Of Eels Mar 08 '15 at 13:03

4 Answers4

1

toString() returns a string representation of the object that it is called on.

When you call toString() on an object, it may give you a String that does not make much sense. When you pass an object into System.out.println(), this function calls the object's toString() method.

You call override the toString() of your class so a human readable string will be provided when toString() is called on objects of your class.

toString() is very useful for logging, debugging, or any time you want to render/display an object as a String.

Dermot Blair
  • 1,600
  • 10
  • 10
  • Thank you for your reply :) I still dont get when I should use it. When I try to solve a task, how can I see that "Ohh, here should I use a toString"? – Minivera Mar 08 '15 at 13:08
  • As updated in my answer, `toString()` is very useful for logging, debugging, or any time you want to render/display an object as a String. – Dermot Blair Mar 08 '15 at 13:16
0

toString is a method in Object class which is parent of all the classes. When you define your own custom class, and if you want to log it in nice readable way, so you get to know state of your customized object, then you define toString method by overriding one present in Object class. Consider following employee class like:

public class Employee {
   private int id;
   private String name;
   ..
   @Override
   public String toString() {
       return "id: " + id +" name: " + name;
   }
}

Now when say you try to write onto Standard output employee object, you will see like:

 Employee employee = ...
 ...
System.out.println(employee);
Output:
id: .. name: ...

If you dont override it, then Object's toString would be called and it would be in unreadable form like:

Employee@abbcc..
SMA
  • 36,381
  • 8
  • 49
  • 73
0

tosTring is a method for converting your class to string. For example:

public class Person
{
    private String name;
    private String age;
    private String address;

    @Override
    public String toString()
    {

        return String.format("%10s %2d %20s",name,age,address);

    }
}
  • I dont fully copy. What does cenverting your class mean? – Minivera Mar 08 '15 at 13:11
  • Read binary data from memory and compose a (usually human readable) String form. Like number `1234567` in memory is 4 bytes (if it's an `int`), but if you convert it to a `String` it becomes 7 bytes and loses the ability to do arithmetic on it. – TWiStErRob Mar 08 '15 at 13:14
  • This is for displaying your class on console or a component. –  Mar 08 '15 at 19:22
0

toString is a method on every Object which converts the logical binary representation in memory to a string of characters (String) in a human readable form.

The default behaviour of toString as seen in Object.java is to return:

class name + @ + memory address in hexadecimal

When you create your own classes it's worth to @Override this method to be able to easily find bugs later on. See SMA's answer on how to do this. Most of the framework's classes have this method already, for example ArrayList prints: [object 0's toString(), object 1's toString(), object 2's toString()].

When you add an arbitrary object to a String object, like "hello " + empoyee, toString is called in the background so it roughly becomes "hello " + employee.toString() (I say "roughly" because there's more magic involving StringBuilder, but that's not to be concerned about as a beginner).

It is mostly used for debugging and logging. It's considered bad practice to actually use it in production code and rely on the output of the method in business logic and UI.

TWiStErRob
  • 44,762
  • 26
  • 170
  • 254
  • Hey! I think I am starting to understanding it now. It works like this: It saves a string somewhere with a hex-code. Whenever you want to out.println this java finds the string that is saved as a hex, and prints out a string. So toString should be used when we use a string, like a name of name of a color etc? – Minivera Mar 08 '15 at 13:16
  • Oh, sorry, wrong wording, `toString` doesn't print anything: it is the one that "saves a string somewhere" (=in memory) and then that String is passed to println and displayed on your console. – TWiStErRob Mar 08 '15 at 13:18
  • Okay :) Thanks! And last question. Should toString always be used when we have print in a string? Like a name or so. – Minivera Mar 08 '15 at 13:19
  • If you have `class Color {...}` then yes, the toString should return it's name or usual representation like `#FF3300`. – TWiStErRob Mar 08 '15 at 13:19
  • `toString` is always called when you print an Object, what it returns is depends on you, won't usually like the default, so you're kind of forced to override/implement it. – TWiStErRob Mar 08 '15 at 13:20
  • Sorry for asking for a simple solution when I guess there is not. But I am about to write an exam in over a week. And when I look at old test it ses "To get full score you should use toString". And the question is always about defining konstruktors and then just print it out in a main method. Is it so that I should use a toString when I have to work with a string? (Kinda looking for a yes or no answer on this one since I dont really get the java talk you guys have yet :D ) – Minivera Mar 08 '15 at 13:26
  • Yep, I understand. Look at SMA's answer, in an exam they expect you to remember and write something like that. Obviously you'll need a constructor too like `public Employee(int id, String name) { this.id = id; this.name = name; }` – TWiStErRob Mar 08 '15 at 13:28
  • The point of an exam is to verify you know that toString is called when doing `System.out.println(emp);` so you don't do this every time you need to print an emp: `System.out.println(emp.id + " " + emp.name)`. – TWiStErRob Mar 08 '15 at 13:30
  • I'm not sure what you are learning, but if you're a programmer you need to understand the basics, not just "pass an exam". It's worth the effort later on millionfold! – TWiStErRob Mar 08 '15 at 13:32
  • I will read just a little developing, so it's okay. But I do understand now :) Thanks all! – Minivera Mar 08 '15 at 16:21