I know how to take integer value to string like
String s = st.getText().toString(0;
but my question is how we will take for a character... suppose the value ofa textView txt1 = 'A' so how we will take the value to a string str1..
String str1 = txt1.getText().toString();
is it correct....?
TextView.getText() return java.lang.CharSequence , and ideally you should be able to apply toString() to get the String value. But, however,
from CharSequence java doc
This interface does not refine the general contracts of the equals and
hashCode methods. The result of comparing two objects that implement
CharSequence is therefore, in general, undefined. Each object may be
implemented by a different class, and there is no guarantee that each
class will be capable of testing its instances for equality with those
of the other. It is therefore inappropriate to use arbitrary
CharSequence instances as elements in a set or as keys in a map.
CharSequence is an interface( though toString() appears as declared), it should work provided the CharSequence implementer did their job properly. To avoid any suprises, you can try a different approch
final StringBuilder sb = new StringBuilder(charSequence.length());
sb.append(charSequence);
return sb.toString();
String str1 = txt1.getText().toString();
Yes. It's the right answer to get the string value from string .
If getText() already returns a String, your job is already done for you. It's a string to begin with.
If you absolutely must create a String from a single char value, you can do so with the constructor that takes a char[] as an argument: new String(new char[] {value}).
If, as Satheesh stated above, it returns a CharSequence, there is also a String constructor that takes that as a parameter. Thus, it may be best to declare a new String(txt1.getText()) rather than relying on the implementation of the returned CharSequence's toString() method.
Related
As you may know Object has some function,
For example we have toString() from oracle Documentacion we can know by default it's return HexValue of hashCode()
https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#toString()
We also can use hashCode() for checking of equality object (of course implementation depends on you)
So I made implementation for my Class Projekt :
public class Projekt {
int i;
public Projekt(int i) {
this.i=i;
// TODO Auto-generated constructor stub
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + i;
return result;
}
}
Test Code:
Projekt projekt = new Projekt(1);
System.out.println(projekt.toString());
System.out.println(projekt.toString() == projekt.toString());
Output:
Projekt#20
false
Also i try to inside value from projekt.toString() in StringPool by writing:
String string = projekt.toString();
String stringABC = projekt.toString();
System.out.println(string == stringABC);
According to PoolString i should have the same reference but outPrint is false.
So this method return different reference value but i can't understand why?
From your comment:
I copied this from diffrent comenatry: But to save memory we're using StringPool. If we have the same value, refereance is also the same it's working just for creating String not by constructor. If i had String s = new String("a"); String s2 = new String("a"); I used 2 space in memory, but when i use String s = "a"; String s2 = "a" I use 1 space in memory. So that's mean toString() return "new String()"?
Your source should have said:
...it's working just for creating String using string literals.
That way it might have been clearer, because there are many ways to create new String objects without directly calling the constructor. String literals are those things surrounded by " (including the quotes), such as "a" or "b" or "Welcome to Stack Overflow".
Only string literals1 are pooled automatically. You can manually put a string into the pool by calling intern().
When you concatenate two strings (e.g. stringA + stringB), a new string is generally created, as described here.
Now let's look at what Object.toString does:
The toString method for class Object returns a string consisting of
the name of the class of which the object is an instance, the at-sign
character `#', and the unsigned hexadecimal representation of the hash
code of the object. In other words, this method returns a string equal
to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
Note that strings are being concatenated here, so a new string object is being created here, hence the output.
And to answer the question of:
So that's mean toString() return "new String()"?
Yes, but not directly. The compiler will turn the + operators in Object.toString into some code using StringBuilder (or rather, "the compiler has turned..." since the Object class has already been compiled). At the end, it will call StringBuilder.toString, and that will create a new String object.
1Constant expressions of strings, to be more accurate.
This is because "toString()" method returns a string. So everytime you call toString() it returns a new reference because Strings are immutable (even if they're the same text)
String class is just a pointer to string (char) data somewhere in the memory. It is a class, it is not a primitive type like boolean, byte, char, short, int, long, float and double.
So, comparing two strings you compare pointers.
You generate two strings in:
String string = projekt.toString();
String stringABC = projekt.toString();
So you have 2 different pointers now. They have the same text inside, but they are in different places in memory.
But you can use equals() method of object:
System.out.println(string.equals(stringABC));
I had used the following code to find the length
String str=strLenData.toString();
int ipLen= str.length();
return ipLen;
ipLen would return 11 every time. whatever be the actual value of strLenData. when I call toString() function, value of str: "[C#40523f80". Now I have to use char[] and i need to know the end (or length) of char[].
How do I do it?
If I understand correctly the strLenData variable is a char[]? In that case, you can just do
return strLenData.length;.
I don't think strLenData is charSequence or something. its just a regular object and may be it does't have toString() method. so toString() method of Object class gets called which just returns the HashCode value of The Objects Reference.
so make sure strLenData.toString() can be used.
ipLen is returning 11 always because you are converting an char array to String equivalent by using toString() method.
if you want to create String by an char array use.
String str = new String(strLenData);
Or if you want just want to get length of your char array use answer given by Steven.
use strLenData.length;
How do String objects work in Java? How does term "immutable" exactly apply to string objects? Why don't we see modified string after passing through some method, though we operate on original string object value?
a String has a private final char[] . when a new String object is created, the array is also created and filled. it cannot be later accessed [from outside] or modified [actually it can be done with reflection, but we'll leave this aside].
it is "immutable" because once a string is created, its value cannot be changed, a "cow" string will always have the value "cow".
We don't see modified string because it is immutable, the same object will never be changed, no matter what you do with it [besides modifying it with reflection]. so "cow" + " horse" will create a new String object, and NOT modify the last object.
if you define:
void foo(String arg) {
arg= arg + " horse";
}
and you call:
String str = "cow";
foo(str);
the str where the call is is not modified [since it is the original reference to the same object!] when you changed arg, you simply changed it to reference another String object, and did NOT change the actual original object. so str, will be the same object, which was not changed, still containing "cow"
if you still want to change a String object, you can do it with reflection. However, it is unadvised and can have some serious side-affects:
String str = "cow";
try {
Field value = str.getClass().getDeclaredField("value");
Field count = str.getClass().getDeclaredField("count");
Field hash = str.getClass().getDeclaredField("hash");
Field offset = str.getClass().getDeclaredField("offset");
value.setAccessible(true);
count.setAccessible(true);
hash.setAccessible(true);
offset.setAccessible(true);
char[] newVal = { 'c','o','w',' ','h','o','r','s','e' };
value.set(str,newVal);
count.set(str,newVal.length);
hash.set(str,0);
offset.set(str,0);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {}
System.out.println(str);
}
From the tutorial:
The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.
Strings in Java are immutable (state cannot be modified once created). This offers opportunities for optimization. One example is string interning, where string literals are maintained in a string pool and new String objects are only created if the particular string literal doesn't already exist in the pool. If the string literal already exists, a reference is returned. This can only be accomplished because strings are immutable, so you don't have to worry that some object holding a reference will change it.
Methods that appear to modify a string actually return a new instance. One example is string concatenation:
String s = "";
for( int i = 0; i < 5; i++ ){
s = s + "hi";
}
What actually happens internally (the compiler changes it):
String s = "";
for( int i = 0; i < 5; i++ ){
StringBuffer sb = new StringBuffer();
sb.append(s);
sb.append("hi");
s = sb.toString();
}
You can clearly see that new instances are created by the toString method (note that this can be made more efficient by directly using StringBuffers). StringBuffers are mutable, unlike Strings.
Every object has state. The state of a String object is the array of characters that make up the String, for example, the String "foo" contains the array ['f', 'o', 'o']. Because a String is immutable, this array can never be changed in any way, shape, or form.
Every method in every class that wants to change a String must instead return a new String that represents the altered state of the old String. That is, if you try to reverse "foo" you will get a new String object with internal state ['o', 'o', 'f'].
I think this link will help you to understand how Java String really works
Now consider the following code -
String s = "ABC";
s.toLowerCase();
The method toLowerCase() will not change the data "ABC" that s contains. Instead, a new String object is instantiated and given the data "abc" during its construction. A reference to this String object is returned by the toLowerCase() method. To make the String s contain the data "abc", a different approach is needed.
Again consider the following - s = s.toLowerCase();
Now the String s references a new String object that contains "abc". There is nothing in the syntax of the declaration of the class String that enforces it as immutable; rather, none of the String class's methods ever affect the data that a String object contains, thus making it immutable.
I don't really understood your third question. May be providing a chunk of code and telling your problem is a better option. Hope this helps.
You can also look into this blogpost for more understanding
[code samples are taken from the wiki. you can also look in there for more information]
I know that at compile time when a String is created, that String will be THE string used by any objects of that particular signature.
String s = "foo"; <--Any other identical strings will simply be references to this object.
Does this hold for strings created during methods at runtime? I have some code where an object holds a piece of string data. The original code is something like
for(datum :data){
String a = datum.getD(); //getD is not doing anything but returning a field
StringBuffer toAppend = new StringBuffer(a).append(stuff).toString();
someData = someObject.getMethod(a);
//do stuff
}
Since the String was already created in data, it seems better to just call datum.getD() instead of creating a string on every iteration of the loop.
Unless there's something I'm missing?
String instances are shared when they are the result of a compile-time constant expression. As a result, in the example below a and c will point to the same instance, but b will be a different instance, even though they all represent the same value:
String a = "hello";
String b = hell() + o();
String c = "hell" + "o";
public String hell() {
return "hell";
}
public String o() {
return "o";
}
You can explicitly intern the String however:
String b = (hell() + o()).intern();
In which case they'll all point to the same object.
The line
String a = datum.getD();
means, assign the result of evaluating datum.getD() to the reference a . It doesn't create a new String.
You are correct that strings are immutable so all references to the same string value use the same object.
As far as being static, I do not think Strings are static in the way you describe. The Class class is like that, but I think it is the only object that does that.
I think it would be better to just call the datum.getD() since there is nothing that pulling it out into its own sting object gains for you.
If you do use the datum.getD() several times in the loop, then it might make sense to pull the value into a String object, because the cost of creating a string object once might be less than the cost of calling the getD() function multiple times.
Here's where I wish Java's String class had a replaceLast method, bu it doesn't and I'm getting the wrong results with my code.
I'm writing a program that searches a data structure for any items that match a string prefix. However, since I'm using an Iterator, the last item returned by the iter.next() call doesn't match the pattern, so I want to change the search string so that the last character of the query is increased by one letter. My testing code is returning [C#b82368 with this code and An as titleSearch:
public String changeLastCharacter(String titleSearch) {
char[] temp= titleSearch.toCharArray();
char lastLetter= temp[temp.length-1];
lastLetter++;
temp[temp.length-1]= lastLetter;
String newTitleSearch= temp.toString();
return newTitleSearch;
}
First, what is the cause of the output from this code?
Second, is there a better way to execute my solution?
You want:
newTitleSearch = new String(temp);
The toString method is not overridden for arrays; it's the usual Object.toString, intended for debugging. The above actually creates a string of the characters. An alternative is:
int len = titleSearch.length();
String allButLast = titleSearch.substring(0, len - 1);
newTitleSearch = allButLast + new Character(titleSearch.charAt(len - 1) + 1);
Whenever you see unexpected output like ....#<hex-digits>, the chances are that you are accidentally using toString() on some object whose class inherits the default implementation from Object.
The default toString() method returns a String whose value consists of the type name for the object combined with the object's "identity hash code" as hex digits. In your case the [C part is the type name for a char[] object. The '[' means "array of" and the 'C' means the char primitive type.
The rules for forming the type names used in the default toString() method are fully documented in the javadocs for java.lang.Class.getName().
Your problem is temp.toString(). Try String newTitleSearch = new String(temp); instead.
I figured this out by System.out.println(temp[0]+","+temp[1]); after temp[1] add been assigned to the incremented value. You could do this even easier by using your IDE's debugger.
Since the array was being assigned properly, the problem had to be in the toString().