Output of the following code
String s1 = "Amit"; //true
String s2 = "Amit"; //true
String s3 = new String("abcd"); //true
String s4 = new String("abcd"); //false
System.out.println(s1.equals(s2)); //true
System.out.println((s1==s2)); //true
System.out.println(s3.equals(s4)); //false
System.out.println((s3==s4)开发者_StackOverflow中文版); //false
Assume it to be in main why the output of the above code is
true true true false and not true true false false???
Java uses a "string literal pool." Since strings are immutable objects, there's no reason two strings initialized to the same literal can't be the same object—and as your code output suggests, they are the same object. (s1 and s2 are two names for the same location in memory)
The reason this isn't true for s3 and s4 is because you're explicitly allocating new strings, and using the constructor to initialize them. This means they are different objects, and hence they fail the "==" test.
In other words,
== compares if two object references are equal
.equals() compares if the contents of two objects are equal, irrespective of where they are in memory.
I'm not going to answer your question directly as it seems to be homework, but what you are looking for is this:
==, .equals(), compareTo(), and compare()
The link above discusses string contents equality and string reference equality. This is what your question is in essence and it gives a great way of explaining the concepts.
public class Question {
private int one;
public void myMethod(int one){
this.one = 30;
int one1 = 12;
}
}
class Test{
public static void main(String[] arg){
int one = 30;
Question q = new Question();
q.myMethod(one);
System.out.println(one);
}
}
精彩评论