Java language Basics

Source: Internet
Author: User
Tags class definition modifiers stringbuffer

1. Statements and statement blocks
Statement: Java is a delimiter, and each sentence with a delimiter is a statement.
Statement BLOCK: The collection of statements inside the {}.

2. Notes
A.//single-line comment

B./* Multiline Comment */

c./** Document Comments */
The text that represents between/** and * * is automatically included in the HTML-formatted document generated with the Javadoc command.
Javadoc is the API document generator in the JDK. This tool parses a set of declarations and document annotations in a Java source file, generating a set of
The HTML page describes the classes, inner classes, interfaces, construction methods, methods, and properties defined in these source programs. API documentation for JDK
is generated using the Javadoc tool.

3. Identifiers and Character sets

A.java Identifier Summary:

1). Consists of letters, numbers, _, or $, and cannot begin with a number;

2). Strictly case-sensitive;

3). Unlimited length

4). Keywords (that is, those words that we type in JC will appear in blue) cannot be used as identifiers.


B. To enhance the readability of the program, Java makes the following conventions:
1). Classes, interfaces: Nouns are usually used, and the first letter of each word is capitalized

2). Method: Usually use verbs, lowercase letters, and then separate each word with uppercase letters

3). Constants: All caps, separated by underscores between words

4). Variables: Usually use nouns, lowercase letters, followed by uppercase letters to separate each word, avoid using the $ symbol.

C. Character Set

1) The Java language uses the international character set (Unicode)

2) Unicode Features:

Each character in the ①unicode character set occupies 16 bits (the usual ASCII code is 8 bits), or 2 bytes, and the entire character set consists of 65,336 characters.
② is ASCII-compatible, and the 256 characters in the front of the Unicode character set are the same.
In addition to representing 256 ASCII codes, ③unicode can also represent Chinese characters, Latin, Greek letters, Korean, and so on.

5. Basic data types
①java defines a total of 8 basic types of four classes:
Logic: Boolean
Text type: Char
Integral type: Byte,short,int,long
Float type: double and float

② in-depth understanding of basic data types:
1). Char is the basic data type (' ') of the literal type, and string is the class is not the base type.
2). Strings are objects in Java, and in Java there are two classes that can represent strings: string and StringBuffer.
String objects represent strings that cannot be modified. If you need to modify the string, you should use StringBuffer.
3). Integer types are divided into four because they represent different ranges of integers, the leftmost range is the smallest, and the rightmost range is the largest.
If a number exceeds the computer's expression range, it is called overflow, or if the maximum value is exceeded, known as overflow, or if the minimum value is exceeded, called
Underflow. The maximum value of an integral type number is added one, the overflow will become the minimum value of the same type, the minimum value minus 1, overflow it will become
The maximum value of the same type.
4). " Integer constants "Can be in three forms, decimal, octal, and hexadecimal. Generally write the decimal first and then convert. In fact, octal integers are preceded by 0,
hexadecimal integers are preceded by 0 x or ox. The default state of an integer constant is int, and for a long constant, add L or L after the value, because lowercase l looks like 1,
In order to avoid misunderstanding, capital is generally used.
5). Double type doubles have a higher precision and larger representation range than the single precision type float, but the float type has the advantage of being fast and taking up little memory.
The default initial value of a floating-point variable is 0.0 (the default double type). When underflow occurs, 0.0 is returned. Overflow occurs, the result is either positive or negative infinity.
6) both char and string represent constants.

③ various forms of anthology

④ wrapper classes for simple types

Note: Java primitives are stored in stacks, so they are stored faster than instance objects stored in the corresponding wrapper class in the heap. The JVM can complete the basic types and their corresponding wrapper classes between

Auto-Convert. So we use their wrapper classes in terms of assignment, parameter passing, and mathematical operations, like using basic types, but the basic types cannot call their wrapper classes for the methods they have. In addition, the wrapper classes for all basic types (including void) are final decorated, so we cannot inherit them to extend new classes, nor can they override any of their methods.

⑤ conversions between simple data types

A. Auto-convert and cast-in mode

(Description: Xiao da byte,short,char,int,long,float,double)

B. Automatic conversion

(1) type (four types):

I. When a smaller data is calculated with a larger data, the system will automatically convert "small" data into "big" data and then perform the operation.

(Note: int to Float,long to Float,long to double is not automatically converted, otherwise the precision will be lost)

II. When the method is called, the actual parameter is "small", and the method called by the form parameter data is more "large" (if there is a match, of course, will call the matching method directly), the system will also

Automatically converts "small" data to "large" data, and then calls the method.

III. For multiple overloaded methods with the same name, it is converted to the most "close" "big" data and called.

IIII. The reference type can be automatically converted to the parent class.

Note: The size of this side is the range size of the value.

(A special note on the above summary:

1) The following statement can be passed directly in Java:

byte B;int i=b; Long l=b; float f=b; Double d=b;

2) If the low-level type is char, converting to the advanced type (int) is converted to the corresponding ASCII value, for example

Char c= ' C '; int i=c;

System.out.println ("Output:" +i); output: output:99;

3) for Byte,short,char three types, they are lateral and therefore cannot be automatically converted to each other, and can be cast using the following coercion type.

Short i=99; Char c= (char) i; System.out.println ("Output:" +c); output: output:c;


C. Casting (enclose the target type in parentheses, before the variable)

When converting "large" data to "small" data, you can use forced type conversions. That is, you must use the following statement format: int n= (int) 3.14159/2; As you can imagine, this conversion is sure to cause a drop in overflow or precision.

Supplement (Simple to understand)

1) Package Transition type Conversion

In general, we declare a variable first, and then generate a corresponding wrapper class, you can use the wrapper class of various methods for the type conversion. For example:

① when you want to convert the float type to double type:

float f1=100.00f;

Float f1=new Float (F1);

Double D1=f1.doublevalue ();//f1.doublevalue () is a method of returning a double value type for the float class

② when you want to convert a double type to an int type:

Double d1=100.00;

Double D1=new double (D1);

int I1=d1.intvalue ();
Description of the method:
(1. In a simple type of variable to the corresponding wrapper class, the use of the wrapper class constructor (not only can this one, there are other, but this does not say)
That is: Boolean (boolean value), Character (char value), Integer (int value), long (Long value), float (float value), double (double Value

2. In each packaging class, the total tangible is xxvalue () method, to obtain its corresponding simple type data.
This method can also realize the conversion between different numerical variables, for example, for a double-precision real class, intvalue () can get its corresponding integer variable, and Doublevalue () can get its corresponding double-precision real variable.

2) conversion between strings and other types

Conversion of other types to strings

① the string conversion method of the Calling class: X.tostring ();

② Automatic conversion: x+ "";

③ method of using String: string.volueof (X);

string as a value, to other types of conversions

The ① is converted to the corresponding wrapper instance before the corresponding method is converted to another type.

For example, the character "32.1" converts the value of a double type to the format: New Float ("32.1"). Doublevalue (). can also be used: double.valueof ("32.1"). Doublevalue ()

② static Parsexxx method

String s = "1";

byte B = byte.parsebyte (s);

Short T = Short.parseshort (s);

int i = Integer.parseint (s);

Long L = Long.parselong (s);

Float f = float.parsefloat (s);

Double d = double.parsedouble (s);

③character getnumericvalue (char-ch) method

3) Conversion of date class to other data types

There is no direct correspondence between the integer and date classes, except that you can use the int to represent the year, month, day, time, minute, and second, thus establishing a correspondence between the two, in which you can use the three forms of the date class constructor:

①date (int year, int month, int Date): type int for years, months, and days

②date (int year, int month, int Date, int hrs, int min): int, month, day, time, minute

③date (int year, int month, int Date, int hrs, int min, int sec): type int for years, months, days, hours, minutes, seconds

There is an interesting correspondence between the long and the date classes, which is to represent a time as a number of milliseconds from 0:0 GMT, January 1, 1970, 0 seconds. For this correspondence, the date class also has its corresponding constructor: date (long date).

Gets the year, month, day, time, minute, second, and week of the date class you can use the date class's getyear (), GetMonth (), GetDate (), getHours (), getminutes (), getseconds (), GetDay ( ) method, you can also interpret it as converting the date class to int.

The GetTime () method of the date class can get the number of long integers that we said earlier, and as with the wrapper class, the date class has a ToString () method that can convert it to a string class.

Sometimes we want to get a specific format for date, for example 20020324, we can use the following methods, first introduced in the file,

Import Java.text.SimpleDateFormat;

Import java.util.*;

Java.util.Date Date = new Java.util.Date ();

If you want to get the YYYYMMDD format

SimpleDateFormat sy1=new SimpleDateFormat ("YyyyMMDD");

String Dateformat=sy1.format (date);

If you want to get a separate year, month, day

SimpleDateFormat sy=new SimpleDateFormat ("yyyy");

SimpleDateFormat sm=new SimpleDateFormat ("MM");

SimpleDateFormat sd=new SimpleDateFormat ("DD");

String Syear=sy.format (date);

String Smon=sm.format (date);

String Sday=sd.format (date);

Summary: Only Boolean does not participate in conversion of data types

6. Conforming data types-classes and interfaces

Concept: This vector of values can be referenced and set by a vector to conform to the data type.

7. Basic type variable and reference type variable.
A. Introduction: Basic data types fall into two main categories: basic data classes and composite data types. There are two types of variables: the base type and the reference type.
B. Concept:
1) Basic type: A variable that uses the basic data class definition is the base type.
2) Reference type: A variable defined with a composite data type is a reference type. The variable is a reference address to the memory space (in other languages, a pointer or memory address), pointing to
A value or a set of values represented by the in-memory depositary variable.

C. How to handle two types of variables
Basic type variable: The system allocates space directly to the variable, so it can be manipulated directly in the program.
(Eg:int a;//Allocated Space
A=3; Direct operation

Reference type variable: Just assign a reference space to the variable, the data space is not allocated and cannot be manipulated directly.
(Eg:mydata A;
a.day=14; Error because it just allocates a reference space and the data space is not assigned

D. Assignment of reference variables
Mydata A, B;//defines two reference spaces
A=new Mydata ();
B=a;//use of the same data space.


8. member variables and local variables

1). Concept:
Member variable: exists as a member of a class and exists directly in the class. Member variables for all classes can be referenced by this.
Local variable: exists as a member of a method or statement block, and exists in the parameter list and method definition of a method.


2). Difference:
A.. Member variables can be decorated with modifiers such as public,protect,private,static, while local variables cannot be controlled modifiers and static modifiers, and both can be defined as final.
Note: Local variables, defined in methods, can be used in methods, local variables in the for loop, and can only be exploited in a for loop.
B. member variables are stored in the heap, and local variables are stored on the stack. The scope of a local variable is limited to the method that defines it, and cannot be accessed outside of the method. The scope of a member variable is visible within the entire class and can be used by all member methods. If access permission is allowed, you can also use member variables outside of the class.

C. The life cycle of local variables is the same as the execution period of the method. When a method executes to a statement that defines a local variable, the local variable is created, and the local variable is destroyed when it executes to the last statement in the scope where it is located. A member variable of a class that, if it is an instance member variable, has the same lifetime as the object. The lifetime of a static member variable is the entire program's run-time.

D. The member variable has a default value, the default value for the base type is 0, and the default value for the composite type is null. (A final modification without static must be explicitly assigned), the local variable is not automatically assigned, so the local variable is defined first to assign the initial value before it can be used.

E. Local variables can have the same name as member variables, and when used, local variables have higher precedence.

Note: The difference between a member variable and a member static variable
Create multiple identical objects with multiple member variables, but with only one member static variable, this member static variable is applied by multiple objects.

9. Operators

10. Process Control Statements

1). Looping statements
A.

while (conditional judgment statement) {}
Only false when it jumps out of the loop.


B.

do{
}while (conditional judgment statement);
The code block is executed at least once, and only if it is false, it jumps out of the loop.

C.for statements
for (initial statement; Logical statement; Iteration statement) {
Statement or statement block

2. Branch statements
A.

if () {}
else{}


B.

if () {}
else if () {}
...
else{}

C.swich statements
Swich (CH) {

Case C1:
Statement Block 1;
Break

Case C2;
Statement Block 2;
Break
...

Default: statement block

/* Description:
The number in 1.swich must match the value after the case
Each case branch in a 2.swich statement can be a single statement, or it can have more than one statement.
3. When more than one case behaves in the same statement block, the pattern is as follows:
Case C1:
Case C2: statement block
Break

4. The default is not executed until the current face is executed, or the break statement is not used before the statement is popped.
5. Regardless of which branch is executed, the program flow executes sequentially until a break statement is encountered.

3. Circular jump Statements
(1) Break statement
Role:

A. Stopping the Swich program flow
B. Jump out of the loop

(2) Continue statement
Function: Skips the block of statements after continue and executes the next loop.

11. Arrays

Foreword: 1. The elements in the array are all of the same type.

2. The length of the array is determined at the time of creation and cannot be changed.

(If you want to change dynamically, you can use the various collections in the Java.util package)

1. How arrays are declared

(1) int s[]

(2) int[] s

(3) int[] S,m,n//DECLARE multiple variables

Note: The declaration method simply assigns an array variable a reference space that can reference the array. The data space is determined by the subsequent decision.

2. Creation and initialization of arrays

(1). Creating an array with new

Initialization method: Initialize directly one by one

(2) Direct initialization creates an array:

Int[] A={1,2,3,...,n};

3. Length of the array

Array name. length

4. Array of objects (arrays are not just primitive type arrays, they can also be object arrays)

Eg:

Point[] P=new point[2];

Int i=0;

while (I<2) {

P[i]=new Point (i,i+1);

i++;

}

5. Multidimensional arrays

A. Declaration of multidimensional Arrays:

(1) int a[][]

(2) int[][] A

B. Multidimensional array instantiation (note: When assigning a number to each location, hold the brackets in the order of 1.1 points to assign the value, do not mess)

(1) Allocate memory directly for each dimension and create an array of rules. Eg:int A[][]=new int[4][4];

(2) from the highest dimension, each dimension is allocated space, this way can construct irregular array.

Eg:int[][] A=new int[2][];

A[0]=new int[2]; A[1]=new Int[3];a[2]=new int[4];

Example: Use a two-dimensional array of int to express a matrix, create the array, and print out its elements.

6. Enhanced for Loop

A. Advanced for loop format: for (type name Variable name: Traversed collection (Collection) or array)

eg

Int[] arr = {1,2,3,4};

for (int i:arr)

{

System.out.out (i);

}

B. Legacy for loops and advanced for the difference between loops :

The advanced for Loop has a limitation and must have a traversed target

(Note: It is recommended that when iterating through an array, you still want to use the traditional for, because the classic for has a corner, there can be other actions, but not advanced)

7. Copying of arrays

Use the Java language to provide an array copy method in the Java.lang.System class.

The method is:

public static void Arraycopy (Object source,int srcindex,object dest, int destindex,int length)

Source: Array of sources

Srcindex: Where the source array begins copying

Dest: Destination Array

Destindex: The destination array begins to hold the location of the copied array

Length: Number of copied elements

Java language Basics

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.