Java (operator, control flow statement, function)

Source: Internet
Author: User
Tags arithmetic operators bitwise bitwise operators case statement

Operator data type conversions:

Small data type--------> Big data type (automatic type conversion)

Big Data Types---------> Small data types (coercion type conversions)

To enforce the format of type conversions:

Small data type variable name = (small data type) Big data type

Note the details:

1. Any byte, short, char data type data is automatically converted to the int type data when the operation is calculated.
2. Two data of different data types at the time of operation, the result depends on the large data type.

classDemo2 { Public Static void Main(string[] args) {/*byte b= 11; A single byteShort s = B;//Assign the value stored in the B variable to the S variable. 2 bytesint i = s; I is 4 byteslong L = i; L is 8 bytes. System.out.println (l);int i = 128; 4 bytesbyte B = (byte) i; 1 bytesSystem.out.println (b); -128//If it is negative, then the highest level is definitely 1, and the maximum number of positive bits is 0. System.out.println (Integer.tobinarystring (-7)); Sun provides us with a function integer.tobinarystring () to view a data in the form of binary data. //11111001 (complement)any byte, short, char data type data is automatically converted to the data of type int when operation. byte B1 =1;byte b2 = 2;byte B3 = (byte) (B1+B2);System.out.println (b3);//3System.out.println (' a ' + 1);//98two data of different data types at the time of operation, the result depends on the large data typeint i =10;long L = +;i = (int) (I+L);System.out.println (i);        */            inti =Ten;//        byteb = i;//When an integer is not added to any identity, the default is data of type int.         //10 is a constant, the compiler can confirm the value of the constant at compile time, byte B = 10, at compile time        The //java compiler will check that 10 does not exceed the representation range of byte, so it is permissible to assign a value.         The //java compiler does not validate the value stored by the variable at compile time, and the value stored in the variable is allocated space in memory when it is run. System. out.println(b); }}
Arithmetic operators:

+ (positive, additive, connector) the role of the connector: let any data can be concatenated with the string. If the + sign is used for strings, then the + sign is a connector, not a function of addition.

Connector Note: Any type of data is concatenated with a string using a connector, and the result is a string type of data.

+ + (self-increment): self-increment is equivalent to the operand +1.

Pre-increment: + + is in front of the operand. For example: ++a;

Pre-increment: The first self-increment, after use.

After self-increment: First use, after self-increment.

--(self-subtraction): operand-1.

Pre-decrement:--precedes the operand. --Operation number

Pre-decrement: first self-subtraction, after use.

Post-decrement:--at the back of the operand. Operand--;

After self-reduction: first use, after the reduction.

Assignment operators:

= (Assignment operator)
+=
-=
*=
/=
%=

Comparison operator: The result of the comparison operator is to return a Boolean value.

! = (Not equal to)
> (greater than)
< (less than)
>= (greater than or equal)
<= (less than or equal)

= = When comparing data of two basic data types, the comparison is that the values stored by the two variables are consistent.
= = When comparing data for two reference-type variables, the memory addresses recorded by the two reference-type variables are compared consistently.

Logical operator: The function of a logical operator is to connect a Boolean expression.

Amp (with, and)
Rule: Only the left and right variables are true at the same time, then the result is true, otherwise false.

| (Or, OR)

Rule: As long as both sides of the Boolean expression has a side of true, then the result is true, only the two sides at the same time false, the result is false.

^ (XOR)

Law: As long as the Boolean expression on both sides of the result is inconsistent, then the result is true, if the left and right side of the Boolean expression consistent, then false.

! Non-

=================

&& (short circuit and \ Double with)

Short-circuit and single-and-sign with the same and different points:

The same point: the short circuit is the same as the result of the single and operation.

Different points: When using short-circuiting, if the Boolean expression on the left is false, then the Boolean expression on the right side of the operation is not used, thus improving the efficiency. When using single-match, even if the Boolean expression on the left is false, the Boolean expression on the right will be calculated. Only the Boolean expression on the left is false, and the efficiency of the double is higher than the single.

|| (short-circuit or \ Dual or)

Short circuit or the same point with a single or different point:

Same point: The result of the operation is consistent.
Differences: When using a short-circuit or, when found to the left of the Boolean expression is true, the right boolean expression is not calculated. The Boolean expression on the left is true, or the right-hand Boolean expression is found when using single or.

Bitwise operators: Bitwise operators are directly manipulated by bits.

amp; (with)
| Or
^ (XOR)
Rule: If the operand A is consecutive or the same operand is two times, the result is the operand a.

The bitwise operator may appear in the written question:

    1. Exchange the value of two variables, no third-party variables are allowed.
    2. Takes out a specified number of bits of a binary data. Requires reading the low 4 bits of the binary data
      00000000-00000000-00010100-01001101
      Amp 00000000-00000000-00000000-00001111
      --------------------------------------------------------------
      00000000-00000000-00000000-00001101
Shift operators:

<< (shift left)
Rule: When an operand is left-shifted, the result is equal to the operand multiplied by 2 N, and N is the number of left-shifted digits.

3<<1 = 3*2 (1) = 6;
3<<2 = 3*2 (2) = 12
3<<3 = 3*2 (3) = 24

>> (move right)

Rule: When an operand is doing a right-shift operation, it is actually equal to the number of the operand divided by 2 N, and N is the number of bits moved.

3>>1 = 3/2 (1) = 1
3>>2 = 3/2 (2) = 0

>>> (unsigned Right shift):

The difference between unsigned right shift and right shift: when the right shift operation is performed, if the operand is a positive number, the left vacant bit uses 0 to fill, and if the operand is a negative number, the left vacant bit uses 1 to fill. When using unsigned right shifts, the 0 complement is used uniformly, whether positive or negative.

Ternary operator (trinocular operator)

Format:
Boolean expression? Value 1: value 2;

The three-dimensional operators should pay attention to the details:
When using the ternary operator, be sure to use the result returned by the expression, or define a variable to receive the result returned by the expression.

Control Flow Statement Control Process statement (IF) judgment statement

Format 1: Suitable for use in one case.

if(判断的条件){    //符合条件执行的代码;        }

Format 2: Suitable for use in both cases.

if(判断条件){    //符合条件执行的代码}else{    //不符合条件执行的代码;}

Format two functions equal to ternary operator: Boolean expression? Value 1: value 2;

Format three: Suitable for use in a variety of situations.

if(判断条件1){    //符合条件1执行的代码}elseif(判断条件2){    //符合条件2执行的代码}elseif(判断条件3){    //符合条件3执行的代码}......else{    //都不符合上述 的条件执行的代码   }

The details of the IF statement should be noted:

  1. If only one statement needs to be executed after qualifying, you can omit the curly braces. However, it is not recommended to omit it because the structure is not clear.
  2. The IF statement can not add a semicolon after judging the condition, otherwise it will affect the effect of the execution.
Control the----of the flow statement switch selection judgment statement

The format of the switch statement:

switch(你的选择){        case 值1:        符合值1执行的代码        break;    case 值2:        2执行的代码        break;    case 值3:        3执行的代码        break;    case 值4:        4执行的代码        break;    ......    default:         你的选择都符合上述的选项时执行的代码;        break;}

Things to note about the switch statement:

  1. The switch statement uses a variable that can only be a byte, char, short, int, string data type, and the string data type is supported from jdk7.0.
  2. The data followed by the case must be a constant.
  3. Stop condition for switch:
    Once the switch statement matches one of the case statements, the statement code in the corresponding case is executed, and if you do not encounter the break keyword or the curly brace of the end Switch statement, the switch statement will no longer be judged. Execute all the code from the top down in the order of the Code. Until a break is encountered or the curly brace of the end Siwitch statement is reached.
  1. In a switch statement, regardless of the order of the Code, the case statement is always judged first, and then the default statement is executed without conformance.

The If--else if---else if statement is very similar to the switch statement:
The advantages of the switch statement: The structure of the switch statement is clear. Switch disadvantage: Using the switch operation is very troublesome if the condition of the judgment is an interval range.

classdemo2{ Public Static void Main(string[] args) {intoption =1;//define a variable to store your selection        Switch(option) { Case 1: System. out.println("Java"); Case 2: System. out.println("C #"); Case 3: System. out.println("JavaScript"); Case 4: System. out.println("Android");default: System. out.println("Your choice is wrong"); }/*String str = "World";switch (str) {Case "Hello":System.out.println ("Hello");Break ;Case "World":System.out.println ("World");Break ;        }        */}}
Loop statement----While loop statement

The format of the while loop statement:

while(循环的条件){    //循环语句;}

Things to keep in mind while looping statements:

  1. A while loop statement is typically the number of times a variable is controlled by its loop.
  2. The Loop body code of the WHILE loop statement if there is only one statement, you can omit the curly brace. But it is not recommended that you omit it.
  3. A while loop statement cannot be followed by a semicolon after the judgment condition, otherwise it will affect the effect of execution.
Control flow statements----do and loop statements

Format:

do{    //...}while(判断条件);

The difference between a while loop statement and a do-while loop statement:
While Loop statement is the first to judge after the execution of the loop statement, Do-while Loop statement is executed first, after judgment. It executes at least once, regardless of whether the condition is satisfied.

11---For loop statement of control flow statements

The format of the FOR Loop statement:

for(初始化语句;判断语句;循环后的语句){    //循环语句;}

Things to note for the FOR Loop statement:

  1. for (;;) This notation is a dead loop statement, which is equivalent to while (true);
  2. The initialization statement for a For Loop statement executes only once, only when the first loop is executed.
  3. The loop body statement for the FOR Loop statement has only one sentence, and you can omit the curly brace from writing. However, it is not recommended to omit.
class Demo13 {    publicstaticvoidmain(String[] args)     {        for(int05 ; i++){            for(int0//控制列数                 System.out.print("*");            }            //换行            System.out.println();        }    }}
Escape character: A special character uses "" to convert it to the output of a character, so the character using "" is called a transfer character.

The common escape characters are:

\b  Backspace (退格键)\t  Tab 制表符(制表符的作用就是为了让一列对齐) 一个tab一般等于四个空格。\n  换行\r  回车  把光标移动到一行的首位置上。

Note: If you need to wrap a file on a Windows system, you need to work with \ r \ n. If you need to line up on a different operating system, just \ n is required.

The Break keyword

Break scope: Can only be used in a switch or a loop statement.

Break Effect:

  1. The effect of break for a switch statement is to end a switch statement.
  2. The effect of break used in a looping statement is to end the current loop statement.
Continue keywords

Continue scope: Continue can only be used for loop statements.
The role of continue: Continue's role is to skip this cycle body content. Continue the next time.

Continue things to be aware of:

1. In one case, the continue cannot be followed by any other statements, because it is never executed.
2.continue can also be used with tags.

Function (method):

Function: Improve the reusability of function code.

The definition format of the function:

修饰符  返回值类型  函数名(形式参数..){    需要被封装的功能代码;    return 结果;}
publicstaticintadd(){    int a =2;    int b =3;    return a+b;}

Modifier: public static

return value type: Int. The return value type is the data type of the result returned after the function has finished running.

Note : Some functions are returned to the caller without a result, and then the return value type is void.

Function Name: add

Function Name: The function name to use if you need to call the function. Function names can be as long as they conform to the naming conventions of identifiers.

Naming conventions for function names: The first word is all lowercase, the first letter of the other word is capitalized, and the other lowercase.

Formal parameters: If a function is running and there is data to be determined by the caller, the formal parameter should be defined at this time.

Return: Returns a result to the caller.

Features of the function:

  1. Once the function is well defined, it needs to be called before it is executed. The main function is called by the JVM and does not need to be called manually.
  2. Once the function is defined, it needs to be called before it is executed.
  3. If a function does not return a value to the caller, the return value type must be represented by a void.
classDemo3 { Public Static void Main(string[] args) {//string result = Getgrade (189);        //system.out.println (result);        Print(7); }//Demand 2: Define a function to print a multiplication table without returning any data.      Public Static void  Print(intRow) { for(inti =1; i<= Row; i++) { for(intj =1; j<=i; j + +) {System. out.Print(i+"*"+j+"="+i*j+"\ t"); }//Line breakSystem. out.println(); }    }//Demand 1: Define a function to determine the rank of a fraction and return the rank of the score to the caller.      Public StaticStringGetgrade(intScore) {String grade ="";//Define a variable storage level        if(score>= -&&score<= -) {grade ="A Grade"; }Else if(score>= the&&score<= the) {grade ="B Grade"; }Else if(score>= -&&score<= -) {grade ="C-Level"; }Else if(score>= -&&score<= the) {grade ="D grade"; }Else if(score>=0&&score<= -) {grade ="E-Class"; }Else{grade ="Retake Grade"; }returnGrade//Return the rank to the caller}}

Note : If the return value type of a function is a specific data type, then the function must ensure that the return value is guaranteed in any case. (except that the return value type is void)

The function of the return keyword:

  1. Returns the data to the caller of the function.
  2. Once the function executes to the return keyword, the function ends immediately. (Can end a function)

Note : A function with a return value type of void can also appear with the return keyword, but there is no data behind the return keyword.

The difference between the break keyword and the return keyword:

The 1.break keyword is the end of a loop.
The 2.return keyword is the end of a function.

Overloading of functions: two or more than two functions of the same name appear in a class, which is called an overload of the function.

Function overloading: The same function name can have different functions to handle parameters of different numbers or different data types.

Requirements for function overloading:

1. Function names are identical.
2. The parameter list is inconsistent (the number of formal parameters or the corresponding data type is inconsistent).
3. The return value type of the function is irrelevant.

classDemo3 { Public Static void Main(string[] args) {//system.out.println ("Hello world!");        (//ADD1);        Add(1,2.0); }//These functions are doing addition operations.      Public Static Double Add(intAintb) {System. out.println("Sum of two parameters:"+ (a+b));return 3.14; }//Repeat definition     Public Static int Add(intADoubleb) {System. out.println("The sum of the double arguments:"+ (a+b));return  A; }/*Public static void Add (int a, int b, int c) {System.out.println ("Sum of three parameters:" + (A+b+c));    }Public static void Add (int a, int b, int c,int d) {System.out.println ("Sum of four parameters:" + (A+b+c+d));    }*/}

Java (operator, control flow statement, function)

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.