How can I convert a Java CharSequence to a String?
By invoking its toString() method.
Returns a string containing the characters in this sequence in the same order as this sequence. The length of the string will be the length of this sequence.
There is a subtle issue here that is a bit of a gotcha.
The toString() method has a base implementation in Object. CharSequence is an interface; and although the toString() method appears as part of that interface, there is nothing at compile-time that will force you to override it and honor the additional constraints that the CharSequence toString() method's javadoc puts on the toString() method; ie that it should return a string containing the characters in the order returned by charAt().
Your IDE won't even help you out by reminding that you that you probably should override toString(). For example, in intellij, this is what you'll see if you create a new CharSequence implementation: http://puu.sh/2w1RJ. Note the absence of toString().
If you rely on toString() on an arbitrary CharSequence, it should work provided the CharSequence implementer did their job properly. But if you want to avoid any uncertainty altogether, you should use a StringBuilder and append(), like so:
final StringBuilder sb = new StringBuilder(charSequence.length());
sb.append(charSequence);
return sb.toString();
You can directly use String.valueOf()
String.valueOf(charSequence)
Though this is same as toString() it does a null check on the charSequence before actually calling toString.
This is useful when a method can return either a charSequence or null value.
The Safest Way
String string = String.valueOf(charSequence);
Let's Dive Deep
There are 3 common ways that we can try to convert a CharSequence to String:
Type Casting: String string = (String) charSequence;
Calling toString(): String string = charSequence.toString();
String.valueOf() Method: String string = String.valueOf(charSequence);
And if we run these where CharSequence charSequence = "a simple string"; then all 3 of them will produce the expected result.
The problem happens when we are not sure about the nature of the CharSequence. In fact, CharSequence is an interface that several other classes implement, like- String, CharBuffer, StringBuffer, etc. So, converting a String to a CharSequence is a straightforward assignment operation, no casting or anything is required. But, for the opposite, Upcasting, it is not true.
If we are sure that the CharSequence is actually an object of String, only then we can use option 1- Type Casting. Otherwise, we will get a ClassCastException. Option 2 and 3 are safe in this case.
On the other side, if the CharSequence is null then option 2, calling toString(), will give a NullPointerException.
Now internally, String.valueOf() method calls the toString() method after doing a null check. So, it is the safest way. JavaDoc:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
Please be aware: If CharSequence is null then String.valueOf() method return the string- "null", not null value.
If you want to convert an array of CharSequence,
You can simply do this and can also be store it in a String[] variable.
CharSequence[] textMsgs = (CharSequence[])sbm.getNotification().extras.get(Notification.EXTRA_TEXT_LINES);
if (textMsgs != null) {
for (CharSequence msg : textMsgs) {
Log.e("Msg", msg.toString());
}
}
Also you can une Stringbuilder.
new StringBuilder(charSequence).toString();
Related
what happens when you call "toString" method without a string variable to collect value that is returned?
For eg: here are two code snippets I tired. the first one gives the correct answer, the second gives a wrong answer but it still compiles. If "toString" method is meant to return a value, shouldn't I get a compiler error for the second block of code?
StringBuffer sb=new StringBuffer(s); //s is a string input taken from user
sb.reverse();
String rev=sb.toString();
if(s.equals(rev)){
System.out.println("yes");
/*second try*/
StringBuffer sb=new StringBuffer(s);
sb.reverse();
sb.toString();//what is happening here?
if(s.equals(sb)){
System.out.println("yes");
It is simple to understand.
In the first case, the value is returned and is being referenced by a variable so that you can make use of that value later on.
In the second case, the value is returned just like before but it is not being referenced by any variable. Thus, the value simply goes into waste and can not be used or manipulated later on.
sb.toString();//what is happening here?
You are converting the StringBuilder object to String which is good but you are not storing the return value to a String type and using it later in your equals call. You should do it the following way:
String reversedString = sb.toString();
if(s.equals(reversedString )){
Or simply
if(s.equals(sb.toString())){
Right now you are comparing s with sb using the equals method of String class. This method returns false if the object passed in as an argument is not an instance of String class. Since StringBuilder object sb is not an instance of String, the equals method returns false.
toString will return whatever the toString method of the object returns.
Try System.out.println(sb.toString); to see what it is returning.
StringBuffer#toString() returns a string, if you don't place that returned value in a variable then nothings happens and the information you've requested is gone.
.toString() is a method that returns a string, it does not convert that StringBuffer into a string.
if(s.equals(sb.toString())) would work because it is comparing s to the value of sb as a string, even though it is not assigning the value to variable.
In Java you don't have to check or store any return value.
sb.toString() is executed and the return value is truncated.
Please note that the method must be executed, because there might be side effects. To test it out, you might implement in your class:
#Override
public String toString() {
System.out.println("toStringTest");
return super.toString();
}
"toStringTest" will be put out!
I did some search on this and all I found was that BigDecimal has a constructor that we can pass String to it and it will convert it for us.
But in my case what I have is a java.lang.CharSequence and what I need it to be is BigDecimal
What is the correct way to do this conversion?
new BigDecimal(myCharSeq.toString())
I'd use CharSequence.toString together with the constructor you mentioned. toString documentation:
Returns a string containing the characters in this sequence in the
same order as this sequence. The length of the string will be the
length of this sequence.
This turns into:
new BigDecimal(mySequence.toString());
Call toString() on the CharSequence and build BigDecimal out of it. Javadoc is your friend.
Use the .toString method of CharSequence Interface
I have corrected my self actually CharSequence is an interface which has its own toString() method.
toString(); -- Returns a string representation of the object.
Refer the ofiicial docs of CharSequnce Interface http://docs.oracle.com/javase/6/docs/api/java/lang/CharSequence.html
BigDecimal bigDecimal = new BigDecimal(charSeq.toString());
Like this
StringBuilder sb = new StringBuilder(charSequence.length());
sb.append(charSequence);
BigDecimal bigDecimal = new BigDecimal(sb.toString());
This protects you in case there's a problem with the charSequence concrete class implementation of toString(). CharSequence is an interface that could be backed by a user written concrete class.
The following is my java code snippet:
static String sortChars(String s) {
char[] chars = s.toCharArray();
Arrays.sort(chars);
return chars.toString();
}
I invoke above function by using:
String result = sortChars(s);
But the result does not meet my expectation:for example,the s="are", the result="aer". However, when I use:
return new String(chars)
It works.
Could somebody tell me the reason of it. Thanks
Since char[] class does not override the default Object's toString() implementation, it does not return a string composed by the characters in the char array, but the char[] class name + hash code. For example: arr[C#19821f.
toString() returns a string representation of the Object. You can look at it as a description of the object.
new String(chars) will give you a String with the content of the char array.
Use toString() if you want to represent an Object to the user or in a log, use new String() if you want to get a String object that is the same as the content of your array
Note that, among the constructors for a Java String is one that accepts a character array. That converts the character array into a string as you would expect, and it is the correct choice for what you are doing.
I'm trying to figure out how java classes work.
When I create a StringBuilder:
StringBuilder testString = new StringBuilder("Hello World!);
If I want to, say, get the value that testSting holds a reference to, I can simply call it like: System.out.println(testString);
This is cool behavior, but I'm unsure how to replicate it in classes that I make.
For instance, if I were to try and re-implement my own version of StringBuilder, the approach I would take (as a beginner), would be this:
class MyBuilder {
char[] string;
public MyBuilder(String s) {
string = new char[s.length()];
string = s.toCharArray();
}
So, to make the string an array I had to store it in a data field of the class. But then, to access this in my code, I can't print it by simply calling the variable name. I would have to use .property syntax. Thus, to duplicate the above example, I would have to type System.out.println(testString.value); Which isn't nearly as pretty.
How do you make a class such that it behaves like String or StringBuilder and returns its value without manually accessing the data fields?
Implement a toString method.
toString is a method on Object, so every java object inherits one. The default implementation that you inherit is only useful for getting the class type, and for distinguishing one object from another; the format is: ClassName#HashCode. There are no details unique to your implementation.
In your own classes, to get the description that you want you'll need to override the toString method, so that in contexts where a String is expected, e.g. when you call System.out.println(myObject.toString());, your own format is used.
It's often a good idea to do this, for a more readable description of your object. You can always call super.toString to include the output from the default - ClassName#HashCode - in your own output.
You can override Object.toString() in your object MyBuilder. System.out.println calls on this method for every object used. For example here, you could use:
#Override
public String toString() {
return Arrays.toString(string);
}
Overwrite the toString-Method
private String value;
public MyClass(String value) {
this.value = value;
}
public String toString() {
return value;
}
i have a requirement, where i need to develop a single method which accepts any type of paramter(String or Integer etc) and applies trim() to remove leading and trialing spaces. please help me how to write generic method to achieve this?
Thanks!
Java has strictly defined types, it's not PHP or Javascript. Integer does not have spaces. Simply use trim() method of String object. If your 'integer' is actually a string, do (String.valueOf(x)).trim()
It does not make a lot of sense, but here it goes:
public String trim(Object o) {
if (o != null) {
return o.toString().trim();
}
return null;
}
if an integer is like 12345---. --- indicates 3 spaces. how can i remove? do i need to convert it to string before trimming?
If an 'integer' has trailing spaces, it is already the string representation of the integer, not the integer itself. Therefore:
String i = "12345 ";
String trimmed = i.trim();
By contrast, the following is simply not legal
int i = "12345 "; // compilation error
and a string representation of an integer produced like this:
String i = String.valueOf(12345);
will not have leading or trailing whitespace.
In java, all objects have .toString() method which returns string representation of that object.
You can then call .trim() method on that string, so your function may look like this:
public static String trimAny(Object o) {
return o.toString().trim();
}