Come restituire la rappresentazione in stringa del valore specificato in Java?


In Java, per restituire la rappresentazione in stringa del valore specificato, si possono utilizzare i seguenti metodi:

  • String.valueOf(): questo metodo converte il valore specificato in una stringa. Se il valore è un oggetto, viene chiamato il metodo toString() dell'oggetto. Ad esempio:
int num = 42;
String strNum = String.valueOf(num);
System.out.println(strNum); // output: "42"

Object obj = new Object();
String strObj = String.valueOf(obj);
System.out.println(strObj); // output: "java.lang.Object@<hashcode>"
  • Integer.toString(), Double.toString(), Boolean.toString(), etc.: questi metodi convertono il valore specificato in una stringa, specifica per il tipo di dato. Ad esempio:
int num = 42;
String strNum = Integer.toString(num);
System.out.println(strNum); // output: "42"

double dbl = 3.14;
String strDbl = Double.toString(dbl);
System.out.println(strDbl); // output: "3.14"

boolean bool = true;
String strBool = Boolean.toString(bool);
System.out.println(strBool); // output: "true"

In entrambi i casi, il risultato è una stringa che rappresenta il valore specificato.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.