😹 作者: gh-xiaohe
😻 gh-xiaohe的博客
😽 觉得博主文章写的不错的话,希望大家三连(✌关注,✌点赞,✌评论),多多支持一下!!!
String:字符串,使用一对""引起来表示。
1.String声明为final的,不可被继承
2.String实现了Serializable接口:表示字符串是支持序列化的。
实现了Comparable接口:表示String可以比较大小
3.String内部定义了final char[] value用于存储字符串数据
4.String:代表不可变的字符序列。简称:不可变性。
体现:1.当对字符串重新赋值时,需要重写指定内存区域赋值,不能使用原有的value进行赋值。
2.当对现有的字符串进行连接操作时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值。
3.当调用String的replace()方法修改指定字符或字符串时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值。
5.通过字面量的方式(区别于new)给一个字符串赋值,此时的字符串值声明在字符串常量池中。
6.字符串常量池中是不会存储相同内容的字符串的。
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zI7wd16N-1663379300462)(面试题.assets/image-20220917092134240.png)]](https://1000bd.com/contentImg/2023/11/07/200914871.png)
@Test
public void Test1(){
// 当对字符串重新赋值时,需要重写指定内存区域赋值,不能使用原有的value进行赋值。
String s1 = "abc"; //字面量的定义方式
String s2 = "abc";
s1 = "hello";
System.out.println(s1 == s2);//比较s1和s2的地址值
System.out.println(s1);//hello
System.out.println(s2);//abc
System.out.println("*********************");
// 当对现有的字符串进行连接操作时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值
String s3 = "abc";
s3 += "def";
System.out.println(s3);//abcdef
System.out.println(s2);//怎么证明是新造了而不是修改了,看s2是否还是abc
System.out.println("**********************");
// 当调用String的replace()方法修改指定字符或字符串时,也需要重新指定内存区域赋值,不能使用原有的value进行赋
String s4 = "abc";
String s5 = s4.replace('a', 'm');//修改第一个位置上的字符a改成m
System.out.println(s4);//abc
System.out.println(s5);//mbc
}
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4A4IRZvi-1663379300463)(面试题.assets/image-20220917093827741.png)]](https://1000bd.com/contentImg/2023/11/07/200914690.png)



String的实例化方式
方式一:通过字面量定义的方式
方式二:通过new + 构造器的方式
面试题:String s = new String("abc");方式创建对象,在内存中创建了几个对象?
两个:(常量池中未声明)一个是堆空间中new结构,另一个是char[]对应的常量池中的数据:"abc"
(常量池中声明)一个是堆空间中new结构,引用常量池中的数据“abc"
@Test
public void test2(){
//通过字面量定义的方式:此时的s1和s2的数据javaEE声明在方法区中的字符串常量池中。
String s1 = "javaEE";
String s2 = "javaEE";
//通过new + 构造器的方式:此时的s3和s4保存的地址值,是数据在堆空间中开辟空间以后对应的地址值。
String s3 = new String("javaEE");
String s4 = new String("javaEE");
System.out.println(s1 == s2);//true
System.out.println(s1 == s3);//false
System.out.println(s1 == s4);//false
System.out.println(s3 == s4);//false
System.out.println("***********************");
Person p1 = new Person("Tom",12);// 字面量的方式
Person p2 = new Person("Tom",12);
System.out.println(p1.name.equals(p2.name));//true
System.out.println(p1.name == p2.name);//true
p1.name = "Jerry";
System.out.println(p2.name);//Tom
}


![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FLc7xQIp-1663396434875)(面试题.assets/image-20220917143035603.png)]](https://1000bd.com/contentImg/2023/11/07/200914961.png)
结论
1.常量与常量的拼接结果在常量池。且常量池中不会存在相同内容的常量。
2.只要其中有一个是变量,结果就在堆中
3.如果拼接的结果调用intern()方法,返回值就在常量池中
4.final 修饰String表示常量 final String s4 = "javaEE";
@Test
public void test3(){
String s1 = "javaEE";
String s2 = "hadoop";
String s3 = "javaEEhadoop";
String s4 = "javaEE" + "hadoop";
String s5 = s1 + "hadoop";
String s6 = "javaEE" + s2;
String s7 = s1 + s2;
System.out.println(s3 == s4);//true
System.out.println(s3 == s5);//false
System.out.println(s3 == s6);//false
System.out.println(s5 == s6);//false
System.out.println(s3 == s7);//false
System.out.println(s5 == s6);//false
System.out.println(s5 == s7);//false
System.out.println(s6 == s7);//false
String s8 = s5.intern();//返回值得到的s8使用的常量值中已经存在的“javaEEhadoop”
System.out.println(s3 == s8);//true
}
@Test
public void test4(){
String s1 = "javaEEhadoop";
String s2 = "javaEE";
String s3 = s2 + "hadoop";
System.out.println(s1 == s3);//false
final String s4 = "javaEE";//s4:常量
String s5 = s4 + "hadoop";
System.out.println(s1 == s5);//true
}


@Test
public void Test1(){
String s1 = "helloworld";
System.out.println(s1.length());//10
System.out.println(s1.charAt(0));//h
System.out.println(s1.charAt(9));//d
// System.out.println(s1.charAt(10));
// s1 = "";
System.out.println(s1.isEmpty());//判断数组的长度是否为空
String s2 = s1.toLowerCase();
System.out.println(s1);//s1不可变的,仍然为原来的字符串
System.out.println(s2);//改成小写以后的字符串
String s3 = " he llo world ";
String s4 = s3.trim();
System.out.println("-----" + s3 + "-----");
System.out.println("-----" + s4 + "-----");
}
@Test
public void test2(){
String s1 = "HelloWorld";
String s2 = "helloworld";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true
String s3 = "abc";
String s4 = "abc" + "def";
// String s4 = s3.concat("def");
System.out.println(s4);//abcdef
String s5 = "abc";//a 97
String s6 = new String("abe");
System.out.println(s5.compareTo(s6));//-2 //涉及到字符串的排序 减法操作
String s7 = "北京尚硅谷教育";
String s8 = s7.substring(2);
System.out.println(s7);//北京尚硅谷教育
System.out.println(s8);//尚硅谷教育
String s9 = s7.substring(0, 2);
System.out.println(s9);//北京
}
@Test
public void test3(){
String str1 = "helloworld";
boolean b1 = str1.endsWith("rld");
System.out.println(b1);//true
boolean b2 = str1.startsWith("He");
System.out.println(b2);
boolean b3 = str1.startsWith("ll",2);
System.out.println(b3);
String str2 = "wor";
System.out.println(str1.contains(str2));
System.out.println("*************");
System.out.println(str1.indexOf("lo"));//3
System.out.println(str1.indexOf("lol"));//没有的话返回 -1
System.out.println(str1.indexOf("lo",5));
String str3 = "hellorworld";
System.out.println(str3.lastIndexOf("or"));//7
System.out.println(str3.lastIndexOf("or",6));
//什么情况下,indexOf(str)和lastIndexOf(str)返回值相同?
//情况一:存在唯一的一个str。情况二:不存在str
}
@Test
public void test4(){
String str1 = "北京尚硅谷教育北京";
String str2 = str1.replace('北','东');
System.out.println(str1);//北京尚硅谷教育北京
System.out.println(str2);//东京尚硅谷教育东京
String str3 = str1.replace("北京", "上海");
System.out.println(str3);//上海尚硅谷教育上海
System.out.println("*************************");
String str = "12hello34world5java7891mysql456";
//把字符串中的数字替换成,,如果结果中开头和结尾有,的话去掉
String string = str.replaceAll("\\d+", ",");
String string1 = str.replaceAll("\\d+", ",").replaceAll("^,|,$", "");//开头结尾有 ,给去掉
System.out.println(string);,hello,world,java,mysql, 把数字换成 “,”
System.out.println(string1);//hello,world,java,mysql
System.out.println("*************************");
str = "12345";
//判断str字符串中是否全部有数字组成,即有1-n个数字组成
boolean matches = str.matches("\\d+");
System.out.println(matches);
String tel = "0571-4534289";
//判断这是否是一个杭州的固定电话
boolean result = tel.matches("0571-\\d{7,8}");
System.out.println(result);
System.out.println("*************************");
str = "hello|world|java";
String[] strs = str.split("\\|");
for (int i = 0; i < strs.length; i++) {
System.out.println(strs[i]);
}
System.out.println();
str2 = "hello.world.java";
String[] strs2 = str2.split("\\.");
for (int i = 0; i < strs2.length; i++) {
System.out.println(strs2[i]);
}
}
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-b9p28IzR-1663408343342)(面试题.assets/image-20220917162158452.png)]](https://1000bd.com/contentImg/2023/11/07/200914815.png)
@Test
public void test1(){
String str1 = "123";
// int num = (int)str1;//错误的
int num = Integer.parseInt(str1);
String s2="abc";
boolean b1 = Boolean.parseBoolean(s2);
System.out.println(s2);
String str2 = String.valueOf(num); //"123"
System.out.println(str2);
// 或者
String str3 = num + "";//在堆里面 "123"
System.out.println(str1 == str2); //false
System.out.println(str1 == str3); //false
}
@Test
public void test2(){
String str1 = "abc123"; //题目: a21cb3
char[] charArray = str1.toCharArray();
for (int i = 0; i < charArray.length; i++) {
System.out.println(charArray[i]);
}
char[] arr = new char[]{'h','e','l','l','o'};
String str2 = new String(arr);
System.out.println(str2);
}
@Test
public void test3() throws UnsupportedEncodingException {
String str1 = "abc123中国";
byte[] bytes = str1.getBytes();//使用默认的字符编码集,进行转换
System.out.println(Arrays.toString(bytes));//数组的循环 [97, 98, 99, 49, 50, 51, -28, -72, -83, -27, -101, -67]
byte[] gbks = str1.getBytes("gbk");//使用GDK字符集进行编码。
System.out.println(Arrays.toString(gbks)); // [97, 98, 99, 49, 50, 51, -42, -48, -71, -6]
System.out.println("*****************************");
String str2 = new String(bytes);//使用默认的字符集,进行解码。
System.out.println(str2); // abc123中国
String str3 = new String(gbks);
System.out.println(str3);//出现乱码。原因:编码集和解码集不一致! abc123�й�
String str4 = new String(gbks,"gbk"); // 编码集 解码集
System.out.println(str4);//没有出现乱码。原因:编码集和解码集一致! abc123中国
}

String 与StringBuffer、StringBuilder之间的转换
String -->StringBuffer、StringBuilder:调用StringBuffer、StringBuilder构造器
StringBuffer、StringBuilder -->String: ①调用String构造器;
②StringBuffer、StringBuilder的toString()
关于StringBuffer和StringBuilder的使用 String、StringBuffer、StringBuilder三者的异同?
String:不可变的字符序列;底层使用char[]存储
StringBuffer:可变的字符序列;线程安全的,效率低;底层使用char[]存储
StringBuilder:可变的字符序列;jdk5.0新增的,线程不安全的,效率高;底层使用char[]存储
源码分析:
问题:
意义:开发中建议大家使用:StringBuffer(int capacity) 或 StringBuilder(int capacity)为了避免扩容,再去复制,制定容量,效率高一些
// StringBuffer 调用父类中的的append方法
@Override
public synchronized StringBuffer append(String str) {
toStringCache = null;
super.append(str);
return this;
}
// 父类(AbstractStringBuilder)中的append方法
public AbstractStringBuilder append(String str) {
if (str == null) // 判断是否为空
return appendNull(); // 避免了空指针
int len = str.length(); // 获取需要添加字符串的长度
ensureCapacityInternal(count + len); // 确保容量是够的
str.getChars(0, len, value, count);
count += len;
return this;
}
// 上面的ensureCapacityInternal方法 确保容量是够的
private void ensureCapacityInternal(int minimumCapacity) {
// overflow-conscious code
if (minimumCapacity - value.length > 0) { // 数组容量不够扩容
value = Arrays.copyOf(value,newCapacity(minimumCapacity));// 把原有的数据 copy到新的数据中
}
}
// 上面的newCapacity方法 扩容的规则
private int newCapacity(int minCapacity) {
// overflow-conscious code
int newCapacity = (value.length << 1) + 2; // value.length 原有的长度 左移一位 (类似以*2(比*效率高))
// 扩容为原来的二倍 + 2
// 一些特殊情况的处理: 如添加的字符串的长度特别的长 *2 + 2 的容量还不够
if (newCapacity - minCapacity < 0) { // 就用 传递过来的长度当做 容量
newCapacity = minCapacity;
}
// 左移一位有个范围 超过这个范围就会变成负数
return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
? hugeCapacity(minCapacity)
: newCapacity;
}
@Test
public void test1() {
StringBuffer sb1 = new StringBuffer("abc");
sb1.setCharAt(0, 'm');
System.out.println(sb1); // 可变 sb1的值发生改变
StringBuffer sb2 = new StringBuffer();
System.out.println(sb2.length()); // 0
}
StringBuffer delete(int start,int end):删除指定位置的内容
StringBuffer replace(int start, int end, String str):把[start,end)位置替换为str
StringBuffer insert(int offset, xxx):在指定位置插入xxx
StringBuffer reverse():把当前字符序列逆转
public int indexOf(String str):当前首次出现的位置
public String substring(int start,int end):返回一个从start开始到end索引结束的左闭右开区间的子字符串
public int length()
public char charAt(int n ):返回指定位置的字符
public void setCharAt(int n ,char ch):将指定位置的字符改成新的
总结:
@Test
public void test2() {
StringBuffer s1 = new StringBuffer("abc");
s1.append(1);
s1.append('2');
System.out.println(s1);//abc12
// s1.delete(2,4);ab1
// s1.replace(2,4,"hello");ab hello 1
// s1.insert(2,false); ab false c11
// s1.reverse();//反转
String s2 = s1.substring(1, 3);
System.out.println(s1);//abc11
System.out.println(s1.length());//5
System.out.println(s2);//bc
char c2 = s1.charAt(2);
System.out.println(c2);//c
}
从高到低排列:StringBuilder > StringBuffer > String
@Test
public void test3() {
// 初始设置
long startTime = 0L;
long endTime = 0L;
String text = "";
StringBuffer buffer = new StringBuffer("");
StringBuilder builder = new StringBuilder("");
// 开始对比
startTime = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
buffer.append(String.valueOf(i)); // 变成基本数据类型 往里面添加
}
endTime = System.currentTimeMillis();
System.out.println("StringBuffer的执行时间:" + (endTime - startTime)); // StringBuffer的执行时间:2
startTime = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
builder.append(String.valueOf(i));
}
endTime = System.currentTimeMillis();
System.out.println("StringBuilder的执行时间:" + (endTime - startTime)); // StringBuilder的执行时间:1
startTime = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
text = text + i;
}
endTime = System.currentTimeMillis();
System.out.println("String的执行时间:" + (endTime - startTime)); // String的执行时间:703
}
public String myTrim(String str) {
if (str != null) {
int start = 0;// 用于记录从前往后首次索引位置不是空格的位置的索引
int end = str.length() - 1;// 用于记录从后往前首次索引位置不是空格的位置的索引
while (start < end && str.charAt(start) == ' ') {
start++;
}
while (start < end && str.charAt(end) == ' ') {
end--;
}
if (str.charAt(start) == ' ') {
return "";
}
return str.substring(start, end + 1);
}
return null;
}
方式一:转换为char[](冒泡排序)
public String reverse(String str,int startIndex,int endIndex){
if(str != null && str.length() != 0) {//str.length() != 0 创建一个长度为0的char型数组,容易出现角标越界
char[] arr = str.toCharArray();
for (int x = startIndex, y = endIndex; x < y; x++, y--) {
char temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
return new String(arr);
}
return null;
}
方式二:使用String的拼接
①截取出从0到开始索引的子串
②遍历(倒序)从结束到开始的下标,在和子串拼接
③在拼接,从结束索引到结尾的子串
public String reverse2(String str, int startIndex, int endIndex) {
if(str != null) {
// 第一部分
String reverStr = str.substring(0,startIndex);// ab
// 第二部分
for (int i = endIndex; i >= startIndex; i--) {//到着取,取字符拼接到str当中
reverStr += str.charAt(i);
} // abfedc
// 第三部分
reverStr += str.substring(endIndex + 1);//从他的后一位开始一直到末尾 拼接起来
return reverStr;
}
return null;
}
方式三:使用StringBuffer/StringBuilder替换String
优化方式二,让其效率高一些StringBuffer(非多线程效率高)/StringBuilder
public String reverse3(String str, int startIndex, int endIndex) {
StringBuilder builder = new StringBuilder(str.length()); // 创建和String字符串相同长度的字符串
if(str != null) {
//第一部分
builder.append(str.substring(0, startIndex));
//第二部分
for (int i = endIndex; i >= startIndex; i--) {
builder.append(str.charAt(i));
}
//第三部分
builder.append(str.substring(endIndex + 1));
return builder.toString(); //StringBuilder -> String
//String.valueOf(builder); //基本、包装 -> String
}
return null;
}
比如:获取“ ab”在“abkkcadkabkebfkabkskab” 中出现的次数
①使用indexOf:返回子串出现第一次出现的索引
②在此查找剩下的字符串,剩下字符串的其实索引(第一次返回出的索引 + 需要查找字符穿的长度)
/**
* 获取subStr在mainStr中出现的次数
* @param mainStr 主串
* @param subStr 需要查找的字符串
*/
public int getCount(String mainStr,String subStr){
int mainLength = mainStr.length();
int subLength = subStr.length();
int count = 0;
int index = 0;
if(mainLength >= subLength){
//方式一:
// while((index = mainStr.indexOf(subStr)) != -1){
// count++;
// mainStr = mainStr.substring(index + subStr.length());
// }
//方式二:对方式一的改进 与上面的区别是没有给mainStr重新赋值,就是用mainStr重头往后面找
while((index = mainStr.indexOf(subStr,index)) != -1){
count++;
index += subLength;
}
return count;
}else{
return 0;
}
}
str1 = "abcwerthelloyuiodef“;str2 = “cvhellobnm”
提示:将短的那个串进行长度依次递减的子串与较长的串比较。
①contains判断是否包某个字符串
②两大轮查找(for),从开始像后搓位
//前提:两个字符串中只有一个最大相同子串
public String getMaxSameString(String str1,String str2){
if(str1 != null && str2 != null){
String maxStr = (str1.length() >= str2.length())? str1 : str2;//true 返回第一个
String minStr = (str1.length() < str2.length())? str1 : str2;
int length = minStr.length(); // 表示轮数(短字符的长度)
for(int i = 0;i < length;i++){//外层多少大轮 每一轮去一个字符串,
// 开始条件 x 表示头 y 表示尾 y <= length 最后一轮 (去尾操作)
// 迭代条件 x++,y++举例:(原长度)cvhellobnm 1轮 cvhellobn 去掉个m 不是为找到 搓一位 vhellobnm (长度不变)
// 结束条件 就是 y搓到 尾就要结束 (原长度)cvhellobnm 搓到结尾 m (搓到末尾的m就不能在搓了)
for(int x = 0,y = length - i;y <= length;x++,y++){//3 去尾操作 未找到 错一位
String subStr = minStr.substring(x,y);//2 截取
if(maxStr.contains(subStr)){//1
return subStr;
}
}
}
}
return null;
}
// 如果存在多个长度相同的最大相同子串
public String[] getMaxSameString1(String str1, String str2) {
if (str1 != null && str2 != null) {
StringBuffer sBuffer = new StringBuffer();
String maxString = (str1.length() > str2.length()) ? str1 : str2;
String minString = (str1.length() > str2.length()) ? str2 : str1;
int len = minString.length();
for (int i = 0; i < len; i++) {
for (int x = 0, y = len - i; y <= len; x++, y++) {
String subString = minString.substring(x, y);
if (maxString.contains(subString)) {
sBuffer.append(subString + ",");// 找到就添加 用,号隔开
}
}
if (sBuffer.length() != 0) {// 如果找到的,举例相同的长度子串长度为6 就不在向下找了
break;
}
}
// 正则 sBuffer 转换成数组 把结尾,号变成空 在此基础上用,号进行切割
String[] split = sBuffer.toString().replaceAll(",$", "").split("\\,");
return split;
}
return null;
}
@Test
public void testGetMaxSameString(){
String str1 = "abcwerthello1yuiodefabcdef";
String str2 = "cvhello1bnmabcdef";
String[] maxSameStrings = getMaxSameString1(str1, str2);
System.out.println(Arrays.toString(maxSameStrings));
}
提示:
@Test
public void testSort() {
String str = "abcwerthelloyuiodef";
char[] arr = str.toCharArray();
Arrays.sort(arr);
String newStr = new String(arr);
System.out.println(newStr);
}
System类提供的System用来返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差。
此方法适于计算时间差。
@Test
public void test1(){
long time = System.currentTimeMillis();
//返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差。
//称为时间戳
System.out.println(time);
}
java.util.Date类 —> 表示特定的瞬间,精确到毫秒
|—java.sql.Date类
@Test
public void test2(){
//构造器一:Date():创建一个对应当前时间的Date对象
Date date1 = new Date();
System.out.println(date1.toString()); //Sun Feb 07 19:56:04 CST 2021
System.out.println(date1.getTime()); //1612698891517
//构造器二:创建指定毫秒数的Date对象
Date date2 = new Date(1612698891517L);
System.out.println(date2.toString());
//创建java.sql.Date对象
java.sql.Date date3 = new java.sql.Date(35235325345L);
System.out.println(date3); //1971-02-13
//如何将java.util.Date对象转换为java.sql.Date对象
//情况一:
// java.util.Date date4 = new java.sql.Date(2343243242323L);多态
// java.sql.Date date5 = (java.sql.Date) date4;
//情况二:
Date date6 = new Date();
java.sql.Date date7 = new java.sql.Date(date6.getTime());
}
如何将java.util.Date对象转换为java.sql.Date对象
@Test
public void test2(){
//如何将java.sql.Date对象转换为java.util.Date对象
java.util.Date date4 = new java.sql.Date(1663491677160L);// 多态直接赋值
//如何将java.util.Date对象转换为java.sql.Date对象
// 情况一: 强转 子类 赋给父类
java.sql.Date date5 = (java.sql.Date) date4;
System.out.println(date5);
// 情况二: 时间戳
Date date6 = new Date();
java.sql.Date date7 = new java.sql.Date(date6.getTime());
System.out.println(date7);
}
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vIgJngTK-1663498326041)(面试题.assets/image-20220918184019072.png)]](https://1000bd.com/contentImg/2023/11/07/200914681.png)
①默认的解析方式(默认的构造器)
@Test
public void testSimpleDateFormat() throws ParseException {
//实例化SimpleDateFormat:使用默认的构造器
SimpleDateFormat sdf = new SimpleDateFormat();
//格式化format:日期--->字符串
Date date = new Date();
System.out.println(date); // Mon Feb 08 13:00:30 CST 2021
System.out.println("********");
String format = sdf.format(date);
System.out.println(format); // 2021/2/8 下午1:00
// 解析parse:格式化的逆过程,字符串--->日期
String str = "2021/2/8 下午1:00";
Date date1 = sdf.parse(str);
System.out.println(date1); // Mon Feb 08 13:00:30 CST 2021
}
②自定义解析方式(带参数的构造器)
- 常用格式:yyyy-MM-dd hh:mm:ss
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FdMjhC05-1663498326042)(面试题.assets/image-20220918184849096.png)]](https://1000bd.com/contentImg/2023/11/07/200913593.png)
@Test
public void testSimpleDateFormat() throws ParseException {
// 按照指定的方式格式化和解析:调用带参的构造器**** 常用格式:年月日时分秒 "yyyy-MM-dd hh:mm:ss"
// SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println("******");
// 格式化
String format1 = sdf1.format(date);
System.out.println(format1); // 2021-02-08 01:08:26
// 解析:要求字符串必须是符合SimpleDateFormat识别的格式(通过构造器参数体现),
// 否则,抛异常
Date date2 = sdf1.parse("2021-02-08 01:08:26");
System.out.println(date2); // Mon Feb 08 01:08:26 CST 2021
}
练习:字符串"2020-09-08"转换为java.sql.Date
@Test
public void testExer() throws ParseException {
String birth = "2020-09-08";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf1.parse(birth);
// System.out.println(date);java.util.Date下
java.sql.Date birthDate = new java.sql.Date(date.getTime());
System.out.println(birthDate);
}
练习2:“三天打渔两天晒网”

public class 三天打鱼两天晒网练习题 {
public static void main(String[] args) throws ParseException {
Scanner s1 = new Scanner(System.in);
System.out.println("请输入启示的年");
int i1 = s1.nextInt();
Scanner s2 = new Scanner(System.in);
System.out.println("请输入启示的月");
int i2 = s2.nextInt();
Scanner s3 = new Scanner(System.in);
System.out.println("请输入启示的日");
int i3 = s3.nextInt();
String s00 = i1 + "-" + i2 + "-" + i3;
System.out.println(s00);
Scanner s4 = new Scanner(System.in);
System.out.println("请输入结尾的年");
int i4 = s4.nextInt();
Scanner s5 = new Scanner(System.in);
System.out.println("请输入结尾的日");
int i5 = s5.nextInt();
Scanner s6 = new Scanner(System.in);
System.out.println("请输入结尾的月");
int i6 = s6.nextInt();
String s01 = i4 + "-" + i5 + "-" + i6;
System.out.println(s01);
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
Date d1 = sdf1.parse(s00);
Date d2 = sdf1.parse(s01);
long l1 = (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24) + 1;
if (l1 % 5 == 1) {
System.out.println("打渔");
} else if (l1 % 5 == 2) {
System.out.println("打渔");
} else if (l1 % 5 == 3) {
System.out.println("打渔");
} else if (l1 % 5 == 0) {
System.out.println("晒网");
} else if (l1 % 5 == 4) {
System.out.println("晒网");
}
}
}
练习3:下班时间
public class 下班时间 {
public static void main(String[] args) throws ParseException {
Scanner s1 = new Scanner(System.in);
System.out.println("请输入下班的年");
int i1 = s1.nextInt();
Scanner s2 = new Scanner(System.in);
System.out.println("请输入下班的月");
int i2 = s2.nextInt();
Scanner s3 = new Scanner(System.in);
System.out.println("请输入下班的日");
int i3 = s3.nextInt();
Scanner s4 = new Scanner(System.in);
System.out.println("请输入下班的时");
int i4 = s4.nextInt();
Scanner s5 = new Scanner(System.in);
System.out.println("请输入下班的分");
int i5 = s5.nextInt();
Scanner s6 = new Scanner(System.in);
System.out.println("请输入下班的秒");
int i6 = s6.nextInt();
String s01 = i1+ "-" +i2+ "-" +i3+ " " +i4 + ":" + i5 + ":" + i6;
//获取现在的时间:2021-02-12 05:33:12
DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//格式化
String str4 = formatter3.format(LocalDateTime.now());
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date parse1= sdf1.parse(s01);
Date parse2 = sdf1.parse(str4);
System.out.println("现在的时间"+str4);
System.out.println("您下班的时间:"+s01);
System.out.println(parse1.getTime() - parse2.getTime());
System.out.println("您还有:"+ (parse1.getTime() - parse2.getTime())/1000+"秒下班,继续努力呦“亲”!");
System.out.println("您还有:"+ (parse1.getTime() - parse2.getTime())/1000/60+"分下班,继续努力呦“亲”!");
System.out.println("您还有:"+ (parse1.getTime() - parse2.getTime())/1000/60/60+"小时下班,继续努力呦“亲”!");
}
}

@Test
public void testCalendar() {
// 1.实例化
// 方式一:创建其子类(GregorianCalendar)的对象
// 方式二:调用其静态方法getInstance()
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getClass()); //class java.util.GregorianCalendar
// 2.常用方法
// get()
int days = calendar.get(Calendar.DAY_OF_MONTH);// 这个月的第几天
System.out.println(days); // 10
System.out.println(calendar.get(Calendar.DAY_OF_YEAR)); // 131,今天是这一年的131天
// set()
// calendar可变性
calendar.set(Calendar.DAY_OF_MONTH, 22);// set 是void 相当于就是把calendar对象本身给修改了
days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days); // 22
// add()
calendar.add(Calendar.DAY_OF_MONTH, -3); // 在本月的基础上加了三天 负数是减
days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days); // 22-3 --》19
// getTime():日历类---> Date
Date date = calendar.getTime();
System.out.println(date); // Fri Feb 19 14:02:37 CST 2021
// setTime():Date ---> 日历类
Date date1 = new Date();
calendar.setTime(date1);
days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days); // 10
}
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EKoXLxUu-1663508014146)(面试题.assets/image-20220918202551850.png)]](https://1000bd.com/contentImg/2023/11/07/200914900.png)
偏移量
@Test
public void testDate(){
// 想要表示 2020 年 9 月 8 号
//偏移量
Date date1 = new Date(2020,9,8);
System.out.println(date1); //Fri Oct 08 00:00:00 CST 3920 存在偏移量
Date date2 = new Date(2020 - 1900,9 - 1,8); // 正确的表示方式
System.out.println(date2); //Tue Sep 08 00:00:00 CST 2020
}
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SKjrsdBx-1663508014146)(面试题.assets/image-20220918212653178.png)]](https://1000bd.com/contentImg/2023/11/07/200914809.png)
说明:
- LocalDateTime相对于用的多一些 类似于Calender
@Test
public void test1(){
//now():获取当前的日期、时间、日期+时间 有偏移量
LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDate);
System.out.println(localTime);
System.out.println(localDateTime);
//of():设置指定的年、月、日、时、分、秒。没有偏移量
LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 6, 13, 23, 43);
System.out.println(localDateTime1);
//getXxx():获取相关的属性
System.out.println(localDateTime.getDayOfMonth());//10
System.out.println(localDateTime.getDayOfWeek());
System.out.println(localDateTime.getMonth());// FEBRUARY 二月
System.out.println(localDateTime.getMonthValue());//数字 2
System.out.println(localDateTime.getMinute());//分钟
//体现不可变性
//withXxx():设置相关的属性
LocalDate localDate1 = localDate.withDayOfMonth(22);
System.out.println(localDate);
System.out.println(localDate1);
LocalDateTime localDateTime2 = localDateTime.withHour(4);
System.out.println(localDateTime);
System.out.println(localDateTime2);
//不可变性
LocalDateTime localDateTime3 = localDateTime.plusMonths(3);//外加月份
System.out.println(localDateTime);
System.out.println(localDateTime3);
LocalDateTime localDateTime4 = localDateTime.minusDays(6);//减 6天
System.out.println(localDateTime);
System.out.println(localDateTime4);
}
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-abEOj2NZ-1663510782372)(面试题.assets/image-20220918215623159.png)]](https://1000bd.com/contentImg/2023/11/07/200914948.png)
@Test
public void test2(){
//now():获取本初子午线对应的标准时间
Instant instant = Instant.now();
System.out.println(instant); //2020-05-10T09:55:55.561Z
//添加时间的偏移量 atOffset
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));//东八区
System.out.println(offsetDateTime); //2020-05-10T18:00:00.641+08:00
//toEpochMilli():获取自1970年1月1日0时0分0秒(UTC)开始的毫秒数 ---> Date类的getTime()
long milli = instant.toEpochMilli();
System.out.println(milli); //1589104867591
//ofEpochMilli():通过给定的毫秒数,获取Instant实例 -->Date(long millis)
Instant instant1 = Instant.ofEpochMilli(1550475314878L);
System.out.println(instant1); //2019-02-18T07:35:14.878Z
}
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-akGHWSD2-1663510782373)(面试题.assets/image-20220918221136608.png)]](https://1000bd.com/contentImg/2023/11/07/200914609.png)
@Test
public void test3(){
//方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
//格式化:日期-->字符串
LocalDateTime localDateTime = LocalDateTime.now();
String str1 = formatter.format(localDateTime);
System.out.println(localDateTime);
System.out.println(str1);//2020-05-10T18:26:40.234
//解析:字符串 -->日期
TemporalAccessor parse = formatter.parse("2020-05-10T18:26:40.234");
System.out.println(parse);
//方式二:
//本地化相关的格式。如:ofLocalizedDateTime()
// FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime
//2021年2月12日 下午8:58:05 2021/2/12 下午8:58
DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
//格式化
String format = formatter1.format(localDateTime);
System.out.println(format);//2020年5月10日 下午06时26分40秒
System.out.println("******************");
//本地化相关的格式。如:ofLocalizedDate()
//FormatStyle.FULL / FormatStyle.LONG 、 FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate
//2021年2月12日星期五 2021年2月12日 2021/2/12
DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
//格式化
String str3 = formatter2.format(LocalDate.now());
System.out.println(str3);//2020-5-10
//重点: 方式三:自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)
DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//格式化
String str4 = formatter3.format(LocalDateTime.now());
System.out.println(str4);//2020-05-10 06:26:40
//解析
TemporalAccessor accessor = formatter3.parse("2020-05-10 06:26:40");
System.out.println(accessor);
}


![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kYPV634t-1663577595470)(面试题.assets/image-20220919155011123.png)]](https://1000bd.com/contentImg/2023/11/07/200914161.png)
自然排序:java.lang.Comparable
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oNsVKul3-1663577595471)(面试题.assets/image-20220919155123088.png)]](https://1000bd.com/contentImg/2023/11/07/200914186.png)
重写compareTo
//指明商品比较大小的方式:按照价格从低到高排序,再按照产品名称从高到低排序
@Override
public int compareTo(Object o) {
if(o instanceof Goods){ // 判断是否是商品 是进行强转
Goods goods = (Goods)o;
//方式一:
if(this.price > goods.price){//当前对象和形参对象
return 1;
}else if(this.price < goods.price){
return -1;
}else{
// return 0;
return -this.name.compareTo(goods.name);//再按照产品名称从高到低排序
// (-)负号表示倒序
}
//方式二: double中的 compare方法(比较两个数的大小)
// return Double.compare(this.price,goods.price);
}
throw new RuntimeException("传入的数据类型不一致!");
}
测试
@Test
public void test1(){
String[] arr = new String[]{"AA","CC","KK","MM","GG","JJ","DD"};
sort(arr);
System.out.println(Arrays.toString(arr));
}
@Test
public void test2(){
Goods[] arr = new Goods[5];
arr[0] = new Goods("lenovoMouse",34);
arr[1] = new Goods("dellMouse",43);
arr[2] = new Goods("xiaomiMouse",12);
arr[3] = new Goods("huaweiMouse",65);
arr[4] = new Goods("microsoftMouse",43);
sort(arr);
System.out.println(Arrays.toString(arr));
}
定制排序:java.util.Comparator

测试
@Test
public void test3() {
String[] arr = new String[]{"AA", "CC", "KK", "MM", "GG", "JJ", "DD"};
sort(arr, new Comparator() {
//按照字符串从大到小的顺序排列
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof String && o2 instanceof String) {
String s1 = (String) o1;
String s2 = (String) o2;
return -s1.compareTo(s2);
}
throw new RuntimeException("输入的数据类型不一致");
}
});
System.out.println(Arrays.toString(arr));
}
@Test
public void test3.1() {
String[] arr = new String[]{"AA", "CC", "KK", "MM", "GG", "JJ", "DD"};
sort(arr, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
System.out.println(Arrays.toString(arr));
}
@Test
public void test4() {
Goods[] arr = new Goods[6];
arr[0] = new Goods("lenovoMouse", 34);
arr[1] = new Goods("dellMouse", 43);
arr[2] = new Goods("xiaomiMouse", 12);
arr[3] = new Goods("huaweiMouse", 65);
arr[4] = new Goods("huaweiMouse", 224);
arr[5] = new Goods("microsoftMouse", 43);
sort(arr, new Comparator() {
//指明商品比较大小的方式:按照产品名称从低到高排序,再按照价格从高到低排序
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof Goods && o2 instanceof Goods) {
Goods g1 = (Goods) o1;
Goods g2 = (Goods) o2;
if (g1.getName().equals(g2.getName())) {
return -Double.compare(g1.getPrice(), g2.getPrice());
} else {
return g1.getName().compareTo(g2.getName());
}
}
throw new RuntimeException("输入的数据类型不一致");
}
});
System.out.println(Arrays.toString(arr));
}

@Test
public void test1() {
String javaVersion = System.getProperty("java.version");
System.out.println("java的version:" + javaVersion); // java的version:1.8.0_152
String javaHome = System.getProperty("java.home");
System.out.println("java的home:" + javaHome); // java的home:E:\JDK\JDK1.8\jre
String osName = System.getProperty("os.name");
System.out.println("os的name:" + osName); // 系统的name:Windows 10
String osVersion = System.getProperty("os.version");
System.out.println("os的version:" + osVersion); // 系统的version:10.0
String userName = System.getProperty("user.name");
System.out.println("user的name:" + userName); // 系统的user的name:gh
String userHome = System.getProperty("user.home");
System.out.println("user的home:" + userHome); // 系统user的home:C:\Users\gh
String userDir = System.getProperty("user.dir");
System.out.println("user的dir:" + userDir); // user的dir:G:\java存储文件\_2java高级编程
}
java.lang.Math提供了一系列静态方法用于科学计算。其方法的参数和返回 值类型一般为double型。

@Test
public void test2() {
BigInteger bi = new BigInteger("1243324112234324324325235245346567657653");
BigDecimal bd = new BigDecimal("12435.351");
BigDecimal bd2 = new BigDecimal("11");
System.out.println(bi);
// System.out.println(bd.divide(bd2));// java.lang.ArithmeticException: 除不尽
System.out.println(bd.divide(bd2, BigDecimal.ROUND_HALF_UP));//b1/12 四舍五入
System.out.println(bd.divide(bd2, 25, BigDecimal.ROUND_HALF_UP));//b1/12 保留多少位小数 四舍五入
}