当前位置:网站首页>Day-14 common APIs
Day-14 common APIs
2022-07-07 12:36:00 【Xiaobai shelter】
1.String
1.1 summary
java.lang.String: It's a string class , The bottom floor is a final Embellished char Array , therefore String Many features are the properties of arrays
such as Once the length is determined , Can't change
① Once the string is created , This string object cannot be changed
② To improve string access and storage efficiency ,java The virtual machine uses a caching mechanism , Save all strings in the string constant pool
③ During program execution , If you want to use a string a, String s1=‘a’; First, search the string constant pool , If not, create one If there is String s2=‘a’; No more creation , Take the existing one a return
So lead to String s1=‘a’ String s2=‘a’ here Use s1==s2 He is also true, Because they point to the same string object , Namely a
1.2 Basic use
1.3 Do not splice frequently
Because the string cannot be changed after it is created , If you splice frequently , Efficiency is very low , And garbage collection may also have problems
1.4 Construction method
① Literal String s1=“djalskdjl”;
②String s2= new String(“xxx”);
③ Byte array
byte[] bytes={97,98,99,100,101,102};
String s3=new String(bytes);
System.out.println(s3) //abcdef
④ Byte array , Just cut it off ,4 Indicates the starting position ( contain ),2 Denotes number
String s4 = new String(bytes,4,2);
System.out.println(s4);
⑤ A character array
char[] chars={‘a’,‘b’,‘c’};
String s5= new String(chars);
System.out.println(s5);
⑥ A character array , Just cut it off ,1 Indicates the starting subscript ,2 Denotes number
String s6=new String(chars,1,2);
System.out.println(s6);
1.5 Common methods
Study API 1. What is the function 2. What are input and output parameters 3. How to use it?
//1 char charAt(int index): Returns... In the string , The character in the specified position
String s1="qwehihasd";
char c1=s1.charAt(2);
//e
System.out.println(c1);
//boolean endsWith(String suffix): Determines whether the string ends with the specified string
//boolean startsWith(String prefix): ditto , Judgment begins
System.out.println("Hello.java".endsWith(".java"));
// Note blank space , If there is a space, it won't match
System.out.println("Hello.java".endsWith(".java"));
//3 boolean equalslgnoreCase(String str): Case insensitive comparison of two strings for equality
System.out.println("abc".equalsIgnoreCase("aBc"));
//4 byte[] getBytes(): Converts a string to a byte array and returns
byte[] bytes="abc".getBytes();
for(int i=0;i<bytes.length;i++){
System.out.println(bytes[i]);
}
//6 int indexOf(String str): Gets the starting index of the specified string in the string , No return found -1
System.out.println("dahdadladl".indexOf("da"));//0
System.out.println("ashdaljdl".indexOf("asd"));//-1
//7 int indexOf(String str,int index):
// Search from the specified location ( contain ), Gets the starting index of the specified string in the string , No return found -1
System.out.println("asyhdklaisudo".indexOf("m", 5));//-1
//8 index lastIndexOf(String str): ditto , The last index to appear No return found -1
System.out.println("sahdalid".lastIndexOf("a", 1));//1
//9 int length(): Returns the length of the string
System.out.println("dahdkah".length());
//10 String replaceAll(String regex.String replacement);
// Replace specified characters , regular expression
//String replace(String str.String replacement); Regular expressions are not supported
// use 1 hold a Replaced and returned a new string
// regular expression , But there is no regular expression , There is no difference
System.out.println("hucgasdqweasd".replaceAll("a", "1"));
System.out.println("hucgasdqweasd".replace("a", "1"));
// because . In regular expressions , Arbitrary character
System.out.println("qwe.rty.yui.uio".replaceAll(".", ","));
// have access to \ escape
System.out.println("qwe.rty.yui.uio".replaceAll("\\.", ","));
System.out.println("qwe.rty.yui.uio".replace(".", ","));
// 11 String[] split(String regex) : Split string , Return string array , regular expression , Be careful .....
// spot , Need to escape
String s2 = "2022.1.14";
String[] arr = s2.split("\\.");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
// 12 String substring(int begin); In the string , Substring starting with a subscript ( contain )
System.out.println("abcdef".substring(2));// cdef
// 13 String substring(int begin, int end) :
// In the string , Start with a subscript ( contain ) Substring ending at a subscript ( It doesn't contain )
System.out.println("abcdef".substring(2, 4));// cd
// 14 String trim() : Remove the spaces on both sides of the string
System.out
.println(" a da sadasd adafga ");
System.out
.println(" a dada d dafafg sadasd "
.trim());
// 15 String toUpperCase() : Turn capitalization
// String toLowerCase() : Turn lowercase
System.out.println("asd".toUpperCase());
// 16 static String valueOf(Object obj) :
// Calling the toString Method , If null, No more calls toString Instead, it returns a string null
String_05 s = null;
// When printing a reference type , Automatically called String Of valueOf therefore Automatically called toString Method
System.out.println(s); Insert a code chip here
2 StringBuffer and StringBuilder
2.1 summary
StringBuffer and StringBuilder : Are all string buffers , It can be used for splicing \
*
* StringBuffer and StringBuilder and String difference
*
* String : The bottom is char Array , Fixed length , Once created , Non modifiable , Not suitable for string splicing
*
* StringBuffer and StringBuilder : The bottom is char Array , Lengthening , Apply for a piece of space in memory in advance , Used to save many characters
* If the reserved space is insufficient , Automatic capacity expansion
* Default capacity is 16, Expand capacity ( Current capacity +1)*2 16->34->70
*
* StringBuffer and StringBuilder The difference between
* StringBuffer Thread safety , In multithreaded environment , No problem
* StringBuilder Non-thread safety , In multithreaded environment , There may be problems
2.2 Basic use
// Create an object
StringBuilder sb = new StringBuilder();
String[] arr = {
"a","b","c"};
for (int i = 0; i < arr.length; i++) {
// append Is to add data , Do the splicing operation
// You can chain call
sb.append(arr[i]).append(",");
}
2.3 Common methods
// reverse
sb.reverse();
// Get the number of existing elements
System.out.println(sb.length());
// Current capacity ( The length of the array )
System.out.println(sb.capacity());
// toString You can put StringBuilder Convert to String type
String str = sb.toString();
System.out.println(str);
3. Packaging
3.1 summary
【 ask 】 Want to do more with basic type data , What do I do ?
【 answer 】 The most convenient way is to encapsulate it as an object . Because more properties and behaviors can be defined in the object description to operate on the basic data type . We don't need to encapsulate basic types by ourselves ,JDK It has been encapsulated for us .
【 Concept 】
- Boxing is the automatic conversion of basic data types to wrapper types
- Unpacking is automatically converting the wrapper type to the basic data type
3.2 Use
public static void main(String[] args) {
// Basic types
byte b1 = 12;
// Encapsulate as wrapper class
Byte b2 = new Byte(b1);
m1(b2);
long l1 = 123L;
Long l2 = new Long(l1);
}
3.3Integer
3.3.1 Basic use
public static void main(String[] args) {
// Maximum
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
System.out.println(Long.MAX_VALUE);
System.out.println(Double.MAX_VALUE);
// Create objects
Integer i1 = new Integer(123);
// Passing strings can also , But it must be pure numbers
Integer i2 = new Integer("1231");
// Report errors java.lang.NumberFormatException: For input string: "1231a"
Integer i3 = new Integer("1231a");
}
3.3.2 Reciprocal transformation
// int ---> Integer
Integer i1 = new Integer(123);
i1 = Integer.valueOf(123);
// Integer --> int
int i2 = i1.intValue();
// String --> integer
Integer i3 = new Integer("123");
i3 = Integer.valueOf("123");
// Integer --> String
String string = i3.toString();
// int --> String
String string1 = 123+"";
// String --> int
// important static int parseInt(String str) : Convert a pure numeric string to int type
int i4 = Integer.parseInt("123");
double d1 = Double.parseDouble("2.4");
// Put numbers in binary string form , And back to
String s1 = Integer.toBinaryString(10);
// ditto , octal
s1 = Integer.toOctalString(10);
// ditto , Hexadecimal
s1 = Integer.toHexString(10);
System.out.println(s1);
3.3.3 Common methods
3.3.4 Automatic packing and unpacking
java1.5 New characteristics Automatic packing and unpacking
* Packing : Basic types To Packaging type
* Unpacking : Packaging type To Basic types
*
* Eight kinds of packaging It's all overwritten toString and equals() Method
// 1.5 That's what I wrote before
Integer i1 = Integer.valueOf(123);
int i2 = i1.intValue();
// 1.5 Start
Integer i3 = 123; // After the compilation Is equal to Integer i3 = Integer.valueOf(123);
int i4 = i3; // After the compilation Is equal to int i4 = i3.intValue();
m1(i3);
// 1234 by int type , The automatic packing will be carried out first Integer type , Then polymorphic transformation occurs to Object type
m1(1234);
}
3.3.5 Deep into the integer constant pool
public static void main(String[] args) {
int i = -128;
System.out.println(-i);
Integer i1 = new Integer(10);
Integer i2 = new Integer(10);
// false
System.out.println(i1 == i2);
// true
System.out.println(i1.equals(i2));
Integer i3 = Integer.valueOf(-126);
Integer i4 = Integer.valueOf(-126);
// true
System.out.println(i3 == i4);
Integer i5 = 12; // After the compilation Integer.valueOf(12);
Integer i6 = 12;
// true
System.out.println(i5 == i6);
Integer i7 = 222; // Is equal to new Integer(222)
Integer i8 = 222;
// false , Because the range of integer constant pool is -128 ~ 127 Between
System.out.println(i7 == i8);
}
3.3.6 summary
summary :
When we adopt new Integer(xx) When creating objects , No matter how much it's worth ,. == Forever false
When we use Integer i1 = xxx; In this way , After the compilation Will be converted to Integer.valueOf() ; This method will pass through the integer constant pool
If xxx This value stay -128 To 127 Between be Unwanted new object , Instead, use the objects already created in the constant pool
otherwise No longer in scope , Is still equal to new Integer(xxx) This way,
therefore
Integer i1 = xxx;
Integer i2 = xxx; If xxx stay -128 ~ 127 Between be i1 == i2 yes true
however Be careful Integer Comparison between types Still need to use equals Comparison is the best
4 System
4.1 summary
System Class provides the public static long currentTimeMillis() Used to return the current time Between and 1970 year 1 month 1 Japan 0 when 0 branch 0 The time difference in milliseconds between seconds .
This method is suitable for calculating time difference .
System Class represents system , Many system level properties and control methods are placed inside the class . This class is located in java.lang package .
Because the constructor of this class is private Of , So we can't create objects of this class , That is, it can't be realized Instantiate this class . Its internal member variables and member methods are static Of , So it can also be very convenient To call .
Member variables
System Class contains in、out and err Three member variables , They represent the standard input stream
( Keyboard entry ), Standard output stream ( Monitor ) And standard error output stream ( Monitor ).
Member method
native long currentTimeMillis():
The function of this method is to return the current computer time , Time is expressed in the current computer
Between and GMT Time ( Greenwich mean time )1970 year 1 month 1 Number 0 when 0 branch 0 The number of milliseconds in seconds .
void exit(int status):
The function of this method is to exit the program . among status The value of is 0 It means normal exit , Non zero means
Abnormal exit . Using this method, the exit function of program can be realized in GUI programming .
4.2 Common methods
5 Date
5.1 summary
Get time and time operations
5.2 Construction method
// Get current system time
Date d1 = new Date();
// Incoming milliseconds , Get the world from the time origin to the specified number of milliseconds
Date d2 = new Date(1000);
// Fri Jan 14 16:15:57 CST 2022
System.out.println(d1);
// Thu Jan 01 08:00:01 CST 1970
System.out.println(d2);
5.3 Common methods
// 1642148327849 Gets the number of milliseconds for the specified time
System.out.println(d1.getTime());
// Convert time into String type
System.out.println(d1.toString());
5.4 format
/** * year y * month M * Japan d * when H * branch m * second s * millisecond S */
// Create a time format object
SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd Japan HH:mm:ss SSS");
// format , Return string
String string = sdf.format(d1);
System.out.println(string);
// String in time format Convert to Date object
String strDate = "2022/01/14 16:21:36";
// Format the time format of the object And the format of the string Agreement
sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// transformation return Date object
Date date = sdf.parse(strDate);
System.out.println(date);
5.5 Calendar
// Get the current calendar
Calendar c = Calendar.getInstance();
// Get the current day of the week , Sunday is the first day
System.out.println(c.get(Calendar.DAY_OF_WEEK));
// year
System.out.println(c.get(Calendar.YEAR));
// month , 0 yes 1 month , 11 yes 12 month , therefore result +1 That's right
System.out.println(c.get(Calendar.MONTH)+1);
// Japan Get the day of the month today
System.out.println(c.get(Calendar.DAY_OF_MONTH));
// when 12 hourly
System.out.println(c.get(Calendar.HOUR));
// 24 hourly
System.out.println(c.get(Calendar.HOUR_OF_DAY));
// branch
System.out.println(c.get(Calendar.MINUTE));
// second
System.out.println(c.get(Calendar.SECOND));
6.Random
6.1 summary
Random number from 0 Start
6.2 Use
// Create random number generator
Random r = new Random();
// stay int Within the scope of I'm going to randomly generate a number
int i = r.nextInt();
System.out.println(i);
// Pass in 10 The explanation should be in 0~9 Between generation
i = r.nextInt(10);
System.out.println(i);
// Generate 10~22
// nextInt( Maximum - minimum value + 1) + minimum value
int result = r.nextInt(100 - 20 + 1) + 20;
System.out.println(result);
边栏推荐
- idea 2021中文乱码
- 广州市召开安全生产工作会议
- Tutorial on principles and applications of database system (009) -- conceptual model and data model
- 30. Feed shot named entity recognition with self describing networks reading notes
- Cookie
- 牛客网刷题网址
- 编译 libssl 报错
- BGP actual network configuration
- Configure an encrypted web server
- 【统计学习方法】学习笔记——第五章:决策树
猜你喜欢
BGP actual network configuration
What is an esp/msr partition and how to create an esp/msr partition
SQL lab 26~31 summary (subsequent continuous update) (including parameter pollution explanation)
浅谈估值模型 (二): PE指标II——PE Band
The hoisting of the upper cylinder of the steel containment of the world's first reactor "linglong-1" reactor building was successful
SQL head injection -- injection principle and essence
对话PPIO联合创始人王闻宇:整合边缘算力资源,开拓更多音视频服务场景
Minimalist movie website
OSPF exercise Report
Configure an encrypted web server
随机推荐
SQL Lab (32~35) contains the principle understanding and precautions of wide byte injection (continuously updated later)
SQL blind injection (WEB penetration)
TypeScript 接口继承
leetcode刷题:二叉树19(合并二叉树)
Session
浅谈估值模型 (二): PE指标II——PE Band
How much does it cost to develop a small program mall?
Realize a simple version of array by yourself from
[statistical learning methods] learning notes - improvement methods
idm服务器响应显示您没有权限下载解决教程
The hoisting of the upper cylinder of the steel containment of the world's first reactor "linglong-1" reactor building was successful
Zhimei creative website exercise
MPLS experiment
Connect to blog method, overload, recursion
leetcode刷题:二叉树25(二叉搜索树的最近公共祖先)
数据库系统原理与应用教程(009)—— 概念模型与数据模型
【统计学习方法】学习笔记——支持向量机(下)
[play RT thread] RT thread Studio - key control motor forward and reverse rotation, buzzer
Cookie
SQL lab 1~10 summary (subsequent continuous update)