Java basic knowledge study notes (2)

Source: Internet
Author: User
Tags 04x mathematical functions

Java basic knowledge study notes (2)
Java basic programming structure 1 a simple java example

public class FirstExample{    public static void main(String[] args){        System.out.println("we will not use 'hello world' ");    }}

What do we know from this program?
1. java is case sensitive. The main is written as Main, and the program cannot be executed.
2. public access modifier, which controls the access level of other parts of the program for this code.
3. The class table name java program is included in the class. Here, you only need to use the class as a loader
The Program Logic defines the behavior of the application.
4. class names are followed by class names. Naming rules: class names start with uppercase letters. If
A name consists of multiple words. The first letter of each word should be capitalized. Others are equivalent
The naming rule of the identifier.
5. The file name is consistent with the Class Name of the public class, for example, FirstExample. java.
6. Each java application must have a main method.
7 {} method body start and end. Each sentence must end with ';', and carriage return is not the sign of the end. Therefore, you can write a java Statement on multiple lines.
8 System. out. println (), method call
9 "" reference string
The 10 method can have no parameters or multiple parameters, but must be expressed with (), for example,
The println method of the parameter prints only one blank line. Use the following statement:

System.out.println()
Note: When you run the Compilation Program, the Java Virtual Machine starts to execute the main method in the specified class (the "method" here is the "function" mentioned in Java), so in order to be able to execute the code, the source file of the class must contain a main method. Of course, you can also add custom methods to the class and call them in the main method. According to the Java language specification, the main method must be declared as publicJava class and C ++ class are very similar, but there are still some differences that may confuse people. For example, all functions in Java belong to methods of a class (referred to as methods in standard terms, rather than member functions ). Therefore, the main method in Java must have a shell class. Readers may be familiar with static member functions in C ++. These member functions are defined inside the class and do not operate on objects. The main method in Java must be static. Finally, like C/C ++, the keyword void indicates that this method has no return value. The difference is that the main method does not return "Exit code" to the operating system ". If the main method Exits normally, the exit code of the Java application is 0, indicating that the program is successfully run. If you want to return other code when terminating the program, you need to call the System. exit method.
2 Note

Like most design languages, annotations in java do not appear in executable programs.
Annotation type:
Single row:// Commented content
Multiple rows:/* Commented content */
Another type:/** Commented content */

Note: in Java,/**/Annotations cannot be nested. That is to say, if the Code itself contains a */, it cannot be included in/* and */annotations.
3. Data Type

Four integer types, two floating point types, one char type and one Boolean Type
1 integer

Type Storage Requirements Value Range
Int 4 bytes -2 147 483 648 ~ 2 147 483 647 (more than 2 billion)
Short 2 bytes -32 768 ~ 32 767
Long 8 bytes -9 223 372 036 854 775 808 ~ 9 223 372 036 854 775 807
Byte 1 byte -128 ~ 127
In java, integer values are fixed and irrelevant to the platform, which solves the portability problem. c/c ++ needs to select the most effective integer for different processors, integer Overflow

2 floating point type

Type Storage Requirements Value Range
Float 4 bytes About ± 3. 402 823 47E + 38F (the valid number is 6 ~ 7 digits)
Double 8 bytes About ± 1. 797 693 134 862 315 70E + 308 (valid digits: 15 digits)
Constants Double. POSITIVE_INFINITY, Double. NEGATIVE_INFINITY, and Double. NaN (same as the corresponding Float Type constants). For example, the result of dividing a positive integer by 0 is positive infinity. The square root of the number 0/0 or negative is NaN. Check whether a number is NaN. if (x = Double. NaN) // All "non-numeric" values are considered to be different. Double. NaN (x) if (Double. NaN (x ))

3 char type
Remember the following:
1 'A' and "A" are different: the former is A character constant 65, and the latter is A string containing character
2. escape characters can be used in "and" ", but only \ u can be excluded, for example, \ u005B and \ u005D are (and) encoded.
3 java uses the UTF-16 to describe a code unit
4 It is strongly recommended not to use the char type in the program

4 boolean Type

In C ++, values or pointers can replace boolean values. An integer 0 is equivalent to a Boolean value of false, and a non-zero value is equivalent to a Boolean value of true. Not in Java. Therefore, Java application programmers will not encounter the following troubles: if (x = 0) // in C ++, this test can be compiled and run, and the result is always false. In Java, this test cannot be compiled because the integer expression x = 0 cannot be converted to a Boolean value.
4 variables

Remember the following points:
1. Variable names are case sensitive
2. Define and declare variables in c/c ++, for example:
Int I = 10; // defines the variable
Extern int I; // declare a variable
Java is not differentiated and can be directly written as: int I = 10; // declaration, definition, initialization

3. The variable corresponds to a constant and is declared using final. The constant name is usually capitalized and cannot be changed, for example:
Final int PI = 3.14;

4. You want a constant to be used in multiple methods in a class. Usually, these constants are called classes.
Constant. You can use the keyword static final to set a class constant. Note that the definition of a class constant is located outside the main method.

Const is a reserved keyword in Java, but it is not currently used. In Java, you must use final to define constants.
5 Operators

Notes for operators:
An exception occurs when an integer is divided by 0. If a floating-point number is divided by 0, an infinite number or NaN is obtained.
2. Auto-increment and auto-increment operators. For example:

int m=7;int n=7;int a=2*++m;//m=8,a=16int b=2*n++;//n=8,b=14

3. Relational operators and boolean operators. For example:

If (x! = 0 & 1/x> x + y) when x is 0, the second part is not calculated. Therefore, if x is 0 and 1/x is not calculated, the error of dividing by 0 is not displayed. & | The value is calculated based on the "Short Circuit" method.

4-bit operator (this is rarely used, but is easy to ignore)

& ("And"), | ("or"), ^ ("different or "),~ ("Not") ">>" and" <"operators shift the binary bitwise right or left >>> operators are filled with 0 to a high position. >> use the symbol bit to fill the high position. No <operator is required for the parameter on the right of the shift operator to perform the modulo 32 operation (unless the operand on the left is of the long type, in which case you need to perform the modulo 64 operation on the right ). For example, 1 <35 and 1 <3 or 8 are the same.

5 mathematical functions and constants
For example:

double x=4;double y=Math.sqrt(x);System.out.println(y);//print 2.0
Note: There are minor differences between the println and sqrt methods. The println method operates a System. out object defined in the System class. However, the sqrt method in the Math class does not operate on objects. Such a method is called a static method. Tip: from JDK 5.0, you do not need to add the prefix "Math." Before the mathematical method name and constant name, but you only need to add the following content to the top of the source file. Example: import static java. lang. Math .*;

6 conversion rules between values
Post a picture, not explained

Solid arrows, indicating conversion without information loss; virtual arrows, indicating conversion with potential loss of precision.
For example, 123 456 789 is a large integer that contains more digits than the float type can express. When this integer value is converted to the float type, the result of the same size is obtained, but the precision is lost.
Int n = 123456789;
Float f = n; // f is 1.234567892 E8

When using values for binary operations, convert the two operands to the same type. The conversion rules are as follows:
If one of the two operands belongs to the double type, the other operand is converted to the double type.
Otherwise, if one of the operands is of the float type, the other operand will be converted to the float type.
Otherwise, if one of the operands is of the long type, the other operand is converted to the long type.
Otherwise, both operands are converted to the int type.

Forced conversion. For example;

double x=9.997;int n=(int)x;//n is 9

To obtain the nearest integer, you can use:

double x=9.997;int n=(int)Math.round(x);//n is 10

Do not force type conversion between the boolean Type and any numeric type. If conversion is performed, use the conditional expression B? 1-0.

7 brackets and operator level
If parentheses are not used, the priority is calculated based on the given operator priority. Operators at the same level are calculated in the order from left to right (except the right Union operator given in the table .)

Operator Associativity
[]. () (Method call) From left to right
! ~ ++-+ (Unary operation)-(unary operation) (forced type conversion) new From right to left
*/% From left to right
Add- From left to right
<>>>> From left to right
<<=>> = Instanceof From left to right
=! = From left to right
& From left to right
^ From left to right
By bit or From left to right
&& From left to right
Or From left to right
? : From right to left
= + =-= * =/= % = <<=>>>>> = From right to left

8 Enumeration type
I will not explain it here

6 string

Technically, java strings are Unicode character sequences. For example, the string "Java \ u2122" consists of five Unicode characters J, a, v, a, and TM. Java does not have a built-in String type (not included in the basic data type). A predefined String class is provided in the java standard class library. Each "" contains an instance of a string:

String string = ""; // an empty stringString String = "hello"; // String is a Java class. The class name is an identifier, so String can be an identifier. String sizeof = "sizeof"; // There is no sizeof operator. Java does not have the sizeof operator, so sizeof can be used as an identifier

1 substring
For example:

String greeting="hello";String s=greeting.subString(0,3);//s is hel

Explain the subString function:
The first parameter starts from 0. The second parameter ends with 3 (0, 1, 2, excluding 3 ).
The length of the substring is relatively simple, that is, 3-0 = 3.
2 Splicing
Concatenate two strings with +. For example:

String a="hello";String b="world";int age=13;String c=a+b;//c is helloworldString d=a+age;//d is hello13

Two principles:
There is no space between 1 word, + concatenates two strings in the given order
2. When a string is concatenated with a non-string value, the latter is converted to a string.

3 immutable string
The String class does not provide a method to modify the String. If you want to change the greeting content to "Help !", You cannot directly change the characters at the last two locations of greeting to 'p' and '! '. Implementation in c is more troublesome:

Here, I will mention that the string is considered as a character array: char greeting [] = "hello"; this recognition is incorrect, and the Java string is more like a char * pointer, char * greeting = "hello"; when another string is used to replace greeting, c code mainly performs the following operations: char * temp = malloc (6); strncpy (temp, greeting, 3); strncpy (temp + 3, "p! ", 3); greeting = temp;

It is very easy to implement this operation in Java. Extract the required characters and then splice the string to be replaced:

greeting=greeting.subString(0,3)+"p!";//greeting is help!

In the source code document of java, the String class object becomes an immutable String, and there is a question:

String greeting="hello";greeting="help!";

The above Code only modifies the address referenced by greeting, that is, the original reference is "hello", and then reference "help !", Where did the original "hello" go?

Will this cause memory omissions? After all, the original string is placed in the heap. Fortunately, Java will automatically recycle garbage. If a piece of memory is no longer used, the system will eventually recycle it.

Of course, the C ++ string object also automatically allocates and recycles memory. Memory Management is performed explicitly by the constructor, value assignment operation, and destructor. However, the C ++ string can be modified, that is, a single character in the string can be modified.

Why is this design? It seems that modifying a code unit is more concise and efficient than creating a new string?

The answer is: yes, no. Indeed, by splicing "El" and "p !" Creating a new string is really inefficient. But immutable strings have one advantage: the compiler can share strings.

To find out how it works, you can imagine storing various strings in a public storage pool. The string variable points to the corresponding location in the storage pool. If you copy a string variable, the original string shares the same character with the copied string.

All in all, Java designers think that sharing brings much higher efficiency than extracting and splicing strings. Check the program and you will find that you need to compare strings rather than modifying strings.

4. Check whether the strings are equal.
If you think the comparison is equal, you can use "=". Then you are wrong. For example:

String greeting="hello";//initialize greeting to a stringif(greeting="hello")...//probably trueif(greeting.subString(0,3)=="hel")...//probably falsewhy?

If the virtual machine always shares the same string, you can use the = Operator to check whether the strings are equal. But in fact, only string constants are shared, and the results produced by operations such as + or substring are not shared. Therefore, do not use the = Operator to test the equality of strings to avoid bad bugs in the program. On the surface, such bugs are similar to random intermittent errors.

In java, how does one compare whether strings are equal?

String greeting = hello; "hello". equals (greeting)... // true "Hello". Reset Signore (greeting)... // true, case insensitive,
Note: For those who are used to the C ++ string class, be careful when performing equality detection. The = Operator is overloaded in the string class of C ++ to detect the equality of string content. Unfortunately, Java does not adopt this method. Its string "looks and feels" is the same as a numerical value, but its operation is similar to a pointer during Equality testing. The language designer should also perform special processing like the + operator, that is, redefinition = Operator. Of course, there are some inconsistencies in each language. C Programmers never use = to compare strings, but use strcmp functions. Java's compareTo method is similar to strcmp, so you can use: if (greeting. comepareTo ("hello") = 0)... however, using equals looks clearer.

5. Code points and code units
What are code points and code units?
In Java, the char [], String, StringBuilder and StringBuffer class adopts UTF-16 encoding, using U + 0000 ~ U + FFFF represents a basic character (BMP character), but char located in U + D800 to U + DBFF and U + DC00 to U + DFFF is considered as non-defining characters. Most common Unicode characters can be expressed by a single code unit, while auxiliary characters need to be represented by a pair of code units. That is, the basic character is represented by a char, and the secondary character is represented by a pair of char.

Java uses the Unicode code pointer to indicate the character values (int type) in the range of U + 0000 and U + 10FFFF, and the code unit (Unicode code unit) represents the 16-bit char value (char type) of the code unit encoded as the UTF-16 ). That is to say, there may be a character whose number of code points is 1 and the number of code units is 2. Therefore, the number of code units is not necessarily the number of characters.

In contrast, code units are more at the bottom layer.

Related functions:
The length () function returns the number of code units required for a given string identified by a UTF-16.
The codePointCount () function returns the number of code points required for a given string identified by a UTF-16.

Test procedure:

Package com. xujin; public class Test {public static void main (String... args) {char [] ch = Character. toChars (0x10400); System. out. printf ("U + 10400 high proxy character: % 04x \ n", (int) ch [0]); // d801 System. out. printf ("U + 10400 low proxy character: % 04x \ n", (int) ch [1]); // dc00 String str = new String (ch); System. out. println ("code unit length:" + str. length (); // 2 System. out. println ("Number of code points:" + str. codePointCount (0, str. length (); // 1 System. ou T. println (str. codePointAt (0); // return the code point starting or ending at a given position, 66560 System. out. println (str. charAt (1); // return the code unit at the given position. Because it is not defined,? // Print the code of all characters by traversing a string. The Code point is str + = "Hello, world! "; Int I = 0; int cp = str. codePointAt (I); while (I <str. length () {System. out. println (str. codePointAt (I); if (Character. isSupplementaryCodePoint (cp) I + = 2; // if the position of the cp is the first part of the code point, run else I ++ here ;} /** 66560*72*108*111*119*114*100 */}}

Java string is composed of char sequences, char is a UTF-16-encoded Representation
The code unit of the Unicode Code Point. A common Unicode character can be expressed by a code unit, while a secondary character must be expressed by a code unit.

The length method returns the number of code units required for a given string expressed in UTF-16 encoding. For example:

String greeting="hello";int l=greeting.length();//5

To get the actual length, that is, the number of code points, you can call:

Int cpCount = greeting. codePointCount (0, greeting. length (); // Why is this actual length?

Call s. charAt (n) To return the code unit of position n, where n is between 0 and ~ S. length ()-1. For example:

Char first = greeting. charAt (0); // first is hchar last = greeting. charAt (4); // last is o // return character // to get the I code point, use the following statement int index = greeting. offsetByCodePoints (0, I); int cp = greeting. codePointAt (index); // returns the ascii Value

6 string API

7 Input and Output 8 control flow 9 large value 10 Array

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.