Difference among several ways of creating string [duplicate] - java

This question already has answers here:
What is the difference between "text" and new String("text")?
(13 answers)
Closed 8 years ago.
Several ways of creating string are shown below. Questions are added following the expressions in the way of comments.
String str = "test";
String str1 = new String(str); //Will it invoke the Constructor of String(String)?
String str2 = new String("test");//Will it invoke the Constructor of String(String)?
String str3 = str; //Which Constructor will it invoke? Or str3 only reference to str and "test" without being constructed?
String str4 = "test";//Which Constructor will it invoke? Or str4 only reference to str and "test" without being constructed?
String strnew = new String("testnew");//Will this expression create "testnew" in String Constant Pool before it creates strnew?
One additional question: Is there any difference bwtween the ways of creating str3 and str4?

Whenever you call new in JAVA it create an object in heap and obviously it will call the constructor also.
String literals will go to String Constant Pool.
It might help you to understand it visually.

Related

String class object [duplicate]

This question already has answers here:
Difference between heap memory and string pool [duplicate]
(2 answers)
Closed 3 years ago.
There is a rule in Java, that to create any object of class we have to use 'new' keyword, but when we use String class,we can create object as
String s = "hello";
so we haven't used new as an operator still new object has been created in String constant pool in heap!
Can anyone explain how we created an object without using new keyword!
Comparision of string initialization performance for String Literal and String object. :
String Literal
String str = “Hello”;
This is string literal. When you declare string like this, you are actually calling intern() method on String. This method references internal pool of string objects. If there already exists a string value “Hello”, then str will reference of that string and no new String object will be created.
String Object
String str = new String(“Hello”);
This is string object. In this method JVM is forced to create a new string reference, even if “Hello” is in the reference pool.

java "== " unusual behaviour [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
== and .equals() not working in java [duplicate]
(1 answer)
Closed 6 years ago.
import java.lang.String;
public class Test {
public static void main(String[] args) {
String a1="ka";
String a2="ka";
System.out.println("a1==a2? "+(a1==a2));
String a3="k";
String a4=new String("k");
System.out.println("a3==a4? "+(a3==a4))
System.out.println("a3==a4? "+(a3==a4.intern()));
String a5="k";
String a6=a4+"a";
System.out.println("a1==a6? "+(a1==a6));
}
}
Output that i got:
a1==a2? true
a3==a4? false
a3==a4? true
a1==a6? false
a1===a2 is true as line 5 will not create new String literal in string pool area.Only reference to previously created string is returned.
a3==a4? false as a4 will have refernce to the String object instead of the string in the string in string pool area. My question is if a3 is referencing the string constant instead of the String object, how is it able to use the methods of the String class?
a4.intern() will return the reference to the string in the string pool which happens to be same as a3
a6=a4+"a" will create a new string "ka". But this actually make use of StringBuilder class and its append method . It is then converted to string using toString(). Does this process store the newly created string "ka" in the string pool area? Since the string is already in the pool the code at line 12 should return the reference to it. So the a1==a6 should be true.rt?
I am new to java. Please guide me where i am doing the mistake?
You are comparing the Strings wrongly (because you are in fact comparing references)
String Class in java is defined in java.lang package and it is exactly that, a class and not a primitive like int or boolean.
String is immutable and final in Java and in this case JVM uses String Pool to store all the String objects.
What are different ways to create String Object?
We can create String object using new operator like any normal java class or we can use double quotes (literal assignment) to create a String object.
To your Question:
When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.
When we use new operator, JVM creates the String object but don’t store it into the String Pool. We can use intern() method to store the String object into String pool or return the reference if there is already a String with equal value present in the pool.
So when you do
String s1 = "abc";
String s2 = "abc";
those are checked in the StringPool and since s1 already exist there, s2 will take the same reference, hence, s1 ==s2 is true.
but when you do:
String s3 = new String("abc");
String s4 = new String("abc");
you are using the new operator, therefore the JVM is not checking if there is an string already in the heap, it will just allocate a new space for s4, so is s3==s4 ??? of course no.
Please take a look at the image below for a more illustrative example.

Java Strings Confusion [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc");
String s4 = new String("abc");
if (s1 == s2) is giving true
while (s3 == s4) is giving false.
Can somebody give a detailed explanation onto what is String pool, heap, how many objects are created in each line and how many objects created in total.
Why s3==s4 is giving false?
A detailed explanation will be much appreciated.
When you do new String(...), it is evaluated at runtime and hence creates two different instances and you end up getting s3 == s4 as false. Same thing happens when you use StringBuilder and do something like sb.toString() which is again evaluated at runtime.
For Example,
StringBuilder sb = new StringBuilder();
String foo = sb.append("abc").toString();
String bar = new String("abc");
String foobar = "abc";
Here foo, bar and foobar are all different objects and hence foo == bar or foo == foobar will evaluate to false.
On the other hand s1 == s2 returns true because abc one declared, already exists in the String Pool and in this case both the objects points to the same reference in the pool.
String Class in java is defined in java.lang package and it is exactly that, a class and not a primitive like int or boolean.
Strings are developed to offer operations with many characters ans are commmonly used in almost all the Java applications
Some interesting facts about Java and Strings:
String in immutable and final in Java and in this case JVM uses String Pool to store all the String objects.
What are different ways to create String Object?
We can create String object using new operator like any normal java class or we can use double quotes (literal assignment) to create a String object.
There are too several constructors available in String class to get String from char array, byte array, StringBuffer and StringBuilderetc etc.
To your Question:
When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.
When we use new operator, JVM creates the String object but don’t store it into the String Pool. We can use intern() method to store the String object into String pool or return the reference if there is already a String with equal value present in the pool.
So when you do
String s1 = "abc";
String s2 = "abc";
those are checked in the StringPool and since s1 already exist there, s2 will take the same reference, hence, s1 ==s2 is true.
but when you do:
String s3 = new String("abc");
String s4 = new String("abc");
you are using the new operator, therefore the JVM is not checking if there is an string already in the heap, it will just allocate a new space for s4, so is s3==s4 ??? of course no.
Please take a look at the image below for a more illustrative example.

What is the difference between "ABC" and new String("ABC")? [duplicate]

This question already has answers here:
What is the difference between "text" and new String("text")?
(13 answers)
Closed 8 years ago.
What is difference between String str = "ABC" and String str = new String("ABC")?
String
In Java String is a special object and allows you to create a new String without necessarily doing new String("ABC"). However String s = "ABC" and String s = new String("ABC") is not the same operation.
From the javadoc for new String(String original):
Initializes a newly created String object so that it represents the
same sequence of characters as the argument; [...]
Unless an explicit copy of original is needed, use of this constructor
is unnecessary since Strings are immutable.
In other words doing String s = new String("ABC") creates a new instance of String, while String s = "ABC" reuse, if available, an instance of the String Constant Pool.
String Constant Pool
The String Constant Pool is where the collection of references to String objects are placed.
String s = "prasad" creates a new reference only if there isn't another one available. You can easily see that by using the == operator.
String s = "prasad";
String s2 = "prasad";
System.out.println(s == s2); // true
Image taken from thejavageek.com.
new String("prasad") always create a new reference, in other words s and s2 from the example below will have the same value but won't be the same object.
String s = "prasad";
String s2 = new String("prasad");
System.out.println(s == s2); // false
Image taken from thejavageek.com.

Confusion in declaring String Objects [duplicate]

This question already has answers here:
What is the difference between "text" and new String("text")?
(13 answers)
Closed 6 years ago.
If I declare a String as
String test=new String("testing");
and
String test1="testing1"
Since String is a class in JAVA how does test1 be a String Object without using a new Operator.Also,when a new Operator is used memory is assigned for new String("testing") so in the case of test1 how is the memory assigned?
Also,when the string is interned ,if two Strings have the same value with what reference is the String store once in the String intern pool?
Let us first consider this String test=new String("testing");
It creates an String Object in Heap.No Checking is done in String Pool for existence of this String in the pool.
and now this String test1="testing1"
It creates String a String Object in String Pool not in Heap.Before Creation check is done whether this string is already there in the pool.If yes its reference is returned else a new String is created in the pool and its reference is returned.Basically this is a String Literal, which is put in Constant pool for memory optimization and re-usability.
intern(): It is used when you construct an object using new() and you call intern() on that object then first a check is done in Stirng pool if that String already exists there or not,if yes it is directly used
Java has a separate memory for Strings that are created without calling the constructor with new. Every time such a String is created Java checks if that String is already in this memory. If it is, then Java sets the same reference to the new String until one of them changes.
When you create a String with the constructor using new then it behaves as a normal object in Java.
Take a look at this example:
String s1 = "Test";
String s2 = "Test";
When you compare this String with the == operator it will return true. s1.equals(s2) will also return true.
It looks different if you create String objects with the constructor like this:
String s1 = new String("Test");
String s2 = new String("Test");
When you now compare this Strings with the == operator it will return false, because the reference of this strings is now different (you created 2 unique String objects).
But if you use s1.equals(s2) it will return true as expected.
When you are using
String test1="testing1"
then it means you are storing only one copy of each distinct string value
but
String test=new String("testing");
gives you a new string object.
Consider your second assignment was:
String1 test1 = System.getenv("PATH");
Here, test1 is most probably also a reference to a String object, without using new().
You can assign references to already existing objects to new variables.
So where is the problem?
The problem is, you must not use sloppy wording like "test1 is a String object". It is not. It is a reference to a String object or null. That's all about it.

Categories