Casting to String or using String.valueOf() in Java [duplicate] - java

This question already has answers here:
Difference between casting to String and String.valueOf
(8 answers)
Closed 9 years ago.
This morning I found an interesting question --- cast object to string check if valid and I found there are two types of answers. One is to cast an object to String, the other one is to get the string representation of that object instead (eg. using String.valueOf() or toString()). My questions are: what is the best practice? what is the difference between them?
Before I asked this questions, I found several existing questions which are relevant, but I didn't find one which answers my question. Please forgive me if I missed the important one and hope you don't mind pointing me to the answers.
Thank you,

If the Object is not a String, a cast will throw a ClassCastException at runtime. For example:
Object o = new Object();
String s = (String) o; //Exception here
The difference between the other two solutions (toString vs. String.valueOf) is in the case of a null object. toString will throw an exception whereas String.valueOf() will simply return "null":
Object o = null;
String s = String.valueOf(o); //s = "null";
String t = o.toString(); //NullPointerException

Related

How to use var in Java [duplicate]

This question already has an answer here:
Any difference between `var x` and `int x`? [duplicate]
(1 answer)
Closed 1 year ago.
I am stuck on how to use var. Is there any difference between this two?
var input = (String) result.get("some field from DB");
String input = (String) result.get("some field from DB");
In java 10 and above when you use var you are allowing the compiler to attempt to decide what the variables type should be. In your example your casting a String so it will give that variable type String.
In your second example you are specifically telling the compiler that your variable is of type String.
The second is safer if you know what your variable type will be as it leaves no confusion down to the compile.

how to view the the address of object of String class? [duplicate]

This question already has answers here:
How can I get the memory location of a object in java?
(4 answers)
Closed 2 years ago.
described above. for example.
String s = "abc";
System.out.println(s); // this method will output the string, not the address
so how to view the address, thanks in advance.
Java has no concept of "address", so it is impossible to get the address of any object, including strings.
if u want an answer as u mentioned in the comment, Actually there is a way to do it that way.
String s = new String("abc");
System.out.println(Integer.toHexString(s.hashCode()));
this will return
1ae66
This answer was historically accepted as correct and will only work for classes that didn't override the hashCode() method

If Strings in java are immutable, why I can do this? [duplicate]

This question already has answers here:
Immutability of Strings in Java
(26 answers)
Closed 3 years ago.
I realize that the hashCode of the variable name, is different after the "update", but objectively what makes a String object in fact immutable ?
public static void main(String[] args) {
String str = "AB";
System.out.println(str ); // AB
str = str .replace(str .charAt(0) ,'W');
System.out.println(str );//WB
}
EDIT 1 : The hashCode is based on the value of the variable and have no relation with memory adress.
EDIT 2 : I now understand that Strings are references and not Objects in it self.
I read back all the answers for this same question and found out good answers in topics like [this] (Immutability of Strings in Java). Thank you whos tried to help me and my excuses for any silly misunderstood.
I also recommend this articles here to who wants better understand how Strings works in Java :
https://www.pushkarrajpujari.com/article/strings-in-java/
and how references works :
https://javaranch.com/campfire/StoryPassBy.jsp
EDIT 3: I cannot DELETE this topic anymore, according with Stackoverflow "You cannot delete this question as others have invested time and effort into answering it." which I agree.
If you look at the documentation of replace(), it mentions:
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
Therefore, the replaced String is an entirely new String.

Java String initialization as primitive type [duplicate]

This question already has answers here:
What is the difference between "text" and new String("text")?
(13 answers)
Closed 7 years ago.
String is an Object. Why it is possible to initialize it the same way as primitive type: String str = "my string";
I was expecting to see initialization by using constructor only: new String("my string");
This is just a simplification provided by java. The other alternative would be enormous ugly. Your alternative solution has one simple logical mistake:
new String("my string");
Just aswell uses a string-literal as simply "my string". The real alternative would be
new String(new char[]{'m','y',' ',...,'n','g'});
Or just the same example using a byte[] (deprecated), which would look even worse.
You can go to the javadocs:
Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.

How many object created when creating object of String [duplicate]

This question already has answers here:
Questions about Java's String pool [duplicate]
(7 answers)
Closed 8 years ago.
Actually I am bit confused that how many object created in below "code processing".
String s=new String("A");
s=s+"B";
Actually someone said that here 4 objects will be created but in whole processing but how not understand.
Please anyone can give me detail description also included memory part such string pool etc.
The first String created is literal "A", that is, if not interned
prior.
The second String is the instance generated by the new keyword.
The third one is literal "B", again, if not interned prior.
The last one is the concatenation of s and "B".
You have two String literal Objects, namely "A" and "B". Then you explicitly instantiate a new instance of "A" with new String("A");. Finally, the fourth instance is created when you perform the String concatenation s+"B"

Categories