Article directory
Ch.III Java basic programming structure:
-
Java case sensitive
-
A standard program format:
public class FirstSample{ public static void main(String[] args){ System.out.println("We will not use 'Hello, World!"') ; } //This is a note }
-
public:
Called an access modifier, it controls the access level of other parts of the program to this code
-
FirstSample:
Class name, the specific definition rules are the same as C + +
Note: the class name here must be the same as the file name of the source code, and it must be case sensitive!
Here. Java is used as the extension of the file, which is equivalent to the. cpp file of C + +
The file extension generated by compilation is. Class, which is a class bytecode file, equivalent to the output. exe -
Like C++, Java also needs a main
When running the. class file, it will navigate to main to start running
-
Like C + +, Java uses {} to annotate code blocks
-
Like C + +, Java ignores all whitespace characters in the source file, so it can be typeset as freely as C + +
-
As with C + +, the annotation method in Java is the same. Use / / or / * * /!
But there is a difference. You can use / * * in Java to build comment documents. In fact, the compiler automatically generates comments for each line, which is easy to write!
-
-
About the differences between Java classes and C + + classes:
In Java, functions in all classes do not become member functions, which are officially called methods
So main needs a wrapper shell class
- Java basic data type:
Mostly the same as C + +
Differences:
-
No unsigned integer
-
No bool type, instead of boolean
-
All data types in Java are machine independent (unlike int and 16 bits in C + +, which are 32-bit machine dependent)
-
Java does not declare variables, while C + + uses extern to declare an external variable:
extern int a;
-
In Java, final is used to represent constants, while const is used in C + +
const in Java has other uses, which we haven't learned yet
-
Char in C + + occupies 1 byte, while char in Java occupies 1-6 bytes, depending on the encoding
But it's usually two bytes
Specific operations in Java:
-
Three special floating-point values:
Positive infinity, negative infinity, NaN
It is represented by double ﹣ positive ﹣ infinity, Double.NEGATIVEJNFINITY and Double.NaN respectively
Notice that Double here is capital -
Rare keyword: strictfp
If you want to make your floating-point operations more accurate, and not because the results of different hardware platforms are inconsistent, you can use the keyword strictfp
However, strict calculation will take more time and may lead to overflow
-
Do not type convert between Boolean and any other types
-
About the mapping of the include header file in C + + in Java:
There is no method to include header files in Java. To use related functions, there are two methods:
-
Directly call related classes:
For example, using the function sqrt in Math:
double x = 4; double y = Math.sqrt(x); //Use directly like calling a member function of a class System.out.println(y); // prints 2.0
-
Or use import in the file header:
import static java.lang.Math.*
The specific use here will be carried out later
-
-
String in Java:
String class can be used to store strings. The specific operation is similar to that of C + +
-
Similarities:
Support String + splicing and other operations
Support the use of = for reassignment
There are empty strings and null strings, where empty strings are equivalent to pointing to strings of length 0, and null is equivalent to null pointers (not pointing to any memory space)
-
Different:
1. String object is static type: Java String is actually equivalent to the char * String pointer in C + +, which points to the characters stored in the static part of the program, = = so the String object in Java is a final static type that cannot be modified = =, that is * * a single character in the String cannot be modified** 2. When the string object is reassigned, you do not need to worry about memory leakage: A big difference between Java and C + + is Java's memory recycling mechanism. When a piece of memory is not used, it will be automatically recycled by the system 3. It is not supported to use = = for detection and judgment This operator is not overloaded
- In Java, each char of String type occupies 2 bytes, and if the encoding is different, the number of bytes occupied by char will also change, so:
```java str.lenth(); / / returns the number of str code units //To return the actual number of str characters, you need to use: str.codePointCount(0,str.lenth()); / / count from 0, and calculate the number of code points (characters) in str ``` To obtain the data at the ith code point, i.e. the ith byte, you need to use: ```java str.codePointAt(i); / / the value at the ith byte will be returned, and the return type is int ``` **Extension: Unicode code point & code unit** You need to understand how Unicode is encoded: -UTF-8: use 1-4 bytes to represent a character -UTF-16: 2 bytes for Basic Multilingual flat characters and 4 bytes for auxiliary flat characters -UTF-32: use 4 bytes to represent a character
-
Code point: code value representing one character of Unicode
-
Code unit: 16bit represents a code unit
In Java, the char basic type and String use UTF-16 encoding, so if String is used to store Chinese, each Chinese character occupies 16bit, that is, code points = code units
But if stored emoji, You need 32. bit, Code points at this time=Number of code units*2 **Here is a small example:** ```java public class Welcome { public static void main(String[] args) { String chineseTest="Microsoft garbage"; System.out.println(chineseTest); System.out.println(chineseTest.length()); System.out.println(chineseTest.codePointCount(0,chineseTest.length())); String emojiTest="\uD83D\uDE1D"; System.out.println(emojiTest); System.out.println(emojiTest.length()); System.out.println(emojiTest.codePointCount(0,emojiTest.length())); } } ``` //Output results: >[Failed to save the image in the external chain,Source station may have anti-theft chain mechanism,It is recommended to save the pictures and upload them directly(img-y6HtqVy0-1579508661723)(C:\Users\Janus II\AppData\Roaming\Typora\typora-user-images\image-20200119170159813.png)] **Expand: Fast splicing of multiple strings:** //Method join using String: ```java String all = String.join(" / ", "S", "M", "L", "XL"); // all is the string "S / H / L / XL" ``` **Expand: Check if strings are equal** //Use equals: ```java str.equals(t); //Case sensitive "Hello".equalsIgnoreCase("hel1o"); ```
Java String API:
char charAt(int index) //Returns the value at the index specified by char. int codePointAt(int index) //Returns the character (Unicode code point) at the specified index. int codePointBefore(int index) //Returns the character (Unicode code point) before the specified index. int codePointCount(int beginIndex, int endIndex) //Returns the number of Unicode code points in the specified text range for this String. int compareTo(String anotherString) //Compares two strings in dictionary order. int compareToIgnoreCase(String str) //Compare the two strings in dictionary order, ignoring case differences. String concat(String str) //Connects the specified string to the end of the string. boolean contains(CharSequence s) //Returns true if and only if the string contains the specified sequence of char values. boolean contentEquals(CharSequence cs) //CharSequence this string with the specified CharSequence. boolean contentEquals(StringBuffer sb) //StringBuffer this string with the specified StringBuffer. static String copyValueOf(char[] data) //Equivalent to valueOf(char []). static String copyValueOf(char[] data, int offset, int count) //Equivalent to valueOf(char[], int, int). boolean endsWith(String suffix) //Tests whether the string ends with the specified suffix. boolean equals(Object anObject) //Compares this string with the specified object. boolean equalsIgnoreCase(String anotherString) //Compare this String with other strings, ignoring case considerations. static String format(Locale l, String format, Object... args) //Returns the formatted string using the specified locale, format string, and parameters. static String format(String format, Object... args) /Returns the formatted string using the specified format string and parameters. byte[] getBytes() //This String is encoded as a byte sequence using the platform's default character set, and the result is stored in a new byte array. byte[] getBytes(Charset charset) //The String is encoded as a byte sequence using the given charset, and the result is stored in a new byte array. void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin) //Abandoned //This method cannot convert characters to bytes correctly. Starting with JDK 1.1, the preferred method is through the getBytes() method, which uses the platform's default character set. byte[] getBytes(String charsetName) //Encode this String as a sequence of bytes using a named character set, and store the results in a new byte array. void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) //Copy the characters in this string to the destination character array. int hashCode() //Returns the hash code for this string. int indexOf(int ch) //Returns the index within the string of the first occurrence of the specified character. int indexOf(int ch, int fromIndex) //Returns the index within the first occurrence of the specified character in the string, starting the search at the specified index. int indexOf(String str) //Returns the index within the first occurrence of a specified substring. int indexOf(String str, int fromIndex) //Returns the index in the first occurrence string of the specified substring, starting with the specified index. String intern() //Returns the canonical representation of a string object. boolean isEmpty() //Returns true if and only if length() is 0. static String join(CharSequence delimiter, CharSequence... elements) //Returns a new string consisting of a copy of CharSequence elements with the specified delimiter's delimiter. static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) //Returns the CharSequence elements of a new String to join the delimiter with the specified copy. int lastIndexOf(int ch) //Returns the index in the last occurrence string of the specified character. int lastIndexOf(int ch, int fromIndex) //Returns the index in the last occurrence string of the specified character, starting with the specified index and searching backward. int lastIndexOf(String str) //Returns the index in the last occurrence of the specified substring. int lastIndexOf(String str, int fromIndex) //Returns the index in the last occurrence string of the specified substring, starting from the specified index and searching backward. int length() //Returns the length of this string. boolean matches(String regex) //Tells whether the string matches the given regular expression. int offsetByCodePoints(int index, int codePointOffset) //Returns the index within this String, and the index codePointOffset code point. boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) //Tests whether two string regions are equal. boolean regionMatches(int toffset, String other, int ooffset, int len) //Tests whether two string regions are equal. String replace(char oldChar, char newChar) //Returns the replacement of all occurrences from the resulting one string oldChar in this string newChar. String replace(CharSequence target, CharSequence replacement) //Replaces each substring of the string that matches the literal target sequence with the specified literal replacement sequence. String replaceAll(String regex, String replacement) ///Replace each substring of this string that matches the given regular expression with the given replacement. String replaceFirst(String regex, String replacement) //Replace the first substring of this string that matches the given regular expression with the given replacement. String[] split(String regex) //Split this string into matches for the given regular expression. String[] split(String regex, int limit) //Split this string into matches for the given regular expression. boolean startsWith(String prefix) //Tests whether the string starts with the specified prefix. boolean startsWith(String prefix, int toffset) //Tests whether the substring of this string that starts at the specified index begins with the specified prefix. CharSequence subSequence(int beginIndex, int endIndex) //Returns a sequence of characters that are subsequences of that sequence. String substring(int beginIndex) //Returns a string that is a substring of this string. String substring(int beginIndex, int endIndex) //Returns a string that is a substring of this string. char[] toCharArray() //Converts this string to a new array of characters. String toLowerCase() //Use all rules of the default locale for this character String, in lowercase. String toLowerCase(Locale locale) //String all in this character to reduce Locale with the given rule. String toString() //This object (already a string!) Itself has been returned. String toUpperCase() //Capitalize all rules that use the default locale for this character String. String toUpperCase(Locale locale) //Use the given rule for all this character String, uppercase Locale. String trim() //Returns a string whose value is the string and removes any leading and trailing spaces. static String valueOf(boolean b) //Returns the string boolean form of the boolean parameter. static String valueOf(char c) //Returns the string char form of the char parameter. static String valueOf(char[] data) //Returns the string char form of the char array parameter. static String valueOf(char[] data, int offset, int count) //Returns the string char form of a specific subarray of a char array parameter. static String valueOf(double d) //Returns the string double form of the double parameter. static String valueOf(float f) //Returns the string float form of the float parameter. static String valueOf(int i) //Returns the string int form of the int parameter. static String valueOf(long l) //Returns the string long form of the long parameter. static String valueOf(Object obj) //Returns the string Object form of the Object parameter.
3.7 basic input and output:
Read input:
The input stream mainly uses the Scanner class
scanner is equivalent to a cursor, scanning the input text
Use different Scanner methods to interpret the next input of cursor as different data types. If the input data type is wrong, an error will be reported
About error reporting:
The specific error reporting content is as follows, and the internal logic is temporarily unknown:
[failed to transfer the pictures in the external link. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-hf4FktWf-1579508661725)(C:\Users\Janus II\AppData\Roaming\Typora\typora-user-images\image-20200116201102918.png))
Before using Scanner, you need to define the Scanner object
New objects are usually created using new:
Scanner inputString=new Scanner(System.in);
There are two common methods:
-
next series:
According to the required data type, use the corresponding method to read the next data. If the data type is inconsistent, an error will be reported, which is equivalent to abnormal termination of the program
-
has series:
It is used to determine the data type of the next input of the cursor, and use the corresponding method to determine whether the next input belongs to the corresponding data type, and the return type is Boolean
Here is the API for the Scanner class:
void close() //Close this scanner. Pattern delimiter() //Returns the Pattern that the Scanner is using to match the delimiter. String findInLine(Pattern pattern) //Try to find the next occurrence of the specified pattern that ignores the delimiter. String findInLine(String pattern) //Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring the delimiter. String findWithinHorizon(Pattern pattern, int horizon) //Try to find the next occurrence of the specified pattern. String findWithinHorizon(String pattern, int horizon) //Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring the delimiter. boolean hasNext() //Returns true if the scanner has another token in its input. boolean hasNext(Pattern pattern) //Returns true if the next full token matches the specified pattern. boolean hasNext(String pattern) //Returns true if the next token matches the pattern constructed from the specified string. boolean hasNextBigDecimal() //Returns true if the next tag of the input information in this scanner can be interpreted as, BigDecimal uses nextBigDecimal()Method. boolean hasNextBigInteger() //Returns true BigInteger using the default cardinality nextBigInteger() method if the next token of information entered by this scanner can be interpreted as. boolean hasNextBigInteger(int radix) //If the next tag of the information entered by this scanner can be interpreted as, true BigInteger is returned in the //Fixed base number nextBigInteger()Method. boolean hasNextBoolean() //Returns true if the next tag in this scanner input can be interpreted as a Boolean value using a case insensitive pattern created from the string "true | false.". boolean hasNextByte() //If the next tag in this scanner input can be interpreted as in the default cardinality using the nextByte() method //Byte value, returntrue. boolean hasNextByte(int radix) //If the next tag in the scanner input can be interpreted as a byte in the specified Radix using the nextByte() method //Value, returntrue. boolean hasNextDouble() //Returns true if the next tag in the scanner's input can be interpreted as a double value using the nextDouble() method. boolean hasNextFloat() //Returns true if the next tag in scanner input can be interpreted as a floating-point value using the nextFloat() method. boolean hasNextInt() //Returns true if the next tag in this scanner input can be interpreted as an int value in the default cardinality using the nextInt() method. boolean hasNextInt(int radix) //Returns true if the next tag in this scanner input can be interpreted as an int value in the specified cardinality using the nextInt() method. boolean hasNextLine() //Returns true if there is another line in the scanner's input. boolean hasNextLong() //Returns true if the next tag in this scanner input can be interpreted as a long integer value in the default cardinality using the nextLong() method. boolean hasNextLong(int radix) //Returns true if the next tag in the scanner's input can be interpreted as a long integer value in the specified cardinality using the nextLong() method. boolean hasNextShort() //Returns true if the next tag in this scanner input can be interpreted as a short value in the default cardinality using the nextShort() method. boolean hasNextShort(int radix) //Returns true if the next tag in the scanner's input can be interpreted as a short value in the specified cardinality using the nextShort() method. IOException ioException() //Return IOException and finally throw the basic Readable of Scanner through this. Locale locale() //Returns the regional settings for this scanner. MatchResult match() //Returns the matching results of the last scan performed by this scanner. String next() //Find and return the next full token for this scanner. String next(Pattern pattern) //If the specified pattern is matched, the next token is returned. String next(String pattern) //If the pattern constructed from the specified string is matched, the next token is returned. BigDecimal nextBigDecimal() //Scan the next tag entered for BigDecimal. BigInteger nextBigInteger() //Scan the next tag entered for BigInteger. BigInteger nextBigInteger(int radix) //Scan the next tag entered for BigInteger. boolean nextBoolean() //Scans the next tag entered for a Boolean value and returns that value. byte nextByte() //Scan the next tag entered as byte. byte nextByte(int radix) //Scan the next tag entered as byte. double nextDouble() //Scan the next tag entered for double. float nextFloat() //Scan the next tag entered for float. int nextInt() //Scan the next tag entered as int. int nextInt(int radix) //Scan the next tag entered as int. String nextLine() //Advances this scanner to the current line and returns skipped input. long nextLong() //Scan the next tag entered as long. long nextLong(int radix) //Scan the next tag entered as long. short nextShort() //Scan the next tag entered for short. short nextShort(int radix) //Scan the next tag entered for short. int radix() //Returns the default cardinality for this scanner. void remove() //This implementation of Iterator does not support deleting Iterator. Scanner reset() //Reset this scanner. Scanner skip(Pattern pattern) //Skips input that matches the specified pattern, ignoring delimiters. Scanner skip(String pattern) //Skips input that matches the pattern formed by the specified string. String toString() //Returns a string representing the Scanner. Scanner useDelimiter(Pattern pattern) //Set the separation mode of this scanner to the specified mode. Scanner useDelimiter(String pattern) //Sets the delimitation mode of this scanner to String from the specified construct. Scanner useLocale(Locale locale) //Set the locale for this scanner to the specified locale. Scanner useRadix(int radix) //Sets the default cardinality for this scanner to the specified cardinality.
Extension: for invisible input, such as password input:
The Console class is introduced in Java SE 6 to realize this function:
Console cons = System.console(); String username = cons.readLine("User name: "); char [] passwd = cons.readPassword("Password: "); System.out.println(passwd);
Unable to test temporarily because it needs to be run in the cmd console environment to be valid
Format output:
The printf method of C language is introduced in Java SE 5, so it is very convenient to format the output
printf in Java is very similar to C language, so I won't elaborate on it here
The cout method of C + + can be solved by System. out. printIn
File I / O:
File input:
Scanner in= new Scanner(Paths.get("myfile.txt"),"UTF-8");
The Scanner class is also used, but the constructor containing the file path is used
-
Paths.get gets the path of the target file
Scanner(File f) //Construct a Scanner to read data from a given file
Note that the filename cannot be used directly here. The compiler interprets it as data instead of filename, so the file cannot be opened
The constructor used becomes this:
Scanner(String data) //Construct a Scanner that reads data from a given string.
-
UTF-8 is the encoding method of files
When the encoding method of the file is not specified, Java will use the default encoding method, and different machines will have different results
Explain:
Double backslashes should be used if the file path contains backslashes
File output:
PrintWriter out = new Printlulriter("myfile.txt", "UTF-8");
If the file does not exist, it is created
API:
static Path get(String pathname) //Construct a Path based on the given Path name
3.8 control process:
This part is actually the logic control part of C + +, which has no special features. Here, only different parts are recorded:
-
Java has no goto statement
-
break can be labeled
Thus, the function of jumping out of multi-layer cycle can be realized
But the specific use method is different from goto
Where the tag is placed at the beginning of the code block of the loop you want to jump out of, and then break will jump directly to the end of the code blockThis is different from goto
The reason for this design is to prevent using break as goto
read_data: while (. . .) // this loop statement is tagged with the label for (. . .) // this inner loop is not labeled { Systen.out.print("Enter a number >= 0: "); n = in.nextlntO; if (n < 0) // should never happen-can't go on break read . data; // break out of readjata loop }
-
Overwriting of variables with the same name is not allowed in Java
That is, the inner block is not allowed to contain variables with the same name as the outer blockIn C + +, although this behavior is allowed, it is also a habit of poor quality, so Java simply lists it as Error
3.9 large value:
Handwritten large number calculation method is required in C + +, but corresponding method is provided in math package in Java:
- BigInteger: integer used to calculate any length
- BigDecimal: floating point number used to calculate arbitrary precision
Use methods to call methods of corresponding classes
Since there are no overloaded operators in Java, only methods can be used
Commonly used method:
- Create the value to be calculated through the constructor
- Call the corresponding method to complete the calculation
Biglnteger c = a.add(b); // c = a + b Biglnteger d = c.nulti piy(b.add(Biglnteger.val ueOf(2))); // d = c * (b + 2)
Here are the API s for these two:
-
BigInteger:
Constructor:
BigInteger(byte[] val) //Converts a byte array of binary complement binary expressions containing BigInteger to BigInteger. BigInteger(int signum, byte[] magnitude) //Converts the symbol size representation of BigInteger to BigInteger. BigInteger(int bitLength, int certainty, Random rnd) //Constructs a randomly generated positive BigInteger, which may be a prime number with the specified bitLength. BigInteger(int numBits, Random rnd) //Construct a randomly generated BigInteger, evenly distributed in the range of 0 to (2 numBits - 1). BigInteger(String val) //Converts the decimal string representation of BigInteger to BigInteger. BigInteger(String val, int radix) //Converts the String representation of BigInteger in the specified cardinality to BigInteger.
Common methods:
Biglnteger add(Biglnteger other) Biglnteger subtract(Biglnteger other) Biglnteger multipiy(Biginteger other) Biglnteger divide(Biglnteger other) Biglnteger mod(Biglnteger other) //Return the sum, difference, product, quotient and remainder of this big integer and an other big integer. int compareTo(Biglnteger other) //If the big integer is equal to another big integer, return 0; if the big integer is smaller than another big integer, return negative; otherwise, return positive. static Biglnteger valueOf(1ong x) //Returns a large integer with a value equal to x.
-
BigDecimal:
Constructor:
BigDecimal(BigInteger val) //Convert BigInteger to BigDecimal. BigDecimal(BigInteger unscaledVal, int scale) //Converts BigInteger values and int levels of BigInteger to BigDecimal. BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) //Converts BigInteger unscale values and int extensions to BigDecimal, rounding based on context settings. BigDecimal(BigInteger val, MathContext mc) //Converts BigInteger to BigDecimal rounding based on context settings. BigDecimal(char[] in) //A converted character array represents BigDecimal as BigDecimal, and accepts the same sequence of characters as BigDecimal(String) construction. BigDecimal(char[] in, int offset, int len) //A converted character array represents BigDecimal as BigDecimal, and accepts the same sequence of characters as BigDecimal(String) construction. At the same time, a sub array is allowed to be specified. BigDecimal(char[] in, int offset, int len, MathContext mc) //A converted character array represents BigDecimal as BigDecimal, which accepts the same sequence of characters as BigDecimal(String) construction, and allows specifying a sub array and rounding according to context settings. BigDecimal(char[] in, MathContext mc) //A converted character array indicates that BigDecimal is a BigDecimal, and accepts the same character sequence as a BigDecimal(String) construction and rounding according to the context setting. BigDecimal(double val) //Convert double to BigDecimal, which is the exact decimal representation of the binary floating-point value of double. BigDecimal(double val, MathContext mc) //Convert double to BigDecimal and round according to the context setting. BigDecimal(int val) //Make int BigDecimal. BigDecimal(int val, MathContext mc) //Convert int to BigDecimal and round it according to the context setting. BigDecimal(long val) //Make long BigDecimal. BigDecimal(long val, MathContext mc) //Convert long to BigDecimal and round according to the context setting. BigDecimal(String val) //Convert the string representation of BigDecimal to BigDecimal. BigDecimal(String val, MathContext mc) //A converted string represents BigDecimal as BigDecimal, accepts the same string as the BigDecimal(String) structure, and rounds it according to the context setting.
Common methods:
BigDecimal add(BigDecimal other) BigDecimal subtract(BigDecimal other) BigDecimal multipiy(BigDecimal other) BigDecimal divide(BigDecimal other RoundingMode mode) 5.0 //Returns the sum, difference, product, and quotient of this large real number and an other large real number. //In order to calculate quotient, rounding mode must be given //Roundingmode.half'up is a rounding method for learning in school (BP, value 0 to 4 rounding, value 5 to 9 rounding) //It is suitable for conventional calculation. See Api documentation for other rounding methods. int compareTo(BigDecimal other) //If this large real number is equal to another large real number, return 0; if this large real number is smaller than another large real number, return negative; otherwise, return positive. static BigDecimal valueOf(1 ong x) static BigDecimal valueOf(1 ong x ,int scale) //Returns a large real number with a value of X or x / 10scale.
3.10 array:
Java's array declaration format is similar to C + +, but there is another way:
int [] a= new int[n]; // Java style, the style adopted by most Java programmers //It is equivalent to declaring a pointer. Due to Java's garbage collection mechanism, it is as convenient to use as an ordinary array int a[] = new int[n]; //C++ style //But different from C + +, it still needs to use new to request memory
Different from C + +:
-
Even if you use the C + + style array definition method, you also need to use new to apply for memory
-
Arrays in Java are automatically initialized to 0 (including 0, false, null) when they are created. No manual initialization is required
-
If the Java array is accessed beyond the bounds, an exception of array index out of bounds will be thrown, causing the program to exit abnormally
-
The essence of arrays in Java is more like pointers in C + +
intD a = new int[100]; // Java //Differ int a[100]; // C++ //And equal to int* a = new int[100]; // C++
And the array has no pointer operation, that is, the next element cannot be obtained through a+1
Initialization of array:
The method is the same as C + +;
int [] arr = new int [] {0,1,2,3,4,5,6,7,8,9}; //The compiler count is also supported int [] arr ={0,1,2,3,4,5,6,7,8,9}; //Simplified initialization method
Fast output of array:
Two methods:
-
Use for each (equivalent to C + + scope for)
int[] a=new int[] {0,1,2,3,4,5,6,7,8,9}; for (int temp: a){ System.out.printf("%d ",temp); }
-
Use toString method:
System.out.println(Arrays.toString(a));
Array copy:
Two methods:
-
Similar to the shallow copy in C + +, using the essence of Java array is the feature of pointer, making two arrays point to the same memory segment
intQ luckyNumbers = smallPrimes; luckyNumbers[S] = 12; // now smallPrimes[5] is also 12
-
Use the copyOf method in the Arrays class:
int[] copiedLuckyNumbers = Arrays.copyOf(luckyNumbers, luckyNumbers.length) ;
API is as follows:
[external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-80UDa502-1579508661726)(C:\Users\Janus II\AppData\Roaming\Typora\typora-user-images\image-20200117173144499.png))
Array sort:
Also call the sort() method of the Arrays class
int[] a = new int[10000]; ... Arrays.sort(a);
Similar to the generic algorithm of STL library in C + +, sort optimizes different types of data better
API is as follows:
static void sort(type[] a) //The optimized fast sorting algorithm is used to sort the array.
The type is similar to the C + + template. The supported data types include int, long, short, char, byte, Boolean, float, double
2D arrays & irregular arrays:
It mainly uses the feature that Java array is actually a pointer
When creating a two-dimensional array, it is equivalent to creating a two-level pointer to an array of pointers:
doublet] [] balances = new double[10] [6]; //Differ double balances [10] [6] ; // C++ //Also different from double (*balances) [6] = new double[10] [6] ; // C++ //Instead, an array of 10 pointers is assigned: double** balances = new double*[10] ; // C++
Because each element in the pointer array can be assigned independently, an irregular array can be created
Extension: Java program console operation:
The difference with C + + program is as follows:
- Program name is not included in arg [], that is, arg[0] is the first parameter
- The files generated by C + + compilation are. exe executable files, while the final files generated by java compilation are. java bytecode files, which need to be run by bytecode interpreter
Extension: random number:
The random number function in Java is in the Math class:
static double random() Return value is double value is positive sign, greater than or equal to 0.0, less than 1.0
Extension: other commonly used methods of Arrays class:
static int binarySearch(type[] a , t y p e v) static int binarySearch(type[] a, int start, int end , type v) 6 static void fi11(type[] a , type v) Set all data element values of the array to V. Parameters: an array of type a: int, long, short, char, byte, boolean, float, or double. v is a value of the same type as a data element. static boolean equals(type[] a, type[] b) Returns true if the two arrays have the same size and the elements with the same subscript correspond to each other. Parameters: two arrays of type a and b: int, long, short, char, byte, boolean, float or double.
-
binarySeach
The binary search algorithm is used to find the value v. If the search is successful, the corresponding subscript value is returned; otherwise, a negative value is returned. R-r-1 is the position where V should be inserted in order to keep a-ordered
Parameters:
- An ordered array of type a: int, long, short, char, byte, boolean, float, or double.
- Start start subscript (containing this value).
- end terminate subscript (does not contain this value. )
- v is the same value as a's data element type.
e[10] [6] ; // C++
//Instead, an array of 10 pointers is assigned:
double** balances = new double*[10] ; // C++
Because each element in the pointer array can be assigned independently, an irregular array can be created ####Extension: Java program console operation: The difference with C + + program is as follows: 1. The program name is not included in arg [], that is, arg[0] is the first parameter 2. The files generated by C + + compilation are. exe executable files, while the final files generated by java compilation are. java bytecode files, which need to be run by bytecode interpreter ####Extension: random number: The random number function in Java is in the Math class: ```java static double random() Return value is double value is positive sign, greater than or equal to 0.0, less than 1.0
Extension: other commonly used methods of Arrays class:
static int binarySearch(type[] a , t y p e v) static int binarySearch(type[] a, int start, int end , type v) 6 static void fi11(type[] a , type v) Set all data element values of the array to V. Parameters: an array of type a: int, long, short, char, byte, boolean, float, or double. v is a value of the same type as a data element. static boolean equals(type[] a, type[] b) Returns true if the two arrays have the same size and the elements with the same subscript correspond to each other. Parameters: two arrays of type a and b: int, long, short, char, byte, boolean, float or double.
-
binarySeach
The binary search algorithm is used to find the value v. If the search is successful, the corresponding subscript value is returned; otherwise, a negative value is returned. R-r-1 is the position where V should be inserted in order to keep a-ordered
Parameters:
- An ordered array of type a: int, long, short, char, byte, boolean, float, or double.
- Start start subscript (containing this value).
- end terminate subscript (does not contain this value. )
- v is the same value as a's data element type.