In Java, a String is an object that represents a sequence of characters. Strings are immutable, meaning that once they are created, their values cannot be changed.
Strings are used frequently in Java programs to represent text, such as user input, program output, and data stored in text files.
To know more about String Class in java read the complete article.
String valueOf () Method:
The valueOf() method is a static method of the java.lang.String class. It returns the string representation of the passed argument. The argument can be of any type, such as a primitive type, an object, or an array.
valueOf(boolean b) – Returns the string representation of the boolean argument.
valueOf(char c) – Returns the string representation of the char argument.
valueOf(int i) – Returns the string representation of the int argument.
valueOf(long l) – Returns the string representation of the long argument.
valueOf(float f) – Returns the string representation of the float argument.
valueOf(double d) – Returns the string representation of the double argument.
valueOf(char[] data) – Returns the string representation of the char array argument.
public static String valueOf(Object obj) – Returns the string representation of the Object argument.
Returns returns the string representation of the argument passed
Note: the valueOf() method is equivalent to calling the toString() method on an object.
public class Main {
public static void main(String[] args) {
int i = 100;
long l = 1223344445555L;
float f = 3.14f;
double d = 1.234;
boolean b = true;
char c = 'A';
Object obj = new Object();
String str = String.valueOf(i);
System.out.println(str); // prints "100"
str = String.valueOf(l);
System.out.println(str); // prints "1223344445555"
str = String.valueOf(f);
System.out.println(str); // prints "3.14"
str = String.valueOf(d);
System.out.println(str); // prints "1.234"
str = String.valueOf(b);
System.out.println(str); // prints "true"
str = String.valueOf(c);
System.out.println(str); // prints "A"
str = String.valueOf(obj);
System.out.println(str); // prints "java.lang.Object@hashcode"
}
}
Output
100
1223344445555
3.14
1.234
true
A
java.lang.Object@2ff4acd0
Explanation:In this example,Here the output comes by using the different valueOf method() such as double d, boolean b, long l, char c, float f obj o.
public class Main{
public static void main(String[] args) {
String str = "PrepInsta has its own compiler";
Object objVal = str;
System.out.println("Value = " + str.valueOf(objVal));
}
}
Output
Value = PrepInsta has its own compiler
Explanation:In this example, it returns the string representation of the Object argument.
Login/Signup to comment