String class
String class: represents a string
The String class is a final class, cannot be inherited, immutable character sequence
When reassigning a string, you need to rewrite the assignment of the specified content area, and you cannot use the original value assignment
When the existing string is concatenated, it is also necessary to re-specify the memory area assignment, and the original value assignment cannot be used
When calling the replace() method of String to modify the specified character or string, it is also necessary to re-specify the memory area for assignment, and the original value cannot be used for assignment
A string is a constant, enclosed in double quotes, and the value cannot be changed after creation
The character content of the String object is stored in a character array value
Common methods of String class
method
meaning
int length()
Returns the length of the string
char charAt(int index)
returns the character indexed somewhere
boolean isEmpty
Check if it is an empty string
String toLowerCase()
Convert characters to lowercase
String toUpperCase()
Convert characters to uppercase
String trim()
Returns a copy of the string, ignoring leading and trailing whitespace
boolean equals(Object Obj)
Compare whether the string content is the same
boolean equalslgnoreCase(String anotherString)
Similar to equals, but ignores case
String concat(String str)
Concatenates the specified string to the end of the substring
int compareTo(String anotherString)
compares the size of two strings
String subString(int beginIndex)
Return a new string, which is intercepted from beginIndex to the last string
String subString(int beginIndex,int endIndex)
Returns a new string that starts at beginIndex and ends at endIndex (exclusive)
boolean startsWith(String suffix)
Tests whether a string starts with the specified string
boolean startsWith(String prefix,int toffset)
Tests whether the string at the specified location starts with the specified prefix
boolean endsWith(String prefix)
Tests whether a string ends with the specified string
boolean contains(CharSequence s)
Returns true if and only if this string contains the specified sequence of char values
int IndexOf(String str)
Returns the index of the first occurrence of this character
int IndexOf(String str,int fromIndex)
Returns the index of the first occurrence of this character, starting at the specified index
int lastIndexOf(String str)
Returns the index of the rightmost occurrence of this character
int lastIndexOf(String str,int fromIndex)
The index of the last occurrence of this character, reverse search from the specified index
String replace(char oldChar,char newChar)
Return a new string, which is obtained by replacing all oldChar with newChar
String replace(CharSequence target,CharSequence replacement)
Replaces all substrings of this string that match the literal target sequence with the specified literal replacement sequence
String replaceAll(String regex,String replacement)
Replaces all matching substrings of the regular expression with the given replacement
String replaceFirst(String regex,String replacement)
Replaces the first substring of all matching regular expressions with the given replacement
boolean matches(String regex)
Tells whether this string matches the given regular expression
String[] split(String regex)
Split a string according to the given regular expression
String[] split(String regex,int limit)
Split the string according to the given regular expression, but not more than the limit, and put more in the last one
String class and basic data conversion
string => basic data type, wrapper class
Call the static method of the wrapper class: parseXXX(str)
Basic Data Types => Wrapper Classes
Call String overloaded valueOf(XXX)
Use the connector "+"
Convert between String and character array
String=>char[] str.toCharArray()
char[]=>String calls the String constructor
Convert between String and byte[] bytes
Conversion between String=>byte[] Call getBytes() of String
Conversion between byte[]=>String Call the constructor of String
StringBuffer class
variable sequence of characters
thread safe, low efficiency
method
meaning
append(XXX)
add element
delete(int start,int end)
delete element
replace(int start,int end,String str)
replace element
insert(int offset,XXX)
Insert at specified position
reverse()
reverse the current character sequence
subString(int start,int end)
Returns a substring from start to end (exclusive)
length()
Returns the length of the array
charAt(int n)
returns the character of n
setCharAt(int n,char ch)
modify a character
StringBuilder class
variable sequence of characters
Thread unsafe, high efficiency
The method is consistent with the StringBuffer class
date time API
java.lang.System class
System.currentTimeMillis()
Used to return the time difference in milliseconds from the current date at 0:00:00 on January 1, 1970
java.util.Date class
Date(): The no-argument constructor can get the local time
Date(long date)
getTime():返回自1970年1月1日00:00:00GMT以此Date对象的毫秒数
toString():把Date转换为以下形式的String:dow mon dd hh:mm:ss zzz yyy
java.sql.Date类
@Test
public void test8 ( ) {
java. sql. Date date2= new java. sql. Date( 1665110725360L ) ;
System . out. println ( date2) ;
}
java.util.Date类转换为java.sql.Date类
java. util. Date date3= new java. util. Date( ) ;
java. sql. Date date4= new java. sql. Date( date3. getTime ( ) ) ;
System . out. println ( date4) ;
SimpleDateFormat类
import org. junit. Test ;
import java. text. ParseException ;
import java. text. SimpleDateFormat ;
import java. util. Date ;
public class DateTest {
@Test
public void testSimpleDateFormat ( ) throws ParseException {
SimpleDateFormat sdf= new SimpleDateFormat ( ) ;
Date date= new Date ( ) ;
System . out. println ( date) ;
String format= sdf. format ( date) ;
System . out. println ( format) ;
String str= "2022/11/8 下午9:14" ;
Date date2= sdf. parse ( str) ;
System . out. println ( date2) ;
SimpleDateFormat sdf1= new SimpleDateFormat ( "yyyy-MM-dd hh:mm:ss" ) ;
String format1= sdf1. format ( date) ;
System . out. println ( format1) ;
String str1= "2000-11-11 11:11:11" ;
Date date3= sdf1. parse ( str1) ;
System . out. println ( date3) ;
}
}
Calendar类
实例化对象
Calendar calendar= Calendar . getInstance ( ) ;
常用方法
Calendar calendar= Calendar . getInstance ( ) ;
int day1= calendar. get ( Calendar . DAY_OF_MONTH) ;
System . out. println ( day1) ;
System . out. println ( calendar. get ( Calendar . DAY_OF_YEAR) ) ;
calendar. set ( Calendar . DAY_OF_MONTH, 10 ) ;
System . out. println ( calendar. get ( Calendar . DAY_OF_MONTH) ) ;
calendar. add ( Calendar . DAY_OF_MONTH, 10 ) ;
System . out. println ( calendar. get ( Calendar . DAY_OF_MONTH) ) ;
Date date1= calendar. getTime ( ) ;
System . out. println ( date1) ;
Date date2= new Date ( ) ;
calendar. setTime ( date2) ;
int day3= calendar. get ( Calendar . DAY_OF_MONTH) ;
System . out. println ( day3) ;
java8新的API
LocalDate,LocalTime,LocalDateTime
import org. junit. Test ;
import java. time. LocalDate ;
import java. time. LocalDateTime ;
import java. time. LocalTime ;
public class java8DateTime {
@Test
public void test ( ) {
LocalDate localDate= LocalDate . now ( ) ;
LocalTime localTime = LocalTime . now ( ) ;
LocalDateTime localDateTime = LocalDateTime . now ( ) ;
System . out. println ( localDate) ;
System . out. println ( localTime) ;
System . out. println ( localDateTime) ;
LocalDateTime localDateTime1 = LocalDateTime . of ( 2022 , 11 , 9 , 21 , 39 , 29 ) ;
System . out. println ( localDateTime1) ;
System . out. println ( localDateTime. getDayOfMonth ( ) ) ;
System . out. println ( localDateTime. getDayOfWeek ( ) ) ;
System . out. println ( localDateTime. getMonth ( ) ) ;
System . out. println ( localDateTime. getMonthValue ( ) ) ;
System . out. println ( localDateTime. getMinute ( ) ) ;
LocalDateTime localDateTime2 = localDateTime. withHour ( 2 ) ;
System . out. println ( localDateTime) ;
System . out. println ( localDateTime2) ;
LocalDateTime localDateTime3 = localDateTime. plusDays ( 3 ) ;
System . out. println ( localDateTime3) ;
LocalDateTime localDateTime4 = localDateTime. minusHours ( 2 ) ;
System . out. println ( localDateTime4) ;
}
}
instant类
import org. junit. Test ;
import java. time. Instant ;
import java. time. OffsetDateTime ;
import java. time. ZoneOffset ;
public class InstantTest {
@Test
public void instantTest ( ) {
Instant instant= Instant . now ( ) ;
System . out. println ( instant) ;
OffsetDateTime offsetDateTime = instant. atOffset ( ZoneOffset . ofHours ( 8 ) ) ;
System . out. println ( offsetDateTime) ;
long toEpochMilli = instant. toEpochMilli ( ) ;
System . out. println ( toEpochMilli) ;
Instant instant1 = instant. ofEpochMilli ( 1668433839379L ) ;
System . out. println ( instant1) ;
}
}
DateTimeFormatter
预定义格式
DateTimeFormatter isoLocalDateTime = DateTimeFormatter . ISO_LOCAL_DATE_TIME;
LocalDateTime now = LocalDateTime . now ( ) ;
String str= isoLocalDateTime. format ( now) ;
System . out. println ( now) ;
System . out. println ( str) ;
TemporalAccessor parse = isoLocalDateTime. parse ( "2022-11-14T22:02:23.117" ) ;
System . out. println ( parse) ;
本地相关格式
DateTimeFormatter dateTimeFormatter = DateTimeFormatter . ofLocalizedDateTime ( FormatStyle . SHORT) ;
String format = dateTimeFormatter. format ( now) ;
System . out. println ( format) ;
自定义格式
DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter . ofPattern ( "yyyy-MM-dd hh:mm:ss" ) ;
String format1 = dateTimeFormatter1. format ( LocalDateTime . now ( ) ) ;
System . out. println ( format1) ;
TemporalAccessor parse1 = dateTimeFormatter1. parse ( "2022-11-14 10:21:14" ) ;
System . out. println ( parse1)
Java比较器
Java中的对象,正常情况下我们只能进行==和!=
比较大小需要实现compareTo(obj)
compareTo接口
像Sting,包装类等实现了comparable接口,重写了compareTo接口
重写compareTo接口规则
如果当前对象this大于形参对象obj,返回正整数
如果当前对象this小于形参对象obj,返回负整数
如果当前对象this等于形参对象obj,返回0
import org. junit. Test ;
import java. util. Arrays ;
public class CompareTest {
@Test
public void test1 ( ) {
Goods [ ] arr= new Goods [ 4 ] ;
arr[ 0 ] = new Goods ( "mouse1" , 34 ) ;
arr[ 1 ] = new Goods ( "mouse1" , 24 ) ;
arr[ 2 ] = new Goods ( "mouse1" , 44 ) ;
arr[ 3 ] = new Goods ( "mouse1" , 14 ) ;
Arrays . sort ( arr) ;
System . out. println ( Arrays . toString ( arr) ) ;
}
}
class Goods implements Comparable {
String name;
double price;
public Goods ( String name, double price) {
this . name= name;
this . price= price;
}
public String getName ( ) {
return this . name;
}
@Override
public String toString ( ) {
return "name:" + this . name+ "price:" + this . 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. price) {
return - 1 ;
} else {
return 0 ;
}
}
throw new RuntimeException ( "输入有误" ) ;
}
}
comparator接口
当元素没有实现java.lang.Comparable接口,而又不方便更改代码时
当元素实现java.lang.Comparable接口,但排序规则不适合当前操作
重写compare(Object o1,Object o2)
如果方法返回正整数,则o1大于o2
如果返回零,则o1等于o2
如果方法返回负整数,则o1小于o2
public void test2 ( ) {
String [ ] arr= new String [ ] {
"AA" , "BB" , "SS" , "CC" } ;
Arrays . sort ( arr, new Comparator < String > ( ) {
@Override
public int compare ( String o1, String 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) ) ;
}
System类
代表系统,系统中很多属性和方法都放置在该类的内部
该类是私有的,无法创造该类的对象,无法实例化该类
内部成员方法都是static的
属性名
属性说明
java.version
java运行时环境版本
java.home
java安装目录
os.name
操作系统名称
os.version
操作系统版本
user.name
用户账户名称
user.home
用户的主目录
user.dir
用户当前工作目录
public void test1 ( ) {
String javaVersion= System . getProperty ( "java.version" ) ;
System . out. println ( javaVersion) ;
String javaHome= System . getProperty ( "java.home" ) ;
System . out. println ( javaHome) ;
String osName= System . getProperty ( "os.name" ) ;
System . out. println ( osName) ;
String osVersion= System . getProperty ( "os.version" ) ;
System . out. println ( osVersion) ;
String userName= System . getProperty ( "user.name" ) ;
System . out. println ( userName) ;
String userHome= System . getProperty ( "user.home" ) ;
System . out. println ( userHome) ;
String userDir= System . getProperty ( "user.dir" ) ;
System . out. println ( userDir) ;
}
Math类
Math类提供了一系列静态方法用于科学计算
其返回值一般为double类型
属性名
属性说明
abs
绝对值
acos,asin,atan,sin,cos,tan
三角函数
sqrt
平方根
pow(double a,doble b)
a的b次幂
log
自然对数
exp
e为底的指数
max(double a,double,b)
最大值
min(double a,double b)
最小值
random()
返回0到1的随机数
long round(double a)
double 数据类型转换为lang(四舍五入)
toDegrees(double angrad)
弧度转角度
toRadians(double angdeg)
角度转弧度