This is my code:
public void idoKiiras(){
String idostring = new String();
idostring.valueOf(System.currentTimeMillis());
System.out.print(idostring);
ido.setText(idostring);
}
What i get in the string is nothing, it's empty. Any solution?
String.valueOf() is a static method that returns a String value. Use it like so
String idostring = String.valueOf(System.currentTimeMillis());
System.out.print(idostring);
ido.setText(idostring);
Previously, you were using the valueOf method but not doing anything with its return value.
idostring.valueOf(System.currentTimeMillis());
Remember that String objects are immutable. No String method will ever change the String internally, it will always return a new String object.
#Sotirios already answered this, beautifully, but, I just want to give you a little tip to help anyone that has this problem.
Set the idostring to a silly value at the initialisation phase that way you can see whether it is being changed from the various methods.
E.g
String idostring = "THIS_SHOULD_CHANGE";
That way, when you get to setting the text of ido, you won't have a blank label/button/textview.
Related
i was solving a question on leetcode and came across the code which I'm having difficulty to understand and had searched through internet for answer but didn't found desired answer
The Question is Shuffle String on leetcode.
so, here is code!
class Solution {
public String restoreString(String s, int[] indices) {
char[] charArray = new char[indices.length];
for(int i=0; i<indices.length; i++){
charArray[indices[i]] = s.charAt(i);
}
return new String(charArray);
}
}
the last statement which return new String(charArray) which is String constructor according to me i don't know may be i'm wrong but if am i right can we return constructor to function which expect String DataType
I want some to understand the concept please can anyone explain me. I would love to have link for the study material if anyone suggest some
looking forward positively,
thanks.
You are not 'returning a constructor'. You are constructing a String and returning it.
This:
return new String(charArray);
can be written as follows, introducing a superfluous variable just to make the point:
String r = new String(charArray);
return r;
In this reformulation, it's important not to think that you are "returning a variable", you are returning the value of a variable.
Similarly, in your original code, what you called "returning a constructor" was returning the value returned from the constructor (a reference to the newly-constructed String).
)
The new String creates a new String object from the char-Array. So we create the String and then Return it. You can interpret this syntax as just doing both of these things consecutively.
Alternatively, you could also first declare and then initialize the variable with the new String(charArray) and then return the new String, but that is unnecessary.
I hope I could help!
My question similar to others but it's little bit more tricky for me
I have a Class DummyData having static defined variables
public static String Survey_1="";
public static String Survey_2="";
public static String Survey_3="";
So, i call them DummyData.Survey_1 and it returns whole string value. Similarly do with DummyData.Survey_2 and DummyData.Survey_3
But the problem is when i call them Dynamically its not return their value.
I have a variable data which value is change dynamically like (data=Survey_1 or data=Survey_2 or data=Survey_3)
I use #Reflection to get its value but failed to get its value
I use methods which I'm mentioning Below help me to sort out this problem.
Field field = DummyData.class.getDeclaredField(data);
String JsonData = field.toString();
and
DummyData.class.getDeclaredField("Survey_1").toString()
but this return package name, class name and string name but not return string value.
What I'm doing can some help me??
Getting the value of a declared field is not as simple as that.
You must first locate the field. Then, you have to get the field from an instance of a class.
Field f = Dummy.class.getDeclaredField(“field”);
Object o = f.get(instanceOfDummy);
String s = (String) o;
Doing the simple toString() of the Field will actually invoke the toString() method of the Field object but won't access the value
You must do something like this:
Field field = SomeClass.class.getDeclaredField("someFieldName");
String someString = (String) field.get(null); // Since the field is static you don't need any instance
Also, beware that using reflection is an expensive and dangerous operation. You should consider redesigning your system
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!
for example, say I have a string called names and I want to .toUpperCase and then use the .replaceAll function before printing it.
The problem I'm having is that only one step is applied at a time and the two functions are handled separately.
System.out.format(names[i].toUpperCase());
System.out.format(names[i].replaceAll("SMITH", "<>JENKINS<>"));
System.out.println(names[i]);
Thanks in advance!
.toUpperCase() returns a String. You need to something like:
names[i].toUpperCase().replaceAll("SMITH", "<>JENKINS<>");
or
names[i] = names[i].toUpperCase();
names[i].replaceAll("SMITH", "<>JENKINS<>")
Because Strings are immutable in java, none of these functions work in-place. They don't change names[i]. So you'd have assign them to a temp variable (or names[i]). Do something like this.
String tmp = names[i].toUpperCase();
System.out.format(tmp);
tmp = tmp.replaceAll("SMITH", "<>JENKINS<>")
System.out.format(tmp);
System.out.println(tmp);
You can chain method calls, since String instances are immutable and each method returns the string as transformed by its operations.
String changed = names[i].toUpperCase().replaceAll("SMITH", "<>JENKINS<>");
System.out.format(changed);
The variable changed has been extracted to make the code more readable.
Strings in Java are immutable, they do not change themselves. The methods you use return a new, changed string:
names[i] = names[i].toUpperCase();
System.out.format(names[i]);
names[i] = names[i]..replaceAll("SMITH", "<>JENKINS<>");
System.out.format(names[i]);
does what you expected your code to do.
names[i].replaceAll("SMITH", "<>JENKINS<>")
this code only returs the replaced string. you need to set it to a variable;
string str = names[i].replaceAll("SMITH", "<>JENKINS<>");
or to replace the current reference;
names[i]= names[i].replaceAll("SMITH", "<>JENKINS<>");
Extract a variable?
String str = names[i].toUpperCase().replaceAll("SMITH", "<>JENKINS<>");
System.out.println(str);
System.out.println(names[i].toUpperCase().replaceAll("SMITH", "<>JENKINS<>"));
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.