java硬知识汇总
1. Integer 与 ==
对于 Integer var=? 在 -128 至 127 之间的赋值,Integer 对象是在 IntegerCache.cache 产生,会复用已有对象,这个区间内的 Integer 值可以直接使用 == 进行 判断,但是这个区间之外的所有数据,都会在堆上产生,并不会复用已有对象
public static void main(String[] args) {
Integer a = -100;
Integer b = 0-100;
System.out.println(a == b); // true
a = 128;
b = 128;
System.out.println(a == b); // false
System.out.println(--a == --b); // true
}
2. intern 与常量池
JDK1.7+ 后,intern() 实现不会再复制实例,只是在常量池中记录首次出现的实例引用。“java”已经在 sun.misc.Version 中声明
public static void main(String[] args) {
String s1 = new StringBuilder("ja").append("va").toString();
System.out.println(s1.intern() == s1);
String s2 = new StringBuilder("swi").append("ft").toString();
System.out.println(s2.intern() == s2);
}
3. 构造函数抛异常
java中构造函数可以抛出异常,如果抛出异常,不会创建对象。
public class TestException extends Exception
{
TestException(String msg)
{
super(msg);
}
}
class Test
{
Test(int n) throws TestException
{
if(n<0)
throw new TestException("出错");
}
}
class Demo
{
public static void main(String[] args)
{
Test t =null;
try
{
t =new Test(1);
}
catch (Exception e)
{
System.out.println(e.toString());
}
System.out.println(t.toString());//如果出错时也创建对象则会返回对象引用,如果不创建对象则是空指针异常
}
}

浙公网安备 33010602011771号