Java Core Technology (ii) Basic program design structure of--java

Source: Internet
Author: User
Tags integer division mathematical functions

This article focuses on the implementation of basic concepts related to programming in Java, which involves a lot of fine content, including annotations, data types, variables, operators, strings, input and output, control flow, large values and arrays.

1. Basic cognition

(1) Java is case sensitive
(2) The source code must have the same name as the public class, with. Java as the extension
(3) The source code file is compiled with a file containing the bytecode of this class and is automatically named as a file with the same name, except that it has a. class extension and is stored in the same directory as the source file.
(4) When you run the compiled program, the Java Virtual machine starts executing from the main method (the method that is the function) in the development class, so in order for the code to execute, a main method must be included in the source file of the class and must be declared as public,static.
(5). Used to invoke methods.

2. Comments

Annotations do not appear in the executable program, so you do not have to worry about code bloat.
(1)//Line Comment
(2)/plus an asterisk start, an asterisk plus/end, a paragraph comment
(3)/plus two asterisks start with an asterisk plus/end to automatically generate the document. Note that each line starts with an asterisk, such as

3. Data type

Java is a strongly typed language, meaning that one type must be declared for each variable.
Java consists of eight basic types, four integers, two floating-point types, one character type, and one Boolean type.

3.1 Integral type


(1) Note that there is no unsigned type in Java (unsigned)
(2) Prefix 0b can be used to write a binary number, such as 0b1001 is 9. You can also underline numeric literals, such as 1_000_000 for 1 million, and of course the underscore is just for people to read, and the Java compiler will remove these underscores.

3.2 Floating-point types


(1) Generally, the float type is rarely used, except for the need to quickly process single-precision data and to store large amounts of data.
(2) Float type value has a suffix f, such as 3.14F, the default is double type.
(3) Note that there are three special floating-point values: positive_infinity, Negative_infinity, and Nan. Note that all non-numeric values are considered to be different and cannot be judged by if, for example, if (x = = Double.NaN) is wrong.
(4) It is also important to note that floating-point values do not apply to financial calculations that prohibit rounding errors, such as SYSTEM.OUT.PRINTLN (2.0-1,1) will print 0.8999999999999 instead of the expected 0.9. This is obviously caused by a binary system representation of floating-point values. If you need a numeric calculation that does not contain any rounding errors, you should use the BigDecimal class described later.

3.3 Char Type

The char type is used to represent a single character and is typically used to denote character constants.
(1) Similarly, ' a ' denotes a character constant, while ' a ' represents a string containing the character A.
(2) \u-time escape sequence character, which can be used to denote the encoding of a Unicode code unit, or some special character, a commonly used special escape sequence character

(3) In Java, the insert type describes a unit of code with UTF-16 encoding, preferably not a char type, preferably a string that needs to be processed in an abstract data type .

3.4 Boolean Type

That is, false and true.
(1) Note that, unlike C + +, there is no reciprocal conversion between an integer value and a Boolean value.

4. Variables

In Java, each variable belongs to a type.
(1) The variable name must be a sequence of characters or numbers beginning with a letter
(2) Case sensitive, unlimited length
(3) Although you can declare multiple variables in a row, it is recommended to declare each variable individually

4.1 Variable Initialization

differs from the declaration and definition of variables that are not differentiated in C++,java. After declaring a variable. Variables must be displayed initialized with an assignment statement, and variables that are not initialized should never be used.

4.2 Constants

(1) using the keyword final in Java to represent a constant, that is, the variable can only be assigned once, once assigned, can not be changed. In practice, the constant name uses all uppercase. Be careful not to use Const.
(2) If a constant needs to be used in more than one method in a class, that is, a class constant, it can be set using the keyword static final.

5. Operators

(1) When the two operands of the participating/operation are integers, the integer division is represented, otherwise the floating point division is represented. Note that an integer divided by 0 produces an exception, and a floating-point number divided by 0 results in infinity or Nan.
(2) floating-point value in different platform operation involves the truncation or expansion of precision, it is difficult to achieve portability. For a method that uses the STRICTFP keyword tag, all instructions in the method must use a strict floating-point calculation.

5.1 Self-increment, auto-decrement operator

When the self-increment decrement operator is used in the expression, the suffix form (that is, ++,– after the variable) is used after the self-decrement, and the prefix is the self-increment after the change of the value of the meal and operation.

5.2 Relational operators and Boolean operators

(1) The result of the relational operator is false or True
(2) with &&, or | |, a short-circuit logic, that is, the previous operand can determine the expression value, does not calculate the latter.
(3) Ternary operator

Condition? Expression1:expression2

That is, the expression 1 is calculated when condition is true, otherwise 2
Example available

x < y? X:y

Returns the smaller value in X and Y

5.3-bit operators

(1)

(2) >> and << move right or left,>>> will be filled with 0 high,>> with symbol for fill high, no <<< operator
(3) The parameter to the right of the shift operator requires modulo 32 operation, unless the left operand is a long type, then the modulo 64 operation can be done, such as 1<<35 and 1<<3 both represent 8.

5.4 Mathematical functions and constants

The math class contains a number of mathematical functions.
(1) There is no power operation in Java, need to borrow Math.power (X,a) method
(2) Math Import just add this line of code at the top of the source file

Import static java.lang.math.*;

5.5 Conversions between numeric types

The following is the legal conversion direction between numeric types

For the operation of the different types of two operands, it is automatically converted to the same type, the conversion mode reference direction, so that the two keep the furthest of that type.

5.6 Coercion of type conversions

When you need to implement a non-existent conversion relationship, you need to make a forced type conversion, which of course causes the information to be lost. By adding (the target type) before the variable name to be converted, such as (int) x.
Note that you do not force type conversions between Boolean types and any other numeric types, which can be used in the case of a conditional expression

B? 1:0

5.7 Brackets and operator levels

5.8 Enum Types

6. String

Each string enclosed in double quotation marks is an instance of the string class.

6.1 Sub-strings

The substring method of the string class can extract a substring from a larger string.
Substring is counted from 0, and S.substring (A, A, a, b) indicates that the first character of the string s is extracted to B (not including the second).

6.2 Stitching

Connect two strings sequentially using the + sign, which is converted to a string when a string is concatenated with a non-string value.

6.3 Immutable strings

The string class does not provide a method similar to the one in C + + that modifies a string, such as modifying "Hello" to "help!" You can only use extraction and stitching to implement replacements.
Therefore, the string class object is referred to as an immutable string in the Java document.

6.4 Detecting whether strings are equal

Using the Equals method

S.equals (t)

Note that s and T can be string variables or string constants.
Equalsignorecase method is case-insensitive detection
Avoid using = = to detect whether strings are equal.

6.5 empty strings and Null strings

The empty string "" is a Java object that has its own string length (0) and content (empty).
There is also a special string value, NULL, which indicates that no object is currently associated with the variable.
Frequently used subordinate statements check that the string is neither null nor empty

if (str! = null && str.length ()! = 0)

6.6 Building a String

Using the string concatenation described above is to build a string, inefficient, because each splicing will build a new string object, time wasted space, you can use the StringBuilder class.

7, input and output 7.1 read input

To enter through the console, you first need to construct a scanner object and associate with the standard input stream system.in

Scanner in = new Scanner (system.in);

You can now use the various methods of the scanner class to implement input operations, such as

String name = In.nextline ();

Used to enter a row.
The scanner class is defined in the Java.util package, and when the class used is not defined in the basic Java.lang package, the corresponding package needs to be loaded using the import designator, which is added at the beginning of the program

Import java.util.*;

It is also important to note that the scanner class does not apply to reading passwords from the console and should use the console class.

7.2 Format output

Much simpler than input, use System.out.print (x) directly to output the value x to the standard output stream (console window). This command prints the output x as the maximum number of non-0 digits allowed for the data type that corresponds to X.
(1) System.out.prinf ("%8.2f", X);
That is, print x with a width of 8 characters and a precision of 2 characters after the decimal point, for example, for 10000.0/3.0, output 3333.33, which is a space and seven characters.
(2) printf can also use multiple parameters

See the explanation of the conversion character

7.3 File input and output

Similar to input, to read a file, you need to construct a scanner object with one file object, such as

Scanner in = new Scanner (Paths.get ("MyFile.txt"));

Of course, if the file name contains the symbol \, you need to add an extra \ To avoid ambiguity in each \ Money.
Note that when constructing a scanner with a nonexistent file or a file name that cannot be created, a printwriter is generated, and if it is known that such an exception is possible, it must be marked in the main method in advance with the throws sentence.

8. Control process

That is, we are going to introduce conditional statements and loop statements. Java does not have a goto statement, and there is a break statement.

8.1 Block Scope

You cannot declare a variable of the same name in a nested two block. , which differs from C + +.

8.2 Article statements

if (condition) statement

And

if (condition) statement1 else statement2

Else is always a group with the nearest if.

8.3 Loop statements

while (condition) statement

The following statement enables the loop body to be executed at least once

Do statement while (condition)

8.4 Determining loops

That is the usual for loop, Note that in loops, it is important to be careful to detect whether two floating-point numbers are equal

for (int i = 0; I! =); i + = 0.1) ...

May never end. Due to the presence of rounding errors, it may not be possible to get an exact value, and X will jump directly from 9.99999999999998 to 10.09999999999998 in the above program.
Similarly, the variable declared in the first part of the for statement is scoped to the entire loop body of the For loop.

8.5 Multi-weight selection
switch (choice){    1:        ...        break;    2:        ...        break;    default:        // bad input        ...        break;}

Note that if you do not have a break statement at the end of the case Branch statement, you will then execute the next one, which triggers multiple case branches, which is quite dangerous and must be avoided.
To avoid this danger, we recommend that you add the-xlint:fallthrough option when compiling your code. This way, if a branch is finally missing a break statement, the compiler gives a warning.
The case label can be
(1) constant expression of type char, Byte, short, or int
(2) enumeration constants
(3) string literal
Note that when using enumeration constants in a switch statement, it is not necessary to Zhong Zhiming the enumeration name in each case, which can be determined by the expression value of switch.

8.6 Interrupt Control Flow statement

(1) The break used earlier is a common usage, and there is a label break usage, such as

When condition is satisfied, it is actually similar to the C + + Goto command to jump to the end of a block of statements after a tagged break to label a colon.
(2) Unlike break, the continue interrupts the normal control flow, which is the header that transfers control to the inner loop. For a For loop, jumps to the update part of the For loop, which is the third part.

9. Large value

Sometimes the accuracy of the basic integer and floating-point numbers can not meet the requirements of the two classes in the Java.math package: BigInteger and BigDecimal, respectively, can achieve arbitrary precision integer operation and arbitrary precision floating-point number operation.
You can convert a normal value to a large value by using the valueof () method in these two classes, but for arithmetic operations between step numbers, you can no longer use +,* and so on, you need to use the add and multiple methods in the class.

10. Arrays

An array is a data structure used to store a collection of values of the same type, with an integer subscript to access each value in the array.
(1) Declaration method

Int[] A;

(2) initializing, creating an array with the new operator

Int[] A = new int[100];

This creates an array that can store 100 integers.
When you create a numeric array, all elements are initialized to 0, the elements of the Boolean array are initialized to false, and the elements of the object array are initialized to null.
(3) Note that an element of the array is a (0)
(4) Once an array is created, the size cannot be changed. To extend the size of an array, you should use a different data structure-the list of arrays, which you'll see later.

10.1 For Each loop

You can quickly and sequentially process each element in the array without using subscript values. The basic syntax is

for (variable:collection) statement

The defined variables are used to stage each element in the collection and execute subsequent statements. Note The SET expression collection must be an array, or a class object that implements the Iterable interface, such as ArrayList (array list).

10.2 Initialization of arrays and anonymous arrays

(1) Java provides a simplified notation for creating arrays and simultaneously assigning initial values

Int[] Smallprimes = {2, 3, 5, 7, 11, 13};

That is, you do not need to call new.
(2) also allows initialization of an anonymous array

New int[] {2, 3, 5, 7, 11, 13}

10.3 Array Copy

Java allows an array variable to be copied to another array variable, at which point two variables will reference the same array. The copy here is implemented with the assignment symbol =.

10.4 Array Sorting

When you need to sort a numeric array, you can apply the sort method in the arrays class.

10.5 Multi-dimensional arrays

Multidimensional arrays use multiple subscripts to access array elements, which are useful for representing tables or more complex permutations. For example, declaring a two-dimensional array

Double[][] A;

Again, it is not available before initialization

A = new Double[b][c];

You can also initialize it in a simple way

Int[][] A = {{4,5,6}, {7,8,9}};

Note For a two-dimensional array, the for every statement cannot automatically handle each of these elements, which is processed in a row, and requires two nested loops to access all the elements of a two-dimensional array, such as

for (double[] row : a)    for (doublevalue : row)        dovalue
10.6 Irregular Groups

Note Because Java does not actually have a multidimensional array concept, the aforementioned multidimensional is actually an array of arrays, so you can construct an irregular array, where each row of an array has a different length.
When you need to create an irregular array, you first need to assign an array with the number of rows included

Int[][] A = new int[nmax+1][];

Next, assign these rows

for (int n=0; n<=NMAX; n++)    newint[n+1];

Thus, a triangular matrix is generated.

Java Core Technology (ii) Basic program design structure of--java

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.