总结 1、= =操作符比较的是操作符两端的操作数是否是同一个对象;另外= =操作符两边的操作数必须是同一类型的(可以是父子类之间)才能编译通过。 2、String的equals()方法比较的是两个String对象的内容是否一样 3、= =比较的是地址,如果是具体的阿拉伯数字的比较,值相等则为TRUE,如: int a=10 与 long b=10L 与 double c=10.0都是相同的(为true),因为他们都指向地址为10的堆栈;如下题111; String s= "hello"; String t = "hello"; char c[] = {'h','e','l','l','o'} Which return true? A. s.equals(t); B. t.equals(c); C. s==t; D. t.equals(new String("hello")); E. t==c. 答案:(acd) 题目:哪些返回true。 这个在前面第10题的equals()方法和==操作符的讨论中论述过。==操作符比较的是操作符两端的操作数是否是同一个对象,而String的equals()方法比较的是两个String对象的内容是否一样,其参数是一个String对象时才有可能返回true,其它对象都返回假。需要指出的是由于s和t并非使用new创建的,他们指向内存池中的同一个字符串常量,因此其地址实际上是相同的(这个可以从反编译一个简单的测试程序的结果得到,限于篇幅不列出测试代码和反编译的分析),因此答案c也是正确的。
Given the following class: public class Sample{ long length; public Sample(long l){ length = l; } public static void main(String arg[]){ Sample s1, s2, s3; s1 = new Sample(21L); s2 = new Sample(21L); s3 = s2; long m = 21L; } } Which expression returns true? A. s1 == s2; B. s2 == s3; C. m == s1; D. s1.equals(m). 答案:(b)//D不对,只有String的equals()方法才比较值; 题目:给出下面的类: … 哪个表达式返回true。 前面已经叙述过==操作符和String的equals()方法的特点,另外==操作符两边的操作数必须是同一类型的(可以是父子类之间)才能编译通过。
再看以下几道 17. float f=4.2F; Float g=new Float(4.2F); Double d=new Double(4.2); Which are true? A. f= =g B. g= =g C. d= =f D. d.equals(f) E d.equals(g) F. g.equals(4.2); 答案:B 93. Click the exhibit button: 1. public class X { 2. public static void main (String[]args) { 3. String s1 = new String (“true”); 4. Boolean b1 = new Boolean (true); 5. if (s2.equals(b1)) { 6. System.out.printIn(“Equal”); 7. } 8. } 9. } What is the result? A. The program runs and prints nothing. B. The program runs and prints “Equal.” C. An error at line 5 causes compilation to fail. D. The program runs but aborts with an exception. 答案:A
比较下题,小心使用equals 和 = =的区别; 93. Click the exhibit button: 1. public class X { 2. public static void main (String[]args) { 3. String s1 = new String (“true”); 4. Boolean b1 = new Boolean (true); 5. if (s2 = = b1) { //= =操作符两边的操作数必须是同一类型的(可以是父子类之间)才能编译通过 6. System.out.printIn(“Equal”); 7. } 8. } 9. } What is the result? A. The program runs and prints nothing. B. The program runs and prints “Equal.” C. An error at line 5 causes compilation to fail. D. The program runs but aborts with an exception. 答案:C 111. Given: 1. public class Foo { 2. private int val; 3. public foo(int v) (val = v;) } 4. public static void main (String [] args) { 5. Foo a = new Foo (10); 6. Foo b = new Foo (10); 7. Foo c = a; 8. int d = 10; 9. double e = 10.0; 10. } 11. } Which three logical expressions evaluate to true? (Choose Three) A.(a ==c) B.(d ==e) C.(b ==d) D.(a ==b) E.(b ==c) F.(d ==10.0) 答案:ABF //= =比较的是地址,他们都指向地址为10的堆栈;
Given the following code, what test would you need to put in place of the comment line? //place test here to result in an output of the string Equal public class EqTest{ public static void main(String argv[]){ EqTest e=new EqTest(); }