Confused in appending Strings in Java [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have a situation of appending String. And i'm confused ..
public static void foo() {
String s = "str4";
String s1 = "str" + s.length();
System.out.println("(s==s1) = " + (s1 == s));
}
And
public static void bar() {
String s = "str4";
String s1 = "str" + "4";
System.out.println("(s==s1) = " + (s1 == s));
}
In 1st case it's returning 'false' but in 2nd case 'true'
As i understand in both cases 'str4' object is being created on the heap. So it should return true in both cases. But it's not.
Kindly someone help me out why it's so. ? Thanks.!

Use
s1.equals(s)
to compare strings, otherwise you compare references.
In second case it returns true because String s1 = "str" + "4"; would be optimized to String s1 = "str4"; and s and s1 would refer to the same String.

The == operator in Java only returns true if both references refer to the same object. If you are trying to compare two Strings for equivalent content, you must use the equals() method.

you need to use .equals() for this
.equals() // if you dont want to ignore case
.equalsIgnoreCase() // if you want to ignore case
== compare the references.
In the second case both strings are equal .So references are also equal.
String s = "str4";
String s1 = "str" + "4"; .//finally str4
Here s1 ans s2 contents are equal.So they have same reference.

In my own understanding :
"str" => String
"4" => String
However,
s.length() => int
With ==, memory locations are compared.
Using the first example, Java creates another String which is in another memory location other than the location of 's' because you are trying to do String + int = String.
The second example returns true because it is just the same memory location as your 's' only that the value is changed. String + String = Concatenated String
Since you are trying to compare if the two strings have the same characters inside but not necessarily the same location, then s.equals(s1) is the best solution.
However, should you want to test if both variables are pointing to the same object then == must be used because of its shallow comparison.

Related

Why does setting the value of two string the same and using == to compare them return true? [duplicate]

This question already has answers here:
Why does == return true for a String comparison? [duplicate]
(1 answer)
How do I compare strings in Java?
(23 answers)
Closed 11 months ago.
String str1 = "apple";
String str2 = "apple";
System.out.println(str1 == str2);
Why does the 3rd line return true? I thought you couldn't compare strings like that
I understand that compareTo should be used for strings, why can I do ==
Because '==' is used to compare the reference of the objects
String string1 = new String("apple");
String string2 = new String("apple");
// Is false, they are two different objects
string1 == string2;
// Is true, their value are the same
string1.equals(string2);
// Is true because java uses the same object if you don't create a new one explicitly
"apple" == "apple";
Read this chapter of the article and you will understand.
The behavior you observe has to do with String literals where the JVM usually optimizes the storage by creating new literals if they don't already exist, otherwise providing the existing reference.
This should not be the way that you handle Strings though as they are still objects and you want to compare them by their content and not their memory reference which is what is happening when you use == .
This is why oracle explicitly advices for Strings to be compared using the equals method. There are many cases where a different object reference would be returned for some string that already exists in memory.
Check the following example to see one of those cases
public static void main(String[] args) {
String str1 = "apple";
String str2 = "apple";
System.out.println(str1==str2); //prints true
String str3 = "apple2";
String str4 = str3.replaceFirst("2","");
System.out.println(str1); //prints apple
System.out.println(str4); //prints apple
System.out.println(str1==str4); //prints false
System.out.println(str1.equals(str4)); //prints true
}

What will be output and explanation? [duplicate]

This question already has answers here:
Getting strange output when printing result of a string comparison
(3 answers)
Closed 3 years ago.
Below code return boolean false value. Any explanation for this ?
String str = "Bee";
String str2 = "Bee";
System.out.println("==" + str == str2);
Actual Result : false
Use equals to compare string, it will return true for this case.
The == operator compares that the Strings are exactly the same Object.
This might theoretically happen in case of internalized strings, but you cannot rely on this. For your case, comparing String values, use str.equals(str2).
str and str2 are both assigned the same String instance, since String literals are automatically stored in the String pool. Therefore str == str2 is true.
However, you are printing the expression "==" + str == str2. That expression is evaluated from left to right, so first "==" + str is evaluated, and results with the String "==Bee". Then the == operator is applied to "==Bee" and "Bee", which returns false.
If you change the statement to:
System.out.println("==" + (str == str2));
you'll get true, since now the comparison will take place prior to the String concatenation.

getting == operator comparison false while comparing reference concatenated with literal with other reference [duplicate]

This question already has answers here:
Java String literals concatenation
(2 answers)
Closed 6 years ago.
When I perform the == operator comparison, I'm seeing false though I'm expecting the value to be true.
Why does this happen?
public class String1 {
public static void main(String[] args) {
//case 1
String s1="Hello";
String s2=s1+"Java";
String s3="HelloJava";
System.out.println(s2.equals(s3));// true
System.out.println(s2==s3);// expected True but getting output False
System.out.println(s2);
System.out.println(s3);
// case 2
String x = "hello";
String y = "he" + "llo";
System.out.println(x == y);// TRUE as exepected
}
}
In Java the == operator tests reference equality -> same object
.equals() tests for value equality
in both of your cases you have different objects (s1, s2, x, y)
== compares references (i.e. pointer values) of objects.
In case 2 the compiler can shorten "he" + "llo" to "hello" as opposed to the first case where the concatination is performed at runtime.
Also string literals are cached in a pool. Thus two occurences of "hello" will normally refer to the same object. This is possible because strings are immutable.
Strings follow the same rule as every other object. If you want to compare pointers use ==, if you want to compare content use equals.

Is string Object Created in Heap if we use new String("abcd") [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
String s1 = new String("anil");
String s2 = s1.toUpperCase();
String s3 = s1.toLowerCase();
System.out.println(s1 == s2);
System.out.println(s1 == s3);
if string object created in heap then both are false.But it gives false,true.
String s1 = new String("anil");
This statement creates a new object
And this ,
String s3 = s1.toLowerCase();
points the location of 1st object that is s1
And thats the reason you are getting true for second condition
Also see how java handles strings to get a clear understanding
Hope this helps!!
There are four String objects here:
the literal, created by the compiler and classloader
s1, created by new String()
s2, created by toUpperCase()
s3, created by toLowerCase().
No two of them are equal via the == operator.
Except that toLowerCase() may return the same object if it is already lowercase. There's nothing in the Javadoc about that, so any such behaviour in an implementation cannot be relied on.
Here S1 object will be created in heap. Its value is stored in the constant string pool.
S2 is String literal not an object. So first JVM will check whether the string is there in constant pool. If String is there constant pool it will not create new object. It will return reference of the object available.
Here the s1.toUpper will return "ANIL". "ANIL" is not in the constant pool. so new object will be created. and comparing it with s1 (using'==') give false.
Same for S3. But for S3 it wont create new object as "anil" is already there in constant pool.
so will return the reference of S1. So it gives true.
Study the following link
Study this
Case 1: String with Capital First Letter.
> String s1 = new String("Ajay")
String s2 = s1.toUpperCase()
String s3 = s1.toLowerCase()
System.out.println s1 == s2
System.out.println s1 == s3
false
false
Case 2: String with Small First Letter.
> String s1 = new String("ajay")
String s2 = s1.toUpperCase()
String s3 = s1.toLowerCase()
System.out.println s1 == s2
System.out.println s1 == s3
false
true
in Case 1, since the string has capital letter, converting to lowercase will yield a new object hence a new reference for it while in Case 2 small first letter after converting to lowercase will still point to the same object because the original object was same hence creating two references for the same object.
You can see the output from the Groovy Shell pretty clear.
If you look at the toLowerCase() method in String class.
It calls toLowerCase(Locale locale)
toLowerCase(Locale locale) inturn uses Character.toLowerCase(c)
Character.toLowerCase(c) in Character class has this comment -
#param ch the character to be converted.
#return the lowercase equivalent of the character, if any;
otherwise, the character itself.

Java String Split Method Error? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
Why does (("+k").split("k"))[0] not equal "+"? I am so confused.
Program:
//The Control Test
String a = "+";
System.out.println(a);
System.out.println((byte) a.charAt(0));
System.out.println(a == "+");
//The Error
a = (("+k").split("k"))[0];
System.out.println(a);
System.out.println((byte) a.charAt(0));
System.out.println(a == "+");
Output:
+
43
true
+
43
false -- Why?
So why in the world does a "+" not equal a "+"?!
You shouldn't compare Strings with ==. You should compare them with .equals() instead.
if(a.equals("+"))
{
// ...
}
This person explained it very well so there is no need for me to explain it again: look at this answer to a similar question.
String literals (strings placed directly in code) are stored in String pool and if some string literal is used few times same object from String pool is used. Since == compares references it will return true for
String a = "+";
System.out.println(a == "+");
Now Strings that are results of methods are separate objects that are not placed in String pool so in
String a = (("+k").split("k"))[0];
String object stored in a is different then "+" from String pool that is why == returns false.
To get rid of this problem you need to use equals method which will compare characters stored in String objects.

Categories

Resources