例如,对于下面的程序,无论创建多少个实例对象,永远都只分配了一个 staticInt 变量,并且每创建一个实例对象,这个 staticInt 就会加 1;但是,每创建一个实例对象,就会分配一个 random,即可能分配多个 random ,并且每个 random 的值都只自加了1次。
public class StaticTest {
private static int staticInt = 2;
private int random = 2;
public StaticTest() {
staticInt++;
random++;
System.out.println("staticInt = "+staticInt+" random = "+random);
}
public static void main(String[] args) {
StaticTest test = new StaticTest();
StaticTest test2 = new StaticTest();
}
}
int 类型在赋值到 Integer 类时,会自动封装,调用 Integer 的 valueOf(int i) 方法。
Integer a = Integer.valueOf(1);
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
当 i >= -128 && i <= 127 时,Integer.valueOf(i) 会将 i 存储在内部类 IntegerCache的static final Integer cache[]里,这一字节的缓存内存地址是静态的,返回值即:
IntegerCache.cache[i + (-IntegerCache.low)]
因此:
Integer a = 1;
Integer b = 1;
a 和 b 的引用都指向同一个对象,即 a == b。
1287Java 基本数据类型
在 java 中,任何字符类型与字符串相加,结果都是拼接。
String s = null;
s += "hello";
System.out.println(s); // 输出 nullhello
原因:先应用 String.valueOf 得出 s 的 value 值,再通过 StringBuilder 拼接 hello,因此将 value 与 hello 进行了拼接。
String s = null;
s = (new StringBuilder(String.valueOf(s))).append("hello").toString();
System.out.println(s);
1291Java 变量类型
静态变量是用来声明规则的,一旦固定都是用用来引用的,类似社会中的法律,规定好后你只能拿来说。但是也可以改的,通过重新的声明法律就行。
1290Java 变量类型
Java 中静态变量和实例变量区别
在程序运行时的区别:
总之,实例变量必须创建对象后才可以通过这个对象来使用,静态变量则可以直接使用类名来引用。
例如,对于下面的程序,无论创建多少个实例对象,永远都只分配了一个 staticInt 变量,并且每创建一个实例对象,这个 staticInt 就会加 1;但是,每创建一个实例对象,就会分配一个 random,即可能分配多个 random ,并且每个 random 的值都只自加了1次。
执行以上程序,输出结果为:
1289Java 基本数据类型
原始类型:boolean,char,byte,short,int,long,float,double。
包装类型:Boolean,Character,Byte,Short,Integer,Long,Float,Double。
Java 中的基本数据类型只有以上 8 个,除了基本类型(primitive type),剩下的都是引用类型(reference type)。
1288Java 基本数据类型
包装类 Integer 的自动封装
int 类型在赋值到 Integer 类时,会自动封装,调用 Integer 的 valueOf(int i) 方法。
当 i >= -128 && i <= 127 时,Integer.valueOf(i) 会将 i 存储在内部类 IntegerCache的static final Integer cache[]里,这一字节的缓存内存地址是静态的,返回值即:
因此:
a 和 b 的引用都指向同一个对象,即 a == b。
1287Java 基本数据类型
在 java 中,任何字符类型与字符串相加,结果都是拼接。
原因:先应用 String.valueOf 得出 s 的 value 值,再通过 StringBuilder 拼接 hello,因此将 value 与 hello 进行了拼接。