是否应将Java String方法(本地)变量初始化为null或“"”? [英] Should Java String method (local) variables be initialized to null or ""?

查看:158
本文介绍了是否应将Java String方法(本地)变量初始化为null或“"”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

初始化String方法(本地)变量以避免Java中的变量可能尚未初始化错误的最佳做法是什么?

What is the best practice for initializing a String method (local) variable to avoid the "Variable might not have been initialized" error in Java?

String s =空值;

String s =;

String s=null; or String s="";

它有所作为吗?
如果是这样,哪一个更好,为什么?

Does it make a difference? If so, which one is better and why?

我在网上看到了相互矛盾的答案。

I've read conflicting answers on the web.

谢谢!

推荐答案

是的,它有所不同。一个是对空字符串的引用,一个是空引用。它们不一样。

Yes, it makes a difference. One is a reference to an empty string, one is a null reference. They're not the same.

哪个更好?这取决于你是想要一个空值还是一个空字符串的引用...它们的行为不同,所以选择一个行为符合你想要它的方式。

Which is better? It depends whether you want a null value or a reference to an empty string... they behave differently, so pick the one which behaves the way you want it to.

我很少需要为变量分配一个虚拟值 - 通常只是在声明点用我想要的 real 值初始化变量就可以了。如果您可以提供更多上下文,我们可以帮助您更好地构建代码,这对您来说不是问题。

I rarely need to assign a "dummy" value to a variable though - usually just initializing the variable at the point of declaration with the real value I want is fine. If you can give us more context, we may be able to help you structure your code better so this isn't a problem for you.

这篇关于是否应将Java String方法(本地)变量初始化为null或“"”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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