1、开始的唠叨正则表达式
上篇里相对重要的是面向抽象与面向接口的编程,两者都体现了开闭原则。编程
本期继续回顾Java中的基础知识。数组
2、学习笔记app
(一)内部类与异常类工具
1.内部类:学习
值得一提的是内部类编译后的格式,代码以下:spa
public class A { class B{ } }
则编译后的字节码文件名字格式为:调试
2.匿名类:code
3.异常类:通常的IDE工具都会提示“此处应有异常”,系统自带的异常就很少说了。惟一值得注意的是try部分一旦发生异常,就会马上结束执行,转而执行catch部分。orm
来看看如何自定义异常:
定义一个异常类继承Exception类
public class TotalException extends Exception{ public String warnMess(){ return "有毒"; } }
在可能产生异常的方法名中throws自定义的异常类,并在具体的方法体重throw一个自定义异常的实例
public class Count { public void count (int a) throws TotalException{ if(a==10){ throw new TotalException(); } }
在使用该方法时包裹try-catch语句
public static void main(String[] args) { Count c=new Count(); try { c.count(10); } catch (TotalException e) { System.out.println(e.warnMess()); } }
4.断言:assert用于代码调试阶段,当程序不许备经过捕获异常来处理错误时就可使用断言。
定义一个断言(表达式为true时继续执行,false则从断言处终端执行)
int a=10; assert a!=10:"a不但是10";
Java解释器默认关闭断言语句,要用-ea命令手动开启
(二)经常使用实用类
1.String:
重要方法:
String (char a[])//由字符数组构造 public int length()//获取长度 public boolean equals(String s)//是否有相同实体 public boolean startsWith(String s)//是否以s开头 public boolean endsWith(String s)//是否以s结尾 public int compareTo(String s)//比较 public boolean contains(String s)//是否包含s public int indexOf(String s)//s首次出现的索引 public String substring(int startpoint)//截取 public String trim()//删除空格
来看一个经典的equals与==的问题:
public static void main(String[] args) { String a=new String("1111"); String b=new String("1111"); System.out.println(a.equals(b)); System.out.println(a==b); a="1111"; b="1111"; System.out.println(a.equals(b)); System.out.println(a==b); }
输出结果为:true false true true,可见equals方法比较当前字符串对象的实体是否与参数指定的实体相同,而==比较的则是引用是否相同。
2.正则表达式:正则表达式很强大,是一个必须掌握的大坑。元字符表直接百度百科。下面给出一个在Java中使用正则表达式的例子:
public static void main(String[] args) { String regex="[a-zA-Z]+"; String in="dhasdd4alidhskjl"; if(in.matches(regex)){ System.out.println("全是英文字母"); }else{ System.out.println("不全是英文字母"); } }
3.Date:Date能够获取当前时间,通常状况下须要格式化
public static void main(String[] args) { DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date=new Date(); System.out.println(df.format(date)); }
4.Math:封装了一系列 数学方法
5.Class:传说中的Java反射技术
先用Class.forName(Sting s)法获取Apple类的class
再利用class对象调用newInstance()方法实例化Apple类的对象
public static void main(String[] args) { try { Class clazz=Class.forName("Apple"); Apple apple=(Apple)clazz.newInstance(); apple.setNumber(1); System.out.println(apple.getNumber()); Apple apple2=new Apple(); Class class1=apple2.getClass(); System.out.println(class1.getName()); } catch (Exception e) { e.printStackTrace(); } }
3、结束的唠叨
之前看大神的博客还没什么感受,如今本身开始写了才发现困难重重。
目前为止,我写博客的主要目的是便于本身的知识巩固,写的很散,属于把一本书上的内容根据本身的短板超浓度压缩。
因此有什么地方看不懂绝对不是你的问题,欢迎讨论。