+ 1
Ans this pls
String s1="abc"; String s2="abc"; Sop(s1==s1); Sop(s1.equals(s2)); output is true true String str = new String("hai"); String s= new String("hai"); System.out.println(str==s); System.out.println(str.equals(s)); output is false true what is the difference between two programs ?
14 Antworten
+ 7
c lover, String is actually a class that is included in java.lang package
+ 4
There's an optimization the compiler makes called the String Constant Pool.
Any Strings with Constant literals are placed here.
In your example,
String s1 = "abc";
The String literal "abc" will be placed in the pool.
Everytime the literal "abc" is used, instead of creating a new object the string will point to the memory location of the string in the pool.
So,
String a = "abc";
String b = "abc";
These variables point to the EXACT same objects.
It's like writing:
Object d = new Object();
Object e = d;
As Nikhil Sharma's said, == compares the value of the memory location of objects. As Donna said, a String is a class.
So,
== will result in true; they are the same obects.
But, there's a catch.
When using the new keyword a String will not be interned unless done manually. In other words, a new String will be created instead of checking the SCP for the same string values.
String a = new String("b");
String b = new String("b");
So, these are different objects.
See:
https://code.sololearn.com/cGquk1UvwLrJ/?ref
+ 3
https://www.sololearn.com/learn/Java/2178/?ref=app
+ 3
== checks whether the references points to the same object or not whereas equals method checks whether the value of the obejcts referenced by the variables are same or not.
+ 3
Donna
Careful, == does not check if two objects are from the same class.
+ 1
Donna but I created str and s in same class not n different class
+ 1
class Demo
{
public static void main (String[] args) throws java.lang.Exception
{
String str = new String("hai");
String s= new String("hai");
System.out.println(str==s);
System.out.println(str.equals(s));
}
}
see Dona
+ 1
yes Donna I created two object of same string class na...
+ 1
I understood Donna ...they r different class...thank you so much
+ 1
thank you donna
+ 1
yes nikil but u didn't understand my question
0
what u mean by class ....then WT is demo class??
0
here string is keyword not class rite
0
ok fine then I created two object of same string class right