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 thetoString
?– Sasaki
To just print, it makes no difference to use
System.out.println(num);
orSystem.out.println(num.toString());
'cause like I said, the functionprint
makes use of the functiontoString
to get the object string and print.– JeanExtreme002
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 methodtoString
classUsuario
and then execute the code with the method. You will see that the outputs are different.– JeanExtreme002