This question already has answers here:
Why must I override toString method instead of just creating another method?
(13 answers)
Closed 4 years ago.
What is the benefit in using toString method in java if it has always need to be overridden?
Example:
String var = "3";
byte [] var_inBytes = var.getBytes();
String var2 = var_inBytes.toString();
this will give me the name of the object followed by the hash code
okay then when we can use toSting method without overriding?
Every Class is inherited from Object Class in Java, Therefore the Object class methods are available to all Java classes.
According to the Java doc :
In general, the toString method returns a string that "textually
represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is
recommended that all subclasses override this method.
You may want to override the default toString() method in your current class to represent a different format string depend on your requirement but since the Object class has this method, All of the other classes have a default toString() method.
You can read more here :
https://docs.oracle.com/javase/10/docs/api/java/lang/Object.html#toString()
Good Luck!
toString() method is one of the programmer best friend. I use it on each business object or each entity at least, to list their variable members content.
At the time an unexpected problem occurs and that your are in big trouble, and especially if you are in emergency, it makes a great change if you can read : "Big trouble on item {Id : 125, name : Smith, Address : 15 King Square}", instead of "Big trouble on an item".
Not only you have the id you can use for your internal research, but you can also tell a end-user about who is really impacted : Mr Smith. May be your end-user will have a clue : "Oh yes, we were doing special operation on him, because..."
In plenty of logs, on TRACE or DEBUG level only of course, I dump many business object or entities content that way. If a really big problem happens, even in production, and that it is reproducible, I may (in the dire case) restart the application in TRACE mode and learn what really happens.
toString() is a life savior, I say.
Related
This question already has answers here:
Does EL automatically convert/cast the type? How does ${a.name} actually work?
(2 answers)
Closed 2 years ago.
I have these pictures from Head First book:
I want you to pay attention to code that replaces ${person.dog.name}. Only thing I want to know is how does it know that attribute "person" is object of type Person? Of course, getAttribute() returns Object, so it must be casted to Person, but how does it know that it is made from Person class?
I guess this code uses findAttribute() previously, to find scope where attribute with value "person" is stored. Later it tries to get it using getAttribute(). So after it finds it, it gets it - but it still doesn't know what it is getting in reality. So how/where did it "figure out" that it is of type Person?
It doesn't. The properties are resolved using reflection, by looking for a method getDog() on whatever object person resolves to, and then repeating that process.
the EL engine sees person and looks it up in the glorified HashMap (which is what request.setAttribute is filling - that glorified hashmap).
It finds an object there, because you set it. It gets this object and invoked .getClass() on it, which returns Person.class. It then runs a capitalizer function on dog to produce getDog. It then scans for all fields using .getFields() as well as all methods using .getMethods(), looking for either a field named dog or a no-args instance method named getDog. It finds the method, and invokes it.
Repeat this principle for how it ends up dealing with the .name part.
Now EL has an object (the result of invoking getName on whatever object wsas returned by reflectively invoking getDog on whatever person was), and toStrings that into place.
I don't think it's HTML escaping it, so this is a book that is 'helpfully' informing you how to use obsolete technology (JSP) to create security holes. Great.
You got a newer book? You might wanna get something that is less than 10 years old :)
This question already has answers here:
Can I add new methods to the String class in Java?
(16 answers)
Closed 5 years ago.
I am trying to add custom function that operates on string variable like below in java (in my android project actually)
String name="tester";
name.isAlreadyEntered();
public static boolean isAlreadyEntered(String name){
return (checkInMyDb(name));
}
I am going to use this for some more functions. I know its a bit stupid question. I know this does exists in javascript & in .Net. As I am new to java I m not aware of its possibility. Forgive if I am asking wrongly. But if possible please help me on how to get this syntax
If you really intend to add a new method to java.lang.String.java then you are probably on a wrong path which will only cause pain and agony in future :d. Better stop, rethink redesign and refactor.
Anyways firstly NO you can not add a new method to String class. It is final and hence you can not and neither you should even intend to sub class it. If you intend to do so then its a poor design, which you must refactor.
If you just wish to check if some String is present in the database, you can simply declare the method which can accept a parameter of type String , check its presence in the database and return true if found else return false.
If above solution does not work for you then you can try takimg help of Composition. If you want a Object with such method (which can tell if the object is present in db) then You can create a class , may decide to name it as per your contextual needs , I am naming it as StringContainer. This class can have a instance variable of type String. Now instead of using String object you can use the object of this newly created custom class composing the object of String You can include a method to check if entry cossponding to an object of this class had been made in database or not.
This question already has answers here:
Converting back from toString to Object
(7 answers)
How to get back an object after performing .toString() on it? [duplicate]
(4 answers)
Closed 8 years ago.
We all know how to implement toString() method. It could be slightly custom implementation and different pattern how we print the object data.
Using the generated toString, can we recreate the Object? I am not talking about Serialization here.
Let me explain a scenario, You might have an application running happily in production and your log prints these objects when you received some request and doing some operations. And some issue might have raised.
To replicate certain hard bugs, you will go back to your unit test cases/mockito to recreate the problem with similar data.
Now If I can reproduce the object from it's toString representation,
since all of it's dependency objects also implements toString, I will
be able to clear most of these scenarios.
Is there any by default plugin/tool to do the same? If not, It could be my next try-on project :)
The toString() method was designed to return a readable representation of an object, not a full representation.
If you want to marshal your object into a string that can later be unmarshalled, the usual options are XML, JSON, flat file,... Check out JAXB perhaps.
You could opt for a custom format, the only requirement being that all the information you need to reconstruct the object is in there and you write a custom parser to build the object again. If said custom format also happens to be readable, you can plug it into toString().
No, there is no general way
(Consider the case of a toString method that returns the empty string)
Your best bet is to log more details in the case of an Exception, possibly on a finer log level
No you cannot.
toString() is only intended for logging and debug purposes. It is not intended for serializing the state of an Object.
If the object in question supports serialization then go with serialization and deserialization to find out how to do this.
This might be a very basic question, apologies if this was already asked.
Should toString() in Java be used for actual program logic or is it only for debugging/human reading only. My basic question is should be using toString() or write a different method called asString() when I need to use the string representation in the actual program flow.
The reason I ask is I have a bunch of classes in a web service that rely on a toString() to work correctly, in my opinion something like asString() would have been safer.
Thanks
Except for a few specific cases, the toString should be used for debugging, not for the production flow of data.
The method has several limitations which make it less suitable for use in production data flow:
Taking no parameters, the method does not let you easily alter the string representation in response to the environment. In particular, it is difficult to format the string in a way that is sensitive to the current locale.
Being part of the java.Object class, this method is commonly overridden by subclasses. This may be harmful in situations when you depend on the particular representation, because the writers of the subclass may have no idea of your restrictions.
The obvious exceptions to this rule are toString methods of the StringBuilder and the StringBuffer classes, because these two methods simply make an immutable string from the mutable content of the corresponding object.
It is not just for debugging/human reading only, it really depends on the context in which the object is being used. For example, if you have a table which is displaying some object X, then you may want the table to display a readable textual representation of X in which case you would usually implement the toString() method. This of course is a basic example but there are many uses in which case implementing toString() would be a good idea.
I have a class called Zebra (not her actual name). Zebra overrides the toString method to provide her own convoluted obfuscated stringification.
Which is more efficient to stringify an instance of Zebra? Presuming that I have to do this stringification millions of times per session.
zebra.toString()
""+zebra
static String BLANK (singleton)
BLANK+zebra (multiple executions).
Where the value of zebra is not assured to be the same.
I am conjecturing that the answer could be - no concern: the compiler makes them all equivalent. If that is not the answer, please describe the instantiation process that makes them different. (2) and (3) could be the same, since the compiler would group all similar strings and assign them to a single reference.
Normally, I do ""+zebra because I am too lazy to type zebra.toString().
ATTN: To clarify.
I have seen questions having been criticised like "why do you want to do this, it's impractical" If every programmer refrains from asking questions because it has no practical value, or every mathematician does the same - that would be the end of the human race.
If I wrote an iteration routine, the differences might be too small. I am less interested in an experimental result than I am interested in the difference in processes:
For example, zebra.toString() would invoke only one toString while, "+zebra would invoke an extra string instantiation and and extra string concat. Which would make it less efficient. Or is it. Or does the compiler nullify that.
Please do not answer if your answer is focused on writing an iterative routine, whose results will not explain the compiler or machine process.
Virtue of a good programmer = lazy to write code but not lazy to think.
Number 1 is more efficient.
The other options create an instance of StringBuilder, append an empty string to it, call zebra.toString, append the result of this to the StringBuilder, and then convert the StringBuilder to a String. This is a lot of unnecessary overhead. Just call toString yourself.
This is also true, by the way, if you want to convert a standard type, like Integer, to a String. DON'T write
String s=""+n; // where "n" is an Integer
DO write
String s=n.toString();
or
String s=String.valueOf(n);
As a general rule, I would never use the + operator unless it is on very small final/hard-coded strings. Using this operator usually results in several extra objects in memory being created before your resulting string is returned (this is bad, especially if it happens "millions of times per session").
If you ever do need to concatenate strings, such as when building a unique statement dynamically (for SQL or an output message for example). Use a StringBuilder!!! It is significantly more efficient for concatenating strings.
In the case of your specific question, just use the toString() method. If you dont like typing, use an IDE (like eclipse or netbeans) and then use code completion to save you the keystrokes. just type the first letter or 2 of the method and then hit "CTRL+SPACE"
zebra.toString() is the best option. Keep in mind zebra might be null, in which case you'll get a NullPointerException. So you might have to do something like
String s = zebra==null ? null : zebra.toString()
""+zebra results in a StringBuilder being created, then "" and zebra.String() are appended separately, so this is less efficient. Another big difference is that if zebra is null, the resulting string will be "null".
If the Zebra is Singleton class or the same instance of zebra is being used then you can store the result of toString in Zebra and reuse it for all future calls to toString.
If its not the case then in implementation of toString cache the part which is unchanges everytime in constructing String at one place, this was you can save creating some string instances every time.
Otherwise I do not see any escape from the problem you have :(
Option 1 is the best option since every option calls the toString() method of zebra, but options 2 and 3 also do other (value free) work.
zebra.toString() - Note that this calls the toString() method of zebra.
""+zebra - This also calls the toString() method of zebra.
static String BLANK; BLANK+zebra; - This also calls the toString() method of zebra.
You admit "I'm lazy so I do stupid stuff". If you are unwilling to stop being lazy, than I suggest you not concern yourself with "which is better", since lazy is likely to trump knowledge.
Since the object's toString method will be invoked implicitly in cases where it is not invoked explicitly, a more "efficient" way doesn't exist unless the "stringification" is happening to the same object. In that case, it's best to cache and reuse instead of creating millions of String instances.
Anyway, this question seems more focused on aesthetics/verbosity than efficiency/performance.
If you want to know things like this you can code small example routines and look at the generated bytecode using the javap utility.
I am conjecturing that the answer could be - no concern: the compiler makes them all equivalent. [...] Normally, I do ""+zebra because I am too lazy to type zebra.toString().
Two things:
First: The two options are different. Think about zebra being null.
Second: I'm to lazy to do this javap stuff for you.