码迷,mamicode.com
首页 > 编程语言 > 详细

Java中字符串内存位置浅析

时间:2018-07-25 01:06:54      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:==   static   说明   直接   对象   print   obj   常量池   als   

String内存位置说明

  1. 显式的String常量

String a = "holten";
String b = "holten";
  • 第一句代码执行后就在常量池中创建了一个值为holten的String对象;
  • 第二句执行时,因为常量池中存在holten所以就不再创建新的String对象了。
  • 此时该字符串的引用在虚拟机栈里面。
  1. String对象

String a = new String("holtenObj");
String b = new String("holtenObj");
  • Class被加载时就在常量池中创建了一个值为holtenObj的String对象,第一句执行时会在堆里创建new String("holtenObj")对象;
  • 第二句执行时,因为常量池中存在holtenObj所以就不再创建新的String对象了,直接在堆里创建new String("holtenObj")对象。

验证一下

/**
 * Created by holten.gao on 2016/8/16.
 */
public class Main {
    public static void main(String[] args){
        String str1 = "高小天";
        String str2 = "高小天";
        System.out.println(str1==str2);//true
        
        String str3 = new String("高大天");
        String str4 = new String("高大天");
        System.out.println(str3==str4);//false
    }
}

返回结果:

true
false

Java中字符串内存位置浅析

标签:==   static   说明   直接   对象   print   obj   常量池   als   

原文地址:https://www.cnblogs.com/little-fly/p/9363263.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!