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 4 years ago.
Improve this question
There are way too many ways to concatenate strings and add variable values in Java. How should I select one (pros, cons, best use cases, etc).
MessageFormat.format
String.format
"string a" + "string b"
StringBuilder
StringBuffer
String.concat
Streams
String.join()
Apache Commons’ StringUtils
Google Guava’s Joiner
...
MessageFormat.format() - Used for dynamically created strings, where parts of the string are positioned and the arguments fill up the place.
MessageFormat.format("My name is {0}. I am {1} years old", "Vignesh", 24);
String.format() - Like position numbering in MessageFormat, it accepts the argument type specifiers.
String.format("Pi is %.2f", 3.14)
String+String - string+string produces a new string leaving the older ones in the garbage, which gets cleared later by JVM.
It internally gets converted to StringBuilder.append() and toString() methods.
hello+world=helloworld null+hello=nullhello
String.concat() - Unlike string+string, if the object on which concat method is called is null, NullPointerException will be thrown.
String a = null, b="hello"; a.concat(b) throws NullPointerException
StringBuffer - They are mutable but they are slower as the methods inside them are synchronized. ie., thread safe
StringBuffer sb = new StringBuffer();
sb.append("hello").append("world");
sb.toString();
StringBuilder - They are mutable and faster than StringBuffer, but not thread safe
StringBuilder sb = new StringBuilder();
sb.append("hello").append("world");
sb.toString();
String.join - If the strings to be concatenated is in the form of array, its better to use String.join rather than looping through the array and appending using a StringBuilder, which String.join does it already inernally. If the array passed is null, it throws NullPointerException.
String[] a = {"hello", "world"};
String.join("", a)
StringUtils.join - If the strings to be concatenated is in the form of array, this can also be used. It internally uses StringBuilder. But just for string concatenation there is no need to include a jar. It precalcualtes the capacity of the StringBuilder object based on the numnber of elements in the array. If the array passed is null, it doesn't throws exception but just returns null string.
String[] a = {"hello", "world"};
StringUtils.join(a, "")
Related
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 2 years ago.
Improve this question
Hello I just had a question about a sorting problem I’m working through. I need to take a list a words and sort them by the first character. So basically I’m creating an array of each letter with a list inside the list. For example at position 0 of the array I could have a list of words that start with A. For position 1 it would be words that start with b. I figured out how to do this by hardcover a bunch of if statements for each letter. I guess my question is, is there a simpler way of achieving this without having to hardcode 27 if statements for each letter?
This is nicely done with the Java Streams API. The operation you ask for is called grouping (by).
The code below will stream over all elements of the array created by split, putting the elements in groups defined by a given function. The code below uses str -> str.charAt(0) as function, which basically says "from element str, get the first character, and this identifies the group", that is, the key.
Map<Character, List<String>> map = Arrays.stream(line.split(" "))
.groupingBy(str -> str.charAt(0));
The abovementioned code uses the functional programming style. Not everyone is familiar with this style, so below you'll find a solution using traditional style.
Map<Character, List<String>> map = new HashMap<>();
String[] words = line.split(" ");
for (String word : words) {
char first = word.charAt(0);
if (!map.containsKey(first)) {
map.put(first, new ArrayList<>());
}
map.get(first).add(word);
}
Why a map? Why not just an ArrayList?
A map has better lookup performance (time complexity of O(1)), while using a List requires you to traverse the list (time complexity O(n)).
Using charAt(0) I assume that none of the words is empty, i.e. has a length of 0.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
String s = "world";
StringBuilder str = new StringBuilder(s);
str.deleteCharAt(0);
System.out.println(s);
this code outputs the following result : world , what am i doing wrong ? why is the first character of string not being deleted ?
The Issue with the StringBuilder and your code is that it does not exactly what you think it does.
A StringBuilder may take any CharSequence as a constructor argument but it will not alter the passed value directly. String in particular are immutable. Anyway StringBuilders do not alter the Object directly. They buffer the characters in a char[] which isn't immutable anymore.
To get the buffered value (and your new "altered" String) you have to call the toString() method of the StringBuilder since it will create a new String based on the interally stored buffer.
But since it System.out.println() implicitly calls the toString() method it is not needed here.
System.out.println(str);
you must put the value of your StringBuilder back to your string.
s = str.toString();
You are printing s, and s has not been changed. When you construct str using s, a copy of s is made. Told in a different way, the reference to each character in s and str is not the same, so even after your deletion in str, s stays the same.
Modify
System.out.println(s);
to
System.out.println(str.toString());
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
public static String getFirstString(String str){
String arr[] = str.split(" ", 2);
String firstWord = arr[0];
return firstWord;
}
i have made this function can any body tell me why i am using
String arr[] = str.split(" ", 2) "2" ,
Number 2 in your split api usage (referred as limit parameter in split api) means you want at max split your string into two parts. So if my string was "blah foo bar", then output you would get would be array of size 2 with content as array[0]="blah", array[1]="foo bar" As per javadoc it says:
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
For details, you could refer to javadoc
"2" is the limit parameter. It sets how many strings to be returned. Check docs for more details
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
public class StringDemo
{
public static void main(String [] args)
{
String s = "Sachin";
s.concat(" Tendulkar");
s.toLowerCase();
System.out.print(s);
}
}
This example giving output as : Sachin
then how many objects have been created?
The answer is: an indeterminate number.
on the face of it, the two operations on s each create a single String object,
two more String objects are created at load time to represent the literals,
objects may be created when print is called: internally to the System.out PrintWriter and the stream stack that it wraps,
each String object may (or may not) have a distinct char[] object inside it,
it is possible that the operations on s could be optimized away, since they actually have no effect on the output of the program (!!),
when the application is called, it will be passed a String[] argument, potentially populated with multiple String, and (finally),
an arbitrary number of objects will be created during JVM bootstrapping and class loading ... prior to the application starting.
So, depending on what objects you count, how you count them, and the other assumptions that you make, the answer could be some number from zero to a very large number of objects.
Note: the normal quiz answer for this would be "2 Strings are created", but as you can see the answer is a lot more complicated than that.
Note 2: the concat and toLowerCase methods do NOT create strings in the string pool. In fact, the only String operation that puts strings into the pool is intern. (It is easy to verify this experimentally, or by reading the Java class library source code.)
String in java is a immutable type.
s.concat(" Tendulkar");
s.toLowerCase();
these 2 lines return 2 distinct strings and doesn't affect the original string.
In java String is considered as immutable which means that it cannot be changed once its created, so if you count how many you have, on the first line you declared the first one, when you did s.concat("SE 6") you created a new object, and finally s.toLowerCase() created the 3rd object, therefore 3 string objects are created.
This question already has answers here:
What is the difference between "text" and new String("text")?
(13 answers)
Closed 7 years ago.
String is an Object. Why it is possible to initialize it the same way as primitive type: String str = "my string";
I was expecting to see initialization by using constructor only: new String("my string");
This is just a simplification provided by java. The other alternative would be enormous ugly. Your alternative solution has one simple logical mistake:
new String("my string");
Just aswell uses a string-literal as simply "my string". The real alternative would be
new String(new char[]{'m','y',' ',...,'n','g'});
Or just the same example using a byte[] (deprecated), which would look even worse.
You can go to the javadocs:
Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.