Home Page > Learning the Java Language > Language Basics > Variables

Home Page > Learning the Java Language > Language Basics > Operators, Expressions, Statements and Blocks, Control Flow Statements

kitt posted @ 2014年1月09日 17:33 in Java , 1258 阅读

简单总结语言基础 --> 操作符, 表达式, 语句和块, 控制流语句

 

Operators(操作符)

 

可以有1或2或3个operands操作数. 优先级从高到低

 

相同优先级时二元操作符从左向右估值,只有赋值操作符从右向左估值。>>>是unsigned right shift operator无符号右移. 

 

Assignment, Arithmetic and Unary Operators(赋值, 算术操作符和一元操作符)

 

The Simple Assignment Operator(简单的赋值操作符)

最常用了, int cadence = 0; 也可用于object来赋一个object reference对象的引用.

 

The Arithmetic Operators(算术操作符)

+  -  *  /(整除 7/2=3)  %  +=    +可用于连接字符串

 

The Unary Operators(一元操作符)

+正号  -负号  ++increment   - -decrement   !布尔取反

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. Prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value.

 

class PrePostDemo {

    public static void main(String[] args){

        int i = 3;

        i++;

        // prints 4

        System.out.println(i);

        ++i;    

        // prints 5

        System.out.println(i);

        // prints 6

        System.out.println(++i);

        // prints 6

        System.out.println(i++);

        // prints 7

        System.out.println(i);

    }

}

 

Equality, Relational, and Conditional Operators(相等,关系,条件操作符)

 

The Equality and Relational Operators(相等,关系操作符)

 

==  !=  >  >=  <  <=

 

The Conditional Operators(条件操作符)

 

&&  || 有必要时才对第二个操作数估值 "short-circuiting" behavior

Ternary operator三元操作符 ? :   shorthand for if-then-else 可以使代码更加紧凑

 

The Type Comparison Operator instanceof(类型比较操作符)

把一个object跟某一个类型做比较. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface. null is not an instance of anything. null不是任何类的实例.

 

class InstanceofDemo {

    public static void main(String[] args) {

 

        Parent obj1 = new Parent();

        Parent obj2 = new Child();

 

        System.out.println("obj1 instanceof Parent: " + (obj1 instanceof Parent));

        System.out.println("obj1 instanceof Child: " + (obj1 instanceof Child));

        System.out.println("obj1 instanceof MyInterface: " + (obj1 instanceof MyInterface));

        System.out.println("obj2 instanceof Parent: " + (obj2 instanceof Parent));

        System.out.println("obj2 instanceof Child: " + (obj2 instanceof Child));

        System.out.println("obj2 instanceof MyInterface: " + (obj2 instanceof MyInterface));

    }

}

 

class Parent {}

class Child extends Parent implements MyInterface {}

interface MyInterface {}

 

Output:

obj1 instanceof Parent: true

obj1 instanceof Child: false

obj1 instanceof MyInterface: false

obj2 instanceof Parent: true

obj2 instanceof Child: true

obj2 instanceof MyInterface: true

 

Bitwise and Bit Shift Operators(按位,移位操作符)

 

按位和移位操作符用于整型。不常用,知道有就行了。The unary一元 bitwise按位 complement operator补操作符 "~" inverts a bit pattern,可用于所有整型,For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111".

 

~一元按位补操作符, <<有符号左移操作符, >>有符号右移操作符, >>>无符号右移操作符, ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension. 

bitwise AND & 按位与

exclusive OR ^ 按位加,异或

inclusive OR | 按位或

 

class BitDemo {

    public static void main(String[] args) {

        int bitmask = 0x000F;

        int val = 0x2222;

        // prints "2"

        System.out.println(val & bitmask);

    }

}

 

Expressions, Statements, and Blocks(表达式, 语句, 块)

 

表达式由变量, 操作符, 调用方法组成. 以下黑体为表达式

 

int cadence = 0;

anArray[0] = 100;

System.out.println("Element 1 at index 0: " + anArray[0]);

 

int result = 1 + 2; // result is now 3

if (value1 == value2

    System.out.println("value1 == value2”);

 

Expression cadence = 0 returns an int because the assignment operator returns a value of the same data type as its left-hand operand. 

 

表达式加分号为语句statement. 表达式语句例子:

// assignment statement

aValue = 8933.234;

// increment statement

aValue++;

// method invocation statement

System.out.println("Hello World!");

// object creation statement

Bicycle myBike = new Bicycle();

 

还有两种语句declaration statements声明语句, control flow statements控制流语句,声明语句如double aValue = 8933.234;

 

块包含零个或多个语句,在{}中,能放单个语句的地方就能放块. 

 

Control Flow Statements 控制流语句

 

if-then语句

 

void applyBrakes() {

    // same as above, but without braces 

    if (isMoving)

        currentSpeed--;

}

then跟一个语句或一个块,是否省略{}看个人, 省略则代码更脆弱了, 比如再往then里加一个语句, 则需要改成块语句, 有时候容易忘了加{}

 

if-then-else语句

 

void applyBrakes() {

    if (isMoving) {

        currentSpeed--;

    } else {

        System.err.println("The bicycle has already stopped!");

    } 

}

 

switch语句

 

可用于byte, short, char, int, enumerated types枚举类型, String, Character, Byte, Short Integer等. 

 

public class SwitchDemo {

    public static void main(String[] args) {

 

        int month = 8;

        String monthString;

        switch (month) {

            case 1:  monthString = "January";

                     break;

            case 2:  monthString = "February";

                     break;

            case 3:  monthString = "March";

                     break;

            case 4:  monthString = "April";

                     break;

            case 5:  monthString = "May";

                     break;

            case 6:  monthString = "June";

                     break;

            case 7:  monthString = "July";

                     break;

            case 8:  monthString = "August";

                     break;

            case 9:  monthString = "September";

                     break;

            case 10: monthString = "October";

                     break;

            case 11: monthString = "November";

                     break;

            case 12: monthString = "December";

                     break;

            default: monthString = "Invalid month";

                     break;

        }

        System.out.println(monthString);

    }

}

 

A statement in the switch block can be labeled with one or more case or default labels. The switch statement evaluates its expression, then executes all statements that follow the matching case label. 

 

用if-then-else还是switch取决于代码可读性和语句测试的表达式. Switch测试的表达式只能是单个值,if-then-else语句可以测试一个范围. 每个break语句都可以结束switch块. 没有break语句的话叫switch的fall through, 例如:

public class SwitchDemoFallThrough {

 

    public static void main(String[] args) {

        java.util.ArrayList<String> futureMonths =

            new java.util.ArrayList<String>();

 

        int month = 8;

 

        switch (month) {

            case 1:  futureMonths.add("January");

            case 2:  futureMonths.add("February");

            case 3:  futureMonths.add("March");

            case 4:  futureMonths.add("April");

            case 5:  futureMonths.add("May");

            case 6:  futureMonths.add("June");

            case 7:  futureMonths.add("July");

            case 8:  futureMonths.add("August");

            case 9:  futureMonths.add("September");

            case 10: futureMonths.add("October");

            case 11: futureMonths.add("November");

            case 12: futureMonths.add("December");

                     break;

            default: break;

        }

 

        if (futureMonths.isEmpty()) {

            System.out.println("Invalid month number");

        } else {

            for (String monthName : futureMonths) {

               System.out.println(monthName);

            }

        }

    }

}

 

Output:

August

September

October

November

December

 

一个语句可有多个case标签:

 

class SwitchDemo2 {

    public static void main(String[] args) {

 

        int month = 2;

        int year = 2000;

        int numDays = 0;

 

        switch (month) {

            case 1: case 3: case 5:

            case 7: case 8: case 10:

            case 12:

                numDays = 31;

                break;

            case 4: case 6:

            case 9: case 11:

                numDays = 30;

                break;

            case 2:

                if (((year % 4 == 0) && 

                     !(year % 100 == 0))

                     || (year % 400 == 0))

                    numDays = 29;

                else

                    numDays = 28;

                break;

            default:

                System.out.println("Invalid month.");

                break;

        }

        System.out.println("Number of Days = "

                           + numDays);

    }

}

 

Output:

Number of Days = 29

 

Using Strings in switch Statements(在switch语句中使用字符串)

 

switch()中的东西与case后面的值可以认为用String.equals方法比较的.

 

switch (month.toLowerCase()) {

    case "january":

        monthNumber = 1;

        break;

    case "february":

        monthNumber = 2;

        break;

    case "march":

        monthNumber = 3;

        break;

    case "april":

        monthNumber = 4;

        break;

    case "may":

        monthNumber = 5;

        break;

    case "june":

        monthNumber = 6;

        break;

    case "july":

        monthNumber = 7;

        break;

    case "august":

        monthNumber = 8;

        break;

    case "september":

        monthNumber = 9;

        break;

    case "october":

        monthNumber = 10;

        break;

    case "november":

        monthNumber = 11;

        break;

    case "december":

        monthNumber = 12;

        break;

    default: 

        monthNumber = 0;

        break;

}

 

The while and do-while Statements(while和do-while语句)

 

无限循环 while(true) { // your code }

 

do {

    statements(s)

} while (expression)

 

do-while中的语句至少执行一次.

 

The for Statement (for语句)

 

class ForDemo {

    public static void main(String[] args){

         for(int i=1; i<11; i++){

              System.out.println("Count is: " + i);

         }

    }

}

 

Output:

Count is: 1

Count is: 2

Count is: 3

Count is: 4

Count is: 5

Count is: 6

Count is: 7

Count is: 8

Count is: 9

Count is: 10

 

无限循环 for( ; ; ) {// your code }

 

for的另一种形式for iteration through Collections and arrays :

 

class EnhancedForDemo {

    public static void main(String[] args){

         int[] numbers = 

             {1,2,3,4,5,6,7,8,9,10};

         for (int item : numbers) {

             System.out.println("Count is: " + item);

         }

    }

}

 

相同输出. 推荐使用这种for形式.

 

Branching Statements (分支语句)

 

The break Statement (break语句)

 

有两种形式: labeled和unlabeled. unlabeled break用于终止最内层的switch, for, while, do-while循环. labeled break用于终止外层的语句. 控制流转到紧接着的labeled语句. 比如:

 

class BreakWithLabelDemo {

    public static void main(String[] args) {

 

        int[][] arrayOfInts = { 

            { 32, 87, 3, 589 },

            { 12, 1076, 2000, 8 },

            { 622, 127, 77, 955 }

        };

        int searchfor = 12;

 

        int i;

        int j = 0;

        boolean foundIt = false;

 

    search:

        for (i = 0; i < arrayOfInts.length; i++) {

            for (j = 0; j < arrayOfInts[i].length;

                 j++) {

                if (arrayOfInts[i][j] == searchfor) {

                    foundIt = true;

                    break search;

                }

            }

        }

 

        if (foundIt) {

            System.out.println("Found " + searchfor + " at " + i + ", " + j);

        } else {

            System.out.println(searchfor + " not in the array");

        }

    }

}

 

Output:

Found 12 at 1, 0

 

Continue语句:

 

Unlabeled continue跳到最内层for, while, do-while循环体末尾并对控制循环的布尔表达式估值. 

 

class ContinueDemo {

    public static void main(String[] args) {

 

        String searchMe = "peter piper picked a " + "peck of pickled peppers";

        int max = searchMe.length();

        int numPs = 0;

 

        for (int i = 0; i < max; i++) {

            // interested only in p's

            if (searchMe.charAt(i) != 'p')

                continue;

 

            // process p's

            numPs++;

        }

        System.out.println("Found " + numPs + " p's in the string.");

    }

}

 

Output:

Found 9 p's in the string.

 

Labeled continue语句跳过一次标有label的外层循环:

 

class ContinueWithLabelDemo {

    public static void main(String[] args) {

 

        String searchMe = "Look for a substring in me";

        String substring = "sub";

        boolean foundIt = false;

 

        int max = searchMe.length() - 

                  substring.length();

 

    test:

        for (int i = 0; i <= max; i++) {

            int n = substring.length();

            int j = i;

            int k = 0;

            while (n-- != 0) {

                if (searchMe.charAt(j++) != substring.charAt(k++)) {

                    continue test;

                }

            }

            foundIt = true;

                break test;

        }

        System.out.println(foundIt ? "Found it" : "Didn't find it");

    }

}

 

Output:

Found it

 

return语句

从当前方法跳出,控制流回到调用该方法的地方. 也有两种:return count; 和 return;

Avatar_small
AP 10th Geography Qu 说:
2022年9月18日 11:10

Geography is an important subject in Class 10t. However, considerable ambiguities persist in its exact position within academia. AP 10th Geography Question Paper As an inclusive discipline, the content of geography is derived from various subjects in the sciences, social sciences and humanities. This is equally true about the geography syllabus in schools as well.Telugu Medium, English Medium & Urdu Medium Students of the State Board can download the AP 10th Geography Model Paper 2023 Pdf with answers for all exam formats conducted by BSEAP for Part-A, Part-B, Part-C, and Part-D exams of SA-1, SA-2, FA-1, FA-2, FA-3, FA-4 along with Assignments which were designed by subject experts of leading educational institutes.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter