Java虚拟机常量池的认识

public static void main(String[] args) {
String str1 = new String("wwe");
String str2 = new String("wwe");
System.out.println(str1 == str2);
System.out.println(str1.intern() == str2.intern());

    Integer a1 = 1;
    Integer a2 = new Integer(1);
    System.out.println(a1.equals(a2));
    System.out.println(a1 instanceof Integer);
}

输出:false true true true

1.false 。 String str1 = new String("wwe"); String str2 = new String("wwe"); System.out.println(str1 == str2);类中的 ‘==’ 比较的是内存地址,通过new生成的对象会在堆中创建一个新的对象,内存地址明显不同。
2.trueSystem.out.println(str1.intern() == str2.intern());。String.intern(),比较的是常量池中的值。当常量池中不存在“wwe”时,会在常量池中新建一个常量。若存在,则直接返回该常量。
源码介绍如下:

/**
* Returns a canonical representation for the string object.
* <p>
* A pool of strings, initially empty, is maintained privately by the
* class {@code String}.
* <p>
* When the intern method is invoked, if the pool already contains a
* string equal to this {@code String} object as determined by
* the {@link #equals(Object)} method, then the string from the pool is
* returned. Otherwise, this {@code String} object is added to the
* pool and a reference to this {@code String} object is returned.
* <p>
* It follows that for any two strings {@code s} and {@code t},
* {@code s.intern() == t.intern()} is {@code true}
* if and only if {@code s.equals(t)} is {@code true}.
* <p>
* All literal strings and string-valued constant expressions are
* interned. String literals are defined in section 3.10.5 of the
* <cite>The Java™ Language Specification</cite>.
*
* @return a string that has the same contents as this string, but is
* guaranteed to be from a pool of unique strings.
*/

public native String intern();

一道思考题 new String("wwe").equals("11去去去") 创建了几个对象

这里创建了1或2 个对象。如果常量池不存在“11去去去”则需要创建一个对象。

3.true System.out.println(a1.equals(a2)); 以下是interger类型的equals函数,不同的复合类是不一样的

/**
* Compares this object to the specified object. The result is
* {@code true} if and only if the argument is not
* {@code null} and is an {@code Integer} object that
* contains the same {@code int} value as this object.
*
* @param obj the object to compare with.
* @return {@code true} if the objects are the same;
* {@code false} otherwise.
*/

public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}

4.true。 System.out.println(a1 instanceof Integer);

用来在运行时指出对象是否是特定类的一个实例

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,155评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 33,456评论 18 399
  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa阅读 12,878评论 0 6

友情链接更多精彩内容