Concatenation of strings in Java [duplicate] - java

This question already has answers here:
"==" in case of String concatenation in Java
(7 answers)
How do I compare strings in Java?
(23 answers)
Closed 2 days ago.
String a="meow"; String ab=a+"deal"; String abc="meowdeal"; System.out.println(ab==abc);
I feel that the output should be 'true' as both strings would be pointing to same location in String Constant Pool. But the output is 'false'. Why?

Strings are objects, you can't directly compare them. You have to use the equals method.
String a="meow"; String ab=a+"deal"; String abc="meowdeal";
System.out.println(ab.equals(abc));
Here are the variations:
public class Main
{
public static void main(String[] args) {
// Constants
System.out.println("abc"=="abc");
// Variables
String a = "a"; // variabe assigned from constant
String b = a+"bc"; // variabe created by concattinating a variable and a constant
String abc = "abc"; // variabe assigned from constant
System.out.println(abc==b);
String c = b.intern(); // intern
System.out.println(abc==c);
System.out.println(abc.equals(b));
System.out.println(abc.intern()==b.intern()); // Compare internal representation
String abc2 = "abc"; // variabe assigned from constant
System.out.println(abc==abc2);
}
}
Result:
true
false
true
true
true
true

Related

Java String pool Storage error [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
public class HelloWorld{
public static void main(String []args){
String a= "hello";
String ab= a +"John";
String abc = "helloJohn";
System.out.println(ab==abc);
}
}
It prints ab==abc false. Shouldnt it be true..??
Use yourStringVar.equals(anotherString) to check if they contain the same sequence of character, use == to check if they refer to the same object.
In java, String is an object, so two String-objects which have same content will not be equal (because those are different objects), hence abc == ab is not true.
But there are methods to compare the contents of String objects. These are:
abc.equals(ab)
or
abc.compareTo(ab) == 0
You should use for String equals/equalsIgnoreCase. '==' compares objects, NOT VALUES. Because when you make String a = "aa" means you create new object.(like new String("aa")). In java there're equals() and hashCode() methods inherited from Object class, but you may override them.

String Concat With Same Reference? [duplicate]

This question already has answers here:
a confusion about java String literal pool and String's concatenation
(4 answers)
When should we use intern method of String on String literals
(14 answers)
Closed 6 years ago.
Here is my code and I am now quite confuse about String pool and
Heap storage by this output.
public class String1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "abcd";
String str1 = "" ;
str1=str1+"abcd";
if(str.equals(str1))
System.out.println("True");
else
System.out.println("False");
if(str == str1)
System.out.println("True");
else
System.out.println("False");
}
}
Now, I am creating String str and will be stored in string pool (Correct me if I am getting wrong!).
Now after concat str1 with string "abcd" they both have same value.
So, I think str and str1 should have same reference in String pool and So, 2nd if statement should print true but it prints false.
So, my question why str and str1 not getting same reference ?
Java automatically interns (means, puts them into the String pool) String literals, not newly created Strings. See also https://stackoverflow.com/a/1855183/1611055.
Remember that Strings are immutable, so the + operator must create a new String - it can not append to the existing one. Internally, the + operator uses a StringBuilder to concatenate the strings. The final result is retrieved through StringBuilder.toString() which essentially does return new String(value, 0, count);.
This newly created String is not automatically put into the String pool.
Hence the str1 reference is different from str even though the strings have the same content. str points to a location in the string pool, while str1 points to a location on the heap.
If you add
str1 = str1.intern();
after str1 = str1 + "abcd"; to explicitly intern the newly created String, your second if statement returns true.
Alternatively, str1 = (str1 + "abcd").intern(); would have the same effect.
In case of strings to compare the values we should use equals method as it compares values that are present in the string variables.
But when we choose to compare string variables using == it compares the addresses of the String object not the values so it will return false even if they have same values in it.
you are right that the strings get added to the string pool. but == checks if both the objects are pointing to the same reference (to make it simpler pointing to the same memory location) in the string pool or not. whereas .equals() method check if the value of the both the object are same or not.

Checking String Values in Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
Im trying to find if the first two letters of a string are "hi". If it does it shold return true, and if not it should return false. I used substring to find the values of the given string, but when the condition comes up true it isn't returning true. I must not be understanding something about Java, which Im new to.
Here is my code:
class Main {
public boolean startHi(String str) {
String str1 = str.substring(0,1);
String str2 = str.substring(1,2);
if(str1=="h" && str2=="i"){
return true;
}
if(str!="hi" || str.length()<=2){
return false;
}
else{
return false;
}
}
public static void main(String[] args) {
System.out.println(new Main().startHi("hi ho"));
System.out.println(new Main().startHi("hi"));
System.out.println(new Main().startHi("howhi"));
}
}
The string starts with "hi" and it sees that, but it returns false.
You could use String.startsWith(String prefix)
public boolean startHi(String str) {
return str.startsWith("hi");
}
So after all you probably don't need your own startHi() method, but can use standard Java API.
It's not returning true because you have to compare strings with the equals() method.
if("h".equals(str1) && "i".equals(str2)){
return true;
}
If you use == to compare objects it will check if it's the same object so it checks if the memory addresses of the objects are the same.
The string class overrides the equals() method to check for content.
If you're creating a string like this
String s1 = "Hi";
Java will put "Hi" in the so called string literal pool
so if you are creating a second string
String s2 = "Hi";
Java will not create a second Object but will refer to the "Hi" in the string literal pool.
Now you could do compare the two strings like s1 == s2 and it would be true
because the two references s1 and s2 point to the same object.
But what the substring() method does is new String("xyz") and if you declare a string like this a new object will be created and the comparison with == will return false because the two references obviously don't point on the same object.
Try this...
if(str1.equals("h") && str2.equals("i")) //equals use instead of (==) Operator.
instead Of
if(str1 =="h" && str2 == "i")
OR
if(str.startsWith("hi") // this will also works

Comparing Same Object of String with '==' and getting different result in both scenerio, where the String Object Value is same [duplicate]

This question already has answers here:
String.equals versus == [duplicate]
(20 answers)
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
In Program 1 I have declared two String and initialized them as "MADAM". When running I am checking the equality of their reference variable (by '==' operator') then I am getting a "true" response.
But in Program 2 I am declaring a String 'S' and initialize it as "MADAM". After that i am running a reverse loop and storing the characters of 'S' in reverse order in other String variable. Now i have again tried to check the equality of reference variable (by '==' operator') and am getting the response as 'false'. As both the String objects are of same value and are stored in constant Pool Area so both the variable should equate and the output in both the scenario should be 'true'. But WHY it is not same?
Program 1:
class Reverse {
public static void main(String[] args) {
String s="MADAM"; String rev="MADAM"; System.out.println(s==rev);
}
}
Output - true
Program 2:
class Reverse {
public static void main(String[] args) {
String s="MADAM"; String rev="";
for(int x=s.length()-1;x>=0;x--) { rev+=s.charAt(x); }
System.out.println(s==rev);
}
}
Output- false
In program 1 java compiler saves "MADAM" string in one memory location and assigns both "s" and "rev" to that location hence "s==rev" returns true because they both refer to the same address.
you should use "equals()" method to compare two strings. e.equals(rev);
have a look at this question:
Java String.equals versus ==
In your first class both strings are initialize to same object. So both are pointing to same memory location.
Next class, Rev is intilialized to "" value and see to madam so both have got different memory location. So false.
In essence,
if you use == for comparison, you are comparing their identity.
If you want to compare the object's value, use .equals()
String s="MADAM"; String rev="MADAM"; System.out.println(s==rev);
The above code will return true, because both Strings will be stored in the same memory location.
However, you can try the following, it will return you false:
String s1 = "aaa";
String s2 = new String("aaa");
System.out.println(s1 == s2); //false (comparing memory location)
System.out.println(s1.equals(s2)); //true (comparing value)
Side note: It is generally a bad practice to create Strings using new String(""). It was only used for demonstration purposes only.

why two literals exists in pool with same data [duplicate]

This question already has answers here:
How String Literal Pool Works
(2 answers)
Closed 9 years ago.
public class ConcatenationRuntime {
public static void main(String[] args) {
String s1 = "jim";
String s3 = "j";
String im = "im";
s3=s3+= im;
System.out.println("s3> " +s3); // jim
System.out.println(s1==s3); // line 8
System.out.println("Hel" + "lo" == "Hello"); // true
}
}
Why it is printing false on line 8? These are all literals, and two references should point to the same literal in the pool - I'm a bit confused.
Why it is returning false at line 8,
Because of s3=s3+= im; .
Strings computed by concatenation at runtime are newly created objects on heap with there own reference. This reference is not same as what reference is provided by jim kept in StringPool . Hence s1==s3 is providing false.
But if you intern the String s3 and then the check for equality it gives true. For example:
s3.intern() == s1 => returns true
Why ?
Because interning a String object first checks if the given string literal exists in StringPool or not . If the String literal exists in StringPool it returns the reference to that String literal , else it stores a copy of that string literal in StringPool and returns the reference to it. Since jim is already stored in StringPool , so s3.intern() will simply return the reference to jim stored in Stringpool. And hence we get same references. This makes s3.intern() == s1 to return true.

Categories

Resources