简单API的使用
- API【Application Programming Interface 应用编程接口】
- API手册下载:oracle.com/java/technologies/javase-jdk8-doc-downloads.html
- API手册在线文档:docs.oracle.com/javase/6/docs/api/index.html
查文档方法:第一列是返回值,第二列是方法名和参数列表列举
java.lang(language包),使用时自动导包,包括java.lang.Object、java.lang.String、java.lang.StringBuilder/StringBuffer等等
一、Object类
1、概念
Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
2、常用方法
- boolean equals(Object obj)
—Indicates whether some other object is “equal to” this one.【指示其他某个对象是否与此对象“相等”】- String toString()
—Returns a string representation of the object.【返回该对象的字符串表示】- int hashCode()
—Returns a hash code value for the object.【返回该对象的哈希码值】- Class<?> getClass()
—Returns the runtime class of this Object.【返回此object的运行类】
3、测试
在这里插入代码片
二、String类
1、源码摘抄
public final class String{ ... }
String 是最终的类,不能被继承
String 底层维护了一个char[],数组长度不能改变,而且是final的,数组的值也不能被修改——也就是说字符串是一个常量,一旦定义不能修改。
private final char value[]
2、创建对象
- String(char[] value)
—Allocates a new String so that it represents the sequence of characters currently contained in the character array argument.
- 方法一:new String(char[]);
- 方法二:String s = “abcd”;
如果是第一次使用字符串,java会在常量池中创建一个对象,当再次使用相同的内容时,会直接访问常量池中存在的对象。
3、常用方法
4、测试
package cn.tonyoliver.api;
import java.util.Arrays;
/**
* 这个类用来测试String类
* @author Tony
*
*/
public class Test02_String {
public static void main(String[] args) {
// 创建字符串对象(字符串底层维护了一个char[]数组,而且是final的,也就是数组长度不能改,数组里的值也不能改.---字符串是一个常量!)
char[] c = new char[] {'a','b','c'};
String s = new String(c);//触发char[]类型的含参构造
String str = "abc";//直接赋值,存在堆内存中的常量池中---高效---因为常量池的相同数据,只会存一次
String str2 = "abc";
System.out.println(str == str2);//true 相同数据,拥有相同的存储空间,内存中就是相同的地址值
System.out.println(s == str);//false 在堆里的地址值,str在常量池的地址值不相同
// 常用方法
System.out.println(s.charAt(1));// 根据下标获取对应的字符
System.out.println(s.concat("abc"));// 在字符串的末尾处拼接指定字符串
System.out.println(s.contains("bc"));// 判断是否包含指定的字符串
System.out.println(s.endsWith("c"));// 判断字符串是否以指定后缀结尾
System.out.println(s.equals(str));// 判断字符串是否与指定的字符串相等【底层已经完成了方法的重写】
System.out.println(s.indexOf("a"));// 获取指定字符串在s中出现的第一次的下标值
System.out.println(s.lastIndexOf("a"));// 获取指定字符串在s中出现的最后一次的下标值
System.out.println(s.isEmpty());// 判断字符串是否
System.out.println(s.length());// 获取字符串的长度
System.out.println(s.replace('a', '0'));// 把旧字符用新字符替换
System.out.println(s.startsWith("ab"));// 判断字符串是否以指定字符串开始
System.out.println(s.substring(1));// 从指定下标处开始截取所有字符串
System.out.println(s.substring(0,2));// 从指定下标开始,到指定下标结束,截取中间段,含头不含尾
System.out.println(s.toLowerCase());// 自动转成小写
System.out.println(s.toUpperCase());// 自动转成大写
System.out.println(s.trim());// 返回字符串的副本,去除前导空白和尾部空白
String num = String.valueOf(123);// 用来把各种类型的数据,转成String类型
System.out.println(num+1);
System.out.println("-----字符串转数组- - - - -");
byte[] bs = s.getBytes();// 转换成整数存在数组里
System.out.println(Arrays.toString(bs));
char[] cs = s.toCharArray();// 将此字符串转换成一个新的char[]字符数组
System.out.println(cs);
String[] ss = s.split(" ");// 按照指定的规则切割字符串
System.out.println(Arrays.toString(ss));
}
}
package cn.tonyoliver.api;
import java.util.Scanner;
/**
* 这个用来接收键盘输入的整数字符串,并求和
* @author Tony
*
*/
public class Test02_String1 {
public static void main(String[] args) {
System.out.println("请输入一串数字:");
String str = new Scanner(System.in).nextLine();
int sum = 0;
for (int i = 0; i < str.length(); i++) {
sum = sum + str.charAt(i) - 48;
}
System.out.println("和为"+sum);
}
}
三、StringBuilder/StringBuffer
【一般不用】
1、源码摘抄
public final class StringBuilder{ ... }
是final类,不可以被继承;
底层仍像String一样,维护了一个char[],只不过值可以随时被修改
char[] value
2、这两个工具类专门用来优化字符串的拼接操作
3、创建对象
- StringBuilder()
—Constructs a string builder with no characters in it and an initial capacity of 16 characters.【构造一个不带任何字符的字符串生成器,其初始容量为16个字符】- initial capacity of 16 characters.
- int newCapacity = value.length * 2 + 2;
4、常用方法
- StringBuilder append(String str)
— Appends the specified string to this character sequence.- StringBuilder insert(int offset, String str)
—Inserts the string into this character sequence.- char charAt(int index)
— Returns the char value in this sequence at the specified index.
5、测试
package cn.tonyoliver.api;
/**
* 测试字符串拼接优化的工具类 StringBuilder/StringBuffer
*
* @author Tony 总结: 1.String通过+拼接字符串效率低,但是就两三次的话就无所谓
* 2.如果有大量的字符串有拼接需求,建议使用工具类StringBuffer/StringBuilder
* 3.StringBuilder/StringBuffer都是用来在原有数据基础上 追加指定的拼接内容,拼接内容的数据类型非常丰富
*/
public class Test03_StringBuffer {
public static void main(String[] args) {
method();// 先用普通方式+拼接字符串
}
private static void method() {
// 将指定的字符串拼接10000次
String s = "abcdefghijklmnopqrstuvwxyz";
// 创建工具类对象
StringBuilder sb = new StringBuilder();
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
sb.append(s);
}
// String res = "";
// // System.currentTimeMillis()用于获取系统时间
// long start = System.currentTimeMillis();
// for (int i = 0; i < 10000; i++) {
// res = res + s;
// }
long end = System.currentTimeMillis();
System.out.println(end - start);// 单位是毫秒
// System.out.println(res);// console会显示空白,因为装不下,全选复制可以发现程序已经拼接完成
}
}
四、包装类
1、用来给对应的基本类型提供更加丰富的功能
基本类型 | byte | short | int | long | float | double | boolean | char |
---|---|---|---|---|---|---|---|---|
包装类型 | Byte | Short | Integer | Long | Float | Double | Boolean | Character |
2、包装类型里的数字类型的父类是Number
Number是一个抽象的父类:
public abstract class Number{...}
方法
3、Integer
- 用来包装基本类型int,提供更加丰富的功能。
- 创建对象
- Integer(int value):构造一个 新分配的Integer对象,它表示指定的int值。
- static Integer valueOf(int i):返回一个表示指定int值的Integer实例。如果数据在-128~127之间(缓存区)是高效的,相同数据只会创建一次。
- 方法:
- int intValue()
— Returns the value of this Integer as an int.- static int parseInt(String s)
—Parses the string argument as a signed decimal integer.
- 测试
package cn.tonyoliver.api;
/**
* 这个类用来测试包装类 包装类的目的是为基本类型提供丰富的功能
*
* @author Tony
*
*/
public class Test01_Number {
public static void main(String[] args) {
// 创建对象 -- 就是把基本类型的5变成包装类型
Integer i = new Integer(5);
Integer i2 = Integer.valueOf(5);// 如果数据在-128~127之间是高效的,相同数据只会创建一次
Integer i3 = Integer.valueOf(5);
Integer i4 = Integer.valueOf(130);
System.out.println(i2 == i3);// 在范围内就高效
System.out.println(i2 == i4);// 超出范围就不高效
// 常用方法
int num = i.intValue();// 就是把包装类型转换成基本类型
System.out.println(num);
int num2 = Integer.parseInt("123");// 把字符串类型的数字转换成int类型
System.out.println(num2);
// 创建对象 -- 就是把基本类型的5变成包装类型
Double d = new Double(5);
Double d2 = Double.valueOf(5);// 静态方法valueOf和new效率一样
// 常用方法
double numd = d.doubleValue();// 就是把包装类型转换成基本类型
System.out.println(numd);
double num2d = Double.parseDouble("123");// 把字符串类型的数字转换成double类型
System.out.println(num2d);
}
}
五、Date日期类
1、概念
类Date表示特定的瞬间,精确到毫秒。
2、创建对象
- Date()
— Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.【分配Date对象并初始化此对象,以表示分配它的时间(精确到毫秒)】
3、常用方法
4、测试
package cn.tonyoliver.api;
import java.util.Date;
/**
* 这个类用来测试Date日期类
* @author Tony
*
*/
public class Test02_Date {
public static void main(String[] args) {
// 创建对象
Date date = new Date();
// 常用方法
System.out.println(date.getDate());// 返回当前是本月的第几天
System.out.println(date.getDay());// 返回当前是星期几
System.out.println(date.getHours());// 返回当前是几点
System.out.println(date.getMinutes());// 返回当前是几分
System.out.println(date.getMonth());// 返回当前月-1【normalize().getMonth() - 1】
System.out.println(date.getSeconds());// 返回当前是几秒
System.out.println(date.getTime());// 1970年1月1日00:00:00 GMT【格林尼治时间】以来此Date对象表示的毫秒值
System.out.println(date.getYear());// 返回当前年份-1900
System.out.println(date.toLocaleString());// 将当前时间以yyyy-MM-dd HH:mm:ss格式输出
}
}
六、日期工具SimpleDateFormat
【字符串和Date对象的相互转换】
1、概念
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization.
2、创建对象
- SimpleDateFormat(String pattern)
—Constructs a SimpleDateFormat using the given pattern and the default date format symbols for the default locale.
pattern有如下形式:
- yyyy-MM-dd HH:mm:ss
- MM/dd/yyyy
时间模式字母表
3、常用方法
- String format(Date date)
—把Date类型的日期格式化为文本类型- Date parse(String text, ParsePosition pos)
—解析字符串的文本,生成 Date。
4、测试
package cn.tonyoliver.api;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
/**
* 这个类用来测试simpleDateFormat日期工具类
* @author Tony
*接收用户输入的出生日期,计算存活天数
*/
public class Test03_SDFormat {
public static void main(String[] args) throws Exception {
//接收用户输入的出生日期
System.out.println("请输入您的生日:");
String birthday = new Scanner(System.in).nextLine();
// 把字符串类型的日期转换成Date类型
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date birth = sdf.parse(birthday);
//获取出生日期对应的毫秒值
long start = birth.getTime();
//获取当前的系统的时间的毫秒值
long now = System.currentTimeMillis();
//计算存活天数
System.out.println((now-start)/1000/60/60/24);
}
}
七、BigDicimal/BigInteger
1、BigDecimal
常用来坐浮点数运算不精确的解决方案,可以把以前的±*/运算优化成两个对象间的运算。
BigInteger
用来解决超大的整数运算
2、创建对象
- BigDecimal(double val) —有坑,不建议用
—Translates a double into a BigDecimal which is the exact decimal representation of the double’s binary floating-point value.- BigDecimal(String val) --建议用这个
—Translates the string representation of a BigDecimal into a BigDecimal.
3、常用方法
- BigDecimal add(BigDecimal augend)
—Returns a BigDecimal whose value is (this + augend), and whose scale is max(this.scale(), augend.scale()).- BigDecimal subtract(BigDecimal subtrahend)
—Returns a BigDecimal whose value is (this - subtrahend), and whose scale is max(this.scale(), subtrahend.scale()).- BigDecimal multiply(BigDecimal multiplicand)
—Returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()).- BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)
—Returns a BigDecimal whose value is (this / divisor), and whose scale is as specified.
4、测试
package cn.tonyoliver.api;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Scanner;
/**
* 这个类用来测试BigDecimal
* @author Tony
*
*/
public class Test04_BigDecimal {
public static void main(String[] args) {
//method();//暴露精确问题
method2();//优化运算过程
}
private static void method2() {
// 接收用户输入的两个小数
System.out.println("请输入两个小数");
double a = new Scanner(System.in).nextDouble();
double b = new Scanner(System.in).nextDouble();
// 创建对象
// BigDecimal aa = new BigDecimal(String.valueOf(a));
// BigDecimal bb = new BigDecimal(String.valueOf(b));
BigDecimal aa = new BigDecimal(a+"");
BigDecimal bb = new BigDecimal(b+"");
System.out.println(aa.add(bb));
System.out.println(aa.subtract(bb));
System.out.println(aa.multiply(bb));
//System.out.println(aa.divide(bb));//除不尽会抛出java.lang.ArithmeticException异常
System.out.println(aa.divide(bb,5,BigDecimal.ROUND_HALF_UP));
}
private static void method() {
// 接收用户输入的两个小数
System.out.println("请输入两个小数");
double a = new Scanner(System.in).nextDouble();
double b = new Scanner(System.in).nextDouble();
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/b);
}
}