在java声明对象和变量比如: String str; String str = null; String str = new String(); "String" is a special class in java ,so i advice you to ues String str = "yourString" when your declaration!在声明的时候用哪一种方式比较好,或者说在什么情况下用那种? 还有在声明变量如: int i; int i = 0; a VAR should be declarated (just like "int i;") and defined ! when you defining the var ,you also should init it,just like "int i = 0;"
不说String了,换成一般的对象,比如: A a; A a = null; A a = new A(); 有什么不同,在什么情况下用哪种?
说说我的理解 A a; // 不推荐使用的。 A a = null; // a对象引用可能指定多个对象的如: List list = ArrayList(); a = new A(); list.add(a); a = new A(); list.add(a);A a = new A(); // 一般某个space中这个a一直会操作这个new出来的对象。
推荐使用 String str = new String (); int i; i = 0; 养成良好的编程习惯!
String str;
String str = null;
String str = new String();
"String" is a special class in java ,so i advice you to ues String str = "yourString" when your declaration!在声明的时候用哪一种方式比较好,或者说在什么情况下用那种?
还有在声明变量如:
int i;
int i = 0;
a VAR should be declarated (just like "int i;") and defined !
when you defining the var ,you also should init it,just like "int i = 0;"
A a;
A a = null;
A a = new A();
有什么不同,在什么情况下用哪种?
A a; // 不推荐使用的。
A a = null; // a对象引用可能指定多个对象的如:
List list = ArrayList();
a = new A();
list.add(a);
a = new A();
list.add(a);A a = new A(); // 一般某个space中这个a一直会操作这个new出来的对象。
String str = new String ();
int i;
i = 0;
养成良好的编程习惯!
String str = new String ()有可能造成浪费
比如
String str1="aaa";//产生字符串对象
String str2="aaa";//此时系统会查找内存,如已有相同字符串("aaa")则直接引用,不产生对象
String str3=new String("aaa");//此格式必定产生新对象