`

SCJP试题

阅读更多
package scjp;

public class Test {
	static boolean foo(char c) {
		System.out.print(c);
		return true;
	}

	public static void main(String[] argv) {
		int i = 0;
		for (foo('A'); (i < 2) && foo('B'); foo('C')) {
			i++;
			foo('D');
		}
	}
}
//运行结果:ABDCBDC


package scjp;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Forest implements Serializable {

	private Tree tree = new Tree(); //但如果只是private Tree tree;则可以正确执行
	public static void main(String[] args) {
		Forest f = new Forest();
		
		try {
			FileOutputStream file = new FileOutputStream("file.txt");
			ObjectOutputStream oo = new ObjectOutputStream(file);
			oo.writeObject(f);
			oo.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
class Tree{
	
}

执行结果:java.io.NotSerializableException: scjp.Tree,出现异常。

package scjp;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Foo implements Serializable {

	public int x,y;

	public Foo(int x, int y) {
		this.x = x;
		this.y = y;
	}
	
	private void writeObject(ObjectOutputStream o) throws IOException{
		o.writeInt(x);
		o.writeInt(y);
		o.close(); //一定要加 ,否则出现Exception in thread "main" java.io.EOFException
	}
	
	private void readObject(ObjectInputStream i) throws IOException{
		x = i.readInt();
		y=i.readInt();
		i.close(); //一定要加
	}
	
	public static void main(String[] args) throws IOException{
		Foo f = new Foo(3,4);
		FileOutputStream fo;
		FileInputStream fi;
		
		ObjectOutputStream oo = null;
		try {
			fo = new FileOutputStream("file.txt");
			 oo = new ObjectOutputStream(fo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		f.writeObject(oo);
		
		
		fi = new FileInputStream("file.txt");
		ObjectInputStream oi = new ObjectInputStream(fi);
		
		f.readObject(oi);
		
		System.out.println(f.x); //3
		
	}
	
}


String test = "this is a test";
		String[] token = test.split("\s"); //compile error,应改为\\s,以空格为分隔符分割字符串
		System.out.println(token.length);


DateFormat df = new SimpleDateFormat(); //DateFormat是java中日期格式的抽象类
		Date d = new Date();
//df.setLocale(Locale.ITALY); //compile error,DateFormat没有设置地方的方法
		String s = df.format(d);
		System.out.println(s);
//11-6-9 下午3:53(在2011年6月9号执行的结果)


System.out.printf("Pi is approximately %f and E is approimately %b",Math.PI,Math.E);
//Pi is approximately 3.141593 and E is approimately true


public class Foo{
public static void main(String[] args) throws IOException{
		Foo f = new Foo(2,4);
		Thread t = new Thread(f);
		t.run();
		t.run();
		t.start();

	}

	@Override
	public void run() {
		System.out.print("running");
	}
	
}

输出:runningrunningrunning
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics