常用类库API
String
字符串操作
- String可以表示一个字符串,String类实际是使用字符数组存储的
- String类的两种赋值方式
String name = "王五"; //直接赋值 (推荐) 在常量池中有该对象则不创建对象
String name = new String("王五"); //调用String的构造方法 new表示申请内存空间
//分析: 先在常量池中寻找“王五”,若常量池中没有这个对象,则在常量池中创建这个对象,若常量池中有则不创建,再通过new在堆中生成一个对象“王五” 最少创建一个对象
-
String类是最终类, 不能被继承
-
如果String类对象的值在编译期可以被确定,那么就使用已有的对象,否则会创建新的对象(方法在运行期得到结果)
String a = "a";
String a1 = a+1;
String a2 = "a1";
System.out.println(a1==a2) //false
final String b = "b";
String b1 = b+1;
String b2 = "b1";
System.out.println(b1==b2) //true
- 字符串常用方法
public char charAt(int index) //根据下标找到指定的字符
public char[] toCharArray() //以字符数组的形式返回全部的字符串内容
public String(char[] value) //将全部的字符数组变为字符串
public String(char[] value,int offset,int count) //将指定范围的字符数组变为字符串
public byte[] getBytes() //将字符串变为字节数组
public String(byte[] bytes) //将字节数组变为字符串
public String(byte[] bytes,int offset,int length) //将指定范围的字节数组变为字符串
public String(byte[] bytes, String charsetName) //通过使用指定的charset解码指定的byte数组,构造一个新的String
public boolean startsWith (String prefix) //从第一个位置开始判断是否以指定的内容开头
public boolean startsWith(String prefix, int toffset) //从指定的位置开始拼单是否以指定的内容开头
public boolean endsWith(String suffix) //判断是否以指定的内容结尾
public String replace(char oldChar,char newChar) //替换指定字符
public String replace(CharSequence target,CharSequence replacement) //替换指定字符串
public String replaceAll(String regex,String replacement) //替换指定的字符串
public String replaceFirst(String regex,String replacement) //替换第一个满足条件的字符串
public String substring(int beginIndex) //从指定位置开始一直截取到末尾
public String substring(int beginIndex,int endIndex) //截取指定范围的字符串
public String[] split(String regex) //按照指定的字符串拆分
public String[] split(String regex,int limit) //拆分字符串,并指定拆分的个数
//从后找 lastIndexOf
public boolean contains(String s) //返回一个字符串是否存在
public int indexOf(int ch) //从头查找指定的字符是否存在,char->int,如果存在则返回位置,不存在则返回-1
public int indexOf(int ch,int fromIndex) //从指定位置查找指定的字符是否存在,char->int,如果存在则返回位置,如果不存在则返回-1
public int indexOf(String str) //从头查找指定的字符串是否存在,如果存在则返回位置,如果不存在返回-1
public int indexOf(String str,int fromIndex) //从指定位置查找字符串是否存在,如果存在则返回位置,如果不存在则返回-1
public boolean isEmpty() //判断是否为空,指的是内容为空
public int length() //取得字符串的长度
public String toLowerCase() //转小写
public String toUpperCase() //转大写
public String trim() //去掉开头和结尾的空格,中间的空格不去
public String concat(String str) //字符串连接操作
StringBuffer
解决字符串相加时带来的性能问题(常量与变量) 常量相加没有性能问题(编译期进行优化)
StringBuffer的内部实现采用字符数组,默认数组的长度为16,超过数组大小时,动态扩充的算法是原来长度*2+2
(当我们预知要添加的数据长度时,建议使用带初始化容量的构造方法,来避免动态扩充的次数,提高效率)
StringBuffer sb = new StringBuffer();
sb.append(变量|常量).append(常量|变量);
- 常用方法
public StringBuffer() //构造一个空的StringBuffer对象
public StringBuffer(String str) //将指定的String变为StringBuffer的内容
public StringBuffer(charSequence seq) //接收CharSequence接口的实例
public StringBuffer append(数据类型 b) //提供了很多append()方法,用于进行字符串连接
public StringBuffer delete(int start,int end) //删除指定位置的内容
public int indexOf(String str) //字符串的查询功能
public StringBuffer insert(int offset,数据类型 b) //在指定位置上增加一个内容
public StringBuffer replace(int start,int end,String str) //将指定范围的内容替换成其他内容
public String substring(int start, int end) //截取指定范围的字符串
public String substring(int start) //字符串截取
public StringBuffer reverse() //字符串反转
StringBuilder
用在字符串缓冲区被单个线程使用的时候
字符串相加在编译后会使用Stringbuilder来优化代码实现拼接(每次都产生一个StringBuilder对象,最好手动创建StringBuilder来拼接)
StringBuffer和StringBuilder的区别
- Stringbuffer: 线程安全,性能低,适合在多线程使用
- StringBuilder: 线程不安全,性能高,适合在单线程中使用,占大多数
Math类
- 包含用于执行基本数学运算的方法(初等指数、对数、平方根和三角函数)
static double PI //pi的double值
abs(double a) //返回double值的绝对值
random() //返回带正号的double值,该值大于等于0.0且小于1.0
round(double a) //返回最接近参数并等于某一整数的double值
sqrt(double a) //返回正确舍入的double值的正平方根
- 使用
- 直接使用(Math所在的包java.lang为默认引入的包)
- 使用import static java.lang.Math.abs (floor); 静态导入 【直接使用abs() 或floor() 】
Random类
生成伪随机数
nextLong() //返回下一个伪随机数的long值
nextBoolean() //返回下一个伪随机数的boolean值
nextDouble() //返回下一个伪随机数,在0.0和1.0之间的double值
nextFloat() //返回下一个伪随机数,在0.0和1.0之间的float值
nextInt() //返回下一个伪随机数,int值
nextInt(int n) //返回一个伪随机数,在0(包括)和指定值分布的int值
日期操作类
Date类
Date date = new Date(); //实例化Date对象,表示当前时间,精确到毫秒
Calendar类
//日期类,使用此类可以将时间精确到毫秒显示
Calendar c = Calendar.getInstance();
Calendar c = new GregorianCalendar();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
int second = c.get(Calendar.SECOND);
int millisecond = c.get(Calendar.MILLISECOND);
StringBuilder sb = new StringBuilder(50);
sb.append(year).append("年").append(month)+append("月").append(day).append("日").append(hour).append(":").append(minute).append(":").append(second);
DateFormat类及子类SimpleDateFormat
DateFormat df = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss SSS");
String nowDate = df.format(new Date());
程序国际化
Locale类
//创建一个本地语言环境对象,该对象会根据参数设置来自动选择与之相关的语言环境
//参数:语言 地区
Locale locale_CN = new Locale("zh","CN");
//获取当前系统默认的语言环境
Locale locale_default = Locale.getDefault();
ResourceBundle类(只读)
-
国际化的实现的核心在于显示的语言上,通常的做法是将其定义成若干个属性文件(后缀是*.properties),属性文件中的格式采用“key=value”的格式进行操作
-
ResourceBundle类表示的是一个资源文件的读取操作,所有的资源文件需要使用ResourceBundle进行读取,读取的时候不需要加上文件的后缀
//用于绑定属性文件的工具类(参数:属性文件的基本名(前缀))
ResourceBundle r = ResourceBundle.getBundle("包.文件")
r.getString("key");
处理动态文本
java.text.MessageFormat [java.text.Format的子类]
对象比较器Comparable
- 自定义对象要实现比较排序,可以实现comparable接口的compareTo方法
public interface Comparable<T> {
public int compareTo(T o);
}
public class User implements Comparable<User>{
private int id;
private int age;
public User() {
}
public User(int id, int age) {
this.id = id;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", age=" + age +
'}';
}
public int compareTo(User o) {
return this.age - o.getAge();
}
}
public class Test {
public static void main(String[] args) {
User user1 = new User(1, 18);
User user2 = new User(2, 12);
User user3 = new User(3, 20);
User[] users = {user1, user2, user3};
Arrays.sort(users);
Arrays.stream(users).forEach(System.out::println);
}
}
- Comparator
实现该接口
对象的克隆
- 实现Cloneable接口
- 重写clone()方法
System
- 代表系统,系统级的很多属性和控制方法都放置在该类的内部(位于java.lang)
- 成员变量 包含in、out、err三个成员变量,分别代表标准输入流(键盘输入)、标准输出流(显示器)和标准错误输出流
- 成员方法
//数组拷贝: 将一个数组中的内容复制到另外一个数组中的指定位置(native(C或C++)方法,性能好)
public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
//返回当前的计算机时间
public static long currentTimeMillis()
//退出程序 status为0代表正常退出,非零代表异常退出
public static void exit(int status)
//请求系统进行垃圾回收
public static void gc()
//获得系统中属性名为key的属性对应的值
public static String getProperty(String key)
// java.version java运行时环境版本
// java.home java安装目录
// os.name 操作系统的名称
// os.version 操作系统的版本
// user.name 用户的账户名称
// user.home 用户的主目录
// user.dir 用户的当前工作目录
Runtime类
- 每个java应用程序都有一个Runtime类实例,使应用程序能够与其运行的环境相连接
//通过静态方法获取对象
Runtime rt = Runtime.getRuntime();
rt.availableProcessors() //处理器数量
rt.totalMemory() //Jvm总内存数
rt.freeMemory() //Jvm空闲内存数
rt.maxMemory() //Jvm可用最大内存数
//在单独的进程中执行指定的字符串命令
rt.exec("notepad") //打开记事本
数字处理工具类
BigInteger
- 可以让超出Integer范围内的数据进行运算
//构造方法
public BigInteger(String val)
//常用方法
public BigInteger add(BigInteger val)
public BigInteger subtract(BigInteger val)
public BigInteger multiply(BigInteger val)
public BigInteger divide(BigInteger val)
public BigInteger[] divideAndRemainder(BigInteger val)
//示例代码
String val1 = "12324354";
String val2 = "234354655";
BigInteger b1 = new BigInteger(val1);
BigInteger b2 = new BigInteger(val2);
b1.add(b2);
b1.substract(b2);
BigDecimal
- 计算小数(保证精度)
public BigDecimal add(BigDecimal augend);
public BigDecimal subtract(BigDecimal subtrahend);
public BigDecimal multiply(BigDecimal multiplicand);
public BigDecimal divide(BigDecimal divisor);
//示例代码
String val1="232.4343545";
String val2="232.31234343";
BigDecimal b1=new BigDecimal(val1);
BigDecimal b2 = new BigDecimal(val2);
b1.add(b2);
b1.subtract(b2);
b1.devide(b2); //除不尽报错
DecimalFormat
- 用最快的速度将数字格式化为你想要的样子
double pi = 3.1415927;
//取一位整数
new DecimalFormat("0").format(pi);
//取两位小数
new DecimalFormat("0.00").format(pi);
//取两位整数和三位小数,整数不足以0填补 03.142
new DecimalFormat("00.000").format(pi);
//取所有整数部分
new DecimalFormat("#").format(pi);
//以百分比的方式计数,并取两位小数
new DecimalFormat("#.##%").format(pi);
MD5工具类(信息摘要算法)
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
public class MD5Demo {
private static String savePassword = "pmq7VoTEWWLYh1ZPCDRujQ=="; //存储的密文
public static void main(String[] args) {
//test();
System.out.println(login("admin123456"));
}
private static boolean login(String password) {
if(savePassword.equals(md5(password))) {
return true;
}
return false;
}
//计算MD5的工具方法
private static String md5(String password) {
try {
MessageDigest md = MessageDigest.getInstance("md5");
byte[] bytes = md.digest(password.getBytes("UTF-8"));
String str = Base64.getEncoder().encodeToString(bytes);
return str;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
private static void test() {
String password = "admin123456";
try {
MessageDigest md = MessageDigest.getInstance("md5");
//通过MD5计算摘要
byte[] bytes = md.digest(password.getBytes("UTF-8"));
System.out.println(Arrays.toString(bytes));
String mdStr = new String(bytes);
//System.out.println(mdStr);
//BASE64编码算法 a-z A-Z 0-9 / * 用==结束 1.8
String str = Base64.getEncoder().encodeToString(bytes);
System.out.println(str);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
Lambda表达式
- 简化java中接口式的匿名内部类
// (参数1,参数2,...)->{...}
//没有参数
public class LambdaDemo {
public static void main(String[] args) {
IEat ieat = new IEatImpl();
ieat.eat();
IEat ieat2 = new IEat() {
public void eat() {
System.out.println("eat apple2");
}
};
ieat2.eat();
//Lambda表达式
IEat ieat3 = ()->{
System.out.println("eat apple3");
};
ieat3.eat();
}
}
//只有一个抽象方法的接口
interface IEat{
public void eat();
}
class IEatImpl implements IEat{
public void eat() {
System.out.println("eat apple");
}
}
//带参数 参数类型可以省略
public class LambdaDemo {
public static void main(String[] args) {
IEat ieat3 = (thing) -> System.out.println("eat..."+thing);
ieat3.eat("apple");
}
}
//只有一个抽象方法的接口
interface IEat{
public void eat(String thing);
}
//带返回值
public class LambdaDemo {
public static void main(String[] args) {
//IEat ieat3 = (thing,name) -> thing == null ? 1 : 0;
IEat ieat3 = (thing,name) -> {
System.out.println(name+"eat"+thing);
return 10;
};
ieat3.eat("大米", "老鼠");
}
}
//只有一个抽象方法的接口
interface IEat{
public int eat(String thing, String name);
}
//结合比较器
Arrays.sort(students,(o1,02)->o1.getAge()-o2.getAge());
System.out.println(Arrays.toString(students));
异常处理
- Throwable是异常的基类,分为Error和Exception,在编程中我们关注Exception
- Exception分为编译器异常(受检)和运行期异常(非受检)
- 异常会导致程序中断,无法继续执行
处理异常可以让程序继续运行 try{}catch(){}
catch可以有多个,顺序为从子类到父类
代码测试时: e.printStackTrace()
异常处理过程分析
- 一旦产生异常,则系统会自动产生一个异常类的实例化对象
- 若此时存在try语句,则会自动找到匹配的catch语句执行,如果没有异常处理,则程序退出,并由系统报告错误
- 所有的catch根据方法的参数匹配异常类的实例化对象,如果匹配成功,则表示由此catch进行处理
- finally 不管程序是否出现异常都会执行该代码块 (try里面有return语句时,先判断是否有Finally,有先执行Finally语句块,再return)
throw与throws关键字(配合使用)
- throws关键字主要在方法的声明上使用,表示方法中不处理异常,而交给调用处理。实际上对于Java程序来讲,如果没有加入任何的异常处理,默认由JVM进行异常处理操作。
- throw关键字表示程序中手动抛出一个异常,因为从异常机制来看,所有的异常一旦产生之后,实际上抛出的就是一个异常类的实例化对象,那么此对象也可以由throw直接抛出
自定义异常
public class MyException extends Exception{
public MyException() {
super();
}
public MyException(String message) {
super(message);
}
}
public class User {
private String username;
private String password;
private int age;
private String sex;
public User() {
super();
}
public User(String username, String password, int age, String sex) {
super();
this.username = username;
this.password = password;
this.age = age;
this.sex = sex;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + ", age=" + age + ", sex=" + sex + "]";
}
}
public class UserService {
public User login(String username,String password) throws MyException{
//排错法
if(!"admin".equals(username)) {
throw new MyException("用户名错误");
}
if(!"123456".equals(password)) {
throw new MyException("密码错误");
}
User user = new User("admin","123456",18,"男");
return user;
}
}
Exception 和RuntimeException的区别
- Exception: 受检异常,在编译期检查,在调用抛出这个异常的方法时,必须显示的使用try…catch…
- RuntimeException: 非受检异常,在运行期检查,在调用抛出这个异常的方法时,可以不用显示的使用try…catch
- 在使用自定义异常时,根据实际业务要求来决定使用哪个作为父类,RuntimeException用的会比较多
assert断言
使用assert要添加参数,给JVM传参