Difference between String and String Builder (not about concatination) [duplicate] - java

This question already has answers here:
String, StringBuffer, and StringBuilder
(12 answers)
Closed 7 years ago.
Yes i have read all material on internet regarding their difference.and that difference is totally based on concatenation performance of both.My question is that in the below code which technique is better.
public class StringBuilderDemo {
public static void main(String[] args) {
StringBuilder str = new StringBuilder("test");
System.out.println(str.toString());
str = new StringBuilder("Hi ");
System.out.println(str.toString());
}
}
here is string demo
public class StringDemo {
static String str="";
public static void main(String[] args) {
str = "test";
System.out.println(str);
str ="Hi";
System.out.println(str);
}
}
My assumptions are since strings are immutable so when we assign "Hi" to str "test " also remain in memory(two objects of string created "Hi" and "test" ).where as in case of string builder when we give value "Hi" "test" is removed.so we have one object in case of string builder. So i concluded that we should use string builder in these cases. Correct me if i am being childish here .

You are right, String is immutable. Means you cannot add things to its memory content directly, meaning you'll need additional memory to access it. However, your application here doesn't seems to be memory intensive, hence you can just use String directly.

In your case an ordinary String is better. You should use StringBuilder in large for loops where you are adding a lot of stuff to a string.
The thing is that a String is imutable and when you assign a variable to a string, java looks in what you can imagine a table of already created ones. If there is one with the same content, you get a reference to that String. However, whenever you are chaining the content of the String, a new object is created and hence a slower performance in large loops.
With the StringBuilder that is not the case, it is mutable, which means that you can modify it's objects and there will be no new objects created, instead it will just resize itself when it needs to.

Yep, when you join more string or you create a string there is a String Builder hided behind it.
For simple string there is no difference in performance but you should use the String Builder if u need join (or add) more strings togheter.

This is very basic thing. you should use 'String' not 'StringBuilder' in your case.

Related

what is the different between string and stringbuilder in the code? [duplicate]

This question already has answers here:
Why does Java's concat() method not do anything?
(6 answers)
Closed 5 years ago.
i would like to know why the output of this code is "roar roar!!!" not "roar!!! roar!!!"?
the code is:
public class Lion
{
public void roar(String roar1, StringBuilder roar2) {
roar1.concat("!!!");
roar2.append("!!!");
}
public static void main(String[] args)
{
String roar1 = "roar";
StringBuilder roar2 = new StringBuilder("roar");
new Lion().roar(roar1, roar2);
System.out.println(roar1 + " " + roar2);
} }
i try to find the reason of method concat() dont appends one String to the end of another. please with explain.
Here roar1 is you string variable and roar2 is your object of class string builder, and only string builder is mutable, string can not be mutated.... Because of which only inbuilt function in class string builder concate will work on its object roar2.
Roar1 is not object of string builder thus concate function will not work on it.
As said before, Objects of the class String are always immutable.
Additionally you have to remember how variables in JAVA are passed to some Methods.
In your case you build a String and a StringBuilder an pass them to your roar() method. The JVM will create two new Variables which are referencing the two orignal Objects. Due to the immutablity of your local String Variable, a new Object will be created, if you want to change this Object. The append() method of an String Object, normally creates and returns a new Instance of a String, with the changes you've made. You doesn't have a reference on this Object. Even if your local String references this object, the String Variable outside of the roar() method still references the old String ("roar").
That's the reason why your System.out.println, doesn't show the changes you made.

String in Java : charAt Function use

Reversing a string can be done by concatenating the Original String through a reverse loop (from str.length-1->0)
but why is this not Working Correctly :
by adding the character by character from last positon to the 0th position:
int i = 0;
while(i<originalStr.length())
{
strRev.charAt(i)=originalStr.charAt(str.length()-1-i);
i++;
}
Strings are immutable in Java. You cannot edit them.
If you want to reverse a String for training purpose, you can create a char[], manipulate it then instantiate a String from the char[].
If you want to reverse a String for professional purpose, you can do it like this :
String reverse = new StringBuilder(originalStr).reverse().toString();
strRev.charAt(i) // use to Retrieve what value at Index. Not to Set the Character to the Index.
All we know that String is a immutable class in Java. Each time if you try to modify any String Object it will Create a new one.
eg :- String abc = "Vikrant"; //Create a String Object with "Vikrant"
abc += "Kashyap"; //Create again a new String Object with "VikrantKashyap"
// and refer to abc again to the new Object.
//"Vikrant" Will Removed by gc after executing this statement.
Better to Use StringBuffer or StringBuilder to perform reverse Operation. The only Difference between these two class is
A) StringBuffer is a Thread Safe (Synchronized). A little slow because each time need to check Thread Lock.
B) StringBuider is not Thread Safe. So, It gives you much faster Result Because it is Not Synchronized.
There are Several Third Party Jars which provides you a Features like Reverse and Many more String base Manipulation Methods
import org.apache.commons.lang.StringUtils; //Import Statement
String reversed = StringUtils.reverse(words);
In your test method, best practice is to use triple A pattern:
Arrange all necessary preconditions and inputs.
Act on the object or method under test.
Assert that the expected results have occurred.
#Test
public void test() {
String input = "abc";
String result = Util.reverse(input);
assertEquals("cba", result);
}

Differences between classes to work with text in Java String and StringBuffer

When I declare a String looks like:
String a= "Hello, World!"
What I would like to ask is: String makes from a an array?
Furthermore I understand that StringBuffer is special for text editing. If I use String the text cannot be changed while executing the program, that means that if I want to change or work with a text I should use StringBuffer.
Is that right guys?
Storage Area
1.1 String - Constant String Pool
1.2 StringBuffer - Heap
1.3 StringBuilder - Heap
Modifiable
2.1 String - No (immutable)
2.2 StringBuffer - Yes( mutable )
2.3 StringBuilder - Yes( mutable )
Thread Safe
3.1 String - Yes
3.2 StringBuffer - Yes
3.3 StringBuilder - No
Performance
4.1 String - Fast
4.2 StringBuffer - Very slow
4.3 StringBuilder - Fast
Strings is immutable in java while the StringBuffer and StringBuilder classes are used when there is a necessity to make a lot of modifications to Strings of characters.
Unlike Strings objects of type StringBuffer and Stringbuilder can be modified over and over again with out leaving behind a lot of new unused objects.
The StringBuilder class was introduced as of Java 5 and the main difference between the StringBuffer and StringBuilder is that StringBuilders methods are not thread safe(not Synchronised).
It is recommended to use StringBuilder whenever possible because it is faster than StringBuffer. However if thread safety is necessary the best option is StringBuffer objects.
example
public class Test{
public static void main(String args[]){
StringBuffer sBuffer = new StringBuffer(" test");
sBuffer.append(" String Buffer");
System.ou.println(sBuffer);
}
}
you can also use delete(int start, int end), public insert(int offset, int i),replace(int start, int end, String str) functions with string builder and buffer class
for more detail see this link
If multiusers are working at a String then better use StringBuffer (Thread-safe)
If only one user will be editing that String better use StringBuilder (Faster, Better Performance)
on the other side String is immutable which means if you are NOT planning to edit your String , you'd better go for Simple String object as it would be faster via caching
You can use both to work with text but the main difference is that 'StringBuffer' is faster than 'String' when performing concatenations.
You can always change a String in java like:
String value = "hello";
value = value + " world";
System.out.println(value); // "hello world"
But this is computationally intensive, you should use StringBuilder instead:
StringBuilder value = new StringBuilder("hello");
value.append(" world");
System.out.println(value.toString()); // "hello world"
hey you can change the value of a string
see example
String s="raju";
s=s+"ravi";
if we print s it will print
raju ravi.
but StringBuffer is for thread safe when you are using String in multithreaded environment recommended to use StringBuffer.
If you want not immutable and not multithreaded environment and better performance should recommended to use StringBuilder
If you have
String a="Hello";
and you make a=a+"World";, then first string is "deleted", and you have a new string object(the object that a refer is changed). On the other hand, if you have
StringBuffer a=new StringBuffer("Hello");
and you write a.append("world");, a remains unchanged(same reference, only the state of the object has been changed, not the reference). Sorry for my english..
public class Puzzle {
public static void main(String args[]) {
String a = new String("Hello");
String b = a;
System.out.println(a == b); //it s true
a = a + "world";
System.out.println(a == b); //it s false
StringBuffer c = new StringBuffer("Hello");
StringBuffer d = c;
System.out.println(c == d); //it s true
c.append("world");
System.out.println(c == d); //it s true
}
}
yes. If you want to store a string that is not going to change, you can use String datatype.
If you want a datatype which supports value modification, StringBuilder or StringBuffer are better than String.

String object creation - double quotes, how? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Strings are objects in Java, so why don't we use 'new' to create them?
In Java, class objects are created like-
MyClass a=new MyClass();
then how String class objects are created like-
String a="Hello";
What does this "Hello" does to create new object?
String a = "Hello" doesn't actually create a new object. Instead, when the compiler sees a string literal like "Hello", it adds the string to the string literal pool, from which it will be loaded later.
Providing a String as a literal finally makes it in the String Literal Pool of the JVM. Quoting from this article:
String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption.For example:
public class Program
{
public static void main(String[] args)
{
String str1 = "Hello";
String str2 = "Hello";
System.out.print(str1 == str2);
}
}
The result is
true
Unfortunately, when you use
String a=new String("Hello");
a String object is created out of the String literal pool, even if an equal string already exists in the pool. Considering all that, avoid new String unless you specifically know that you need it! For example
public class Program
{
public static void main(String[] args)
{
String str1 = "Hello";
String str2 = new String("Hello");
System.out.print(str1 == str2 + " ");
System.out.print(str1.equals(str2));
}
}
The result is
false true

Strings are objects in Java, so why don't we use 'new' to create them?

We normally create objects using the new keyword, like:
Object obj = new Object();
Strings are objects, yet we do not use new to create them:
String str = "Hello World";
Why is this? Can I make a String with new?
In addition to what was already said, String literals [ie, Strings like "abcd" but not like new String("abcd")] in Java are interned - this means that every time you refer to "abcd", you get a reference to a single String instance, rather than a new one each time. So you will have:
String a = "abcd";
String b = "abcd";
a == b; //True
but if you had
String a = new String("abcd");
String b = new String("abcd");
then it's possible to have
a == b; // False
(and in case anyone needs reminding, always use .equals() to compare Strings; == tests for physical equality).
Interning String literals is good because they are often used more than once. For example, consider the (contrived) code:
for (int i = 0; i < 10; i++) {
System.out.println("Next iteration");
}
If we didn't have interning of Strings, "Next iteration" would need to be instantiated 10 times, whereas now it will only be instantiated once.
Strings are "special" objects in Java. The Java designers wisely decided that Strings are used so often that they needed their own syntax as well as a caching strategy. When you declare a string by saying:
String myString = "something";
myString is a reference to String object with a value of "something". If you later declare:
String myOtherString = "something";
Java is smart enough to work out that myString and myOtherString are the same and will store them in a global String table as the same object. It relies on the fact that you can't modify Strings to do this. This lowers the amount of memory required and can make comparisons faster.
If, instead, you write
String myOtherString = new String("something");
Java will create a brand new object for you, distinct from the myString object.
String a = "abc"; // 1 Object: "abc" added to pool
String b = "abc"; // 0 Object: because it is already in the pool
String c = new String("abc"); // 1 Object
String d = new String("def"); // 1 Object + "def" is added to the Pool
String e = d.intern(); // (e==d) is "false" because e refers to the String in pool
String f = e.intern(); // (f==e) is "true"
//Total Objects: 4 ("abc", c, d, "def").
Hope this clears a few doubts. :)
We usually use String literals to avoid creating unnecessary objects. If we use new operator to create String object , then it will create new object everytime .
Example:
String s1=“Hello“;
String s2=“Hello“;
String s3= new String(“Hello“);
String s4= new String(“Hello“);
For the above code in memory :
It's a shortcut. It wasn't originally like that, but Java changed it.
This FAQ talks about it briefly. The Java Specification guide talks about it also. But I can't find it online.
String is subject to a couple of optimisations (for want of a better phrase). Note that String also has operator overloading (for the + operator) - unlike other objects. So it's very much a special case.
In Java, Strings are a special case, with many rules that apply only to Strings. The double quotes causes the compiler to create a String object. Since String objects are immutable, this allows the compiler to intern multiple strings, and build a larger string pool. Two identical String constants will always have the same object reference. If you don't want this to be the case, then you can use new String(""), and that will create a String object at runtime. The intern() method used to be common, to cause dynamically created strings to be checked against the string lookup table. Once a string in interned, the object reference will point to the canonical String instance.
String a = "foo";
String b = "foo";
System.out.println(a == b); // true
String c = new String(a);
System.out.println(a == c); // false
c = c.intern();
System.out.println(a == c); // true
When the classloader loads a class, all String constants are added to the String pool.
Well the StringPool is implemented using The Hashmap in java. If we are creating always with a new keyword its not searching in String Pool and creating a new memory for it which might be needed later if we have a memory intensive operation running and if we are creating all the strings with new keyword that would affect performance of our application. So its advisable to not to use new keywords for creating string because then only it will go to String pool which in turn is a Hashmap ,(memory saved , imagine if we have lots of strings created with new keyword ) here it will be stored and if the string already exists the reference of it(which would usually reside in Stack memory) would be returned to the newly created string.
So its done to improve performance .
Syntactic sugar. The
String s = new String("ABC");
syntax is still available.
You can still use new String("string"), but it would be harder to create new strings without string literals ... you would have to use character arrays or bytes :-) String literals have one additional property: all same string literals from any class point to same string instance (they are interned).
There's almost no need to new a string as the literal (the characters in quotes) is already a String object created when the host class is loaded. It is perfectly legal to invoke methods on a literal and don, the main distinction is the convenience provided by literals. It would be a major pain and waste of tine if we had to create an array of chars and fill it char by char and them doing a new String(char array).
Feel free to create a new String with
String s = new String("I'm a new String");
The usual notation s = "new String"; is more or less a convenient shortcut - which should be used for performance reasons except for those pretty rare cases, where you really need Strings that qualify for the equation
(string1.equals(string2)) && !(string1 == string2)
EDIT
In response to the comment: this was not intended to be an advise but just an only a direct response to the questioners thesis, that we do not use the 'new' keyword for Strings, which simply isn't true. Hope this edit (including the above) clarifies this a bit. BTW - there's a couple of good and much better answers to the above question on SO.
The literal pool contains any Strings that were created without using the keyword new.
There is a difference : String without new reference is stored in String literal pool and String with new says that they are in heap memory.
String with new are elsewhere in memory just like any other object.
Because String is an immutable class in java.
Now why it is immutable?
As String is immutable so it can be shared between multiple threads and we dont need to synchronize String operation externally.
As String is also used in class loading mechanism. So if String was mutable then java.io.writer could have been changed to abc.xyz.mywriter
TString obj1 = new TString("Jan Peter");
TString obj2 = new TString("Jan Peter");
if (obj1.Name == obj2.Name)
System.out.println("True");
else
System.out.println("False");
Output:
True
I created two separate objects, both have a field(ref) 'Name'. So even in this case "Jan Peter" is shared, if I understand the way java deals..

Categories