X32专项练习部分11
- StringBuffer扩容规则
- Math方法返回值类型
- 临时修改引用
- 类的初始化过程(复杂)
- Java异常易混点
- instanceof方法
- 构造方法内部调用构造方法
- 修饰符列表
- 文本文件和二进制文件
- 编译器优化与堆栈数据共享(复杂)
- 对象地址改变
- 总目录
StringBuffer扩容规则
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer(10);
s1.append("1234");
System.out.println(s1.length()); // 4
System.out.println(s1.capacity()); // 10
StringBuffer sb = new StringBuffer("abcd");
StringBuffer buffer1 = new StringBuffer(10);
StringBuffer buffer2 = new StringBuffer(3);
StringBuffer buffer3 = new StringBuffer(1);
buffer1.append("abcd");
buffer2.append("abcd"); // 扩容的长度为原来的2倍+2
buffer3.append("abcd"); // 2*1<4 扩容长度为4
System.out.println(buffer1.length() + " && " + buffer2.length() + " && " + buffer3.length() + " && " + sb.length());
System.out.println(buffer1.capacity() + " && " + buffer2.capacity() + " && " + buffer3.capacity() + " && " + sb.capacity());
}
Math方法返回值类型
public static void main(String[] args) {
double d = Math.floor(-8.5);
System.out.println(d); // (double)-9.0
double d1 = Math.ceil(-1.5);
System.out.println(d1); // (double)-1.0
long l = Math.round(-2.6);
System.out.println(l); // (long)-3
// String s;
// System.out.println("s=" + s); // 不能通过编译,必须初始化
}
临时修改引用
class Test2 {
public static void main(String []args){
int i = 5;
func(i);
System.out.println(i);
}
static void func(int j){
j = 10;
}
}
类的初始化过程(复杂)
class Test1 {
public static void main(String[] args) {
System.out.println(new B().getValue());
}
static class A {
protected int value;
public A(int v) {
setValue(v);
}
public void setValue(int value) {
this.value = value;
}
public int getValue() {
try {
value++;
return value;
} finally {
this.setValue(value);
System.out.println(value);
}
}
}
static class B extends A {
public B() {
super(5);
setValue(getValue() - 3);
}
public void setValue(int value) {
super.setValue(2 * value);
}
}
}
Java异常易混点
instanceof方法
class Test4 {
public static void main(String[] args) {
// 向上转型 父类引用指向子类对象
A obj = new D();
System.out.println(obj instanceof B); // true
System.out.println(obj instanceof C); // false
System.out.println(obj instanceof D); // true
System.out.println(obj instanceof A); // true
}
}
构造方法内部调用构造方法
class MyClass {
public MyClass(){}
public MyClass(int i){
this(1.2);
}
public MyClass(double l){}
}
修饰符列表
文本文件和二进制文件
编译器优化与堆栈数据共享(复杂)
// 下列程序的输出结果是
class StringDemo{
private static final String MESSAGE="taobao";
public static void main(String [] args) {
String a ="tao"+"bao";
String b="tao";
String c="bao";
System.out.println(a==MESSAGE); // true
System.out.println((b+c)==MESSAGE); // false
}
对象地址改变
class foo {
public static void main(String sgf[]) {
StringBuffer a=new StringBuffer("A");
StringBuffer b=new StringBuffer("B");
operate(a,b);
System.out.println(a+"."+b); // AB.B
}
final static void operate(StringBuffer x,StringBuffer y) {
x.append(y);
y=x; // 这一步有个坑,y和b都是指针,这里只改了y的引用,对b毫无影响
}
}
总目录