1.Java编程,打印昨天的当前时刻
public class YesterdayCurrent{
public void main(String[] args){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println(cal.getTime());
}
}
2.文件读写,实现一个计数器
public int getNum(){
int i = -1;
try{
String stri="";
BufferedReader in = new BufferedReader(new FileReader(f));
while((stri=in.readLine())!=null){
i = Integer.parseInt(stri.trim());
}
in.close();
}catch(Exception e){
e.printStackTrace();
}
return i;
}
public void setNum(){
int i = getNum();
i++;
try{
PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter(f,false)));
out.write(String.valueOf(i)); //可能是编码的原因,如果直接写入int的话,将出现java编码和windows编码的混乱,因此此处写入的是String
out.close() ;
}catch(Exception e){
e.printStackTrace();
}
}
3. 指出下面程序的运行结果:
class A{
static{
System.out.print("1");
}
public A(){
System.out.print("2");
}
}
class B extends A{
static{
System.out.print("a");
}
public B(){
System.out.print("b");
}
}
public class Hello{
public static void main(String[] ars){
A ab = new B(); //执行到此处,结果: 1a2b
ab = new B(); //执行到此处,结果: 1a2bab
}
}
注:类的static 代码段,可以看作是类首次加载(被虚拟机加载)执行的代码,而对于类的加载,首先要执行其基类的构造,再执行其本身的构造
4.写一个Singleton模式的例子
public class Singleton{
private static Singleton single = new Singleton();
private Singleton(){}
public Singleton getInstance(){
return single;
}
}