声明字符串对象时的混乱 [英] Confusion in declaring String Objects

查看:67
本文介绍了声明字符串对象时的混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将字符串声明为

String test=new String("testing");

String test1="testing1"

由于String是JAVA中的类,因此test1在不使用新运算符的情况下如何成为String对象.此外,当使用新运算符时,会为new String("testing")分配内存,因此在test1情况下,如何分配的内存? 另外,当字符串被插入时,如果两个字符串具有相同的值,并且在String实习生池中一次将String存储了什么引用?

Since String is a class in JAVA how does test1 be a String Object without using a new Operator.Also,when a new Operator is used memory is assigned for new String("testing") so in the case of test1 how is the memory assigned? Also,when the string is interned ,if two Strings have the same value with what reference is the String store once in the String intern pool?

推荐答案

让我们首先考虑一下String test=new String("testing");

  • 它将在堆中创建一个String对象.不检查String Pool中是否存在此String.

,现在是这个String test1="testing1"

  • 它在String池中不在Heap中的String对象中创建一个String对象,在创建之前检查该字符串是否已经在池中.如果是,则返回其引用,否则将在池中创建一个新的String并且其引用为返回.基本上,这是一个字符串文字,将其放入常量池中以进行内存优化和可重用性.

intern()::在使用new()构造对象并对该对象调用intern()时使用,然后首先在Stirng池中检查该字符串是否已存在是否可以直接使用

intern(): It is used when you construct an object using new() and you call intern() on that object then first a check is done in Stirng pool if that String already exists there or not,if yes it is directly used

这篇关于声明字符串对象时的混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆