Java Core Technology-The Basic Programming Structure of Java

1. A simple Java application

public class FirstSample
{
    public static void main(String[] args)
    {
        System.out.pringln("We will not use 'Hello,World!'");
    }
}

This program is simple, but all Java applications have this structure:

First of all, Java is case-sensitive (such as writing main as Main program will not run)

Let's analyze this code line by line:

  The public keyword is called an access modifier and is used to control the level of access to this code by other parts of the program.

  The class keyword indicates that everything in a Java program is contained within a class.

  The class name follows the class keyword. The name must start with a letter and can be followed by any combination of letters and numbers. Java keywords cannot be used.

  A method modified by the static keyword is called a class method

  void keyword means no return type

Standard naming convention - camel nomenclature

The file name of the source code must be the same as the class name


 

2. Notes

1.// The most common way of commenting, the comment content starts from // to the end of the line

2. /* and */ are used for long comments, put the comment content in the middle of /* and */

3. /** and */ are used to generate automatic documentation, and the comment content is placed between /** and */


 

3. Data Type

Java is a strongly typed language and a type must be declared for every variable.

Basic data types: 4 integers, 2 floats, 1 character, 1 boolean

3.1 Integer

Starting from Java7, binary numbers can be written with the prefix 0b or 0B.

Since Java7, it is also possible to underline numeric literals (1_000_000 means 1 million)

3.2 Floating point types

Three special floating-point values: positive infinity (a positive integer divided by 0), negative infinity, and NaN (not a number, such as 0/0 or the square root of a negative number)

You cannot use x==Double.NaN to check whether x is equal to Double.NaN, you can use Double.isNaN(x) to check

2.0-1.1 will print 0.899999999999. If the value does not allow any errors in the calculation, the BigDecimal class should be used

3.3 char type

Literals of type char should be enclosed in single quotes

Some Unicode characters can be described with one char value, while others require two char values

3.4 boolean type

Used to determine logical conditions: true/false


 

4. Variables

4.1 Variables

The variable name must be a sequence of letters (including "_", "$") or numbers starting with a letter.

After declaring a variable, it must be explicitly initialized with an assignment statement.

It is good programming style to declare variables as close as possible to where they are first used

4.2 Constants

The final keyword is used to indicate constants (it is customary to use all capitals for constant names)

static final sets a class constant


 

5. Operators

Methods marked with the strictfp keyword must use strict floating-point arithmetic to produce reproducible results (with the potential for overflow)

5.1 Mathematical functions

The floorMod method is to solve the problem of integer remainder

In the Math class, in order to achieve the fastest performance, all methods use routines in the computer's floating-point unit. If obtaining a completely predictable result is more important than the operation speed, the StrictMath class should be used.

5.2 Conversion between numeric types

 

Conversion order: double->float->long->int

Reasons for int to float failure (https://blog.csdn.net/m1n_love/article/details/55224990)

5.3 Coercion

Rounding a floating point number: Math.round

5.4 Combining assignments and operators

x+=4;

5.5 Increment and Decrement Operators

5.6 Relations and boolean operators

==、!=、&&、||(短路)、x<y?x:y;

5.7 Bitwise operators

&, | (not short-circuiting), ^, ~, >>, << (shift operation is modulo 32 or 64)

5.8 Parentheses and operator levels

5.9 Enumeration Types

enum Size{ SMALL,MEDIUM,LARGE,EXTRA_LARGE}

Size s=Size.MEDIUM


 

6 strings

Java does not have a built-in string type, but instead provides a predefined class in the standard Java class library called String

6.1 Strings

substring method of String class

6.2 Splicing

1. Use the + sign to connect: when a string is concatenated with a non-string, the latter will be converted into a string (any Java object can be converted into a string)

2. If you need to put multiple strings together and separate them with a delimiter, you can use the static join method: String.join("/","S","M","L","XL") ;

6.3 Immutable Strings

The String class does not provide methods to modify strings, so the Java documentation refers to String class objects as immutable strings.

Immutable strings have an advantage: the compiler can make strings shared

Java designers believe that the high efficiency brought by sharing is far better than the inefficiency brought by extracting and splicing strings

6.4 Checking whether strings are equal

Use equals instead of ==

If the virtual machine always shares the same string, you can use the == operator to check for equality. But in fact only string constants are shared, and the results generated by operations such as + or substring are not shared. When using the == operator to test string equality, on the surface, this bug looks like a random occurrence. Intermittent errors.

6.5 Empty and null strings

if(str != null && str.length != 0) first check that str is not null

6.6 Code Points and Code Units

Do not use char data type (code unit) to hold code points taken from strings

6.7 Building Strings

If the string concatenation method is used when constructing a string, a new String object will be constructed every time the string is concatenated, which is time-consuming and wastes space. Use the StringBuilder class to avoid this problem (single thread).

The StringBuffer class is slightly less efficient than the StringBuilder class, but allows use in multiple threads.


 

7 Input and output

7.1 Reading input

The input is visible: Scanner in=new Scanner(System.in);

Input not visible: Console cons=System.console();

      String username=cons.readLine("User name:");

      char[] passwd=cons.readPassword("Password:"); - only one line of input can be read at a time, and there is no way to read a word or a value

7.2 Formatting output

System.printf("Hello,%s. Next year,you'll be %d",name,age);

Each format specifier starting with % is replaced with the corresponding parameter

 

String date=String.format("%1$s %2$tB %2$te,%2$tY","Due date:",new Date());

Syntax diagram for format specifiers:

7.3 File input and output

If the filename contains backslashes, remember to add an extra backslash before each backslash: "c:\\mydirectory\\myfile.txt"

Find file path: String dir=System.getProperty("user.dir");


 

8 Control Flow

Java uses conditional statements and looping constructs to determine control flow

8.1 Block scope

A block refers to a number of simple Java statements enclosed by a pair of curly braces, and a block determines the scope of a variable.

8.2 Conditional Statements

if/else

8.3 Loop Statements

while/do-while

8.4 Determining the cycle

In a loop, testing for equality of two floats requires extra care:

for(double x=0;x!=10;x+=0.1) Because 0.1 cannot be represented exactly in binary, the loop may never end

8.5 Multiple selection

switch

8.6 Interrupt Control Flow Statements

A labelled break has been added in Java to break out of multiple loops.

Any code that uses a break statement needs to detect whether the loop ended normally or was broken out of by a break.


 

9 large values

Large numbers can handle numbers that contain sequences of numbers of arbitrary length

BigInteger (arbitrary precision integer) and BigDecimal (arbitrary precision floating point number)

BIgInteger lotterOdds=lotterOdds.multiply(BigInteger.valueOf(n-i+1).divide(BigInteger.valueOf(i));


 

10 array

An array is a data structure used to store a collection of values ​​of the same type.

All elements of a numeric array are initialized to 0; elements of a Boolean array are initialized to false; elements of an object array are initialized to null.

Get the number of elements in the array: array.length

Once an array is created, its size cannot be changed. If you frequently need to expand the size of an array on the fly, you should use an ArrayList.

To print an array you can use Arrays.toString(a);

10.1 Enhanced for loop

The for each loop can be used to process each element of the array in turn (without using subscripts)

10.2 Array initialization and anonymous arrays

Initialization of the array:

int[] smallPrimes={2,3,5,6,11};

Use anonymous arrays to reinitialize an array without creating new variables.

smallPrimes=new int[]{17,18,23,29,31};

10.3 Array copy

One array variable is copied to another array variable: both variables will now refer to the same array.

int[] luckyNumbers=smallPrimes;

To copy the values ​​of one array to another: use the Arrays.copyOf method:

int[] copiedLuckyNumbers=Arrays.copyOf(luckyNumbers,2*luckyNumbers.length);

10.4 Command Line Parameters

10.5 Array sorting

Sorting a numeric array can use the sort method in the Arrays class, which uses an optimized quicksort algorithm.

10.6 Two-dimensional arrays

Multidimensional arrays will use multiple subscripts to access array elements, which are suitable for representing tables or more complex arrangements.

Iterate over a two-dimensional array:

for(int i=0;i<balances.length;i++)

{

  for(int j=0;j<balances[i].length;j++)

  { ...   }

}

The for each loop statement cannot automatically process each element of the two-dimensional array, you need to use two nested loops

To quickly print a list of data elements of a two-dimensional array, call: Arrays.deepToString(a));

10.6 Irregular arrays

Java doesn't actually have multidimensional arrays, only one-dimensional arrays, multidimensional arrays are interpreted as "arrays of arrays"

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325038638&siteId=291194637