Fundamentals of Java language programming

Source: Internet
Author: User
Tags modifier java keywords

Basic elements of the Java language

High-level languages such as C + +, C #, Java, and so on have some common things: keywords, identifiers,

operators, comments, data types, constants and variables, statements, functions, arrays . High-level languages are similar on these elements.

Java keywords: Some have a specific meaning, have a special purpose string (keyword). The keywords in Java are lowercase. such as do and if int. Do not need to remember, with more natural will know.

Identifier

The name of the customization. such as the class name, variable name, method name, and so on. Legal identifier rule: 1 cannot use the key word 2 cannot begin with a number. In Java, identifiers can be composed of 26 uppercase and lowercase letters, numbers 0~9, and _$. Java are strictly case sensitive.

★: In the programming generally make meaningful identifiers, easy to read. This is also a good programming habit.

Comments

As the name implies, the code is labeled, explained, or temporarily "deleted."

The comment format for Java is://single-line comment/* xxxxx */Multiline comment. Note: The code of the comment does not participate in the compilation, i.e. it is not included in the bytecode.

Data type

Java is a strongly typed language, each of which defines an unambiguous data type, in which memory is always allocated a different size of memory space. NOTE: integer default int, decimal default double. Type conversions: Divided into forced type conversions (display) and automatic type conversions (implicit). The value of byte, short, and char in the expression is promoted to int, and the other long, double, float, corresponding to its own type

Example: System. out. println (' a ' + 1);//char Automatic type Conversion 98

System. out. println ((char) (' a ' + 1));//strong transfer B acsii code

byte b = 4; BYTE range -128~127 values in this range Java is automatically strongly converted to byte

byte = B1 + B2;//variable not detectable, compile error, should be enhanced to extrapolate the following types

Byte 8-bit signed integer-any integer between 128 and 127

Any integer between short 16-bit unsigned integer -32768~32767

An int 32-bit signed integer -2^31 to 2^31-1 any integer

Long 64-bit signed integer -2^63 to 2^63-1 any integer

Float 32-bit single-precision floating-point number according to ieee754-1985 standard

Double 64-bit dual-precision floating-point number according to the ieee754-1985 standard some hints:

Unlike other programming languages, the number of integers in the Java language is fixed and not different depending on the hardware platform and the operating system.

Value passing: (formal parameter type is the basic data type plus string type): When the method is called, the actual parameter passes its value to the corresponding formal parameter, the formal parameter only initializes its own storage unit content with the value of the actual parameter, is two different storage units, Therefore, the change of the formal parameter value in the method execution does not affect the value of the actual parameter.

Reference passing: (formal parameter type is a reference data type parameter): Also known as a pass-through address. Method invocation, the actual parameter is an object (or an array), then the actual parameters and formal parameters point to the same address, in the execution of the method, the operation of the formal parameters is actually the operation of the actual parameters, the result is preserved after the end of the method, so the change in the method execution parameters will affect the actual parameters.

Constants and variables

Constants represent values that cannot be changed. Constants in Java: 1 integer constants, all integers 2 decimal constants, all decimals. 3 Boolean constant, True and false. 4 Character constants with ' identity 5 string constant with ' "" identifies 6 null constant, which is a null.

Variable: An area of memory in which there is a name (variable name) and type (data type), and the data for that region can change continuously under the same data type. Purpose: Constant storage of the data type, reusable. The scope of the variable: valid in {}. Initialization required. To define the variable format:

Data type variable name = initialization value ; The basic type variable in Java has a default initialization value, so it can also be the base type variable name; The precondition is that the variable is a member variable of the class with a default value, which must be initialized as a local variable;

Operator

Arithmetic operations: + Plus, connectors such as "3" + 2 output 32-minus * Multiply/pick-up%

+ + self-increment (original base +1, re-assigned to the original data a++ equivalence and a = a+1)--Self-reduction

+ = plus equals a+= 4 equivalence with a = A+4

★:a++ participate in other operations, a original value after the operation of +1, ++a is a+1 after the participation in the Operation

Assignment operations: =, + =,-=,/=,%=

Comparison operation:

> greater than < less than = = equals = = Not equal to <= less than or equal to >= greater than or equal

instanceof Check if it is a class object example: "Hello" instanceof String//true

The result of the comparison operator is only two true or false

Logical Operation:&& with | | Or & | Also, the difference between a single and 2: expression 1& expression 2: Both sides of the simultaneous operation, the result and the expression 1&& expression 2: expression 1 if =false, expression 2 no longer operation. Used to connect two Boolean types of values

Bitwise operations: Direct binary operation << left shift >> right shift >>> unsigned right shift & and | or ^ Xor ~ Anti-code

★2<<3 = 16 Left shift 3 bit post low 0 equivalent with 2 * 2 (3)

6>>1 = 3 1 bits after right shift, if the high is 0, the vacancy is 0, otherwise the complement 1 is equivalent to 6/2 (1)

Using bit operations to be more efficient than arithmetic operations 3*8, 3<<3 premise: integer multiples of 2

Two methods for exchanging values of numeric variables:

1.a = temp, a = b, b = temp;

2.a =a + B, b= A-a, a = a-A;

3.a=a^b; B=a^b; A=a^b; A number XOR or two times equal to the original number

Ternary operation: Format: (conditional expression)? Expression 1: Expression 2 If the conditional expression is true, the result is equal to expression 1, which is false, and the result is an expression of 2. Can be seen as a simplified if else statement, but the difference is that ternary operations are bound to have results.

Example: Get the larger of two number: int a=4,b=3,c;c= a>b?a:b; result c=4

Statement (program flow control)

Judging structure, sequential structure, cyclic structure, selection structure.

Sequential structure: There is nothing to say, the program is executed from top to bottom.

Judge structure: If statement, if Else statement, if else if else if. Statement:

if (conditional judgment) {

True to execute

} else{

False execution};

The following program that does not write else default if is the program that else executes, if there is no bracket, but in a certain format (such as removing the brackets above) The IF Else statement is also true.

The function of {}: The enclosing code is called a local code block, which determines the life cycle of the local variable.

Select structure: switch statement: switch (expression) {

Case (take value 1):

break;//has taken 1 values, interrupts the selection, and executes the next bar of switch

Case (take value 2):

execute; break;

......

Default: statement; break;//If you do not select a value for case (the case value is judged first, regardless of where the default is written), the defaults are taken.

}

Note : Only four data types are available for switch selection, byte, short, int, char, enum (enum type), String (Java7 new). Immediately after the statement can not write break;

Loop structure: statement: While, do while, for.

while (conditional expression) {do{

EXECUTE statement; EXECUTE statement;

}while (conditional expression);//Note semicolon

}

while () {} If the condition is true, execute the statement and then judge the condition again, if True then execute the second statement again, then judge ... until the condition is false.

The Do and execute statements in do are executed at least once, regardless of the condition. Do it first and then judge.

For statement: Format for (initialize expression; loop condition expression; post-loop action expression) {

Execute statement;//Loop body

}

Run Order: The initialization expression is executed first, then the loop condition expression is interpreted, and if true, the loop body is executed, then the operation expression after the loop is executed, then the conditional expression is judged and the repetition process is known until the tuning is not satisfied. The For statement can nest for, if.

Note : While and for can be used interchangeably, the variables defined in for are included in the initialization expression, and the variables defined in the initializer are freed by memory after the loop ends. Infinite loop: while (true) for (;;)

Other statements: Break jumps out of the loop application and selection and loop structure, continue out of the loop, executes the next loop, and applies to the loop structure.

Note: Two statements must work in their own application. When these two statements exist separately, they are not followed by other statements because they do not.

Function

A function is a method that refers to a block of code that has specific functionality in a class. Functions can be used to encapsulate the function code, and it will be executed only when it is called, which improves the reusability of the code.

How to design a function: Take function as the center, consider how the function is implemented? How many formal parameters do you need? What the return value is, it's natural to do it.

Note: You cannot define another function within a function, you can call other functions (you need to see the modifier, you will mention it), and the result of the function should be returned to the caller. After the function is called, it is removed by the memory and then loaded into memory when it is called (the type of attendee hangs). )。

Format: Modifier returns the type function name (parameter type form parameter 1, parameter type parameter 2 ... ){

Execute the statement;

return value

}

Special: The function has no return value and does not need to return a value when the return type can be void,return without writing.

Overloading of functions : Multiple functions with duplicate names are allowed in a class, as long as their number of formal parameters or parameter types are different.

Overloads: Homogeneous, same name, same return value, different parameters.

Note: There is no relationship to the return type, except for the parameter list.

Array

A collection of data of the same type, an array is actually a container.

Format:

element type [] Array name = new element type [array length]

element type [] Array name = new element type {element 1, Element 2, ...}

The array automatically labels the elements, starting with 0. Not clear exactly what the data is when using format 1,

Known specific data in format 2.

Common Exceptions for arrays:

ArrayIndexOutOfBoundsException: Subscript is out of bounds, that is, access to the array does not exist in the corner label.

NullPointerException: This exception occurs when the referenced variable does not have any entities pointing to arr=null.

The operation of the array is done by the operation Angle mark, arr[x] = XX; Print (arr[x]);.. You can iterate through the array with a for loop. Traversing an array can accomplish many useful functions, finding a particular data, summing, maximizing, sorting, etc.

Basic traversal mode: for (int = 0;i<arr.length;i++) {

Arr[i];

}

Two-dimensional arrays: arrays in arrays.

Format: int[][] arr = new int[2][3];//The two-dimensional array has 2 one-dimensional arrays containing three elements.

int[]][] arr = new int[3][];//The two-dimensional array has three one-dimensional arrays.

Sorting and finding: In data structures and algorithms.

Fundamentals of Java language programming

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.