java中的比较

来源:互联网 发布:2017年海外代购数据 编辑:程序博客网 时间:2024/05/01 13:09

先看junitTest的例子程序:

@Testpublic void testNewString() {String a = new String("helloWorld");String b = "helloWorld";if (a == b){System.out.println("b srting equals a string");}else {System.out.println("b string not equals a string");}}

 

console输出b string not equals a string
两个等号比较的是引用a跟引用b在内存的地址,永远不可能相等的?(理解有误了,再看看下面的junitTest例子)

equals比较的对象的toString返回值?

 

@Testpublic void testNoNewString() {String a = "helloWorld";String b = "helloWorld";if(a == b) {System.out.println("b string equals a string");}else {System.out.println("b string is not equals a string");}}


console输出 b string equals a string

那究竟java中两个等于号比较的是什么?

b为字符串常量,存放在java虚拟机为它分配的内存在常量池中。如果常量池中存在“helloWorld”,b就会指向其内存地址。如果不存在Java虚拟机会为“helloWorld”分配一个地址

 

 

0 0
原创粉丝点击