1.String类
是final类型的,不可被继承
实现了Serializable接口,可序列化
实现了Comparable接口,compareTo()方法,可以比较大小
final char[] value,String代表一个不可变的字符序列,不可变性:
1)重新赋值,改变不了原有的value,只能重新指定内存区域
2)字符串对象用'+'进行拼接,会重新指定内存区域
String str = "abc"; //字面量的方式赋值
利用字面量的方式给String对象赋值会存储在方法区的字符串常量池中,字符串常量池不会存储相同内容的字符串
String对象的创建
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");
String s4 = new String("hello");
System.out.println(s1 == s2); //true
System.out.println(s1 == s3); //false
System.out.println(s3 == s4); //false
String s1 = "java";
String s2 = "EE";
String s3 = "javaEE";
String s4 = "java" + "EE"; //常量与常量进行拼接,结果还在常量池中
String s5 = s1 + "EE"; //含有变量的拼接,会在堆空间开辟新空间
String s6 = "java" + s2;
System.out.println(s3 == s4); //true
System.out.println(s3 == s5); //false
System.out.println(s5 == s6); //false
final String s7 = "java"; //在常量池
2.常用方法
length()
charAt(index)
trim() //返回去除了前面和后面的空格的字符串
"a".compareTo("c") //返回结果为-2
substring(index) //返回index及其之后索引的字符组成的字符串
substring(start, end) //返回start(包含)到end(不包含)的字符组成的字符串
startsWith(preffix)
startsWith(preffix, index)
endsWith(suffix)
contains(CharSequence seq)
indexOf(str) 返回str第一次出现的索引
indexOf(str, fromIndex)
lastIndexOf(str)
replace(oldChar, newChar) //全部替换
split(regex)
String类转换
char[] str.toCharArray() //字符数组
byte[] str.getBytes() //字节数组
byte[] str.getBytes("gbk") //编码
new String(bytes, "gbk") //解码
new StringBuffer(String str)
new StringBuilder(String str)
new String(StringBuffer str)
new String(StringBuilder str)
3.日期
1java.lang.System
long currentTimeMillis() //1970年1月1日0时0分0秒至今毫秒数
2java.util.Date
|--java.sql.Date
构造器
Date date = new Date(); //当前时间的对象
Date date = new Date(long millis); //指定时间的对象
java.sql.Date date = new java.sql.Date(long millis); //指定时间的对象
方法
date.getTime() //1970年1月1日0时0分0秒至date的毫秒数
SimpleDateFormat() //默认格式
SimpleDateFormat(String pattern)
eg: "yyyy-MM-dd GGG hh:mm:ss aaa"
String sdf.format(Date date)
Date sdf.parse(str)
5.Calendar
Calendar是抽象类
1静态方法getInstance()返回对象 //当前时刻对象
2子类new GregorianCalcendar
get() //eg: calendar.get(Calendar.DAY_OF_MONTH)
//注意:
//1.获取月份时,一月是0,二月是1,依此类推
//2.获取星期时,周日是1,周一是2...周六是7
set() eg: calendar.set(Calendar.DAY_OF_MONTH, day)
add()
getTime() //返回java.util.Date对象
setTime(Date date)
6.jdk1.8新日期API
Date类的一月从0开始
jdk1.8引入Joda Time
常用类
LocalDate LocalTime LocalDateTime
静态方法返回对应类的对象
now() //当前时间
of() //指定时间
7.Instant类
Instant instant = Instant.now(); //本初子午线处的时间对象
OffsetDateTime offsetDateTime = instant.atFoffset(ZoneOffset.ofHours(hour));
instant.toEpochMilli() //类似Date类的getTime()
Instant Instant.ofEpochMilli(long millis)