java课后作业(2,4,5,6,7,8,9,10,14,15,16)(更新完毕)
第二章
1.java包含哪些数据类型?
基本数据类型:
(1)整型:byte、short、int、long.
(2)浮点型:float、double.
(3)字符型:char.
(4)布尔型:booleen.
复合数据类型:
(1)类class
(2)接口interface
(3)数组
2.java的基本数据类型转换包含哪两类?请举例说明。
(1)自动类型转换
public class javaConp{
public static void main(String args[]){
byte num = (byte)200;//int常量强制转换
System.out.println(num);//输出 byte 型变量
}
(2)强制类型转换
public class javaDemo{
public static void main(String args[]){
float x = (float)10.2;
float y = 10.1F;
}
}
3.为什么需要包装类?
引人包装类的目的如下(以int和Integer为例):
(1)基本数据类型不是对象,在一些场合不能直接使用(例如某些类方法参数必须是对象类型),需要转化为对应的包装类对象才能继续使用。
(2)包装类的-些静态方法可实现不同数据类型的转化,如将字符串类型的数字"123"转为整数类型,可以通过int a= Integer. parseInt(“123”)完成,而将整数转为字符串使用,则要通过String c=String.valueOf(123)来完成。
(3)包装类的静态属性中含有相应数据类型的范围,如Integer.MIN_VALUE(int的最小值),Integer.MAX_VALUE(int的最大值),Double.NaN(非数类型)、Double.NEGATIVE-INFINITY(负无穷)、Double.POSITIVE_INFINITY(正无穷)。
4.int与integer有什么区别?他们之间的相互转化是怎样的?
区别:
(1)Integer是int的包装类,int则是java的一种基本数据类型.
(2)Integer变量必须实例化后才能使用,而int变量不需要.
(3)Integer实际是对象的引用,当new一个Integer时,实际上是生成一个指针指向此对象;而int则是直接存储数据值.
(4)Integer的默认值是null,int的默认值是0.
5.逻辑运算符&和&&有什么区别?逻辑运算符&与位运算符的区别是什么?请分别举例说明。
(1)&和&&的区别:
例如A&&B,如果A为false,就不会去判断B是True还是False了。
而A&B,则如果A为false仍会执行一次B。
(2)逻辑运算符&与位运算符的区别:
逻辑运算符&左右两边是表达式,而位运算符&两边是二进制的数。
6.Java语言中可以采用什么语句跳出多重循环?请举例说明。
两种跳转方式:
(1)break
(2)break lab;
lab:
for(int i =0; i<2; i++) {
for(int j=0; j<10; j++) {
if (j >1) {
break lab;
}
System.out.println(“break");
}
}
//输出结果为:break,break;
第四章
1.对象与对象引用的区别是什么?请举例说明。
一、Java对象
所谓的对象其实就是通过java类所产生的实体。
java中可以通过构造类来产生对象
通过new + 构造方法就可以得到一个类的对象。因此上一个类中的构造方法就显得很重要,所以我们通过class关键字定义出来的java类,默认就是有一个无参数的构造方法存在,只不过我们没有显式写出这个无参数的构造。当出现有参数的构造方法时,最好能够显式写出这个无参数的构造方法。
类中的构造方法就是为了创建对象而存在的。
通过new 构造方法就可以得到一个类的对象是一个没有名称的对象,因此上也叫匿名对象。所以通常情况下我们都是需要定义/声明一个该类的变量来保存这个类的对象。我们把保存对象的这个类的变量又叫引用。【引用中实际上保存的是该对象在内存的实际地址】
例如:
public class MyTestClass {
public int testid=1001;
public String testname=“zhangsan”;
public MyTestClass(){
System.out.println(“无参数的构造方法–创建对象的时候要使用”);
}
public void method(){
System.out.println(“MyTestClass类中的实例方法”);
}
public static void staticMethod(){
System.out.println(“MyTestClass类中的类方法”);
}
}
二、Java对象的引用
每种编程语言都有自己的数据处理方式。有些时候,程序员必须注意将要处理的数据是什么类型。你是直接操纵元素,还是用某种基于特殊语法的间接表示(例如C/C++里的指针)来操作对象。所有这些在 Java 里都得到了简化,一切都被视为对象。因此,我们可采用一种统一的语法。尽管将一切都“看作”对象,但操纵的标识符实际是指向一个对象的“引用”(reference)。 对Java对象的引用,是描述的定义。
例如:
int a;
a=2;
a=3;
这里先声明了一个int类型的变量a,先对a赋值为2,后面又赋值为3。也就是说int类型的变量a,可以让它的值为2,也可以为3,只要是合法的int类型的数值即可。所以Java中的引用可以指向多个对象。
2.对象作为参数传递的特点是什么?请举例说明。
对象是引用传递,当对象作为参数传递的时候,传递的是参数的地址。
public class ValuePass {
private static int a;
public static void main(String [] args) {
modify(a);
System.out.println(a);
}
public static void modify(int a) {
a++;
}
}//值传递,输出为0
class IntClass {
int value;
}
public class RunIntClass {
public static void modifyValue(IntClass s, int val){
s.value = val;
}
public static void main(String[] args) {
IntClass a = new IntClass();
modifyValue(a,8);
System.out.println(a.value);
}
}//引用传递,值为8
3.对象初始化顺序是怎样的?请举例说明。
系统先对数据成员进行默认初始化
执行数据成员定义处的初始化语句
调用构造方法为数据成员指定初值
class IntClass {
int value; //自动初始化,默认值为0
//int value = 5; //在定义时指定初值
public IntClass(){}
//定义构造方法将属性value初始化
public IntClass(int val){
value = val ;
}
}
4.类的static字段与非static字段的区别是什么?什么情况应该使用static修饰符?请举例说明。
(1)类的static字段修饰的域变量不属于任何一个类的具体对象,而专属与类。
(2)用static修饰符修饰的方法称为静态方法,它属于类方法,不属于类的任何对象。
静态数据成员仅在类加载时进行初始化,且只执行一次初始化
5.Java中final修饰符 都有什么作用?请举例说明。
以final修饰类属性,则该属性为常量,如果修饰方法,则方法称为最终方法,在子类中不能被覆盖。利用这一点可以防止子类修改此方法,保证了程序的安全性和正确性。
public F{
2 static final int a = 0;//a的值不能被覆盖
3 static final ff(){}//方法不能被重写
6.Java中float[10] arr;语句正确么?为什么?
不正确,数组的声明中不能初始化数组的长度。
7.Java数组元素类型为基本数据类型和引用类型时,有什么不同?请举例说明。
区别:数组元素类型为基本元素类型时;数组中存储的就是所要使用的值,而数组元素类型为引用类型的时候,数组中存储的不是所用的值,而是通过存储的引用来查找到所需值的地址。
例:
int[] arr = new int[10]; //此时分配了数组空间,每个单元初始化为默认值0
产生一个有10个单元,类型为int的数组对象,所有单元的初始值为0;
例:
String[]example = new String[10]; //对象引用数组
产生一个具有10个单元的数组对象,每个单元存放的是一个String对象的引用,所有单元的初值为null,此时并未创建具体的String对象。
第五章
1. Java的访问控制修饰符有哪些?各有什么访问权限?请对照第7页ppt的表格分别写程序验证。
访问权限首先看类前的修饰符,当类的修饰符为public时,
则类可以被所有的类所访问(可以import),当为默认时,
则只能为包中的类所访问。在此前提下,再看属性和方法前的修饰符。
类前修饰符为public时,当属性和方法前的修饰符为public时,则该属性可以被所有类访问;当属性和方法前为protected修饰时,对于类定义而言,可以被同包中的类和所有子类访问(子类和父类可以不在同一个包中),也就是B+C范围,但对于对象而言,只能被同一个包的类对象所访问,也就是B的范围;当为默认时,只能被同包中的类所访问(比protected访问权限小);当为private时,只能被本类内部所访问 。
同一个包——演示public类的protected属性访问:
不同包——演示public类的protected属性访问:
2. 子类对于从父类继承的哪些属性与方法是可见的?请分别写程序进行验证。
父类的public和proected的属性与方法对子类来讲是可见的。
3. 什么是组合?有什么作用?请举例说明。
组合是在一个类的内部应用了别的类的引用,通过现有的对象进行拼装产生新的、更加复杂的功能。
class FighterPlane
{
String name;
int missileNum;
public FighterPlane(String _name,int _missileNum){
name = _name;
missileNum = _missileNum;
}
public void fire(){
if (missileNum>0){
System.out.println(“now fire a missile !”);
missileNum -= 1;
}
else{
System.out.println(“No missile left !”);
}
}
}
class A
{
FighterPlane fp;
public A(FighterPlane fpp){
this.fp = fpp; //A对象中拥有了FighterPlane对象的引用
}
public void invoke(){
//A中对象发送消息给FighterPlane的对象
System.out.println(fp.name);
}
}
public class Run{
public static void main(String[] args)
{
FighterPlane ftp = new FighterPlane(“su35”,10);
//产生A对象,并将ftp对象引用作为参数传入
A a = new A(ftp);
//发送消息,产生调用关系
a.invoke();
}
}
4. 什么是重载?有什么作用?请举例说明。
重载:方法名称相同,参数类型或个数不同。重载可以对其功能进行复用,同时又可以对其进行补充。
class Parent{
public int getScore(){
return 3;
}
public int getScore(int i){
return i;
}
}
5. 什么是覆盖?有什么作用?请举例说明。
子类对父类的同名方法(方法名称相同,参数相同,返回类型相同)重新进行定义,即在子类中定义与父类中已定义的同名而内容不同的方法。
class Parent {
public int getScore()
{ return 3; }
public String getCountryName()
{ return “China”; }
}
class Son extends Parent {
public int getScore(){
return 4;
}
}
public class RunSon{
public static void main(String args[]){
Son s = new Son();
System.out.println(s.getScore());
System.out.println(s.getCountryName());
}
}
第六章
1.实验:利用IDE的debug功能给例6.4和例6.6的new语句设置断点,使用单步调试(step into/step over)跟踪子类对象实例化(初始化)的执行顺序,并总结该过程。
2.如何实现两个对象之间互发消息,请举例说明。
1)引用必须真实引用了特定的对象。
2)被访问对象必须定义了相应的属性或方法。否则编译不通过
3)被访问的属性或方法必须具有可访问的权限。
class FighterPlane{
String name;
int missileNum;
public FighterPlane(String _name,int _missileNum){
name = _name;
missileNum = _missileNum;
}
public void fire(){
if (missileNum>0){
System.out.println(“now fire a missile !”);
missileNum -= 1;
}
else{
System.out.println(“No missile left !”);
}
}
}
class A
{
FighterPlane fp;
public A(FighterPlane fpp){
this.fp = fpp; //A对象中拥有了FighterPlane对象的引用
}
public void invoke(){
//A中对象发送消息给FighterPlane的对象
System.out.println(fp.name);
}
}
public class Run{
public static void main(String[] args)
{
FighterPlane ftp = new FighterPlane(“su35”,10);
//产生A对象,并将ftp对象引用作为参数传入
A a = new A(ftp);
//发送消息,产生调用关系
a.invoke();
}
}
3.谈谈组合与继承的区别以及两者的使用场景(即什么时候宜用组合?什么时候宜用继承?)
组合只是将两个类结合起来其中一个类是另外一个类的域变量两个类之间无上下级关系。
而继承则是如果子类建立那么父类一定要先建立的这种关系。
只需要使用另外一个类的方法时使用组合,但是如果你需要使用另外一个类的作用时但你不想被其他的类访问用继承反之组合。
4. Java中的运行时多态的含义是什么?有什么作用?请举例说明。
指一个程序中同名但不同方法共存的情况。由于完成同一功能时可能遇到不同的具体情况,所以有些方法通过方法覆盖实现(子类覆盖父类方法)。
5. 使用接口改写例6.8中的程序。
package runshape;
public interface Shapes {
public double getArea();
public double getPerimeter();
public void show();
}
package runshape;
public class Circle implements Shapes{
private int r;
public Circle(int r){
this.r=r;
}
public double getArea() {
return Math.PI*Math.pow(r, 2);
}
public double getPerimeter(){
return 2*Math.PI*r;
}
public void show(){
System.out.println("圆形:");
System.out.println("圆的面积是"+this.getArea());
System.out.println("圆的周长是"+this.getPerimeter());
}
}
package runshape;
public class Rect implements Shapes{
private int height;
private int width;
public Rect(int height, int width){
this.height=height;
this.width=width;
}
public double getArea(){
return height*width;
}
public double getPerimeter(){
return 2 * height + 2 * width;
}
public void show(){
System.out.println("矩形:");
System.out.println("矩形的面积是"+this.getArea());
System.out.println("矩形的周长是"+this.getPerimeter());
}
}
package runshape;
public class Triangle implements Shapes {
private int x;
private int y;
private int z;
public Triangle(int x, int y, int z){
this.x=x;
this.y=y;
this.z=z;
}
@Override
public double getArea() {
double m=(x+y+z)/2.0;
return Math.sqrt(m*(m-x)*(m-y)*(m-z));
}
@Override
public double getPerimeter() {
return x+y+z;
}
public void show(){
System.out.println("三角形:");
System.out.println("三角形的面积是"+this.getArea());
System.out.println("三角形的周长是"+this.getPerimeter());
}
}
package runshape;
public class RunShape {
public static void print(Shapes s){
s.show();
}
public static void main(String[] args) {
Rect rect=new Rect(25,25);
Triangle triangle=new Triangle(5,5,8);
Circle circle=new Circle(12);
//打印输出
print(rect);
print(triangle);
print(circle);
}
}
6.简述instanceof的使用场景
用instanceof判断一个对象是不是某个类或者其子类的实例,还可以将这个对象强制转换成这个类的类型。
a为对象的引用,A为类。如果a是A或其子类的实例,则返回true,若为A父类的子类,则返回false。若无关,则错误
public class Test {
static class A{ }
static class B extends A{ }
public static void main(String[] args) {
A a = new A();
B b = new B();
System.out.println( “a instanceof A 的结果:” + ( a instanceof A ) );
System.out.println( “b instanceof A 的结果:” + ( b instanceof A ) );
System.out.println();
System.out.println( “a instanceof B 的结果:” + ( a instanceof B ) );
System.out.println( “b instanceof B 的结果:” + ( b instanceof B ) );
System.out.println();
Object o = new A();
System.out.println( “o instanceof A 的结果:” + ( o instanceof A ) );
System.out.println( “o instanceof B 的结果:” + ( o instanceof B ) );
System.out.println();
o = new B();
System.out.println( “o instanceof A 的结果:” + ( o instanceof A ) );
System.out.println( “o instanceof B 的结果:” + ( o instanceof B ) );
System.out.println();
}
}
第七章
1. 简述Java Error类与Exception类的区别。
Java Error类:所有错误类的祖先类
Exception类:所有异常类的祖先类
Error类一般是指与虚拟机相关的问题,如系统崩溃,虚拟机错误,内存空间不足,方法调用栈溢等。对于这类错误的导致的应用程序中断,仅靠程序本身无法恢复和和预防,遇到这样的错误,建议让程序终止。
Exception类表示程序可以处理的异常,可以捕获且可能恢复。遇到这类异常,应该尽可能处理异常,使程序恢复运行,而不应该随意终止异常。
2. 简述异常处理的两种方式,并举例说明区别。
隐式声明处理
import java.util.*;
class TestEmptyStack {
public static void main(String[] args){
Stack st = new Stack();
Object ob = st.pop();
}
/*
Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Unknown Source)
at java.util.Stack.pop(Unknown Source)
at TestEmptyStack.main(TestEmptyStack.java:5)
*/
显示声明处理
import java.io. *;
class TestScreenIn{
public static void main(String[] args) throws IOException{ //抛出IOException异常
BufferedReader keyin = new BufferReader(new
InputStreamReader(System.in));
String c1;
int i=0;
String[] e = new String[10];
while( i<10){
c1 = keyin.readLine();
e[i] = c1;
i++;
}
}
}
3. 选取RuntimeException类的五个子类,编写抛出并捕获上述子类异常的程序。(例如算术异常,空指针异常,类转换异常,数组越界异常等)
package TestException;
class Father{
int i;
}
class Son extends Father{
public Son(){
int i;
this.i=i;
}
public int getI(){
return this.i;
}
}
public class CatchException {
public static void main(String[] args) {
int a=1;
int b=0;
int c;
Father father_f = new Father();
Son son_1 = new Son;
int[] x = new int[10];
try{
c=a/b;
}
catch (ArithmeticException e){
e.printStackTrace();
System.out.println("算术异常Arithmetic");
}
try{
son_1= (Son) father1;
}
catch (ClassCastException e){
e.printStackTrace();
System.out.println("类转换异常ClassCast");
}
try{
System.out.println(x[100]);
}
catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
System.out.println("数组越界异常ArrayIndexOutOfBounds");
}
try{
System.out.println(x[1]);
}
catch (NullPointerException e){
e.printStackTrace();
System.out.println("空指针异常");
}
}
}
4. 仿照例7.9,自定义一个异常类,并在某场景下抛出该异常对象。
package TestException;
import java.util.Scanner;
public class MakeException extends Exception{
MakeException(String exa){
super(exa);
}
static void GPA(int s) throws MakeException{
if(score < 60){
throw new MakeException("重修");
}
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);//创建一个键盘扫描类对象
System.out.println("输入分数");
int s = 80;
try {
GPA(score);
}
catch (MakeException e) {
e.printStackTrace();
}
}
}
第八章
1.借助JDK,选取几个String与StringBuffer、StringBuilder的常用API,并编写实例测试API的功能。
2. 请简述String,StringBuffer,StringBuilder三者之间的共同点与区别,应该分别在何种场景下使用?
String、StringBuffer、StringBuilder 比较:
String、StringBuffer、StringBuilder相同点
1、内部实现基于字符数组,封装了对字符串处理的各种操作
2、可自动检测数组越界等运行时异常
String、StringBuffer、StringBuilder不同点
1、String内部实现基于常量字符数组,内容不可变;
StringBuffer、StringBuilder基于普通字符数组,数组大小可根据
字符串的实际长度自动扩容,内容可变
2、性能方面,对于字符串的处理,相对来说
StringBuilder >StringBuffer>String
3、StringBuffer线程安全;StringBuilder非线程安全
3、为什么不建议在for循环中使用“+”进行字符串拼接?
需要一直创建新的对象,浪费大量空间资源且费时,效率过于低下。
4. 什么是字符串的编码与解码?请举例说明。
对于同一个汉字,GB2312和Unicode对应的代码并不一样,需要一个转化过程。
编码:将Unicode字符集转换为本地字符集(GB2312或GBK)的过程。
import java.io.*;
public class CharCode {
public static void printByteArray(String msg,byte[] t){
System.out.println(msg+"****************");
for(int i=0;i<t.length;i++){
System.out.println(Integer.toHexString(t[i])); }
}
public static void printCharArray(String msg,char[] c){
System.out.println(msg+"****************");
for(int i=0;i<c.length;i++){
System.out.println(Integer.toHexString(c[i])); }
}
public static void main(String[] args){
try{
String str = "中文";
System.out.println(str);
printCharArray("unicode:",str.toCharArray()); //unicode字符集中对"中文"二字的对应代码
byte[] b =str.getBytes(“GB2312”); //编码:转为本地字符集GBK2312对应的代码
printByteArray("GB2312",b);
byte[] m =str.getBytes("ISO8859-1"); //转为ISO8859-1对应的代码
printByteArray("ISO8859-1",m); // ISO8859-1是英文字符集,没有对应的汉字代码,所以转化错误
}
catch(UnsupportedEncodingException e){
System.out.println("没有相应的字符集!"); } } }
解码:将本地字符集转换为Unicode字符集的过程。
```java
public static void main(String[] args){
byte[] b = new byte[6];
int t=0,pos=0;
String s;
try{
while(t!='\n'){
t=System.in.read();
b[pos]=(byte)t;
pos++;
}
printByteArray("本地码:",b);
s = new String(b,“GBK”); //解码
System.out.println(s);
printCharArray("unicode码:",s.toCharArray());
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
第九章
1.volatile关键字有什么作用?
1)保证可见性,不保证原子性。
可见性:当某个线程修改volatile变量时,JMM会强制将这个修改更新到主内存中,并且让 其他线程工作内存中存储的副本失效。
volatile变量并不能保证其操作的原子性,具体来说像i++这种操作并不是原子操作,使用volatile修饰变量后仍然不能保证这一点。
2)禁止指令重排
指令重排是指JVM在编译Java代码的时候,或者CPU在执行JVM字节码的时候,对现有的指令顺序进行重新排序
指令重排的目的是为了在不改变程序执行结果的前提下,优化程序的运行效率。需要注意的是,这里所说的不改变执行结果,指的是不改变单线程下的程序执行结果。
重排序操作不会对存在数据依赖关系的操作进行重排序。比如:a=1;b=a; 这个指令序列,由于第二个操作依赖于第一个操作,所以在编译时和处理器运时这两个操作不会被重排序。
重排序是为了优化性能,但是不管怎么重排序,单线程下程序的执行结果不能被改变。比如:a=1;b=2;c=a+b这三个操作,第一步(a=1)和第二步(b=2)由于不存在数据依赖关系, 所以可能会发生重排序,但是c=a+b这个操作是不会被重排序的,因为需要保证最终的结果一定是c=a+b=3。
然而,指令重排是一把双刃剑,重排序在单线程下一定能保证结果的正确性,但是在多线程环境下,可能发生重排序,影响结果,下例中的1和2由于不存在数据依赖关系,则有可能会被重排序,先执行status=true再执行a=2。而此时线程B会顺利到达4处,而线程A中a=2这个操作还未被执行,所以b=a+1的结果也有可能依然等于2。
2.编写Java程序模拟烧水泡茶最优工序。
package MakeTea;
public class MakeTea extends Thread{
private int time;
private String name;
MakeTea(int time,String name){
this.time=time;
this.name=name;
}
public String getname(){
return this.name;
}
public int getTime(){
return time;
}
public void run(){
this.setName(getname());
int count=0;
while (count<=getTime()) {
System.out.println(this.getname() + "线程工作中,已进行了" +count+"分钟");
count++;
}
System.out.println(this.getName() +"工作已经完成!");
}
}
***************************************************
package MakeTea;
public class TestMakeTea {
public static void main(String[] args) {
MakeTea WashPot = new MakeTea(1,"WashPot");
MakeTea BoilWater = new MakeTea(15,"BoilWater");
MakeTea WashTeaPot = new MakeTea(1,"WashTeaPot");
MakeTea WashGlass = new MakeTea(2,"WashGlass");
MakeTea GetTea = new MakeTea(1,"GetTea");
WashPot.start();
try {
WashPot.join(); //让WashPot线程一直进行直至结束;
}catch (InterruptedException it){}
BoilWater.start();
/*
try{
BoilWater.sleep(500);
}catch (InterruptedException it){}
*/
//烧水过程中可以同时进行洗茶壶
WashTeaPot.start();
try{
WashTeaPot.join();
}catch (InterruptedException it){}
//洗完茶壶洗茶杯
WashGlass.start();
try {
WashGlass.join();
}catch (InterruptedException it){}
//洗完茶杯去拿茶叶
GetTea.start();
try{
GetTea.join();
}catch (InterruptedException it){}
try{
BoilWater.join();
}catch (InterruptedException it){}
System.out.println("a good cup of tea is done!");
}
}
第十章
1.编写程序测试Java集合框架中各种常用类的 基本操作(包括添加元素,删除元素,遍历集合元素等)
package Collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ArrayList_Test {
public static void main(String[] args) {
List <Integer> Int_Num = new ArrayList<Integer>();
//添加元素
Int_Num.add(new Integer(1));
Int_Num.add(new Integer(4));
Int_Num.add(new Integer(10));
Int_Num.add(new Integer(5));
Int_Num.add(new Integer(209));
//Int_Num.add(new Double(2.5));编译时会报错
// 删除元素
Int_Num.remove("1");//根据对象删除
Int_Num.remove(0);//根据下标删除
//元素遍历
//1.迭代器
Integer value = null;
Iterator iter = Int_Num.iterator();
while (iter.hasNext()) {
value = (Integer)iter.next();
System.out.print(value+ " ");
}
System.out.println();
//2.随机访问,通过索引值去遍历
int size = Int_Num.size();
for (int i=0; i<size; i++) {
value = (Integer)Int_Num.get(i);
System.out.print(value+ " ");
}
System.out.println();
//3.for循环遍历
for (Integer integ:Int_Num) {
value = integ;
System.out.print(value+ " ");
}
}
}
第十四章
1.Java中流的分类有哪些?
1)从流的流动方向上看:一般分为输入流(InputStream)和输出流(OutputStream)。
输入流:如System.in是一个InputStream类型输入流
输出流:如System.out 是一个PrintStream类型输出流
程序可以用输出流向文件中写数据,用输入流从文件中读数据。
2)从流的读取类型上分:一般分为字节流和字符流。
字节流:如System.in是一个InputStream类型字节流
字符流:如new InputStreamReader(System.in)是一个字符流对象
3)从流发生的源头可以分为节点流和过滤流。
节点流:直接操作目标设备对应的流, 如文件流,标准输入输出流
过滤流:继承带有关键字Filter的流 , 用于包装操作节点流,方便读写各种类型的数据
2.字节流InputStream和OutputStream的子类分别有哪些?请举例说明其使用场景。与其对应的字符流分别有哪些?
3.字节流和字符流的转化是怎样的?Java对此提供了哪些支持?
1)输入字节流转为字符流需要用到InputstreamReader的构造方法:
InputStreamReader(InputStream in)I
例如:
InputStreamReader ins = new InputStreamReader(System.in);
InputStreamReader ins = new InputStreamReader(new FileInputStream(“test.txt”));
2)输出字符流转为字节流用到OutputStreamWriter或PrintWriter的构造方法:
OutputStreamWriter(OutputStream out)
PrintWriter(OutputStream out)
例如:
OutputStreamWriter outs = new OutputStreamWriter(new FileOutputStream(“test.txt”));
4.Java中的过滤流(流的装配)有什么作用?请举例说明常用的过滤流。
import java.io.*;
public class inDataSortMaxMinIn {
public static void main(String args[]) {
try{
BufferedReader keyin = new BufferedReader(new
InputStreamReader(System.in));
String c1;
int i=0;
int[] e = new int[10];
while(i<10){
try{
c1 = keyin.readLine();
e[i] = Integer.parseInt(c1);
i++;
}
catch(NumberFormatException ee){
System.out.println("请输入正确的数字!");
}
}
}
catch(Exception e){
System.out.println("系统有错误");
}}}
5.什么是对象的序列化和反序列化?Java对此提供了哪些支持?
序列化和反序列化:序列化将实现了Seriallizable接口的对象转换成一个字节序列,并能够在以后将这个字节序列完全恢复为原来的对象,后者又称反序列化。
序列化的目的:便于介质存储和网络传输
Java提供了ObjectInputStream类和ObjectOutputStream类
6.Java的File类表示什么?有什么作用?
Java中的File类,以抽象的方式代表文件名和目录路径名。该类主要用于文件和目录的创建、文件的查找和文件的删除等。
它有四个构造函数:
File(String parent,String child)
File(File parent,String child)
File(URI uri)
File(String pathname)
封装了以下主要方法:
canWrite() 返回文件是否可以读写
canRead() 返回文件是否可读
compareTo(File pathname)检查文件路径间的顺序
createNewFile() 当文件不存在时生成文件
delete() 从文件系统内删除该文件
deleteOnExit() 程序顺利结束时删除文件
equals(Object obj) 检查特定对象的路径名是否相等
exists() 判断文件是否存在
getAbsoluteFile() 返回文件完整路径的File实例
7.Java对文件的读写分别提供了哪些支持?
读取:
import java.io.*;
public class OpenFile
{
public static void main(String args[]) throws IOException
{
try
{ //创建文件输入流对象
FileInputStream rf = new FileInputStream("OpenFile.java");
int n=512,c=0;
byte buffer[] = new byte[n];
while ((c=rf.read(buffer,0,n))!=-1 ) //读取输入流
{
System.out.print(new String(buffer,0,c));
}
rf.close(); //关闭输入流
}
catch (IOException ioe)
{ System.out.println(ioe);}
catch (Exception e)
{ System.out.println(e);}
}
}
写入:
import java.io.*;
public class Write1
{
public static void main(String args[])
{
try
{ System.out.print("Input: ");
int count,n=512;
byte buffer[] = new byte[n];
count = System.in.read(buffer); //读取标准输入流
FileOutputStream wf = new FileOutputStream("Write1.txt");
//创建文件输出流对象
wf.write(buffer,0,count); //写入输出流
wf.close(); //关闭输出流
System.out.println("Save to Write1.txt!");
}
catch (IOException ioe)
{ System.out.println(ioe);}
catch (Exception e)
{ System.out.println(e);}
}
}