Doubt about toString Java method

Asked

Viewed 298 times

-1

I would like to know the difference between using and not using the method toString in Java, because I understood that it serves as a print normal. Has some advantage in using this method ?

My question basically is between using for example:

System.out.println(product.name + product.price + product.add);

and between using the toString to print this on the screen.

1 answer

2


Sasaki you are quite wrong about using the method toString. To print something on the console you must use the method print as you yourself did in the code of your question.

The method toString is a method that all classes have in Java ( since they all inherit from Object ) and serves only for return a String and nay print it. See an example below for you to better understand:

public class Exemplo {
    public static void main(String[] args) {

        Integer num = 17;
        System.out.println(num.toString().getClass());
    }
}

The exit code above will be java.lang.String because by calling the method toString he returned a String from the Integer object.

The advantage of using this method is that we can "convert" any object to String. Including, the method itself print prints any kind of value because it calls the method internally toString.

See this other example where I overwrite the method in the class Usuario to print the formatted object attributes:

class Usuario {

    private String nome = "Bruno";
    private int idade = 29;

    public String toString(){
        return "Nome = " + this.nome + " Idade = " + this.idade;
    }
}

public class Exemplo{
    public static void main(String[] args) {

        Usuario usuario = new Usuario();

        System.out.println(usuario);
    }
}
  • I still don’t understand the difference in case I show the information to the user between using the print or make use of this method, because the output will not be the same if I print the return of the toString?

  • To just print, it makes no difference to use System.out.println(num); or System.out.println(num.toString()); 'cause like I said, the function print makes use of the function toString to get the object string and print.

  • But the toString is important to modify what will be printed as shown in the second example. Try the following test: run the code from the second example I showed by removing the method toString class Usuario and then execute the code with the method. You will see that the outputs are different.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.