Day31
Q1
以下JAVA程序的运行结果是什么( )
public static void main(String[] args) {
Object o1 = true ? new Integer(1) : new Double(2.0);
Object o2;
if (true) {
o2 = new Integer(1);
} else {
o2 = new Double(2.0);
}
System.out.print(o1);
System.out.print(" ");
System.out.print(o2);
}
- 1.0 1
题解
三元操作符如果遇到可以转换为数字的类型,会做自动类型提升
Q2
下面代码的运行结果是( )
public class Arraytest{
int a[] = new int[6];
public static void main ( String arg[] ) {
System.out.println ( a[0] );
}
}
- 编译出错
题解
在static方法中是不能访问非静态变量 a 的,需要将 a 声明为static,答案才会是 0 ,否则是编译出错
Q3
已知表达式int m[]={0,1,2,3,4,5,6};下面哪个表达式的值与数组下标量最大值相等?
- m. length-1
- m. length()-1
- m.size()-1
题解
length属性:数组
length():String
size():集合
Day32
Q1
以下哪种方式实现的单例是线程安全的
- 枚举
- 静态内部类
- 双检锁模式
- 饿汉式
题解
- 第一种:饿汉模式(线程安全)
public class Single2 {
private static Single2 instance = new Single2();
private Single2(){
System.out.println("Single2: " + System.nanoTime());
}
public static Single2 getInstance(){
return instance;
}
}
- 第二种:懒汉模式 (如果方法没有synchronized,则线程不安全)
public class Single3 {
private static Single3 instance = null;
private Single3(){
System.out.println("Single3: " + System.nanoTime());
}
public static synchronized Single3 getInstance(){
if(instance == null){
instance = new Single3();
}
return instance;
}
}
- 第三种:懒汉模式改良版(线程安全,使用了double-check,即check-加锁-check,目的是为了减少同步的开销)
public class Single4 {
private volatile static Single4 instance = null;
private Single4(){
System.out.println("Single4: " + System.nanoTime());
}
public static Single4 getInstance