+ 2

String and References

If i say String text1 = "Hello World"; String text2 = "Hello World"; and then System.out.println(text1 == text2); is it true because both texts are stored in the same reference because they contain the same String? And with System.out.println(text1.equals(text2)); I would compare the String itself? Thanks for your help

18th Oct 2020, 5:30 PM
Manfred h
10 odpowiedzi
+ 11
• Requirement of String Pool String pool (String intern pool) is a special storage area in Method Area. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference. The following code will create only one string object in the heap. String str1 = "Hi there.."; String str2 = "Hi there.."; If string is not immutable, changing the string with one reference will lead to the wrong value for the other references. • https://code.sololearn.com/clfOay4iwY7p/?ref=app
18th Oct 2020, 8:24 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 5
In Java, strings are immutable 🙂 It means, you cannot use 2 strings with same values but different reference (without using new) == checks for reference and as told above the strings with same value will have same reference but as you see the "new" keyword it becomes clear that a new reference is created .equals checks for the value and not the reference so both the cases i.e. without "new" and with "new" will output the same.
18th Oct 2020, 5:36 PM
Namit Jain
Namit Jain - avatar
+ 4
The SCP or the String Constant Pool doesn't store duplicate string. So when you create text1, it gets stored in SCP and when you create text2 with the same value then you just point to the same string with a new reference variable. Since both point the same string, text1==text2 returns true. And yes the equals method compares the string content.
18th Oct 2020, 5:39 PM
Avinesh
Avinesh - avatar
+ 3
Only one string object was created so both variables are given the same reference to the same object in string pool, if you wanted to create 2 seprate string objects you need to use the new keyword String str= new String("hello"); String str2 = new String("hello");
18th Oct 2020, 6:02 PM
D_Stark
D_Stark - avatar
0
what is java ? please explain tell tamil and english
19th Oct 2020, 11:14 AM
RS Ss
RS Ss - avatar
0
Thank you for your answers:-)
19th Oct 2020, 1:47 PM
Manfred h
0
I studying java only
22nd Oct 2020, 2:07 AM
RS Ss
RS Ss - avatar
- 1
Java meaning
19th Oct 2020, 2:22 PM
RS Ss
RS Ss - avatar
- 1
Tell
19th Oct 2020, 2:23 PM
RS Ss
RS Ss - avatar
- 1
How to sound recognition by HTML code????
21st Oct 2020, 5:19 PM
Belay Tadele