What is the difference between
Object foo = "something";
String bar = String.valueOf(foo);
and
Object foo = "something";
String bar = (String) foo;
Casting to string only works when the object actually is a string:
Object reallyAString = "foo";
String str = (String) reallyAString; // works.
It won't work when the object is something else:
Object notAString = new Integer(42);
String str = (String) notAString; // will throw a ClassCastException
String.valueOf() however will try to convert whatever you pass into it to a String. It handles both primitives (42) and objects (new Integer(42), using that object's toString()):
String str;
str = String.valueOf(new Integer(42)); // str will hold "42"
str = String.valueOf("foo"); // str will hold "foo"
Object nullValue = null;
str = String.valueOf(nullValue); // str will hold "null"
Note especially the last example: passing null to String.valueOf() will return the string "null".
String.valueOf(foo) invokes foo's .toString() method and assigns the result to the the bar. It is null and type safe operation.
Casting will just assign foo to the bar, if the types are matching. Otherwise, the expression will throw a ClassCastException.
Casting means that the object needs to be of type String, while String.valueOf() can take other types as well.
Both generates same output in case of String.
Casting fails in case of provided object is Not a string.
String.valueOf method is used to get the String represenation of it's parameter object.
(String) value casts object value to string.
You can use the String.valueOf method to get the String representation of an object without worrying about null references. If you try to cast String on a null reference you would get a NullPointerException.
final Object obj = null;
final String strValOfObj = String.valueOf(obj);
final String strCastOfObj = (String) obj;
if (strValOfObj == null) System.out.println("strValOfObj is null");
if (strCastOfObj == null) System.out.println("strCastOfObj is null");
Output: strCastOfObj is null
The first one i.e, String.valueOf returns a string only if the object is a representable type which is a value type or a String.. Else it throws the exception.
In the latter one, you are directly casting which can fail if the object isn't a string.
Online example.
http://ideone.com/p7AGh5
in String.valueOf(); string as work typecasting all the argument passed in valueof() method convert in String and just like integer.string() convert integer into string only
Related
What is the difference between
Object foo = "something";
String bar = String.valueOf(foo);
and
Object foo = "something";
String bar = (String) foo;
Casting to string only works when the object actually is a string:
Object reallyAString = "foo";
String str = (String) reallyAString; // works.
It won't work when the object is something else:
Object notAString = new Integer(42);
String str = (String) notAString; // will throw a ClassCastException
String.valueOf() however will try to convert whatever you pass into it to a String. It handles both primitives (42) and objects (new Integer(42), using that object's toString()):
String str;
str = String.valueOf(new Integer(42)); // str will hold "42"
str = String.valueOf("foo"); // str will hold "foo"
Object nullValue = null;
str = String.valueOf(nullValue); // str will hold "null"
Note especially the last example: passing null to String.valueOf() will return the string "null".
String.valueOf(foo) invokes foo's .toString() method and assigns the result to the the bar. It is null and type safe operation.
Casting will just assign foo to the bar, if the types are matching. Otherwise, the expression will throw a ClassCastException.
Casting means that the object needs to be of type String, while String.valueOf() can take other types as well.
Both generates same output in case of String.
Casting fails in case of provided object is Not a string.
String.valueOf method is used to get the String represenation of it's parameter object.
(String) value casts object value to string.
You can use the String.valueOf method to get the String representation of an object without worrying about null references. If you try to cast String on a null reference you would get a NullPointerException.
final Object obj = null;
final String strValOfObj = String.valueOf(obj);
final String strCastOfObj = (String) obj;
if (strValOfObj == null) System.out.println("strValOfObj is null");
if (strCastOfObj == null) System.out.println("strCastOfObj is null");
Output: strCastOfObj is null
The first one i.e, String.valueOf returns a string only if the object is a representable type which is a value type or a String.. Else it throws the exception.
In the latter one, you are directly casting which can fail if the object isn't a string.
Online example.
http://ideone.com/p7AGh5
in String.valueOf(); string as work typecasting all the argument passed in valueof() method convert in String and just like integer.string() convert integer into string only
Converting the value to String in java; There are multiple ways of doing it.
Just wanted to know what's the difference between each other in the following ways.
strValue.toString()
strValue+""
""+strValue
It depends on java version. Java 7 would act a bit smarter using StringBuilder + append().
Generally, you do not want unnecessary allocations. Use first one.
strValue.toString()
will return itself, because the toString() implementation of String (I'm guessing strValue is indeed of type String) returns this.
strValue+""
""+strValue
Will result in the same value (strValue) but won't invoke the toString() method
All Strings contain the same value, try it out:
String strValue = "Hello world"; // not null
String a = strValue.toString();
String b = strValue+"";
String c = ""+strValue;
Measuring its length give all the result 11, because adding an empty String to another one equals the original String itself:
System.out.println(a.length());
...
Try the equality between these Strings:
System.out.println(a.equals(b));
System.out.println(b.equals(c));
System.out.println(c.equals(a));
They are all true, because these Strings have the same value to be compared. All it in the case the strValue is not null.
One major difference is how null is handled.
If strValue is null, strValue.toString() will throw a NullPointerException, while the other two options will return the String "null".
Other differences may be observed if strValue is of a boxed numeric type, and you try to concatenate other numeric variables to it.
For example :
If
Integer a = 5;
Integer strValue = 6;
Then
a+strValue+""
would return
"11"
while
a+""+strValue
or
""+a+strValue
would return
"56"
Why sometimes cast will not work but String.valueOf() will? Aren't they all exist for same functionality of converting current type to String?
For example:
addgui.getIdField().setText(String.valueOf(jtable.getValueAt(rowNum, 0)));
here jtable.getValueAt(rowNum, 0) returns an Integer value and if I directly cast it to String it causes eroor, but String,valueOf works instead.
Remember that String.valueOf(Object) invokes Object.toString(), creates a String out of it and assigns it to the the Object.
Casting will just assign object2 to the object1, If both have same type it will work. Otherwise, the expression would throw a ClassCastException.
Example
Object a1 = "abc";
String s =(String)a1; //this works
But this shall give you a ClassCastException
int b = 1;
Object c = b;
String s1 =(String)c;
Where as String.valueOf() converts whatever to pass to it as a String
I am using Bonita Api Java docs(Bonita Api) to get the instanceUUID of process and get the instanceUUID of type ProcessInstanceUUID.using getValue(), i am convert the object value in string and send another java class where i want to typecast String into ProcessInstanceUUID class object type.
it is possible,if possible please give me some idea to solve this problem.
ProcessInstanceUUID instanceUUID = this.getProcessInstanceUUID();
instanceUUIDValue = instanceUUID.getValue();
Thanks
Why do you want to convert the object to string, and reconvert it back to ProcessInstanceUUID object?
You can pass the ProcessInstanceUUID object itself.
BTW, typecasting is not what you think. It is not a mechanism to convert from any object type any other object.
From the API:
ProcessInstanceUUID instanceUUID = this.getProcessInstanceUUID()
String instanceUUIDValue = instanceUUID.getValue();
ProcessInstanceUUID newUUID = new ProcessInstanceUUID(instanceUUIDValue);
As #Nivas said, this is not typecasting. Here is an example of type casting:
Object obj1 = "Hello World"; // obj1 is in fact a String
Object obj2 = new Integer(2); // obj2 is an Integer
String myString1 = (String) obj1; // explicitly type cast an Object to String
// The next statement will throw an exception at runtime because obj2 is not a String
String myString2 = (String) obj2;
I have these two situations:
String s = "aa";
s = s + " aa";
System.out.println(s);
//......
that work fine! It prints aa aa.
But there is a problem:
String s = "aa";
this.addStringToStatement(s, " aa");
System.out.println(s);
//...
private void addStringToStatement(String statement, Object value) {
statement += value;
}
It prints: aa.
What is the reason??
Thanks!
There are two issues to understand here.
The String append operator will create a new immutable String object. The expression s + value is a different object in memory from s.
In your function addStringToStatement when you execute statement += value; you aren't changing the value of the variable s, rather you are reassigning the local pointer statement to a new String instance.
EDIT: Fixed usual noob mistake: In Java, object references are passed, not the objects themselves.
This is because in Java a reference is passed by value. Here when you passed s and " aa" as two parameters.
In the method statement variable (which has reference of s) is altered to point to something else ie "aa aa". Note only the statement reference is passed, s is still pointing to "aa".
So when you print s you get what is expected :)
this is because of how passing by value works in Java, you need to do something like this:
String s = "aa";
s = this.addStringToStatement(s, " aa");
System.out.println(s);
//...
private string addStringToStatement(String statement, Object value) {
statement += value;
return statement;
}
Strings in Java are immutable. If you have a String s="aa", you only have a reference to the String "aa" inside the JVM. If you want the String "aa aa" assigned to s, you assign only the reference (address) to "aa aa" (another String inside the JVM) to s, "aa" lurks still somewhere in the JVM.
The statement "Java references are passed by value" is somewhat confusing (if true). If you use a StringBuilder sb and give this StringBuilder to a function, the reference is "copied" but still points to the same object as sb:
public static void main(String[] args) {
final StringBuilder sb = new StringBuilder();
f(sb);
System.out.println(sb);
}
private static void f(final StringBuilder sb) {
sb.append("aa aa");
}
You have to return the "statement" variable. Without the "this.*" part.
String s = "aa";
s = addStringToStatement(s, " aa");
System.out.println(s);
//...
private String addStringToStatement(String statement, Object value) {
statement += value;
return statement;
}
#Frank Meißner (new to this, can't reply to answers yet)
Just to clarify the difference between String and StringBuilder (in case anyone reading this is confused), while both store the CharSequence they hold as a char[], the char[] within String cannot be changed, thus a new String has to be created for every alteration. In the case of a StringBuilder, there are methods like StringBuilder.append(String) that can change the internal char[] of the StringBuilder, so if StringBuilder.append(String) is called, no new object will have to be created for the content of the StringBuilder to change.
As per Frank Meißner's example, System.out.println(sb); will print "aa aa", since the method append(String) was called on the StringBuilder sb. final doesn't hurt here since the identity of sb isn't changed, only its state.
+= in case of string doesn't modify string itself but produce new string. in case of your method you set this new string reference to local variable (parameter)
Java references are passed by value. When you pass a String to a method and it changes inside it points to different String. You can either return the String after appending or use StringBuffer as argument.