Java中常用的API— String、Math和System

Java中常用的API

1. API的概念与作用

API 中文名为应用程序编程接口;是指一些预定的函数。目的是提供应用程序与开发人员基于某软件或某硬件得以访问一组例程的能力,而又无需访问源码或理解工作的细节。

大白话就是别人写了个接口,我不必知道具体是怎么实现的,也不用去思考里面的构造怎么样的,我只需知道这个接口能实现怎么样的功能,我直接拿过来使用就可以了。

2. 一些常用的API
2.1 String
StringBuffer StringBuilder
线程安全,效率较低 线程不安全,效率较高
为了解决字符串操作导致的内存冗余和提高内存的效率,java提供
了StringBuffer 和 StringBuilder 两种方法来操作字符串。

这两个方法类似,只介绍StringBuffer
注意 以下代码中的方法全部基于构造方法
StringBuffer stringBuffer2 = new StringBuffer(“疫情结束,我要去吃火锅!!!”); 进行演示

//构造方法
StringBuffer stringBuffer = new StringBuffer();
StringBuffer stringBuffer2 = new StringBuffer("疫情结束,我要去吃火锅!!!");

//查看方法
System.out.println(stringBuffer2.toString());  //疫情结束,我要去吃火锅!!!
System.out.println(stringBuffer2.indexOf("火锅"));    // 9 
System.out.println(stringBuffer2.substring(5));	  //我要去吃火锅!!!
System.out.println(stringBuffer2.substring(5, 11));  //我要去吃火锅
System.out.println(stringBuffer2.length());  // 14

//两种添加方法
stringBuffer2.insert(3, "羊肉汤");  //在第3个字符后插入
stringBuffer2.append("油泼面,热干面"); //末尾插入

//修改方法
stringBuffer2.replace(0, 2, "夏天假期");  //夏天假期结束,我要去吃火锅(下标0开始,长度为2,修改成 夏天假期)
stringBuffer2.setCharAt(1, 'A'); // 使用字符A代替下标为 1 的字符

//删除
stringBuffer2.delete(0, 5); // 删除 疫情结束,
stringBuffer2.deleteCharAt(1); // 删除指定位置的字符

//反序
stringBuffer2.reverse(); // 反过来
2.2 Math数学类
方法 作用
public static double abs(double a); 绝对值
public static double ceil(double a); 向上取整
public static double floor(double a); 向下取整
public static double round(double a); 四舍五入
public static double random(); 随机数

在此处需要注意负数的四舍五入的取值

System.out.println(Math.round(-2.5)); // -2
System.out.println(Math.round(-2.4)); // -2
System.out.println(Math.round(-2.6)); // -3

是的,你没有看错, -2.5.的四舍五入是 -2。我们可以这样理解:就近原则, -2.4 离 -2 近,所以是 -2 ;-2.6离 -3 近,所以是 -3;当是 -2.5 的时候距离一样,哪个数值大是哪个,-2 比 -3 大,所以为 -2。

2.3 System类
方法 作用
long currentTimeMillis() 可以获取当前时间戳
Properties getProperties(); 获取系统属性的方法
arraycopy(Object src, int srcPos, Object dest, int destPos, int length); 数组拷贝
// 数组拷贝方法
  int[] arr = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10};
  int[] temp = new int[10];
  /**
  * Object src,  int  srcPos,   Object dest,   int destPos,   int length
  *   原数组  从原数组指定下标开始  目标数组  从目标数组指定下表开始 数据个数
  */
  System.arraycopy(arr, 0, temp, 1, arr.length - 2);
  // 输出结果 [0, 1, 3, 5, 7, 9, 2, 4, 6, 0]
  System.out.println(Arrays.toString(temp));
发布了9 篇原创文章 · 获赞 11 · 访问量 1800

猜你喜欢

转载自blog.csdn.net/weixin_43932553/article/details/104562483