Basic program design structure of Java core technology-java

Source: Internet
Author: User
Tags mathematical functions naming convention square root

1. A simple Java application
 Public class firstsample{    publicstaticvoid  main (string[] args)    {        System.out.pringln ("We'll not use ' hello,world! '" );    }}

Although this program is simple, all Java applications have this structure:

First, Java is case-sensitive (such as writing main to the main program will not work)

This code is parsed on a line-by-row basis:

The Public keyword is called an access modifier and is used for the level of access to the code in other parts of the control program.

The class keyword indicates that all content in a Java program is contained in a class.

The class name immediately follows the class keyword, and the name must start with a letter, followed by any combination of letters and numbers, and cannot use the Java keyword

The Static keyword-decorated method is called a class method

The Void keyword indicates no return type

The standard naming convention--Camel name law

The source code must have the same file name as the class name

2. Notes

1.//most commonly used notation, with comments from//start to the end of the bank

2./* and * * For lengthy comments, place the comments in/* and/* in the middle

3./** and/* are used to generate automatic documents, placing comments in/** and */center

3. Data type

Java is a strongly typed language, and one type must be declared for each variable.

Basic data types: 4 integer, 2 floating-point, 1-character, one-Boolean

3.1 Integral type

Starting with Java7, a binary number can be written with the prefix 0b or 0 b.

Starting with Java7, you can also underline the number literal (1_000_000 represents 1 million)

3.2 Floating-point types

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

You cannot use X==double.nan to detect if X is equal to Double.NaN and can be detected using Double.isnan (x)

2.0-1.1 will print out 0.899999999999, if the value is not allowed in the calculation of any error, it should be used BigDecimal class

3.3 Char Type

Literal literals of type char are enclosed in single quotation marks.

Some Unicode characters can be described with a char value, and some Unicode characters require two char values

3.4 Boolean Type

Used to determine the logical condition: true/false

4. Variable 4.1 variable

The variable name must be a sequence that begins with a letter and consists of a letter (including "_", "$"), or a number.

After declaring a variable, you must explicitly initialize the variable with an assignment statement.

The declaration of a variable is as close as possible to the place where the variable was first used is a good programming style

4.2 Constants

The final keyword is used to indicate constants (customary constant names use all caps)

Static final sets a class constant

5. Operators

STRICTFP keyword tagging methods must use strict floating-point calculations to produce reproducible results (potentially overflow)

5.1 Mathematical functions

Floormod method is to solve the problem of integer redundancy

In the math class, in order to achieve the fastest performance, all methods use the routines in the computer floating-point unit, and the Strictmath class should be used if a fully predictable result is more important than the speed of the operation.

5.2 Conversions between numeric types

Conversion Order: Double->float->long->int

int turn float failure reason (55224990)

5.3 Coercion of type conversions

Rounding a floating-point number: Math.Round

5.4 Combining assignments and operators

x+=4;

5.5 Self-increment and decrement operator 5.6 relationship and Boolean operator

= =,! =, &&, | | (short circuit), x<y?x:y;

5.7-bit operators

&, | (non-short circuit), ^, ~, >>, << (shift operation for modulo 32 operation or 64)

5.8 Brackets and operator levels

5.9 Enum Types

Enum size{Small,medium,large,extra_large}

Size S=size.medium

6 string

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 Sub-strings

The substring method of the String class

6.2 Stitching

1. Connect using +: When a string is spliced with a non-string, the latter is converted to a string (any Java object can be converted to a string)

2. If you need to put multiple strings together, separated by 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 a way to modify the string, so the string class object is called an immutable string in the Java document.

Immutable strings have one advantage: The compiler can let strings share

Java designers believe that sharing brings more efficiency than extracting and stitching strings.

6.4 Detecting whether strings are equal

Use equals instead of = =

If the virtual machine always shares the same string, you can use the = = operator to detect equality. But in fact only the string constants are shared, and the results of operations such as + or substring are not shared, and when the = = operator is used to test the equality of strings, the bug is, on the surface, much like a randomly generated intermittent error.

6.5 empty string with null string

if (str! = NULL && str.length! = 0) First check that STR is not NULL

6.6 Yards point and code unit

Do not use char data type (code unit) to save code points taken from a string

6.7 Building a string

When you build a string with a string connection, each connection string constructs a new string object that is time consuming and wasted space. Use the StringBuilder class to avoid this problem (single-threaded).

The StringBuffer class is less efficient than the StringBuilder class, but is allowed to be used in multiple threads.

7 input/Output 7.1 read input

Input 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 number

7.2 Format output

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

Each format specifier that starts with a% 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 specifier:

7.3 File input and output

If the file name contains a backslash symbol, remember to add an extra backslash before each backslash: "C:\\mydirectory\\myfile.txt"

Find file path: String dir=system.getproperty ("User.dir");

8 Control process

Java uses conditional statements and loop structures to determine control flow

8.1 Block Scope

A block is a number of simple Java statements enclosed by a pair of curly braces that determine the scope of the variable.

8.2 Article statements

If/else

8.3 Loop statements

While/do-while

8.4 Determining loops

In a loop, it takes extra care to detect whether two floating-point numbers are equal:

for (double x=0;x!=10;x+=0.1) because 0.1 cannot be used to accurately use binary representations, the loop may never end

8.5 Multi-weight selection

Switch

8.6 Interrupt Control Flow statement

A tagged break is added to Java to jump out of multiple loops.

For any code that uses the break statement, you need to detect whether the loop ends normally or break out.

9 Large values

Large values can handle numeric values that contain any number of length sequences

BigInteger (arbitrary precision integers) and bigdecimal (arbitrary precision floating-point numbers)

BIgInteger lotterodds=lotterodds.multiply (biginteger.valueof (n-i+1). Divide (biginteger.valueof (i));

10 arrays

An array is a data structure that is used to store the same type worth collection.

All elements of a numeric array are initialized to a 0;boolean array element to be initialized to false, and the elements of an object array are initialized to null.

Get the number of elements in an array: Array.Length

Once you have created an array, you cannot change its size. If you frequently need to extend the size of the array in the run, you should use the array list (ArrayList).

To print a group you can use Arrays.tostring (a);

10.1 Enhanced for Loop

The For Each loop can be used to sequentially process each element in the array (without using subscript)

10.2 Initialization of arrays and anonymous arrays

Initialization of the array:

Int[] smallprimes={2,3,5,6,11};

Use an anonymous array to reinitialize an array without creating a new variable.

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

10.3 Array Copy

An array variable is copied to another array variable: At this point two variables will refer to the same array.

Int[] Luckynumbers=smallprimes;

Copy the value of an array to another array: Use the Arrays.copyof method:

Int[] copiedluckynumbers=arrays.copyof (luckynumbers,2*luckynumbers.length);

10.4 command line parameter 10.5 array sorting

Sorting a numeric array can use the sort method in the arrays class, which uses an optimized fast sorting algorithm.

10.6 Two-dimensional arrays

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

To traverse 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 does not automatically process each element of a two-dimensional array, requiring the use of two nested loops

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

10.6 Irregular arrays

Java does not actually have multidimensional arrays, only one-dimensional arrays, and multidimensional arrays are interpreted as "arrays of arrays"

Basic program design structure of Java core technology-java

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.