这两个语句有什么区别... [英] What is the difference in these two statements...

查看:107
本文介绍了这两个语句有什么区别...的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一次采访中有人问我这个问题,但找不到答案.我也做了一些谷歌,但也许没有正确的方向.也许codeproject的人可以帮忙...

字符串s ="Codeproject";
String s = new String();

这两个语句有什么区别..?
等待答案............

I was asked this question in an interview, but could not figure out the answer. I did some google too, but maybe was not in a proper direction. Maybe someone at codeproject can help...

String s = "Codeproject";
String s = new String();

what is the difference in these two statements..?
Waiting for the answer............

推荐答案

这是一个非常基本且非常好的问题sam.
第一行String s ="Codeproject"不会创建新变量,而只是在字符串池中查找具有此值的所有文字.如果编译器找到一个,则使用此引用初始化s.
但是第二行String s = new String("Codeproject")(应该是这样的)只是在内存中创建一个值为"Codeproject"的新存储.
因此,如果您写第一行10次,它将仅创建一个变量,并且该引用将存储在您声明的十个实例中.
虽然第二行将创建所需数量的变量,但每次在内存中创建新空间.

您可以在 http://en.csharp-online.net/CSharp_String_Theory%E2%上找到很好的参考. 80%94String_intern_pool [ ^ ]

希望对您有所帮助,下次您再进行采访吧.
祝一切顺利.

我发现了一个用于JAVA字符串池的非常好的链接:
http://www.xyzws.com/Javafaq/what-is-string-literal-池/3 [ ^ ]

对于.NET:
http://www.webpronews.com/blogtalk/2006/10/17/net-string-internal-pool [ ^ ]
This is a very basic and very good question sam.
First line String s = "Codeproject" doesn''t create new variable but simply looks for any literal having this value in the string pool. If compiler finds one, s is initialized with this reference.
But the second line String s = new String("Codeproject") (It should have been like this) simply creates new storage in the memory with the value "Codeproject".
so if you write first line 10 times, it will create only one variable and that reference will be stored in ten instances that you declared.
While the second line will create as many variables as you want, every time creating new space in the memory.

You can find a very good reference at http://en.csharp-online.net/CSharp_String_Theory%E2%80%94String_intern_pool[^]

I hope this helps and you crack the interview next time.
All the best.

I found one more very nice link for JAVA string pooling :
http://www.xyzws.com/Javafaq/what-is-string-literal-pool/3[^]

and for .NET :
http://www.webpronews.com/blogtalk/2006/10/17/net-string-internal-pool[^]


第一个:s就像常量,其值为"codeproject"
第二:您创建的字符串对象s可以接受任何字符串...
对于前. String s = new String();
s =任何动态或静态的内容"
first one: s is like constant, its value is "codeproject"
second : u r creating the string object s, that can take any string ...
for ex. String s = new String();
s = "anything dynamically or statically"


这篇关于这两个语句有什么区别...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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