Scanner
获取键盘的输入
public class TextScanner {public static void main(String[] args) {Scanner scan = new Scanner(System.in); //System.in一个io流对象System.out.println("输入字符:");String a = scan.nextLine(); //获取输入的字符System.out.println("输入数字:");int b = scan.nextInt(); //获取输入的数字System.out.println("#########");System.out.println(a);System.out.println(b);scan.close();}}
包装类
基本数据类型不是对象,实际应用中经常需要将基本数据转化成对象,以便于操作。Java在设计类时为每个基本数据类型设计了一个对应的类进行代表,这样八个和基本数据类型对应的类统称为包装类
public class WrapperClass {public static void main(String[] args) {//基本数据类型转为包装对象Integer a = new Integer(3);Integer b = Integer.valueOf(30); //推荐这种//把包装类对象转成基本数据类型int c = b.intValue(); //转成整数double d = b.doubleValue();System.out.println(c);System.out.println(d);//把字符串转成包装类对象Integer e = new Integer("233");Integer f = Integer.parseInt("345");System.out.println(e);//把包装类对象转成字符串String str = f.toString();//常见的常量System.out.println("int最大整数"+Integer.MAX_VALUE);}}
自动装箱
基本类型的数据处于需要对象的环境中时,会自动转为"对象"
自动拆箱
每当需要一个值时,**对象会自动转成基本数据类型**,没必要再去显式调用intValue()、doubleValue()等转型方法
public class AutoBox {public static void main(String[] args) {Integer a = 123;//自动装箱,编译器自动转换为对象int b = a; //自动拆箱,编译器自动修改System.out.println("########");//缓存[-128,127]之间的数字,系统在初始化时创建了[-128,127]之间的缓存数组Integer in1 = Integer.valueOf(-128);Integer in2 = -128;Integer in3 = 128;System.out.println(in2 == in3);//false 两个是不同的对象System.out.println(in1 == in2);//true 因为在缓存范围内System.out.println(in1.equals(in2));//true hashcode相同}}
String类
三大特性
- String类又称作不可变字符序列,主要在一个对象被多个线程频繁访问时,可以保证数据的一致性(不可变是值,当对string进行操作时,它本身的对象不会改变,任何对它的操作都是创建一个新的对象)
- 常量池优化:string对象在创建之后,会在常量池中进行缓存,下次创建同样的对象时,会直接返回缓存的引用;字符串常量池位于堆内存中
- final:string类不可被继承,提高了系统的安全性
实例化的两种方式:
- 直接赋值
- 通过构造函数,可以直接将字符串的值传入,也可以传入一个char数组。
注:直接赋值和通过构造函数创建主要区别在于存储的区域不同,直接赋值存储在字符串常量池中。通过构造函数创建,存储在堆内存中
构造器方法

Java没有内置的字符串类型,而是在标准Java类库中提供了一个预定义的类String,每个用双引号括起来的字符串都是String类的一个实例

//string 常用用法public class TextString {public static void main(String[] args) {String s1 = "core Java";String s2 = "Core Java";System.out.println(s1.charAt(3));//提取下标为3的字符System.out.println(s2.length());//字符串的长度System.out.println(s1.equals(s2));//比较两个字符串是否相等System.out.println(s1.equalsIgnoreCase (s2));//比较两个字符串(忽略大小写)System.out.println(s1.indexOf("Java"));//字符串s1中是否包含JavaSystem.out.println(s1.indexOf("apple"));//字符串s1中是否包含appleString s3 = s1.replace(' ', '&');//将s1中的空格替换成&System.out.println("result is :" + s3);System.out.println("######");//contains() 方法用于判断字符串中是否包含指定的字符或字符串System.out.println(s3.contains("aaa"));//返回一个布尔值String s = "";String s5 = "How are you?";System.out.println(s5.startsWith("How"));//是否以How开头System.out.println(s5.endsWith("you"));//是否以you结尾s = s5.substring(4);//提取子字符串:从下标为4的开始到字符串结尾为止System.out.println(s);s = s5.substring(4, 7);//提取子字符串:下标[4, 7) 不包括7System.out.println(s);s = s5.toLowerCase();//转小写System.out.println(s);s = s5.toUpperCase();//转大写System.out.println(s);String s6 = " How old are you!! ";s = s6.trim();//去除字符串首尾的空格。注意:中间的空格不能去除System.out.println(s);System.out.println(s6);//因为String是不可变字符串,所以s2不变}}
split()方法
字符串的分割;支持正则表达式
String nn = new String("hh,mm,ss");String[] split = nn.split(","); //按照指定字符分割for (String s1 : split) {System.out.println(s1);}String mn = new String("hh,mm;s-s");mn.split("[,|;|-]");for (String s1 : split) {System.out.println(s1);}
intern()方法
当调用某个字符串对象的intern()方法,会去字符串常量池中寻找,如果已经存在一个值相等的字符串对象的话,则直接返回该对象的引用。如果不存在,则在字符串常量池中创建该对象
String m = "hh";String n = new String("hh");System.out.println(m==n); //false 比较的是地址System.out.println(m==n.intern()); //true比较的是值
考点
String s1 = "hh";String s2 = "h"+"h"; //常量和常量拼接System.out.println(s1==s2); //trueString s4 = "hh";String s5 = "h";s5+="h"; //修改之后再拼接 存放在堆内存中System.out.println(s1==s3); //falseString s1 = "hh";String s2 = "h";String s3= "h"+s2; //常量和变量拼接 存放在堆中System.out.println(s1==s3); //falseString s3 = "hh";final String s4 = "h"; //final修饰后作为一个常量用String s5= "h"+s4;System.out.println(s3==s5); //trueString s6 = "hh";final String s7 = new String("h"); //s7是一个存放在堆内的对象String s8= "h"+s7;System.out.println(s6==s8); //false
为什么String不可变
不可变指类的实例一旦被创建后,其内容就是不可变的
- 类被final修饰,不可继承
- 底层value数组用final修饰,初始化后,就不能改变它的引用
- 没有暴露成员变量。成员变量的访问修饰符是private,也没有提供方法去访问,要修改只能通过string提供的方法
- string类中的方法不会改动value中的元素,需要改变的话都是直接创建一个新的string对象返回
好处
- 提高安全性
- 节省空间。通过维护字符串常量池
- 线程安全。调用string方法去修改string对象时返回的是新的对象,不存在并发修改同一个对象的场景
- 提高性能。比如string的哈希码只用计算一次,以后调用的都是缓存
StringBuffer和StringBuilder
可变的字符序列, 这两个类都是抽象类
//StringBuilder线程不安全 效率高(一般使用它)//StringBuffer 线程安全 效率低StringBuilder a = new StringBuilder("abc");System.out.println(Integer.toHexString(a.hashCode()));//打印hash地址System.out.println(a);a.setCharAt(1, 'B'); //改变字符System.out.println(Integer.toHexString(a.hashCode()));System.out.println(a);
常用方法
public class TextStringBuilder2 {public static void main(String[] args) {StringBuilder a = new StringBuilder();for (int i = 0; i < 7; i++) {char temp = (char)('A'+i);a.append(temp);//append方法 数组对象不变 累加字符序列}System.out.println(a);a.reverse();//倒序System.out.println(a);a.setCharAt(1, 'B');System.out.println(a);a.insert(2, 'a');System.out.println(a);a.insert(0, 'z').insert(1,'y').insert(2,'x');//链式调用 因为该方法每次都是返回自己System.out.println(a);a.delete(1, 3);//删除某个区间 也可以链式调用System.out.println(a);}}
注:累加字符序列用stringbuilder append方法 防止创建多个对象影响程序效率
时间类
Date时间类(java.util.Date)
DateFormat类和SimpleDateFormat类
把时间对象转化成指定格式的字符串。反之,把指定格式的字符串转化成时间对象。DateFormat是一个抽象类,一般使用它的的子类SimpleDateFormat类来实现
public class TextDate {public static void main(String[] args) throws ParseException {Date d = new Date(); //什么都不传表示当前时刻System.out.println(d);System.out.println(d.getTime()); //返回一个毫秒数//把时间对象按照指定格式转换成字符串DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");String str = df.format(new Date(666666));//格式化时间转成字符串System.out.println(str);//把字符串按照指定格式转换成时间对象DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");Date date = df2.parse("2020-6-27 18:8:8");//解析时间System.out.println(date); //时间格式 Sat Jun 27 18:08:08 CST 2020//D字符 获得本时间式所处年份的第几天DateFormat df3 = new SimpleDateFormat("D");String str3 = df3.format(new Date());System.out.println(str3);}}
Calendar日历类
Calendar 类是一个抽象类,提供了关于日期计算的相关功能
GregorianCalendar 是 Calendar 的一个具体子类,提供了世界上大多数国家/地区使用的标准日历系统
public class TextCalendar {public static void main(String[] args) {Calendar calendar = new GregorianCalendar();//不输入 默认当前日期//日期计算calendar.get(Calendar.DATE); //获取当前天数calendar.add(Calendar.DATE, 100);//往后100天的日期System.out.println(calendar);//日期对象和时间对象的转换Date d4 = calendar.getTime();//geTime()方法返回当前的时间System.out.println(d4); //日期对象转换成时间对象Calendar c = new GregorianCalendar();c.setTime(new Date()); //转成对应的日历类System.out.println(c);System.out.println("######");printCalendar(c); //封装方法打印日期类}public static void printCalendar(Calendar c) {int year = c.get(Calendar.YEAR);int month = c.get(Calendar.MONTH)+1;//0-11表示对应的月份int day = c.get(Calendar.DAY_OF_MONTH);int dayweek = c.get(Calendar.DAY_OF_WEEK);int hour = c.get(Calendar.HOUR);int min = c.get(Calendar.MINUTE);int sec = c.get(Calendar.SECOND);System.out.println(year+"-"+month+"-"+day+" "+dayweek+" "+hour+":"+min+":"+sec);}}
练习
//将一个时间字符串增加n天后返回public static void main(String[] args) throws ParseException {DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");Date date = df2.parse("2020-6-27 18:8:8");//解析时间Calendar calendar = new GregorianCalendar();calendar.setTime(date);calendar.add(Calendar.DATE, 10);Date time = calendar.getTime();String format = df2.format(time);System.out.println(format);}
LocalDateTime
#实例创建的方式--静态方法LocalDateTime localDateTime = LocalDateTime.now();LocalDateTime time = LocalDateTime.of(2022, 3, 26, 0, 0);
#日期的获取--类似与calendarlocalDateTime.getDayOfMonth();#日期的增加、减少 这几个api返回的都是新对象LocalDateTime dateTime = localDateTime.plusDays(10);LocalDateTime time = localDateTime.minusDays(10);//将日期的某个值修改为指定值后返回LocalDateTime dateTime = localDateTime.withDayOfMonth(6);//获取当前时间 有时差问题Instant instant = Instant.now();System.out.println(instant);//添加时差偏移量OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));System.out.println(offsetDateTime);//获取时间戳 有时差long l1 = instant.toEpochMilli();Instant instant1 = Instant.ofEpochMilli(l1);System.out.println(instant1);#计算两个时间之间的间隔 Duration以秒和纳秒为基准; Period以年、月、日为衡量LocalDateTime time1 = LocalDateTime.now();LocalDateTime time2 = LocalDateTime.of(2022, 3, 26, 0, 0);Duration duration = Duration.between(time2, time1);System.out.println(duration.getSeconds());
#格式化时间String format = formmater.format(LocalDateTime.now());System.out.println(format);TemporalAccessor parse = formmater.parse("2022-03-26 02:46:37");System.out.println(parse);
Math类
public class TestMath {public static void main(String[] args) {//取整相关操作System.out.println(Math.ceil(3.2));System.out.println(Math.floor(3.2));System.out.println(Math.round(3.2));//四舍五入System.out.println(Math.round(3.8));//绝对值、开方、a的b次幂等操作System.out.println(Math.abs(-45));System.out.println(Math.sqrt(64));System.out.println(Math.pow(5, 2));System.out.println(Math.pow(2, 5));//Math类中常用的常量System.out.println(Math.PI);System.out.println(Math.E);//随机数System.out.println(Math.random());// [0,1)}}
Math.random()类
public class TestRandom {public static void main(String[] args) {//随机数System.out.println(Math.random());// [0,1)Random rand = new Random();//随机生成[0,1)之间的double类型的数据System.out.println(rand.nextDouble());//随机生成int类型允许范围之内的整型数据System.out.println(rand.nextInt());//随机生成[0,1)之间的float类型的数据System.out.println(rand.nextFloat());//随机生成false或者trueSystem.out.println(rand.nextBoolean());//随机生成[0,10)之间的int类型的数据System.out.print(rand.nextInt(10));//随机生成[20,30)之间的int类型的数据System.out.print(20 + rand.nextInt(10));}}
File类的基本用法
java.io.File类:代表文件和目录。 在开发中,读取文件、生成文件、删除文件、修改文件的属性时经常会用到本类。
//文件类的使用public class TextFile {public static void main(String[] args) throws IOException {//user.dir就是本项目的目录System.out.println(System.getProperty("user.dir"));File f = new File("gg.txt");//相对路径 默认当前项目下f.createNewFile();System.out.println("File是否存在:"+f.exists());System.out.println("File是否是目录:"+f.isDirectory());System.out.println("File是否是文件:"+f.isFile());System.out.println("File最后修改时间:"+new Date(f.lastModified()));System.out.println("File的大小:"+f.length());System.out.println("File的文件名:"+f.getName());System.out.println("File的目录路径:"+f.getPath());//相对路径System.out.println(f.getAbsolutePath());//绝对路径f.delete();//mkdir使用File f2 = new File("d:/电影/华语/大陆");boolean flag = f2.mkdir(); //目录结构中有一个不存在,则不会创建整个目录树System.out.println(flag);//创建失败//mkdirs 创建整个目录树File f3 = new File("c:/电影/华语/大陆");boolean flag1 = f3.mkdirs();System.out.println(flag1);System.out.println(f3.getAbsolutePath());f3.delete();}}
使用递归算法,以树状结构展示目录树
//递归遍历目录树public class TextFile2 {public static void main(String[] args) {File f1 = new File("C:\\C语言\\eclipse\\eclipse jee\\Practice\\src\\CommonClass");printFile(f1,0);countfile(f1);System.out.println(len);}static void printFile(File file,int n) {//输出层级for (int i = 0; i < n; i++) {System.out.print("-");}System.out.println(file.getName());if (file.isDirectory()) {File[] files = file.listFiles();//返回子目录子文件for (File temp : files) {printFile(temp,n+1);}}}//统计文件内容的大小private static long len=0;static void countfile(File file) {if(file.exists()) {if(file.isFile()) {len += file.length();}else {for(File tempFile:file.listFiles()) {countfile(tempFile);}}}}}
//使用面向对象方法实现文件大小的统计public class CountFile {private static long len;private String dirpath; //文件夹路径private File srcFile; //源头文件private int filesize; //文件个数private int dirsize; //文件夹个数public CountFile(String dirpath) {super();this.dirpath = dirpath;this.srcFile = new File(dirpath);//传入对象countfile(this.srcFile);}//统计文件内容的大小private void countfile(File file) {if(file.exists()) {if(file.isFile()) {len += file.length();this.filesize++;}else {this.dirsize++;for(File tempFile:file.listFiles()) {countfile(tempFile);}}}}public static long getLen() {return len;}public int getFilesize() {return filesize;}public int getDirsize() {return dirsize;}public static void main(String[] args) {CountFile coun1 = new CountFile("C:/C语言/eclipse/eclipse jee/Practice");System.out.println(coun1.getLen());System.out.println(coun1.getFilesize());System.out.println(coun1.getDirsize());}}
