Pessoal, surgiu uma dúvida aqui.
Por exemplo:
quando eu uso o seguinte código:
String s=String.valueOf("Novo Objeto String");
Quando resolvo imprimir na tela a String s
System.out.println(s);
Saída:
Novo Objeto String
Até ai tudo bem, mas no caso a variável s é uma variável de reference, pq ela retorna a String “Novo Objeto String” e não o valor da referência? Sei que não seria lógico, mas como eles conseguiram fazer isso?
valeuu
Bom, quando você chama o valueOf de um objeto, internamente é chamado o método toString desse objeto. No caso de uma String, o valueOf retorna a própria String.
Se você tivesse chamado o valuOf para um objeto qualquer, ao invés de o valor da referência, você iria ver um número estranho precedido do caracter “NomeDaclasse@”. Esse número é o hashCode do objeto. Ou então, se esse objeto tiver sobrescrito o método toString, você verá a String que representa esse objeto. Por exemplo:
[code]public class Cachorro {
}[/code]
Cachorro cachorro = new Cachorro();
String s = String.valueOf(cachorro);
System.out.println(s);
A saída é:
Cachorro@addbf1
Agora se você tivesse sobrescrito o método toString da classe Cachorro, teríamos:
public class Cachorro {
public String toString() {
return "au! au!";
}
}
Cachorro cachorro = new Cachorro();
String s = String.valueOf(cachorro);
System.out.println(s);
A saída seria:
au! au!
Ou seja, valueOf sempre retornará uma String e no caso de objetos, ele chama o método toString() do referido objeto.
Olá matheusLmota
A sua resposta foi boa, mas acabou me deixando em dúvida. Segundo a documentação da API Java, no caso de String e valueOf temos o seguinte:
static String valueOf(boolean b) Returns the string representation of the boolean argument.
static String valueOf(char c) Returns the string representation of the char argument.
static String valueOf(char[] data) Returns the string representation of the char array argument.
static String valueOf(char[] data, int offset, int count) Returns the string representation of a specific subarray of the char array argument.
static String valueOf(double d) Returns the string representation of the double argument.
static String valueOf(float f) Returns the string representation of the float argument.
static String valueOf(int i) Returns the string representation of the int argument.
static String valueOf(long l) Returns the string representation of the long argument.
static String valueOf(Object obj) Returns the string representation of the Object argument.
Em nenhum caso temos valueOf(String s), assim a frase que o colega inseriu foi tratada como objeto? Como String é um objeto, valueOf identificou a frase entre aspas como objeto e a inseriu no “case” valueOf(Object obj)? Foi isso que ele fez?
Abs.
String.valueOf (Object obj) é implementada como return obj.toString(), e nesse caso o método toString da classe String retorna a própria String.
Olá entanglement
Obrigado, agora ficou totalmente claro.