将实例变量初始化为null,“"或0 [英] Initialising instance variables as null, "" or 0

查看:189
本文介绍了将实例变量初始化为null,“"或0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用默认值初始化变量时:

When initialising variables with default values:

有什么区别:

private static String thing = null;

private static String thing = "";

我不明白哪个更好,为什么以及处理其他数据的最佳方式是什么类型。

I'm not understanding which is better and why nor what is the best way to deal with other data types.

private static int number = 0;
private static double number  = 0;
private static char thing = 0;

抱歉,我很难学习新语言。

推荐答案

除了将 String 初始化为空字符串

Except for initializing String to an empty string

private static String thing = "";

其他分配是不必要的:Java会将原始类型的所有成员变量设置为默认值,并且所有引用类型(包括 java.String )到 null

the other assignments are unnecessary: Java will set all member variables of primitive types to their default values, and all reference types (including java.String) to null.

String 初始化为 null 或空字符串的决定取决于您:有nothing和empty string * 之间的区别,所以你必须决定你想要哪一个。



* 无和空字符串之间的差异源于观察到 null <无法进行任何操作/ code> string - 例如,它的长度未定义,您无法迭代其字符。相反,空字符串的长度是明确定义的(零),您可以迭代它的字符(它是一个空的迭代)。

The decision to initialize a String to a null or to an empty string is up to you: there is a difference between "nothing" and "empty string" *, so you have to decide which one you want.


* The differences between "nothing" and "empty string" stem from the observation that no operations are possible on a null string - for example, its length is undefined, and you cannot iterate over its characters. In contrast, the length of an empty string is well-defined (zero), and you can iterate over its characters (it's an empty iteration).

这篇关于将实例变量初始化为null,“&quot;或0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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