toString in the java code - java

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.

Related

Why we can't add character at certain position by charAt(index) in java

public class ReverseString {
public static void main(String[] args) {
String s = "mnop";
s.charAt(0) = 'l';
}
}
Java only allows you to assign to variables, fields and array elements.
The result of a method - like s.charAt(0) - is none of these, so you can't assign to it.
The reason for this is down to the way Java returns: it returns by value, not by reference, and that value only exists temporarily. As such, if you were able to assign it, the side effect of that assignment is immediately lost, making it pointless.
It's also true that String is immutable; but this limitation on what you can assign to is the reason you couldn't do this even for some notional MutableString class you might try to create.
Strings in java are immutable, meaning they can't change at all.
To do something like this, use a StringBuilder:
StringBuilder sb = new StringBuilder("mnop");
sb.setCharAt(0, 'l');
//later, you probably want to get back to a String:
String s = sb.toString();
s.charAt(0) returns a char value, not a char variable to which you could assign a value.
And anyway, String is immutable, so you can't modify the value of an existing String.
You can obtain a copy of the array of all the characters of the String, and modify that array:
String s = "mnop";
char[] chars = s.toCharArray();
chars[0]= 'l';
However, this doesn't modify the original String, since it's immutable.
You can create a new String using that array though:
String newS = new String(chars);
charAt returns a char that's a copy of the character at that position in the string. It's not a reference back to the original string, which is immutable.
You could use a StringBuilder instead, though:
StringBuilder sb = new StringBuilder("mnop");
sb.setCharAt(0, 'l');
String s = sb.toString();

how can i get word from arraylist?

I made an arraylist data and when I do
int last=data.size();
int random = r.nextInt(last) + 0;
string a = ""+data.get(random).toString();
a gets the address of the data.
Actually , data.get(random) returns you the object from the list. Since, you are calling data.get(random).toString(), you are getting the string representation which by default returns the hexadecimal characters.
Try the following:
a. Perform your code with a list of String. -> it should return the string at that index position(random).
b.
Try overriding the toString() method inside you java object, you will get the output from your toString() method of the java object,.

Difference between new String(char[]) and char[].toString

The output for following two code blocks in Java is different. I am trying to understand why.
private String sortChars(String s){
char[] arr = s.toCharArray(); //creating new char[]
Arrays.sort(arr); //sorting that array
return new String(arr);
}
This one returns a string with sorted characters as expected.
private String sortChars(String s){
char[] arr = s.toCharArray(); //creating new char[]
Arrays.sort(arr); //sorting that array
return arr.toString();
}
Sorry. My bad!
Using to compare two strings.
The output to second string looks like this as suggested by many -
[C#2e0ece65
Thanks!
In Java, toString on an array prints [, then a character representing the array element type (C in this case) and then the identity hash code. So in your case, are you sure it is returning the original string and not something like [C#f4e6d?
Either way, you should use new String(arr). This is the shortest, neatest, way of converting a char[] back to a String. You could also use Arrays.toString(arr)
Related trivia
The reason that your arr.toString() method returns something like [Cf4e6d is that Object.toString returns
getClass().getName() + '#' + Integer.toHexString(hashCode())
For a char array, getName() returns the string [C. For your program you can see this with the code:
System.out.println(arr.getClass().getName());
The second part of the result, Object.hashCode(), returns a number based on the object's memory address, not the array contents. This is because by default the definition of "equals" for an object is reference equality, i.e. two objects are the same only if they are the same referenced object in memory. You will therefore get different arr.toString() values for two arrays based on the same string:
String s = "fdsa";
char[] arr = s.toCharArray();
char[] arr2 = s.toCharArray();
System.out.println(arr.toString());
System.out.println(arr2.toString());
gives:
[C#4b7c8f7f
[C#5eb10190
Note that this is different for the String class where the equality rules are overridden to make it have value equality. However, you should always use string1.equals(string2) to test for string equality, and not == as the == method will still test for memory location.

Generic trim function in java?

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();
}

Removing Backing Array From Strings

I want to get the first 4 characters of a string to compare with another string. However, when I do something like
String shortString;
shortString = longString.subString(0,3);
It takes along longString's backing array and makes it impossible to compare easily.
I've also tried converting longString into a character array and inserting each character but I always seem to end up with long string. The Android Development documents say to use the String constructor to remove the backing array but it doesn't seem to work for me either.
String shortString = new String(longString.subString(0,3));
Any suggestions would be appreciated!
First, it's string.substring() not .subString().
Second, what do you mean "impossible to compare easily"? You can compare strings with .equals() easily.
public static void main(String[] args) {
String longString = "abcdefghijklmn";
String shortString = longString.substring(0, 3);
System.out.println(shortString.equals(longString));
}
this code prints false, as it should.
Update:
If you call .substring() so that it produces string of the same length as original string (e.g. "abc".substring(0,2)) than it will return reference to the same string. So, .equals() in this case will return true.
How would you want to compare? There's built in method for simple comparison:
longString.subString(0, 3).compareTo(anotherString);
Alternatively, since String is a CharSequence, something like:
for (int i=0; i<4; i++){
if (anotherString.charAt(i) != shortString.charAt(i)) return false;
}
would work as well.
Finally, every String is constructed in backing Array, there's no way to deny it, and longString.subString(0,3) would always (except index out of bound) return a String with a 4-element Char Array.
In the event that you actually need to get rid of the backing array the following will work:
String newString = StringBuilder(oldString).toString();
This might be necessary, for example, if you are parsing strings and creating substrings and you might need to do this:
String newString = StringBuilder(oldString.substring(start,end).toString();
This creates a truly new string with a zero offset and independent backing array. Otherwise, you maintain the same backing array which, in rare cases might cause a problem for the heap because it can never be garbage collected.

Categories