This question already has answers here:
When is `StringBuilder` is preferred instead appending `String` to `String`? [duplicate]
(2 answers)
Closed 7 years ago.
Say I have 3 String variables:
String firstName = "aaa";
String middleName = "bbb";
String lastName = "cccc";
To append string variables we can use:
String fullName = firstName + "-" + middleName + "-" +lastName ;
Or we can use StringBuilder:
StringBuilder builder = new StringBuilder();
builder.append(firstName);
builder.append("-");
builder.append(middleName);
builder.append("-");
builder.append(lastName);
String fullName = builder.toString();
When to use StringBulider or when to append it directly?
As a programmer we should always care about the readability of our code and the first case looks quite readable to me than the second one.
Now if your question is which one should I choose ?
Than answer is any of them and you should not bother for this.StringBuilder only make difference with loop, other than that currently both of the cases would be almost same.
Simplest way : If you have access to apache common, you could use StringUtils.join().
Next, if all the Strings could be marked as final, then use + directly as using + on final Strings (which are compile time constants) is actually a compile-time operation.
If, you don't want to do the 2 things above, then use StringBuilder to concatenate strings (Even though + on Strings is done using StringBuilder internally.
Related
This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 6 years ago.
I am trying to only display data after a certain static word (in)
Example:
String jobName = job.getDescription();
returns the following:
XYZ/LMNOP in ABCEFG
I only want the data after the "in" in this scenario. However the XYZ/LMNOP is different in almost every case so I cannot simply call out that section of the string.
You can use split() in the String class.
String jobName = job.getDescription();
String[] parts = jobName.split("in"); { "XYZ/LMNOP", "ABCEFG" }
String before = parts[0]; // XYZ/LMNOP
String after = parts[1]; // ABCEFG
Find index of "in" in the string and then use the string from that particular index+3 to last.
int k = p.indexOf("in");
System.out.println(p.substring(k+3));
index+3 because "i", "n" , " " are 3 characters.
First you need to understand your strings possible data values. If it is always <some_text> in <some_text> then there are muliple ways as other users have mentioned.
Here is another way, whih is bit simpler
String[] strArray = job.getDescription().split(" "); //splits array on spaces
System.out.println(strArray[2]);
try using this
String search = " in ";
String d = job.getDescription();
d = d.substring(d.indexOf(search) + search.length(), d.length());
Outputs, given the inputs:
[find something in a string] -> [a string]
[finding something in a string] -> [a string] // note findINg, that does not match
The search key can be changed to simply in if desired, or left as is to match the question posted to avoid an accidental in in a word.
If you so choose, you can also use .toLower() on getDescription() if you want to be case insensitive when matching the word in as well.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Strings are immutable. Stringbuilders are not, so you can append characters at the end. Strings are character arrays if i am not wrong, than why do we use character arrays separately and Strings separately, Do we really need to use character arrays?
Secondly, there are character arrays and then there are Arraylists. Array lists holds complete objects? I am a bit confused actually.
String cat = "c" + "a" + "t";
cat = cat + cat;
StringBuilder sb = new StringBuilder();
sb.append(city);
sb.append(", ");
sb.append(state);
sb.toString();
Char apple[5]={'a','p','p','l','e'};
Arraylist<MyCar>obj = new Arraylist<MyCar>();
Which should be used where?
This Explain the best: between string and stringBuilder
Ref:Correct way to use StringBuilder
Note that the aim (usually) is to reduce memory churn rather than total memory used, to make life a bit easier on the garbage collector.
Will that take memory equal to using String like below?
No, it'll cause more memory churn than just the straight concat you quoted. (Until/unless the JVM optimizer sees that the explicit StringBuilder in the code is unnecessary and optimizes it out, if it can.)
If the author of that code wants to use StringBuilder (there are arguments for, but also against; see note at the end of this answer), better to do it properly (here I'm assuming there aren't actually quotes around id2 and table):
StringBuilder sb = new StringBuilder(some_appropriate_size);
sb.append("select id1, ");
sb.append(id2);
sb.append(" from ");
sb.append(table);
return sb.toString();
Note that I've listed some_appropriate_size in the StringBuilder constructor, so that it starts out with enough capacity for the full content we're going to append. The default size used if you don't specify one is 16 characters, which is usually too small and results in the StringBuilder having to do reallocations to make itself bigger (IIRC, in the Sun/Oracle JDK, it doubles itself [or more, if it knows it needs more to satisfy a specific append] each time it runs out of room).
You may have heard that string concatenation will use a StringBuilder under the covers if compiled with the Sun/Oracle compiler. This is true, it will use one StringBuilder for the overall expression. But it will use the default constructor, which means in the majority of cases, it will have to do a reallocation. It's easier to read, though. Note that this is not true of a series of concatenations. So for instance, this uses one StringBuilder:
return "prefix " + variable1 + " middle " + variable2 + " end";
It roughly translates to:
StringBuilder tmp = new StringBuilder(); // Using default 16 character size
tmp.append("prefix ");
tmp.append(variable1);
tmp.append(" middle ");
tmp.append(variable2);
tmp.append(" end");
return tmp.toString();
So that's okay, although the default constructor and subsequent reallocation(s) isn't ideal, the odds are it's good enough — and the concatenation is a lot more readable.
But that's only for a single expression. Multiple StringBuilders are used for this:
String s;
s = "prefix ";
s += variable1;
s += " middle ";
s += variable2;
s += " end";
return s;
That ends up becoming something like this:
String s;
StringBuilder tmp;
s = "prefix ";
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable1);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" middle ");
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable2);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" end");
s = tmp.toString();
return s;
...which is pretty ugly.
It's important to remember, though, that in all but a very few cases it doesn't matter and going with readability (which enhances maintainability) is preferred barring a specific performance issue.
Normally String is used for normal string based requirement, and when a String can suffice it.
String Builder is used whenever you want to manipulate and play with the string.
Character Array is used when you want to easily iterate over each and every character
ArrayList is a collection. Use it for holding object of a particular type.
String is immutable object that includes underlying char array.
In your line 2 you discard your String that you created in line 1 and create a new String.
String builder avoids creating new String objects for every separate substring.
Both arrays and Arraylist can contain objects, the main difference is that Arraylist can grow, arrays can not. The second difference is that Arraylist is really a List...
A String uses a char[]. A String is not a char[], in the same way that an ArrayList<String> is not a String[].
ArrayList type is a dynamic data structure. This means that it can grow depending on need. Array is static, meaning it's dimensions do not change over its lifetime.
This question already has answers here:
String can't change. But int, char can change
(7 answers)
Closed 8 years ago.
I am confuse about String and String Builder. Here is my simple code
StringBuilder sb1 = new StringBuilder("123");
String s1 = "123";
sb1.append("abc");
s1.concat("abc");
System.out.println(sb1 + " " + s1);
sb1 output for 123abc. It is ok! because it use append method.But String s1 should be abc123
but it output is abc. Why? And what is concat method purpose? Please explain me.
Thank you
.But String s1 should be abc123 but it output is abc.
Strings are immutable in Java. concat doesn't change the existing string - it returns a new string. So if you use:
String result = s1.concat("abc");
then that will be "123abc" - but s1 will still be "123". (Or rather, the value of s1 will still be a reference to a string with contents "123".)
The same is true for any other methods on String which you might expect to change the contents, e.g. replace and toLowerCase. When you call a method on string but don't use the result (as is the case here), that's pretty much always a bug.
The fact that strings are immutable is the whole reason for StringBuilder existing in the first place.
concat function not change the string but it returns the result which is not assigned in your case:
String concat(String textToAppend)
so change:
s1 = s1.concat("abc");
string objects are immutable. Immutable simply means unmodifiable or unchangeable
but if you give
String result = s1.concat("abc");
output is 123abc
and
StringBuilder are mutable
you can perform changes
s1.concat("abc") will create a new object in heap with the "abc" concatenated to s1. but s1 is still pointing to original s1 which is "123". so you need to make your s1 reference to point to new object using s1 = s1.concat("abc");
This question already has answers here:
String replace method is not replacing characters
(5 answers)
Closed 7 years ago.
I want the text "REPLACEME" to be replaced with my StringBuffer symbols. When I print symbols, it is a valid string. When I print my query, it still has the text REPLACEME instead of symbols. Why?
private String buildQuery(){
String query = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(REPLACEME)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
deserializeQuotes();
StringBuffer symbols = new StringBuffer();
for(int i = 0; i < quotes.size();i++){
if(i == (quotes.size()-1))
symbols.append("%22" + quotes.get(i).getSymbol() + "%22%"); //end with a quote
else
symbols.append("%22" + quotes.get(i).getSymbol() + "%22%2C");
}
System.out.println("***SYMBOLS***" + symbols.toString());
query.replaceAll("REPLACEME", symbols.toString());
return query;
}
Change
query.replaceAll("REPLACEME", symbols.toString());
to:
query = query.replaceAll("REPLACEME", symbols.toString());
Strings in Java are designed to be immutable.
That is why replaceAll() can't replace the characters in the current string, so it must return a new string with the characters replaced.
Also if you want to simply replace literals and don't need regex syntax support use replace instead of replaceAll (regex syntax support is only difference between these two methods). It is safer in case you would want to replace literals which can contain regex metacharacters like *, +, [, ] and others.
Read the documentation :) replaceAll() returns a new String, it does replace inside the existing String. The reason for that is that Strings are immutable objects.
The String object in Java is immutable. The replaceAll will not replace the data in the string, it will generate a new string. Try this:
query = query.replaceAll("REPLACEME", symbols.toString());
This question already has answers here:
String replace method is not replacing characters
(5 answers)
Closed 7 years ago.
I would like to replace "." by "," in a String/double that I want to write to a file.
Using the following Java code
double myDouble = myObject.getDoubleMethod(); // returns 38.1882352941176
System.out.println(myDouble);
String myDoubleString = "" + myDouble;
System.out.println(myDoubleString);
myDoubleString.replace(".", ",");
System.out.println(myDoubleString);
myDoubleString.replace('.', ',');
System.out.println(myDoubleString);
I get the following output
38.1882352941176
38.1882352941176
38.1882352941176
38.1882352941176
Why isn't replace doing what it is supposed to do? I expect the last two lines to contain a ",".
Do I have to do/use something else? Suggestions?
You need to assign the new value back to the variable.
double myDouble = myObject.getDoubleMethod(); // returns 38.1882352941176
System.out.println(myDouble);
String myDoubleString = "" + myDouble;
System.out.println(myDoubleString);
myDoubleString = myDoubleString.replace(".", ",");
System.out.println(myDoubleString);
myDoubleString = myDoubleString.replace('.', ',');
System.out.println(myDoubleString);
The original String isn't being modified. The call returns the modified string, so you'd need to do this:
String modded = myDoubleString.replace(".",",");
System.out.println( modded );
The bigger question is why not use DecimalFormat instead of doing String replace?
replace returns a new String (since String is immutable in Java):
String newString = myDoubleString.replace(".", ",");
Always remember, Strings are immutable. They can't change. If you're calling a String method that changes it in some way, you need to store the return value. Always.
I remember getting caught out with this more than a few times at Uni :)