基本数据类型的包装类
字符串相关类
不可变字符序列:String
可变字符序列:StringBuffer ,StringBuilder
时间处理相关类
Date
DateFormat ,SimpleDateFormat ,Calendar
枚举类
Math类
public class Test {
public static void main(String[] args) {
//包装类型什么时候使用
//当传输的是一个对象时
int a =121;
Integer b =new Integer(456);
//自动装箱和自动拆箱 1.5之后
//自动装箱:基本类型---》包装类型
Integer i =666;
//自动拆箱
int c =b ;
System.out.println(c);
//包装类提供了一些好用的方法和常量
System.out.println("int的最大值"+Integer.MAX_VALUE);
System.out.println("int的最小值"+Integer.MIN_VALUE);
System.out.println("int的占有大小空间"+Integer.SIZE);
//重要 ,包装类提供了将字符串转换成基本类型的方法
String num="123";
int n = Integer.parseInt(num);
System.out.println(n);
//基本数据类型和包装类型计较
int x =123;
Integer y =new Integer(123);
}
}
包装类
/*
* 包装类中的一些细节
* 1.6种数值类型的包装类都继承了number类,Boolean 和character 没有继承
* 2.自动装箱和自动拆箱问题
*/
public class TestWrapper {
public static void main(String[] args) {
//自动装箱:auto_boxing
Integer i =123;
//手动装箱
Integer j =new Integer(123);
//自动拆箱
int a =new Integer(356);
//手动拆箱
int b =new Integer(356).intValue();
int x =123;
Integer z =123;
Integer y =new Integer(123);
//System.out.println(x==y.inValue())
System.out.println(x==y);//true
System.out.println(x==z);//true
Integer zz =129;//valueof 范围是127,-128
Integer ww=129;
//当-128,-127
System.out.println(y==zz);//false
System.out.println(ww==zz);//false
System.out.println(zz.equals(ww));//true
}
}
String (不可变字符序列)
常用基本方法
public class TestString {
public static void main(String[] args) {
//String 中常用的方法
String str="断水断电dssd";
//字符串长度:length
System.out.println("length:"+str.length());
//字母转换大小写
String upperCase = str.toUpperCase();
String lowerCase = upperCase.toLowerCase();
System.out.println("大写:"+upperCase);
System.out.println("小写:"+lowerCase);
//判断方法:字符串以什么开头。以什么结尾,是否包含某个字符串
System.out.println("开头"+str.startsWith("断"));
System.out.println("结尾"+str.endsWith("dssd"));
System.out.println("包含"+str.contains("断水断电"));
//根据索引获取字符 index
char charAt = str.charAt(2);//异常java.lang.StringIndexOutOfBoundsException
System.out.println(charAt);
//查找子串所在的索引
int indexOf = str.indexOf("水");
System.out.println(indexOf);
//其他方法(截取)
//截取电
String substring = str.substring(3,4);
System.out.println(substring);
}
}
StringBuilder,StringBuffer
StringBuilder,StringBuffer是AbstractStringBuilder 子类分别继承于他
/*
* 可变字符序列:StringBuffer,StringBuilder
*/
public class TestString2 {
public static void main(String[] args) {
//创建StringBuilder对象
StringBuilder builder=new StringBuilder();
//向StringBuilder添加字符串
builder.append("adc");
builder.append(true);
builder.append(123);
System.out.println(builder);//println方法的特点,打印对象时,默认会调用toString方法
//删除,替代,插入,判断位置,反转,
//insert在指定位置插入
builder.insert(2,"hello");//index,data
System.out.println(builder);
//delete 删除 delete deleteCharAt
//builder.delete(2,7);//删除【2-7】区间的字符串
builder.deleteCharAt(3);//删除指定位置字符串
System.out.println(builder);
//indexof,lastindexof 查找指定数据的索引位置
int indexof = builder.indexOf("l");
int lastIndexOf = builder.lastIndexOf("l");
System.out.println(builder.length());
System.out.println(indexof+","+lastIndexOf);
//reverse 将字符串反转
StringBuilder reverse = builder.reverse();
System.out.println(reverse);
//replace 替换
builder.replace(12, 14, "张杰");
System.out.println(builder);
}
}
结果
adctrue123
adhelloctrue123
adhlloctrue123
14
3,4
321eurtcollhda
321eurtcollh张杰
StringBuilder 实现原理
自己重写StringBuilder
import java.util.Arrays;
public class MyStringBuilder {
// 用于存放字符串
char[] value;
// 已经使用了多少长度
int count;
/**
* 无参构造器,默认长度16
*/
public MyStringBuilder() {
this(16);
}
// 有参构造器传入一个容量,创建字符数组
public MyStringBuilder(int capacity) {
this.value = new char[capacity];
}
public MyStringBuilder(String str) {
this(str.length() + 16);
// 将字符串添加到字符数组中
append(str);
}
/**
* 向StringBuilder中添加数据
*
* @param str
*/
public MyStringBuilder append(String str) {
// 判断null;
if (str == null) {
return appendNull();
}
// 获取要放进去的字符串的长度
int len = str.length();
// 确保数组容量足够
ensureCapacity(count + len);
// 将字符串存入字符数组
str.getChars(0, len, value, count);
// 让使用长度count变大
count += len;
// 返回当前对象
return this;
}
// 将null 存在到字符数组中
private MyStringBuilder appendNull() {
// 确保容量足够
ensureCapacity(count + 4);
// 记录当前放的长度
int c = count;
// 将"null" 存放在字符数组中
value[c++] = 'n';
value[c++] = 'u';
value[c++] = 'l';
value[c++] = 'l';
// 使长度count变大
count = c;
// 返回当前对象
return this;
}
/*
* 确保字符数组容量足够
*/
private void ensureCapacity(int minCapacity) {
if (minCapacity - value.length > 0) {
// 复制原数组的内容并扩大数组
value = Arrays.copyOf(value, newCapacity(minCapacity));
}
}
/**
* 根据传入的容量生成一个新的容量
*
* @param minCapacity
* @return
*/
private int newCapacity(int minCapacity) {
int newCapacity = value.length * 2 + 2;
int result = minCapacity > newCapacity ? minCapacity : newCapacity;
return result < 0 ? Integer.MAX_VALUE : result;
}
@Override
public String toString() {
return new String(value,0,count);
}
//返回实际存放的字符串的长度
public int length(){
return count;
}
//返回字符数组长素
public int size(){
return value.length;
}
}
测试
public class TestMyStringBuilder {
public static void main(String[] args) {
//创建对象
MyStringBuilder builder=new MyStringBuilder();
System.out.println("默认长度"+builder.size());
System.out.println("使用的长度"+builder.length());
//存放数据
builder.append("祖国万岁!!").append("china,").append("congratulations");
//打印
System.out.println(builder);
System.out.println("默认长度"+builder.size());
System.out.println("使用的长度"+builder.length());
}
}
StringBuilder 其他方法特性
关于equals 方法
/**
* 关于equals 方法
* @author lenovo
*
*/
public class TestMyStringBuilder {
public static void main(String[] args) {
//创建对象
StringBuilder builder=new StringBuilder("asda");
StringBuilder builder1=new StringBuilder("asda");
System.out.println(builder==builder1);
System.out.println(builder.equals(builder1));//false StringBuilder中没有重写equals方法
String s1="asda";
String s2="asda";
String s3=new String("asda");
System.out.println(s1==s2);//true
System.out.println(s1==s3);//false
System.out.println(s1.equals(s3));//true
//String 重写了equals 方法,但是会先比较类型,类型不一般,直接返回false
System.out.println(s1.equals(builder1));//false
System.out.println(s1.equals(builder1.toString()));//true
}
}
public void mian (String[]args){
String a="asas";
String b="sdsd";
String c =a+b;//虚拟机默认调用StringBuilder
}
string实践
trim :去除字符串两端的空白
split:可以用指定的字符分割字符串,会得到一个数组
tocharArray:将一个字符串转换为一个字符数组
public class Demo {
/**
* 用户提交用户名
* 用户名必须在6-12字符之间
* 用户之间不能有数字
* @param args
*/
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入用户名");
String username = sc.nextLine();
//获取用户名自符串长度
int len =username.length();
//判断用户名长度
if(len<6||len>12){
System.out.println("用户名长度错误请在6-12字符");
return;
}
//判断用户名中是否包含数字
for (int i = 0; i < len; i++) {
char c = username.charAt(i);
if(c>='0' && c<='9'){
System.out.println("用户名中有数字");
return;
}
}
System.out.println(username);
}
时间处理相关的类
- Calendar日历类 抽象类----要使用他的子类 GregorianCalendar
- DateFormat 时间格式类 抽象类 ----要使用它的子类
SimpleDateFormat - java.util. Date —日期类–java.sql.Date ,java.sql.Time java.sql.Timestamp
date
import java.util.Date;
public class TestDate {
public static void main(String[] args) {
//创建Date对象,当前日期
Date date = new Date();
Date date2 = new Date(System.currentTimeMillis());
//输出格式
System.out.println(date);
System.out.println(date2.toLocaleString());//转换为当前日期方法
//认识一下过时的方法
//未过时的方法
System.out.println(date.getTime());//日期对应的毫秒数
}
}
java.util. Date —日期类–java.sql.Date ,java.sql.Time java.sql.Timestamp
import java.sql.Date;
public class TestDate {
/**
* java.util.Date有三个子类
* java.sql.Date:只能表示年月日,没有无参构造
* java.sql.time:只能表示时分秒
* java.sql.TimeStamp:更精确的日期时间表示
* @param args
*/
public static void main(String[] args) {
//创建sql下的DATE对象
//1.通过构造器创建
Date date=new Date(System.currentTimeMillis());
//2.sql.Date中提供了一个静态方法,用于通过一个字符得到sql.Date对象,valueof
//字符格式必须是:年-月-日
date=Date.valueOf("2018-02-06");
//输出格式
System.out.println(date);//2018-02-06
//sql.Date--->util.Date
java.util.Date utilDate=date;
System.out.println(utilDate);//toString,子类重写了父类的toString,调用时,用到是子类的方法
//通过getTime方式转换
utilDate = new java.util.Date(date.getTime());
System.out.println(utilDate);
//util.Date--->sql.Date
date = new Date(utilDate.getTime());
System.out.println(date);
}
}
DateFormat 时间格式类 抽象类 ----要使用它的子类 SimpleDateFormat
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner
/**
* 接收用户输入日期(String)格式:年-月-日,时:分:秒
* 1,先将日期字符串转换为util.Date
* 2,再把util.Date转换为字符串,格式:xxxx年xx月xx日 时:分:秒
* @author lenovo
*需要使用DateFormat
*/
public class TestDateFormat {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入日期格式(yyyy-MM-dd HH:mm:ss)");
String dateStr=sc.nextLine();
Date date=null;
//创建时间格式化对象
DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//str--->Date,解析(parse)
try {
date = format.parse(dateStr);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
//重新创建格式化对象
DateFormat format2=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
//Date--->STR(format)格式化
if(date!=null){
String dateStr1 = format2.format(date);
System.out.println(dateStr1);
}
}
}
日历类
Calendar日历类 抽象类----要使用他的子类 GregorianCalendar
import java.time.Year;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* 测试日历
* @author lenovo
*
*/
public class TestGregorianCalendar {
public static void main(String[] args) {
//创建Calendar 对象
//1.new GregorianCalendar()得到一个日历对象
Calendar calendar = new GregorianCalendar();
//2.Calendar中提供一个静态方法,getInstance
calendar = Calendar.getInstance();
//输出格式
System.out.println(calendar);
//获取对应的信息,get()
System.out.println("年:"+calendar.get(Calendar.YEAR));
System.out.println("月:"+calendar.get(Calendar.MONTH));//0-11
System.out.println("日:"+calendar.get(Calendar.DATE));
//修改对应的信息,set()
//修改年为2022年
calendar.set(calendar.YEAR, 2022);
//add 增加
calendar.add(calendar.YEAR, 2);
System.out.println(calendar.get(Calendar.YEAR));
//Calendar 和Date之间的转换
Date date=new Date();
//date--->Calendar
//calendar.setTime(date);
//System.out.println(calendar.get(calendar.YEAR));
//Calendar --->date
date=calendar.getTime();
System.out.println(date);
//获取一个月中的最大天数
System.out.println(calendar.getActualMaximum(Calendar.DAY_OF_MONTH));//4月30天
}
}
日历练习
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Scanner;
/*
* 技能点:
* 1.字符串--->util.Date==>getTime();
* 2.Date--->Calendar ==>setTime();
* 3.修改日期-->set
* 4.记录用户输入的是哪一天--->get
* 5.判断星期几--->get
* 6.获取该月份的最大数-->getActuralMax
* 7.日期自增--->add
*/
public class TestGregorianCalendar1 {
public static void main(String[] args) {
//创建扫描器
Scanner sc =new Scanner(System.in);
while(true){
//提示用户输入
System.out.println("请输入一个日期,格式为:yyyy-MM-dd,输入exit退出");
//接收用户输入
String temp = sc.nextLine();
if(temp.equalsIgnoreCase("exit")){
System.out.println("ByeBye");
break;
}
//创建日期格式化对象
DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
try {
//1.字符串--->util.Date==>parse();//解析
Date date=dateFormat.parse(temp);
//Date--->Calendar ==>setTime();
//创建日历对象GregorianCalendar()
Calendar calendar=new GregorianCalendar();
//设置日期为用户输入的日期
calendar.setTime(date);
//打印日历抬头
System.out.println("日\t一\t二\t三\t四\t五\t六");
//记录用户输入的日器
int currDay=calendar.get(Calendar.DAY_OF_MONTH);
//修改日期为这个月的第一天
calendar.set(Calendar.DAY_OF_MONTH, 1);
//获取第一天的星期数
int fistDayWeek=calendar.get(Calendar.DAY_OF_WEEK);
for (int i = 1; i <fistDayWeek; i++) {
System.out.print("\t");
}
//获得当月的最大天数
int maxDay=calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
//循环打印
for (int i = 1; i <= maxDay; i++) {
//如果是当天打印*
if(calendar.get(Calendar.DATE)==currDay){
System.out.print("*");
}
System.out.print(i+"\t");
//如果是周六换行
if(calendar.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY){
System.out.println();
}
//天数加一
calendar.add(Calendar.DATE, 1);
}
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println();
System.out.println("--------------------------------------");
}
}
}
Math类
/**
* Math的特征:
* 1.该类final修饰的类,没有继承
* 2.构造器稀有不能直接new 对象
* 3.提供了静态的常量和静态的方法供用户使用
* @author lenovo
*
*/
public class TestMath {
public static void main(String[] args) {
//常量
System.out.println(Math.PI);//圆周率
System.out.println(Math.E);//自然对数的底数
//方法
System.out.println(Math.random());//产生随机数[0,1)
System.out.println(Math.abs(-100));//绝对值abs
System.out.println(Math.ceil(1.233));//天花板向上取整返回double
System.out.println(Math.floor(1.223));//向下取整返回double
System.out.println(Math.round(1.56));//四舍五入//返回long
System.out.println(Math.pow(5,2));//幂函数
System.out.println(Math.sqrt(25));//开根
System.out.println(Math.max(2, 4));//最大小
System.out.println(Math.min(34, 4));
}
}
枚举 (abstract)
只能取特定值中的一个;
使用enum 关键字
implements
Serializable ,Comparable
所有的都隐形继承java.lang.enum
默认将常量定义为 public static final
file(public)
import java.io.File;
import java.util.Date;
public class TestFile {
public static void main(String[] args) {
//创建file对象
//绝对路径的方式寻找文件
//File file=new File("E:\\JAVA实战项目\\file\\file");//pathname表示文件路径
//相对路径
//File file=new File("src/com/zhangjie/file/TestFile.java");
File file=new File("aa","test.txt");//parent ,child 到父文件夹下查找子文件夹
//判断file是否存在
System.out.println(file.exists());
//查看文件属性
System.out.println("文件名:"+file.getName());
System.out.println("文件大小:"+file.length()+"字节");//只有文件有大小文件夹不确定
System.out.println("文件最后修改日期:"+new Date(file.lastModified()));
System.out.println("判断文件是否可执行:"+file.canExecute());
System.out.println("判断文件是否可读:"+file.canRead());
System.out.println("判断文件是否可写:"+file.canWrite());
System.out.println("判断文件是否隐藏:"+file.isHidden());
System.out.println("判断文件是否是文件:"+file.isFile());
System.out.println("判断文件是否是目录:"+file.isDirectory());
}
}
实现dir命令功能
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class TestDir {
public static void main(String[] args) {
//创建扫描器
Scanner sc=new Scanner(System.in);
System.out.println("请输入命令。。。");
//接收命令
String code = sc.nextLine();
//判断输入命令是否为空
if(code.equalsIgnoreCase("dir")){
File file=new File("E:\\JAVA实战项目\\file");
//获取到file 文件夹所有文件和文件夹
/*String[] list = file.list();
for (String name : list) {
System.out.println(name);
}*/
//获取file文件夹下的所有文件和文件夹的Fileal对象
File[] filelist = file.listFiles();
for (File f : filelist) {
//获取最后修改时间
long lastModified = f.lastModified();
DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date=new Date(lastModified);
String format2 = format.format(date);
System.out.print(format2);
//判断是否是文件夹
boolean directory = f.isDirectory();
if(directory==true){
System.out.print("\t<DIR>");
}else{
System.out.print("\t\t");
}
//判断是否是文件
if(f.isFile()){
System.out.print("\t"+f.length());
}else{
System.out.print("\t\t");
}
System.out.println("\t"+f.getName());
}
}
}
}
文件的创建和删除
public class TestCreatFile {
public static void main(String[] args) {
//文件的创建
File file=new File("demo.txt");
//创建文件
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//文件夹的创建
File file2=new File("a/ab/demo2.txt");
File parentFile = file2.getParentFile();
if(!parentFile.exists()){
//创建文件夹
parentFile.mkdirs();
}
if(!file2.exists()){
try {
file2.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
文件删除,文件路径打印
file.delete();
file.getpath();
file.getabsloudepath();
string 是不可变的,为同一个string多次赋值,之前的值将会被直接回收。
Stringbuffer Stringbuilder,是可变的可以直接利用append 进行字符串的拼接,StringBuffer是线程安全从java1.1就开始沿用,Stringbuilder是线程不安全的但效率高,