Java期末重点题整理
一、简答题
1.1 JVM是( Java Virtual Machine )的缩写。
1.2 缩写API代表( Application Programming Interface )。
1.3 final, finally, finalize各自有何含义,作用分别是什么?
final:
1. final修饰成员变量,意为不可改变。
2. final声明的类不能派生子类,即不能作为父类使用。
3. final修饰的方法,不可以在子类中重写。
注:final修饰的变量是对象时,对象的值可以改变。(因为final修饰的变量指的是引用不可变,对象值是可变的。)
finally:
必须定义在异常捕获机制的最后,它可以保证内部的代码一定执行,无论try块中的代码是否出现异常。
通常会将诸如释放资源等操作放在finally中。(注:finally中不要写return否则一定返回这里的内容。)
finalize:
finalize是Object中定义的方法,所有的类都有该方法,该方法是JVM调用,当一个对象即将被GC释放时调用该方法,方法调用完毕意味着该对象的资源被释放,finalize 方法在垃圾回收器清除对象之前调用。
1.4 什么是jdk和jre
JRE: Java Runtime Environment
JDK:Java Development Kit
JRE顾名思义是java运行时环境,包含了java虚拟机,java基础类库。是使用java语言编写的程序运行所需要的软件环境,是提供给想运行java程序的用户使用的。
JDK顾名思义是java开发工具包,是程序员使用java语言编写java程序所需的开发工具包,是提供给程序员使用的。JDK包含了JRE,同时还包含了编译java源码的编译器javac。
二、改错&写结果
2.1 阅读给出的程序段,写出其运行结果。
public class TestMainClass {
public static void main(String[] args) {
A[] oArray = new B[6];
int sum1=0, sum2=0;
for (int i=0; i<oArray.length; i++) {
oArray[i] = new B(i);
sum1 += oArray[i]._value;
sum2 += ((B)oArray[i])._value;
}
System.out.println("Sum1 = " + sum1);
System.out.println("Sum2 = " + sum2);
A aa = new A();
A ab = new B(10);
aa.go();
ab.go();
}
}
class A {
public int _value = 1;
public A() {
_value = 2;
}
public void go() {
System.out.println("A-go");
System.out.println("value = " + _value);
}
}
class B extends A {
public int _value = 3;
public B(int value) {
_value = value;
}
public void go() {
System.out.println("B-go");
System.out.println("value = " + _value);
}
}
Sum1 = 15 Sum1 = 12
Sum2 = 18 Sum2 = 15
A-go
value = 2
B-go
value = 10
2.2
D
三、代码实现
3.1 File类基本应用
import java.io.*;
public class User21{
public static void main(String [] args){
System.out.println("Begin:");
File f = new File("c:/jdk15");
if( f.exists() )
show(f);
System.out.println("End.");
}
public static void show(File tree){
int i;
File f;
String []files;
files = tree.list();
for(i=0; i<files.length; i++){
f = new File( tree.toString()+"/"+files[i] );
if( f.isFile() )
System.out.println("file "+f);
if( f.isDirectory() )
System.out.println("directory "+f);
}
}
}
3.2 设计 4 个线程,线程 1 每次对整数 j 增加 1,线程 2 将 j 数据写入文件“file.dat”中,线程 3 每次对整数 j 减少 1,线程 4 将文件“file.dat”中数据值为 j 的数据删除。写出程序。
package Java_08;
public class J {
int val;
@Override
public String toString() {
return "" + val;
}
}
package Java_08;
public class Thread1 extends Thread{
J j;
public Thread1(J j) {
this.j = j;
}
@Override
public void run() {
while(true)
{
j.val++;
System.out.println("Thread1--->" + j.val);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package Java_08;
import java.io.*;
public class Thread2 extends Thread{
J j;
File file = new File("D:/file.txt");
public Thread2(J j) {
this.j = j;
}
@Override
public void run() {
OutputStream output = null;
try {
output = new FileOutputStream(file,true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (true)
{
try {
output.write(j.toString().getBytes());
System.out.println("Thread2");
sleep(1000);
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
package Java_08;
public class Thread3 extends Thread{
J j;
public Thread3(J j) {
this.j = j;
}
@Override
public void run() {
while (true)
{
j.val--;
System.out.println("Thread3--->" + j.val);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package Java_08;
import java.io.*;
public class Thread4 extends Thread{
J j;
File file = new File("D:/file.txt");
byte[] b = new byte[1024];
byte[] result;
int len;
public Thread4(J j) {
this.j = j;
}
@Override
public void run() {
try {
InputStream input = new FileInputStream(file);
OutputStream output = new FileOutputStream(file,true);
while(((len = input.read(b)) != -1))
{
String s = new String(b,0,len);
System.out.println(j.toString());
result = s.replace(j.toString(),"").getBytes();
output.write(result);
System.out.println("Thread4");
sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package Java_08;
public class Test {
public static void main(String[] args) {
J j = new J();
j.val = 0;
new Thread(new Thread1(j)).start();
new Thread(new Thread2(j)).start();
new Thread(new Thread3(j)).start();
new Thread(new Thread4(j)).start();
}
}
3.2.Plus 设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。循环100次。写出程序。
package a;
public class Test {
private int j;
public static void main(String[] args) {
Test t = new Test();
for(int i =0;i<2;i++) {
Thread t1 = new Inc(t);
t1.start();
Thread t2 = new Dec(t);
t2.start();
}
}
public synchronized void inc() {
j++;
System.out.println(Thread.currentThread().getName() + ":inc" + j);
}
public synchronized void dec() {
j--;
System.out.println(Thread.currentThread().getName() + ":dec" + j);
}
}
class Inc extends Thread {
private Test a;
Inc(Test a) {
this.a = a;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
a.inc();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Dec extends Thread {
private Test a;
Dec(Test a) {
this.a = a;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
a.dec();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
3.3 编写程序,将一个文本文件中的内容以行为单位,按行调整为倒序排列(即第一行为最后一行)。
package Java_15;
import java.io.*;
public class SwitchLine {
public static void main(String[] args) throws IOException {
File file = new File("D:/org.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,true)));
String[] s = new String[100];
String temp;
int count = 0;
while((temp = reader.readLine()) != null)
{
s[count] = temp;
count++;
}
for(count--; count >= 0; count--)
{
writer.write(s[count]);
writer.newLine();
}
writer.close();
reader.close();
}
}
3.4
package Java_19;
public class Char_WHU {
public String tempChar;
}
package Java_19;
public class MyThread extends Thread{
private Char_WHU cw;
private String nextChar;
public MyThread(String next, Char_WHU cw)
{
this.cw = cw;
this.nextChar = next;
}
@Override
public void run() {
for(int i = 0; i < 6; i++)
{
synchronized (cw)
{
while(Thread.currentThread().getName() != cw.tempChar)
{
try {
cw.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(cw.tempChar);
cw.tempChar = nextChar;
cw.notifyAll();
}
}
}
}
package Java_19;
public class WHUTest {
public static void main(String[] args) {
Char_WHU temp = new Char_WHU();
temp.tempChar = "W";
Thread thread1 = new Thread(new MyThread("H", temp), "W");
Thread thread2 = new Thread(new MyThread("U", temp), "H");
Thread thread3 = new Thread(new MyThread("W", temp), "U");
thread1.start();
thread2.start();
thread3.start();
}
}
3.5
package Java_19;
public class QuizEle {
boolean temp = false;
}
package Java_19;
public class QuizNum extends Thread{
QuizEle quizEle;
public QuizNum(QuizEle quizEle)
{
this.quizEle = quizEle;
}
@Override
public void run() {
int x = 0;
for(int i = 0; i < 20; i++)
{
synchronized (quizEle)
{
if(quizEle.temp == true)
{
try {
quizEle.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j = 0; j < 3; j++)
{
System.out.print(x);
x++;
}
quizEle.temp = true;
quizEle.notify();
}
}
}
}
package Java_19;
public class QuizChar extends Thread{
QuizEle quizEle;
static char c = 'A';
public QuizChar(QuizEle quizEle)
{
this.quizEle = quizEle;
}
@Override
public void run() {
for(int i = 0; i < 20; i++)
{
synchronized (quizEle)
{
if(quizEle.temp == false)
{
try {
quizEle.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(c);
c++;
quizEle.temp = false;
quizEle.notify();
}
}
}
}
package Java_19;
public class Test {
public static void main(String[] args) {
QuizEle quizEle = new QuizEle();
Thread thread1 = new Thread(new QuizNum(quizEle));
Thread thread2 = new Thread(new QuizChar(quizEle));
thread1.start();
thread2.start();
}
}
3.6 多线程卖火车票,每个窗口随机卖1-5张,一共卖掉500张后输出每个窗口卖出的张数
package Java_19;
import java.util.Random;
public class Sell extends Thread{
int sold = 0;
static int ticketSum = 500;
Random rand = new Random();
@Override
public void run() {
while (ticketSum > 0)
{
synchronized ("")
{
int i = rand.nextInt(5) + 1;
if(ticketSum - i <= 0)
{
if(ticketSum != 0)
{
System.out.println(Thread.currentThread().getName() + "号窗口卖出" + ticketSum + "张票");
}
this.sold += ticketSum;
ticketSum = 0;
}
else
{
System.out.println(Thread.currentThread().getName() + "号窗口卖出" + i + "张票");
ticketSum -= i;
this.sold += i;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println(Thread.currentThread().getName() + "号窗口共卖出" + this.sold + "张票");
}
}
package Java_19;
public class Test {
public static void main(String[] args) {
Thread thread1 = new Thread(new Sell(),"1");
Thread thread2 = new Thread(new Sell(),"2");
Thread thread3 = new Thread(new Sell(),"3");
thread1.start();
thread2.start();
thread3.start();
}
}
3.7 读取文件,统计字母,数字和其他字符个数并输出到文件
package Java_19;
import java.io.*;
public class Census {
public static void main(String[] args) throws IOException {
int numCount = 0;
int charCount = 0;
int otherCount = 0;
File orgFile = new File("D:/org.txt");
InputStream input = new FileInputStream(orgFile);
OutputStream output = new FileOutputStream(orgFile,true);
byte[] b = new byte[1024];
int len;
while((len = input.read(b)) != -1)
{
String s = new String(b,0,len);
for(int j = 0; j < s.length(); j++)
{
int c_ASCII = s.charAt(j);
if((c_ASCII >= 65 && c_ASCII <= 90) || (c_ASCII >= 97 && c_ASCII <= 122))
{
charCount++;
}
else if(c_ASCII >= 48 && c_ASCII <= 57)
{
numCount++;
}
else
{
otherCount++;
}
}
}
String s1 = "\n数字:" + numCount + "\n";
String s2 = "字母:" + charCount + "\n";
String s3 = "其它:" + otherCount + "\n";
output.write(s1.getBytes());
output.write(s2.getBytes());
output.write(s3.getBytes());
output.close();
input.close();
}
}
3.8 Socket网络编程,发送一个数字,接收端接收后输出这个数的全部因数
package Java_19;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Random;
public class Client {
public static void main(String[] args) throws IOException {
Random rand = new Random();
int i = rand.nextInt(100);
Socket socket = new Socket("127.0.0.1",8888);
OutputStream output = socket.getOutputStream();
output.write(i);
socket.close();
}
}
package Java_19;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8888);
Socket socket = server.accept();
InputStream input = socket.getInputStream();
byte[] bytes = new byte[1024];
int len = input.read(bytes);
String s = new String(bytes,0,len);
int i = s.charAt(0);
for(int j = 2; j <= i; j++)
{
if(i % j == 0)
{
System.out.println(j);
}
}
socket.close();
server.close();
}
}
3.9
package EXP1;
abstract class Pizza {
String description = "Unknown Pizza";
public String getDescription()
{
return description;
}
public abstract int getCost();
}
package EXP1;
public class SubstanceDecorator extends Pizza{
@Override
public String getDescription() {
return this.description;
}
@Override
public int getCost() {
return this.getCost();
}
}
package EXP1;
public class VegPizza extends Pizza{
@Override
public int getCost() {
//普通蔬菜披萨30元
return 30;
}
@Override
public String getDescription() {
return "蔬菜披萨";
}
}
package EXP1;
public class NonVegPizza extends Pizza{
@Override
public int getCost() {
//普通非蔬菜披萨50元
return 50;
}
@Override
public String getDescription() {
return "无蔬菜披萨";
}
}
package EXP1;
public class ChickenDecorator extends SubstanceDecorator{
Pizza pizza;
public ChickenDecorator(Pizza pizza) {
this.pizza = pizza;
System.out.println("鸡肉已添加!");
}
@Override
public String getDescription() {
return "鸡肉" + pizza.getDescription();
}
@Override
public int getCost() {
//鸡肉8元
return pizza.getCost() + 8;
}
}
package EXP1;
public class CheeseDecorator extends SubstanceDecorator{
Pizza pizza;
public CheeseDecorator(Pizza pizza) {
this.pizza = pizza;
System.out.println("芝士已添加!");
}
@Override
public String getDescription() {
return "芝士" + pizza.getDescription();
}
@Override
public int getCost() {
//芝士6元
return pizza.getCost() + 6;
}
}
package EXP1;
public class test {
public static void main(String[] args) {
Pizza myPizza = new VegPizza();
myPizza = new ChickenDecorator(myPizza);
myPizza = new CheeseDecorator(myPizza);
System.out.println(myPizza.getDescription() + "总价:¥" + myPizza.getCost());
}
}
3.10 在以OutputStream为基类的输出字节流类库中,创建一个自己的、用来过滤掉空格字符的输出处理流类SkipWhitespaceOutputStream,在输出文本之前,过滤掉所有的空格字符。然后,从控制台读取输入字符串(包含空格字符),过滤掉空格,并再次输出到控制台中。
package EXP2;
import java.io.*;
public class SkipWhitespaceOutputStream extends FilterOutputStream {
public SkipWhitespaceOutputStream(OutputStream out) {
super(out);
}
@Override
public void write(byte[] b) throws IOException {
byte[] result;
String str = new String(b);
String replace = str.replace(" ", "");
result = replace.getBytes();
super.write(result);
}
}
package EXP2;
import java.io.*;
import java.util.Scanner;
public class test {
public static void main(String[] args) throws IOException {
System.out.println("自定义输出处理类流测试:");
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
byte []b = s.getBytes();
System.out.println("去除空格结果为:");
SkipWhitespaceOutputStream out = new SkipWhitespaceOutputStream(System.out);
out.write(b);
out.close();
}
}
3.11 使用File类,从一个指定的目录中找出所有后缀名为txt的文本文件,使用Reader和Writer字节流类,逐一读取并将它们复制到新建的d:\tmp目录中。
package EXP3;
import java.io.*;
import java.nio.file.Files;
public class MyTxt {
public static void main(String[] args) throws IOException {
File file = new File("D:/test");
String extName =".txt";
String oldPath = "D:/test";
String newPath = "D:/tmp";
String[] list = file.list();
if (list != null) {
for(String s : list)
{
if(s.endsWith(extName))
{
copy(s, oldPath, newPath);
}
}
}
System.out.println("复制完成!");
}
private static void copy(String filename, String oldPath, String newPath) throws IOException
{
File oldPaths = new File(oldPath + "/" + filename);
File newPaths = new File(newPath + "/" + filename);
if (!newPaths.exists())
{
Files.copy(oldPaths.toPath(), newPaths.toPath());
}
else
{
if(newPaths.delete())
{
Files.copy(oldPaths.toPath(), newPaths.toPath());
}
}
String newFile = "";
newFile += newPaths.toPath();
Reader r = new FileReader(oldPaths);
File file = new File(newFile);
if (!file.exists())
{
file.createNewFile();
}
Writer w = new FileWriter(newPaths);
char[] buffer = new char[1024];
int c;
while ((c = r.read(buffer)) != -1)
{
for (int i = 0; i < c; i++)
{
w.write(buffer[i]);
}
}
r.close();
w.close();
}
}
3.12 使用RandomAccessFile类,首先打开一个名为Readme.txt 的文本文件,并指定读写权限,然后向文件中写入两行文本,然后将文件指针指向第二行开始处,然后读取第二行的内容,并输出到控制台。随后移至文件尾部,增加第三行文本,保存关闭文件。
package EXP4;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class EXP4 {
public static void main(String[] args) throws IOException{
String filePath = "D:/test/Readme.txt";
RandomAccessFile raf = null;
File file = new File(filePath);
if(file.exists())
{
file.delete();
}
String line1 = "床前明月光,\n";
String line2 = "疑是地上霜。\n";
String line3 = "举头望明月,低头思故乡。";
long pos = 0;
raf = new RandomAccessFile(file,"rw");
raf.write(line1.getBytes());
pos = raf.length();
raf.write(line2.getBytes());
raf.seek(pos);
String s;
s = new String(raf.readLine().getBytes("ISO-8859-1"), "utf-8");
System.out.println(s);
raf.seek(raf.length());
raf.write(line3.getBytes());
raf.close();
}
}