题目01
说出下面程序的运行结果
package com.jerry.java; /** * @author jerry_jy * @create 2022-10-03 10:59 */ public class Exer1 { public static void main(String[] args) { Person p1 = new Person(); p1.name = "jerry"; Person p2 = new Person(); p2.name = "jerry"; System.out.println(p1.name.equals(p2.name)); //true System.out.println(p1.name == p2.name); //true System.out.println(p1.name == "jerry"); //true String s1 = new String("bcde"); String s2 = new String("bcde"); System.out.println(s1 == s2); //false } } class Person { String name; }
题目02
说出下面程序的运行结果
package com.jerry.java; /** * @author jerry_jy * @create 2022-10-03 11:24 */ public class Exer2 { public static void main(String[] args) { String s = new String(" 123aBcD "); String s1 = new String("123"); System.out.println(s.length());//9 System.out.println(s.charAt(0));// System.out.println(s.isEmpty());//false System.out.println(s.toLowerCase());// 123abcd System.out.println(s.toUpperCase());// 123ABCD System.out.println(s.equals(s1));//false System.out.println(s.concat(s1));// 123aBcD 123 System.out.println(s.compareTo(s1));//-17 System.out.println(s.substring(5));//BcD String str = "12hello34world5java7891mysql456"; System.out.println("==========================="); //把字符串中的数字替换成,,如果结果中开头和结尾有,的话去掉 String string = str.replaceAll("\\d+", ",").replaceAll("^,|,$", ""); System.out.println(string); String str1 = "12345"; //判断str字符串中是否全部有数字组成,即有1-n个数字组成 boolean matches = str1.matches("\\d+"); System.out.println(matches);//true String tel = "0571-4534289"; //判断这是否是一个杭州的固定电话 boolean result = tel.matches("0571-\\d{7,8}"); System.out.println(result);//true String str2 = "hello|world|java"; String[] strs = str2.split("\\|"); for (int i = 0; i < strs.length; i++) { System.out.println(strs[i]); } System.out.println(); String str3 = "hello.world.java"; String[] strs2 = str3.split("\\."); for (int i = 0; i < strs2.length; i++) { System.out.println(strs2[i]); } System.out.println("=========字符串转为字符数组========"); for (char c : str.toCharArray()) { System.out.println(c); } System.out.println(); char[] chars1={'2','1'}; str.getChars(0, 2, chars1, 0); for (char c : chars1) { System.out.println(c); } System.out.println("打印数组索引为0的元素:"+str.toCharArray()[0]);//1 System.out.println("=========字符数组转为字符串========"); char[] chars = {'a','b','c','d'}; System.out.println(chars.getClass());//class [C System.out.println(new String(chars));//abcd System.out.println(new String(chars).getClass());//class java.lang.String } }
题目03
说出下面程序的运行结果
package com.jerry.java; /** * @author jerry_jy * @create 2022-10-03 11:19 */ public class StringTest { String str = new String("good"); char[] ch = {'t', 'e', 's', 't'}; public void change(String str, char ch[]) { str = "test ok"; ch[0] = 'b'; } public static void main(String[] args) { StringTest ex = new StringTest(); ex.change(ex.str, ex.ch); System.out.print(ex.str + " and ");//good and best,注意:这里的ex.str还是调用的常量池中str,不是change()方法后的test ok System.out.println(ex.ch); } }
题目04
package com.jerry.java; /** * @author jerry_jy * @create 2022-10-03 19:27 */ public class StringBufferTest { public static void main(String[] args) { String str = new String("我爱学习"); StringBuffer stringBuffer = new StringBuffer("我爱学习"); stringBuffer.append("Java"); System.out.println(stringBuffer);//我爱学习Java stringBuffer.delete(0, 2); System.out.println(stringBuffer);//学习Java stringBuffer.replace(2, 6, "C++"); System.out.println(stringBuffer);//学习C++ System.out.println(stringBuffer.insert(0, "我爱")); System.out.println(stringBuffer.reverse());//++C习学爱我 System.out.println(stringBuffer.indexOf("C"));//2 System.out.println(stringBuffer.substring(0, 3));//++C System.out.println(stringBuffer.length());//7 System.out.println(stringBuffer.charAt(0));//+ stringBuffer.setCharAt(0, '-'); stringBuffer.setCharAt(1, '-'); System.out.println(stringBuffer);//--C习学爱我 System.out.println(new StringBuffer("123456").reverse());//654321 System.out.println(str.equals(stringBuffer));//false } }
题目05
对比String、StringBuffer、StringBuilder三者的效率
package com.jerry.java; /** * @author jerry_jy * @create 2022-10-03 19:58 */ public class StringBuilderTest { /* 对比String、StringBuffer、StringBuilder三者的效率: 从高到低排列:StringBuilder > StringBuffer > String */ public static void main(String[] args) { long startTime = 0L; long endTime = 0L; StringBuffer buffer = new StringBuffer(""); StringBuilder builder = new StringBuilder(""); String str = ""; //StringBuffer的执行时间 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的执行时间:3 //StringBuilder的执行时间 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的执行时间:3 //String的测试时间 startTime = System.currentTimeMillis(); for (int i = 0; i < 20000; i++) { str = str + i; } endTime = System.currentTimeMillis(); System.out.println("String的测试时间:" + (endTime - startTime));//String的测试时间:908 } }
题目06
日期时间API的测试
package com.jerry.java; import org.junit.Test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.*; import java.time.temporal.Temporal; import java.time.temporal.TemporalAdjuster; import java.time.temporal.TemporalAdjusters; import java.util.Calendar; import java.util.Date; /** * @author jerry_jy * @create 2022-10-04 8:36 */ public class DateTimeTest { public static void main(String[] args) { } @Test public void test() { String str = null; StringBuffer sb = new StringBuffer(); sb.append(str); System.out.println(sb.length());//4 System.out.println(sb);//null StringBuffer sb1 = new StringBuffer(str); System.out.println(sb1);//java.lang.NullPointerException } @Test public void test2() { Date date = new Date(); System.out.println(date);//Mon Oct 03 20:44:17 CST 2022 System.out.println(date.getTime());//返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数1664804213645 System.out.println(date.getMonth());//9 } @Test public void test3() { // 产生一个Date实例 Date date = new Date(); // 产生一个 simpleDateFormat 格式化的实例 SimpleDateFormat simpleDateFormat = new SimpleDateFormat(); System.out.println(simpleDateFormat.format(date));//22-10-3 下午9:41 SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy年MM月dd日 EEE HH:mm:ss"); System.out.println(simpleDateFormat1.format(date));//2022年10月03日 星期一 21:42:58 try { // 实例化一个指定的格式对象 Date date1 = simpleDateFormat1.parse("2008年08月08日 星期一 08:08:08"); // 将指定的日期解析后格式化按指定的格式输出 System.out.println(date1);//Fri Aug 08 08:08:08 CST 2008 } catch (ParseException e) { e.printStackTrace(); } } @Test public void test4() { System.out.println(Calendar.getInstance()); System.out.println(Calendar.getInstance().getTime());//Mon Oct 03 21:55:58 CST 2022 System.out.println(Calendar.getInstance().getWeekYear());//2022 Calendar calendar = Calendar.getInstance(); // 从一个 Calendar 对象中获取 Date 对象 Date date = calendar.getTime(); // 使用给定的 Date 设置此 Calendar 的时间 date = new Date(234234235235L); calendar.setTime(date); calendar.set(Calendar.DAY_OF_MONTH, 8); System.out.println("当前时间日设置为8后,时间是:" + calendar.getTime()); calendar.add(Calendar.HOUR, 2); System.out.println("当前时间加2小时后,时间是:" + calendar.getTime()); calendar.add(Calendar.MONTH, -2); System.out.println("当前日期减2个月后,时间是:" + calendar.getTime()); } @Test public void test5() { System.out.println(LocalTime.now());//22:13:47.190 System.out.println(LocalDateTime.now());//2022-10-03T22:15:05.801 System.out.println(LocalDateTime.now().getDayOfYear()); System.out.println(LocalDateTime.now().getYear()); //ZoneId:类中包含了所有的时区信息 // ZoneId的getAvailableZoneIds():获取所有的ZoneId // Set<String> zoneIds = ZoneId.getAvailableZoneIds(); // for (String s : zoneIds) { // System.out.println(s); // } // ZoneId的of():获取指定时区的时间 LocalDateTime localDateTime = LocalDateTime.now(ZoneId.of("Asia/Tokyo")); System.out.println(localDateTime); //ZonedDateTime:带时区的日期时间 // ZonedDateTime的now():获取本时区的ZonedDateTime对象 ZonedDateTime zonedDateTime = ZonedDateTime.now(); System.out.println(zonedDateTime); // ZonedDateTime的now(ZoneId id):获取指定时区的ZonedDateTime对象 ZonedDateTime zonedDateTime1 = ZonedDateTime.now(ZoneId.of("Asia/Tokyo")); System.out.println(zonedDateTime1); } @Test public void test6() { //Duration:用于计算两个“时间”间隔,以秒和纳秒为基准 LocalTime localTime = LocalTime.now(); LocalTime localTime1 = LocalTime.of(15, 23, 32); //between():静态方法,返回Duration对象,表示两个时间的间隔 Duration duration = Duration.between(localTime1, localTime); System.out.println(duration);//PT-6H-45M-43.908S System.out.println(duration.getSeconds());//-24344 System.out.println(duration.getNano());//92000000 LocalDateTime localDateTime = LocalDateTime.of(2016, 6, 12, 15, 23, 32); LocalDateTime localDateTime1 = LocalDateTime.of(2017, 6, 12, 15, 23, 32); Duration duration1 = Duration.between(localDateTime1, localDateTime); System.out.println(duration1.toDays());//-365 } @Test public void test7(){ //Period:用于计算两个“日期”间隔,以年、月、日衡量 LocalDate localDate = LocalDate.now(); LocalDate localDate1 = LocalDate.of(2028, 3, 18); Period period = Period.between(localDate, localDate1); System.out.println(period);//P5Y5M14D System.out.println(period.getYears());//5 System.out.println(period.getMonths());//5 System.out.println(period.getDays());//14 Period period1 = period.withYears(2); System.out.println(period1);//P2Y5M14D } @Test public void test8(){ // TemporalAdjuster:时间校正器 // 获取当前日期的下一个周日是哪天? TemporalAdjuster temporalAdjuster = TemporalAdjusters.next(DayOfWeek.SUNDAY); LocalDateTime localDateTime = LocalDateTime.now().with(temporalAdjuster); System.out.println(localDateTime);//2022-10-09T08:42:31.928 // 获取下一个工作日是哪天? LocalDate localDate = LocalDate.now().with(new TemporalAdjuster() { @Override public Temporal adjustInto(Temporal temporal) { LocalDate date = (LocalDate) temporal; if (date.getDayOfWeek().equals(DayOfWeek.FRIDAY)) { return date.plusDays(3); } else if (date.getDayOfWeek().equals(DayOfWeek.SATURDAY)) { return date.plusDays(2); } else { return date.plusDays(1); } } }); System.out.println("下一个工作日是:" + localDate);//下一个工作日是:2022-10-05 } }
题目07
Comparable 和 Comparator 的使用
package com.jerry.java; import org.junit.Test; import java.util.Arrays; import java.util.Comparator; /** * @author jerry_jy * @create 2022-10-04 8:53 */ public class ComparableTest { public static void main(String[] args) { Goods[] all = new Goods[4]; all[0] = new Goods("《红楼梦》", 100); all[1] = new Goods("《西游记》", 80); all[2] = new Goods("《三国演义》", 140); all[3] = new Goods("《水浒传》", 120); Arrays.sort(all); System.out.println(Arrays.toString(all)); } @Test public void test1(){ Goods[] all = new Goods[4]; all[0] = new Goods("War and Peace", 100); all[1] = new Goods("Childhood", 80); all[2] = new Goods("Scarlet and Black", 140); all[3] = new Goods("Notre Dame de Paris", 120); Arrays.sort(all,new Comparator(){ @Override public int compare(Object o1, Object o2) { Goods goods1 = (Goods) o1; Goods goods2 = (Goods) o2; return goods1.getName().compareTo(goods2.getName()); } }); System.out.println(Arrays.toString(all)); } } class Goods implements Comparable { private String name; private double price; public Goods() { } public Goods(String name, double price) { this.name = name; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "Goods{" + "name='" + name + '\'' + ", price=" + price + '}'; } //指明商品比较大小的方式:按照价格从低到高排序,再按照产品名称从高到低排序 @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.getPrice()) { // return -1; // }else { // return 0; // } //方式二: return Double.compare(this.price,goods.price); } throw new RuntimeException("传入的数据类型不一致!"); } }
题目08
System类的测试
package com.jerry.java; import sun.plugin2.os.windows.Windows; /** * @author jerry_jy * @create 2022-10-04 10:20 */ public class SystemTest { public static void main(String[] args) { String javaVersion = System.getProperty("java.version"); System.out.println("java的version:" + javaVersion);//java的version:1.8.0_301 String javaHome = System.getProperty("java.home");//java的home:E:\Java_tools\jdk1.8.0_301\jre System.out.println("java的home:" + javaHome); String osName = System.getProperty("os.name"); System.out.println("os的name:" + osName);//os的name:Windows 10 String osVersion = System.getProperty("os.version"); System.out.println("os的version:" + osVersion);//os的version:10.0 String userName = System.getProperty("user.name"); System.out.println("user的name:" + userName);//user的name:Admin String userHome = System.getProperty("user.home"); System.out.println("user的home:" + userHome);//user的home:C:\Users\15718 String userDir = System.getProperty("user.dir"); System.out.println("user的dir:" + userDir);//user的dir:E:\CodeLife\IdeaProject\JVM } }
题目09
/* 1. 模拟一个trim方法,去除字符串两端的空格。 */
package com.jerry.exer; /** * @author jerry_jy * @create 2022-10-03 17:33 */ public class Exer1 { /* 1. 模拟一个trim方法,去除字符串两端的空格。 */ public static void main(String[] args) { String str = " 123 abc "; Exer1 exer1 = new Exer1(); System.out.println(exer1.myTrim(str)); } 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; } }
题目10
/* 将一个字符串进行反转。将字符串中指定部分进行反转。比如“abcdefg”反转为”abfedcg” */
package com.jerry.exer; /** * @author jerry_jy * @create 2022-10-03 18:14 */ public class Exer2 { /* 将一个字符串进行反转。将字符串中指定部分进行反转。比如“abcdefg”反转为”abfedcg” */ public static void main(String[] args) { String str = "abcdefg"; Exer2 exer2 = new Exer2(); System.out.println(exer2.myReverse(str, 2, 5)); } public String myReverse(String str, int start, int end) { if (str != null) { char[] chars = str.toCharArray(); int i = start, j = end; for (; i < j; i++, j--) { char temp = chars[i]; chars[i] = chars[j]; chars[j] = temp; } return new String(chars);//记住:把字符数组转化为字符串 } return null; } }
题目11
/* 获取一个字符串在另一个字符串中出现的次数。比如:获取“ab”在 “abkkcadkabkebfkabkskab” 中出现的次数 */
package com.jerry.exer; /** * @author jerry_jy * @create 2022-10-03 18:26 */ public class Exer3 { /* 获取一个字符串在另一个字符串中出现的次数。比如:获取“ab”在 “abkkcadkabkebfkabkskab” 中出现的次数 */ public static void main(String[] args) { String str1 = "abkkcadkabkebfkabkskab"; String str2 = "ab"; Exer3 exer3 = new Exer3(); System.out.println("出现的次数:"+exer3.countString(str1, str2)); } public int countString(String str1, String str2){ char[] chars1 = str1.toCharArray(); char[] chars2 = str2.toCharArray(); int count = 0; for (int i = 0; i < chars1.length; i++) { if (chars2[0]==chars1[i]&&chars2[1]==chars1[i+1]){ count++; } } return count; } }
题目12
/* 获取两个字符串中最大相同子串。比如: str1 = "abcwerthelloyuiodef“;str2 = "cvhellobnm" 提示:将短的那个串进行长度依次递减的子串与较长的串比较。 */
package com.jerry.exer; /** * @author jerry_jy * @create 2022-10-03 18:44 */ public class Exer4 { /* 获取两个字符串中最大相同子串。比如: str1 = "abcwerthelloyuiodef“;str2 = "cvhellobnm" 提示:将短的那个串进行长度依次递减的子串与较长的串比较。 */ public static void main(String[] args) { Exer4 exer4 = new Exer4(); String str1 = "abcwerthelloyuiodef"; String str2 = "cvhellobnm"; System.out.println("最大相同子串:" + exer4.getMaxSameSubString(str1, str2)); } // 如果只存在一个最大长度的相同子串 public String getMaxSameSubString(String str1, String str2) { if (str1 != null && str2 != null) { String maxStr = (str1.length() > str2.length()) ? str1 : str2; String minStr = (str1.length() > str2.length()) ? str2 : str1; int len = minStr.length(); for (int i = 0; i < len; i++) {// 0 1 2 3 4 此层循环决定要去几个字符 for (int x = 0, y = len - i; y <= len; x++, y++) { if (maxStr.contains(minStr.substring(x, y))) { return minStr.substring(x, y); } } } } return null; } // 如果存在多个长度相同的最大相同子串 // 此时先返回String[],后面可以用集合中的ArrayList替换,较方便 public String[] getMaxSameSubString1(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 + ","); } } System.out.println(sBuffer); if (sBuffer.length() != 0) { break; } } String[] split = sBuffer.toString().replaceAll(",$", "").split("\\,"); return split; } return null; } // 如果存在多个长度相同的最大相同子串:使用ArrayList // public List<String> getMaxSameSubString1(String str1, String str2) { // if (str1 != null && str2 != null) { // List<String> list = new ArrayList<String>(); // 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)) { // list.add(subString); // } // } // if (list.size() != 0) { // break; // } // } // return list; // } // // return null; // } }
题目13
/* 对字符串中字符进行自然顺序排序。 提示: 1)字符串变成字符数组。 2)对数组排序,选择,冒泡,Arrays.sort(); 3)将排序后的数组变成字符串。 */
package com.jerry.exer; import java.util.Arrays; /** * @author jerry_jy * @create 2022-10-03 19:15 */ public class Exer5 { public static void main(String[] args) { String str = "cGbZiLnM"; char[] chars = str.toCharArray(); Arrays.sort(chars); System.out.println(new String(chars)); } }