常用类
String :方法
1.charAt:例子:
2.replace:例子:
String str3 = "d:/a/bjpg/aa.jpg";
System.out.println(str3.substring(str3.lastIndexOf(".")+1));
String str4 = str3.replace("jpg", "png");
System.out.println(str4);
3.contains:例子:
public static String index(String source, String target) {
if (null != source) {
if (source.contains(target)) {
return target + ":" + source.indexOf(target);
} else {
return "沒有找到子串";
}
} else {
return "source未定义";
}
}
4.split
String a="hello world ni hao";
String[] array1=a.split(" ");
System.out.println(array1[0]);
System.out.println(array1.length);
}
输出的是hello
输出的是4
5.indexOf:例子:
String s1 = new String(“Good Good Study ,Day Day up !”);
int pos = s1.indexOf(“s”);
System.out.println(“pos = ” + pos);// -1
pos = s1.indexOf(“S”);
System.out.println(“pos = ” + pos);// 10
6.substring
public String substring(int beginIndex, int endIndex)
StringBuffer
在进行大数据的字符串拼接时使用 StringBuffer
StringBuffer类的对象能够进行多次修改并且不会产生新的未使用的对象,因此在内存上要优于String对象
java.util.Date
java.util.Date类用于描述日期信息:年月日时分秒,可以精确到毫秒。1秒=1000毫秒。
例子:
String s = "2018年08月30日 11:36:36.538";
String b = "2017年10月30日 12:46:36.538";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss.SSS");
try {
Date begin = sdf1.parse(s);
Date end = sdf1.parse(b);
System.out.println("打印出"+(begin.getTime()-end.getTime()));
} catch (ParseException e) {
e.printStackTrace();
异常的处理
如果不处理异常,一旦在出现异常的地方,程序就会被「异常指令流」直接终止,不再往下运行。
在程序方法设计,特别是方法的实现中,对于传入的参数,是不可知的,所以要对传入的参数进行最基础的验证后,才能使用,例如,判断是否为 null。
1.try catch
public static int div(int x, int y) {
int rs = 0;
try {
rs = x / y;
System.out.println("xxx");
// Client1 c1 = null;
// System.out.println(c1.toString());
} catch (NullPointerException e) {
e.printStackTrace();
rs = 0;
}
2.finally
无论是否出现异常都会被执行,特别要注意的是,如果没有写 catch ,那么 finally 是会被执行的,但是中断后的语句是不会被执行的
public static int div(int x, int y) {
int rs = 0;
try {
rs = x / y;
System.out.println("xxx");
// Client1 c1 = null;
// System.out.println(c1.toString());
} catch (NullPointerException e) {
e.printStackTrace();
rs = 0;
} catch (Exception e) {
e.printStackTrace();
rs = 0;
} finally {
// 资源回收
System.out.println("finally action");
}
3.throw
自定义的创建一个异常对象。在一般的异常发生时候,虚拟机会动态的创建一个「系统异常」抛出,和自定义使用 throw 抛出是一个概念
例子:
public static void fun1(int age) throws Exception {
if (age < 18) {
System.out.println("不允许进入房间");
throw new Exception("年龄限制不允许进入");
} else {
System.out.println("允许进入");
}
}
异常的堆栈信息
异常类
异常提示信息:getMessage()
异常所在的代码位置:自下而上是异常出现的代码所在方法的调用顺序的先后。
数组越界:
public static void fun2(Student stu) {
int[] shu = {1,2,3};
// 数组的越界
for(int i = 0;i<4;i++) {
System.out.println(shu[i]);
}
}
2.空指针异常