了解包装器,装箱,拆箱操作
一.包装器
java创建的一种包装类用于把基本数据类型包装成对象类型
包装器的作用
1.提供一种将基本值"包装"到对象中的机制,从而使基本值能够包含在为对象而保留的操作中,或从带对象的返回值的方法中返回,在java1.5之后增加了自动装箱和拆箱功能
二.装箱,拆箱
自动装箱从java1.5引入,目的是将原始类型值自动的转换成对应的对象.
package Demo ;
public class Demo1 {
public static void main ( String [ ] args) {
int a = 10 ;
Integer b = 20 ;
Integer m = Integer . valueOf ( "10" ) ;
System . out. println ( b. intvalue ( ) ) ;
int c = m;
int d = c. intvslue ( ) ;
}
}
异常
异常是指在程序运行的过程中发生的异常事件,一般由外部问题所导致.
异常都是运行时产生的,并非编译时产生的错误
自定义异常类
声明异常类
自定义异常类案例
package Demo ;
public class Demo2 {
public class SexException extends Exception {
public SexException ( ) {
super ( "性别设置错误,必须是男或女" ) ;
}
public SexException ( String message) {
super ( message) ;
}
}
}
抛出异常
package Demo ;
public class Demo3 {
private int id;
private String name;
private String genter;
public int getId ( ) {
return id;
}
public void setId ( int id) {
this . id = id;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
public String getGenter ( ) {
return genter;
}
public void setGenter ( String genter) throws Demo2. SexException {
if ( "男" . equals ( genter) || "女" . equals ( genter) ) {
} else {
throw new Demo2. SexException ( "性别设置异常,必须为男或女" ) ;
}
this . genter = genter;
}
}
package Demo ;
import java. util. Scanner ;
public class Demo4 {
public static void main ( String [ ] args) {
Demo3 stu = new Demo3 ( ) ;
Scanner sc = new Scanner ( System . in) ;
try {
System . out. println ( "请输入学生性别" ) ;
String line = sc. nextLine ( ) ;
stu. setGenter ( line) ;
} catch ( Demo2. SexException ex) {
System . out. println ( "性别设置错误,必须为男或女" ) ;
} catch ( Exception ex) {
System . out. println ( "未知异常" ) ;
}
}
}
try-with-resources语句
package Demo ;
import java. io. * ;
public class Demo5 {
public static void main ( String [ ] args) {
String f = "user.txt" ;
try ( var fw = new FileWriter ( f) ; var fr = new BufferedReader ( new FileReader ( f) ) ) {
fw. write ( "hello world" ) ;
fw. flush ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
集合工具类
package Demo ;
import java. util. ArrayList ;
import java. util. List ;
public class Demo6 {
public static void main ( String [ ] args) {
List < String > list = new ArrayList < > ( ) ;
list. add ( "Hello World" ) ;
list. add ( "Hell" ) ;
System . out. println ( list) ;
list. clear ( ) ;
System . out. println ( list) ;
list. add ( "Held" ) ;
list. add ( "World" ) ;
list. add ( "Hello " ) ;
list. set ( 2 , "Hello World" ) ;
System . out. println ( list) ;
for ( String str : list) {
System . out. print ( str+ " " ) ;
}
}
}