What is the difference between this two ways of initializing String [duplicate] - java

This question already has answers here:
What is Java String interning?
(8 answers)
What is the difference between "text" and new String("text")?
(13 answers)
Closed 6 years ago.
This two codes have defferent outputs and i don't know why.
String a="abc";
String b="abc";
System.out.println(a==b + " " + a.equals(b));
The output is "true true"
String a="abc";
String b=new String("abc");
System.out.println(a==b + " " + a.equals(b));
The output is "false true"

when you use this
String a="abc";
String b="abc";
the java creates only one object in memory which is abc and here a and b are pointing to same object and == don't check the string content instead it check the reference value. but as soon as you do this
String b=new String("abc");
java creates a new object b in memory which is different from a ,now b and a are pointing to two different objects hence if you compare contents with equals function result will be true but if you compare reference now, result will be false
Read about it's usage

This has to be a duplicate of a large number of questions, but I will comment by saying that when you do the following:
String a = "abc";
String b = "abc";
The JVM creates a single String object in the constant pool which contains the String abc. Hence, the a and b Strings simply point to the same string in the pool.
However, when you do the following:
String a = "abc";
String b = new String("abc");
a new object is created even though abc already exists in the pool. Hence the comparison a == b returns false, although the contents of both these strings remains equivalent.

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
}

Difference between Strings added directly and with references [duplicate]

This question already has answers here:
Java String Instantiation
(3 answers)
Closed 5 years ago.
I came across a question asking the output of the below:
String s1 = "String 1";
String s2 = "String 2";
String s3 = s1 + s2;
String s4 = "String 1" + "String 2";
System.out.println(s3==s4);
Output - false
Now, since the strings are not created using new operator, so the objects are created in the string pool, so as per my understanding s1 + s2 and "String 1" + "String 2" should be equal, and s3==s4 should be true.
But it is not happening in real. Can any one please explain this?
The concatenation is happening at runtime, unless both operands are compile-time constant expressions.
Put a final modifier before s1 and s2, and the result will be true, because the compiler will simply replace
String s3 = s1 + s2;
by
String s3 = "String 1String 2";
If you don't, a new String is created at runtime, by appending both strings to a StringBuilder and getting the result.
Note that, although that is interesting from an intellectual point of view, in practice, you shouldn't care about that performance optimization, and always compare Strings with equals().
This line compare memory addresses of two strings. Because of both are separate objects and output will be false.
s3==s4
You need to compare using equals()
System.out.println(s3.equals(s4));
equals() is compare value of object not address.

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.

Confused in appending Strings in Java [duplicate]

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.

Categories

Resources