This article is to share the basic general knowledge of Java in the summary of SE knowledge, is my notes in the learning process and the summary sorted out later, very practical, I hope to help you.

Let’s share:

directory

String-related classes

1.1 the String

1.2 Common methods of String

1.3 StringBuffer and StringBuilder date and time

2.1 Date and time before JDK8

2.2 Dates and times in the JDK

2.3 Instant

2.4 DateTimeFormatter 3

System, Math, BigInteger, and BigDecimal

4.1 the System

4.2 Math

4.3 BigInteger and Bigdecimal

1.1 String A String is a final class, representing an immutable sequence of characters. Cannot be inherited. The character content of a String object is stored in a byte array called byte[]. Char [] is stored in JDK1.8.

String implements the Serializable interface and supports serialization

The Comparable interface is implemented, which means you can compare sizes

Assigns a literal value to a String (as opposed to new) in the String constant pool (the same place as the method area).

When a String joins, reassigns, replaces (), and so on, it reassigns the memory region instead of using the original value

String str = “hello”; // Literal assignment

String s1 = new String(); // essentially, this.value = new byte[0]

String s2 = new String(String str); // Put a String argument

String s3 = new String(byte[] a);

String s3 = new String(byte[] a,int off,int length); Char [] = char[]

Consider the following code:

String s1 = “javaEE”; String

s2 = “javaEE”; String

s3 = new String(“javaEE”); String

s4 = new String(“javaEE”);

Here, s1==s2 is true, s1==s3, s1==s4, s3==s4 are false

Here’s why:

In fact, constructing a String through a constructor points to value, which in turn points to a String constant. String s3 = new String(“javaEE”); Two objects are created in memory: a value structure in the heap and string data in the constant pool.

Intern () returns the canonical representation of the string object. This will return a string constant. The memory space is in the constant pool.

In addition, there is one thing to note about parameter arguments:

public class StringTest {

String str = new String(“hello”);

char[]ch = {‘t’,’e’,’s’,’t’};

public void change(String str,char ch[]){

str = "hello,world";

ch[0]='b';
Copy the code

}

public static void main(String[] args) {

StringTest st = new StringTest();

st.change(st.str, st.ch);

System.out.println(st.str);

System.out.println(st.ch);
Copy the code

}}

The result here is: “hello” /n “best”

Similar to C language, the content of two Pointers is exchanged according to the pointer. In the process of value transfer, the value of the actual parameter is passed into the parameter to form a copy. After the method is finished, the parameter disappears and the actual parameter value does not change.

One other thing to note:

String str = null; // This pointer points to null and is not instantiated

System.out.println(str); / / output “null”

System.out.println(str.length()); / / exception

1.2 Common String methods The common String methods are summarized as follows (if not summarized, please refer to yourself) :

At the same time, some methods that need to be paid attention to are as follows, with decreasing importance, but still need to be mastered:

Note: The four int methods at the bottom of the table above return -1 if not found

Here are a few more examples (some that may be less common) :

String regex is usually represented by regular expressions

A String is converted to a basic data type or wrapper class

Call a static method that wraps the class: the corresponding type, such as to int, calls integer.parseint (STR)

The base data type and wrapper class are converted to String

Call valueOf(XXX) for String overload

In addition

int num = 100;

String str = num+””; // the heap is returned only if there are variables, and the constant pool is returned if constants are added

This can also be converted to String, but note that this type generates an array of values in the heap, similar to new String.

Char []; char[]; byte[]

String–>char[] : calling string. toCharArray returns a char[]

Char [] or byte[] –> String: calls the constructor directly

String–>byte[] : Calling String.getBytes returns a byte[], which is converted using the default character set (for example, “GBK, UTF-8”, etc.).

GetBytes (Charset Charset) encodes the String as a sequence of bytes using the given Charset, storing the result in a new byte array. Different encoding methods may return different results.

Char [] char[] byte[

–>char[] : call string. toCharArray to return a char[]

Char [] or byte[] –> String: calls the constructor directly

String–>byte[] : Calling String. GetBytes returns a byte[].

, use the default character set (for example, “GBK”, utF-8) for conversion.

GetBytes (Charset Charset) encodes the String as a sequence of bytes using the given Charset, storing the result in a new byte array. Different encoding methods may return different results.

What are the similarities and differences between StringBuffer and StringBuilder?

String: immutable sequence of characters. Note immutability

StringBuffer: variable character sequences, thread-safe, inefficient (both synchronous methods)

StringBuilder: new in JDk5.0, mutable character sequences, thread unsafe, high efficiency

Final byte[] value //String

Byte [] value // In StringBuffer and StringBuilder

StringBuffer String str = new String(); // new char[0]

String str1 = new String(“abc”); //new char[] {‘a’,’b’,’c’};

StringBuffer sb = new StringBuffer(); //new char[16] The initial capacity is 16

sb.append(‘a’); // value[0]=’a’; In turn to

StringBuffer sb1 = new StringBuffer(“abc”); //new char[“abc”.length()+16]

System.out.println(sb.length()); //return count for each append operation count+=len (1), not value.length

Let’s look at how StringBuffer expands

In general, if the size of the array is not enough, expand the size of the original array by 2 +2, and copy the elements of the original array into the new array JDK15.

private int newCapacity(int minCapacity) {

int oldLength = value.length;

int newLength = minCapacity << coder;

int growth = newLength – oldLength;

int length = ArraysSupport.newLength(oldLength, growth, oldLength + (2 << coder));

if (length == Integer.MAX_VALUE) {

throw new OutOfMemoryError("Required length exceeds implementation limit");
Copy the code

}

return length >> coder; }

Arrayssupport. newLength compares growth with oldLength + (2 << coder), and oldLength + (2 < coder). Here, the original value of coder is 0. I only looked at the append source code, and the value of coder is unchanged.

In JDK1.8, the shift operation +2 is performed directly, the current version has been updated.

StringBuffer is a common method

StringBuilder has the same API, except that it is not thread-safe and does not guarantee synchronization.

Static Long currentTimeMillis() in java.lang.system returns the time difference in milliseconds between the current time and 00:00:00, January 1, 1970. Suitable for calculating time difference. (Time stamp) The main standards for calculating world time are UTC, GMT, and CST

java.util.Date

Java.sql also has a Date class, which is a subclass of java.util.Date

Indicates a specific time, to the millisecond

Use of two constructors:

Constructor 1: Create a Date object at the current time

Date date = new Date();

System.out.println(date); ToString: Mon Apr 26 01:16:00 CST 2021

System.out.println(date.getTime()); // Returns the timestamp of the current date object

// No arguments in Date construct source code

public Date() {

this(System.currentTimeMillis());
Copy the code

}

Constructor 2: Creates a Date object at the specified time

Date date1 = new Date(1619371381884L); // Select a timestamp

System.out.println(date1);

The rest of the constructor’s methods are outdated and not recommended.

Java.sql. Date corresponds to the date-time class in the database, which is generally used during database interaction

java.sql.Date date2 = new java.sql.Date(1619371381884L); //2021-04-26System.out.println(date2);

This class has no no-parameter constructs. The output forms are different.

The two types of Date convert each other:

Date date3 = (Date)date2; // Subclass to parent

System.out.println(date3);

java.sql.Date date4 = new java.sql.Date(new Date().getTime()); // Superclass to subclass, cannot cast

Java. Text. SimpleDateFormat allows formatting: date – > text, analytic: text – > date

Formatting:

Resolution:

Date Parse (String text, ParsePosition pos) parses the text from the String to produce a Date.

Examples of Pattern are as follows:

Demo1 Default mode:

SimpleDateFormat sdf = new SimpleDateFormat();

Date date = new Date();

String format = sdf.format(date);

System.out.println(date); //Mon Apr 26 02:38:11 CST 2021

System.out.println(format); / / 2021/4/26 instant in the morning

// Parsing process

String STR = “2021/4/16 12:38 am “; // The format is required

Date date1 = sdf.parse(str);

System.out.println(date1); //Fri Apr 16 00:38:00 CST 2021

Using the specified mode:

SimpleDateFormat sdf1 = new SimpleDateFormat(“yyyy,MM,dd HH:mm:ss aaa”);

String str2 = sdf1.format(date);

System.out.println(str2); / / 2021,04,26 02:47:22 morning

The normal mode is “YYYY-MM-DD hh: MM :ss”.

String str3 =”2021,04,26 02:47:22 am “;

Date date2 = sdf1.parse(str3);

System.out.println(date2); //Mon Apr 26 02:47:22 CST 2021

Calendar Calendar is an abstract class that is primarily used to complete interoperation between date fields.

Calendar provides a kind of method, getInstance, to get generally useful objects of this type. The getInstance method of Calendar returns a Calendar object whose Calendar fields have been initialized with the current date and time:

Calendar rightNow = Calendar.getInstance(); The constructor of its subclass GregorianCalendar is called

Calendar calendar = Calendar.getInstance();

System.out.println(calendar.getClass()); //class java.util.GregorianCalendar

A Calendar object can produce all the Calendar field values needed to implement date-time formatting in a particular language and Calendar style (for example, Japanese-Gregorian Calendar, Japanese-traditional). Calendar defines the range of values returned by certain Calendar fields and their meanings. For example, the value of the first MONTH in the calendar system is MONTH == JANUARY for all calendars. Other values are defined by specific subclasses, such as ERA. See the individual entity documentation and subclass documentation for more information.

Common methods:

Void set(int field, int value) sets the given calendar field to the given value.

Void add(int field, int amount) Adds or subtracts a given calendar field by a specified amount of time according to calendar rules.

Final Date getTime() returns a Date representing the Calendar time value of this object

Void setTime(Date Date) Sets the time of this calendar with the given Date

The demo is as follows:

Calendar calendar = Calendar.getInstance();

//get

int i = calendar.get(Calendar.DAY_OF_MONTH);

System.out.println(i); // Get the day of the month, in this case 26, the current time 4/26

System.out.println(calendar.get(Calendar.DAY_OF_YEAR)); // Similar to the previous one

//set

calendar.set(Calendar.DAY_OF_MONTH,12);

int j = calendar.get(Calendar.DAY_OF_MONTH); //12, changed

System.out.println(j);

//add

calendar.add(Calendar.DAY_OF_MONTH,3);

j = calendar.get(Calendar.DAY_OF_MONTH); //15, still change, add 3 days

System.out.println(j);

//getTime

Date date = calendar.getTime(); //Thu Apr 15 03:10:28 CST 2021

System.out.println(date);

//setTime: Date –> Calendar

calendar.setTime(date); // Directly manipulate the current object

int days = calendar.get(Calendar.DAY_OF_MONTH); / / 15

System.out.println(days);

When getting the month, January is 0; Get the day of the week, Sunday is 1

2.2 Date and time in JDK8 because the previous class has four problems:

Variability: For example, Calendar sets are mutable

Offset: The year in Date starts at 1900, the month starts at 0, and is offset if the call has a parameter construct.

Formatting: Formatting only works for Date, not Calendar

Thread insecurity

The Java.time API in Java 8 has corrected past defects.

Time and date related packge:

LocalDate, LocalTime and LocalDateTime are some of the most important classes. Their instances are immutable instances and use isO-8601 calendar system.

The ISO-8601 calendar system is a modern citizen’s representation of dates and times developed by the International Standard Language Organization (ISO) (Gregorian calendar)

Related methods:

The above four levels are actually the construct, get, set, and addition and subtraction operations. Similar to Calendar.

LocalDate is a final class with constructors like String, Math, and examples of current time generation:

LocalDate localDate = LocalDate.now(); / / 2021-04-27

LocalTime localTime = LocalTime.now(); / / 19:24:37. 171676500

LocalDateTime localDateTime = LocalDateTime.now(); / / the 2021-04-27 T19:24:37. 171676500

Example For setting the specified time:

LocalDateTime localDateTime1 = LocalDateTime. Of,10,6,13,12,13 (2020); //2020-10-06T13:12:13

Example get operations:

System.out.println(localDateTime.getMonth()); //APRIL

System.out.println(localDateTime.getMonthValue()); / / 4

The months here start at 1.

.with action (set related properties) :

LocalDate localDate1 = localDate.withDayOfMonth(22); / / 2021-04-22

System.out.println(localDate); / / 2021-04-27

System.out.println(localDate1);

The locatDate instance itself does not change (immutability).

Addition and subtraction operations:

LocalDate localDate2 = localDate.plusDays(4); / / localDate for 4-27

System.out.println(localDate2); / / 2021-05-01

// Add Plus to minus

An Instant point in a timeline that may be used to record event timestamps in an application.

Also a timestamp (nanosecond) from 00:00:00, January 1, 1970.

Related methods:

The UTC time is the same as London time and 8 hours earlier than Beijing time.

Instant instant = Instant.now();

System.out.println(instant); //2021-04-27T11:45:00.321544Z, actual time 19:45, difference of 8 hours

Offset application:

OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));

System.out.println(offsetDateTime); / / the 2021-04-27 T19: open. 448368100 + 08:00

Return the timestamp (milliseconds) :

System.out.println(instant.toEpochMilli()); / / 1619524168468

Set a specific time, similar to Date:

Instant instant1 = Instant.ofEpochMilli(1619524168468L); // 2021-04-27T11:49:28.468z

System.out.println(instant1);

2.4 DateTimeFormatter

There are three predefined standard formats:

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

// Format: date –> string

LocalDateTime localDateTime = LocalDateTime.now();

String str = dateTimeFormatter.format(localDateTime); // Format the current time

System.out.println(str); / / the 2021-04-27 T19: they. 0153049

// Parse: string –> date

TemporalAccessor TemporalAccessor = dateTimeFormatter. Parse (” the 2021-04-27 T19: they. 0153049 “);

System.out.println(temporalAccessor); / / {}, ISO resolved to the 2021-04-27 T19: they. 015304900

Localization-related formats:

DateTimeFormatter format = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);

//SHORT 2021/4/27 8:09 PM, MEDIUM April 27, 2021 8:10:02 PM,

In Java15, LONG is abnormal, 1.8 is not, DateTime is not FULL,Date is

String str1 = format.format(localDateTime);

System.out.println(str1);

Custom format (similar to SimpleDateFormat) :

DateTimeFormatter format = DateTimeFormatter.ofPattern(“yyyy-MM-dd hh:mm:ss”);

String str1 = format.format(localDateTime); / / the 2021-04-27 08:21:52

System.out.println(str1);

TemporalAccessor temporalAccessor1 = format.parse(str1);

System.out.println(temporalAccessor1);

//{MicroOfSecond=0, HourOfAmPm=8, MilliOfSecond=0, NanoOfSecond=0, MinuteOfHour=21, SecondOfMinute=52},ISO resolved to 2021-04-27

Note that a TemporalAccessor subcontract is required.

Some other apis (not to be detailed) :

Convert between the above three types of Date:

Implement the Comparable interface (natural ordering) by overriding the compareTo() method. This is greater than the parameter object obj and returns a positive integer. This is less than, returns a negative integer; This is equal to, return 0;

Using the Comparator interface (custom sorting)

The Comparable interface is not implemented for this type and it is not convenient to modify the code; Or the Comparable interface is implemented but the sorting rules are not appropriate for the current operation

Contrast:

The Comparable interface ensures that objects of a class can be compared anywhere

The Comparator interface is a temporary comparison

The application was implemented in a previous blog post

(Set, Map, Collections utility class) JAVA Collections Framework ii

System, Math, BigInteger, and BigDecimal 4.1 System

java.lang.System

Member variables: in, out and ERR represent standard input stream (keyboard input), standard output stream (monitor) and standard error output stream (monitor) respectively.

Static Long currentTimeMillis() returns the current time in milliseconds. Expression format with time stamp.

Static void Exit (int Status) Terminates the currently running Java VIRTUAL machine. If the status is 0, the exit is normal; if the status is not 0, the exit is abnormal.

Static void gc() runs the garbage collector. Request a garbage collection from the system.

Static String getProperty(String Key) Gets the system property indicated by the specified key. For commonly used keys:

4.2 Math

This is a summary of common Math methods. Visible development documentation.

BigInteger vs. BigDecimal

BigInteger provides equivalents for all of Java’s basic integer operators and all of the related methods for Java.lang. Math, plus operations such as modular arithmetic, GCD calculation, prime number testing, prime number generation, bit manipulation, and so on.

BigDecimal can be used when Float and Double are not accurate enough to meet user requirements

Construction method:

BigDecimal(double val) converts double to BigDecimal, which is the exact decimal representation of the binary floating-point value of double.

BigDecimal(String val) converts the String representation of BigDecimal to BigDecimal.

There are many more, just two common ones.

The addition, subtraction, multiplication and division operations are similar to BigInteger. Devide:

Scale is the number of decimal places reserved.

Several rounding modes:

Among them, some translation is not accurate, explain:

ROUND_UP: round up. 0.1203456789. When the precision is 3, the result is 0.121 according to ROUND_UP mode

ROUND_DOWN indicates the round down.

And ROUND_HALF_EVEN, like neighboring even directions rounded.

These several can refer to the corresponding English for understanding.

4.4 Other categories of personal summary

In fact, we often use Ramdom, we often use random numbers in our life.

For example, take a random integer.

Random r1 = new Random();

int i = r1.nextInt(100); // Take a random integer from 0 to 100, with no 100

The other methods are similar and can be found in the development documentation.

Above is today’s Java basic general knowledge class summary of SE knowledge sharing, thank you for watching, but also welcome everyone to exchange and discuss, if the article is not correct, I hope you forgive.

If it’s helpful, give a thumbs up to your image.png