操作符:

5.操作符  
馬克- to-win:馬克 java社區(qū):防盜版實(shí)名手機(jī)尾號(hào): 73203。
public class Test{
  public static void main(String[] args){
    int i, k;
    i = 10;
/*下面一句話的意義是:假如i小于零,k就等于-i,否則k就等于i*/
    k = i < 0 ? -i : i; // get absolute value of i
    System.out.print("Absolute value of ");
    System.out.println(i + " is " + k);

    i = -10;
    k = i < 0 ? -i : i; // get absolute value of i
    System.out.print("Absolute value of ");
    System.out.println(i + " is " + k);
  }
}

result is:
Absolute value of 10 is 10
Absolute value of -10 is 10

5.1 算術(shù)操作符


運(yùn)算符

使用

描述

+

op1 + op2

op1 加上op2

-

op1 - op2

op1 減去op2

*

op1 * op2

op1乘以op2

/

op1 / op2

op1 除以op2

%

op1 % op2

op1 除以op2的余數(shù)

 

  這里注意,當(dāng)一個(gè)整數(shù)和一個(gè)浮點(diǎn)數(shù)執(zhí)行操作的時(shí)候,結(jié)果為浮點(diǎn)型。整型數(shù)是在操作之前轉(zhuǎn)換為一個(gè)浮點(diǎn)型數(shù)的。

   




5.2 自增自減操作符

下面的表格總結(jié)自增/自減運(yùn)算符:

運(yùn)算符

用法

描述

++

a++

自增1;自增之前計(jì)算op的數(shù)值的。

++

++b

自增1;自增之后計(jì)算op的數(shù)值的。

--

a--

自減1;自減之前計(jì)算op的數(shù)值的。

--

--b

自減1;自減之后計(jì)算op的數(shù)值的。

5.3 Bitwise Operators(位運(yùn)算符)
~
&
|
>>
<<

int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary
int c = a | b;//c=0111
int d = a & b;//d=0010


public class Test {


      public static void main(String args[])
      {
          int k = 3; // 0 + 2 + 1 or 0011 in binary
          int b = 6; // 4 + 2 + 0 or 0110 in binary
          int c = k | b;//c=0111
          int d = k & b;//d=0010
          System.out.println("c @馬克-to-win is "+c);
          System.out.println("d is "+d);
      }
}


結(jié)果是:
c @馬克-to-win is 7
d is 2




5.4 關(guān)系運(yùn)算符

>,>=,<,<=,==,!=

5.5 邏輯運(yùn)算符

  如下表所示;

運(yùn)算符

用法

什么情況返回true

&&

o1 && o2

Short-circuit(短路) AND, o1 和 o2都是true,有條件地計(jì)算o2

||

o1 || o2

o1 或者 o2是true,有條件地計(jì)算o2

!

! o

o為false

&

o1 & o2

o1 和 o2都是true,總是計(jì)算o1和o2

|

o1 | o2

o1 或者 o2是true,總是計(jì)算o1和o2

 


public class Ternary{
  static boolean doThing()
  {
    System.out.println("in doThing");
    return true;
  }
  public static void main(String[] args){
    if((2>3)& doThing()) {
        System.out.println("ok");
    }

  }
}

result is:

in doThing

 

 

public class Ternary{
  static boolean doThing()
  {
    System.out.println("in doThing");
    return true;
  }
  public static void main(String[] args){
    if((2>3)&& doThing()) {
        System.out.println("ok");
    }

  }
}

result is:

什么結(jié)果也沒(méi)有。

 

5.6 賦值運(yùn)算符

  

i = i + 2;

可以這樣簡(jiǎn)化:

i += 2;

上面的兩行是等價(jià)的。




6.控制流程 

6.1 if-else statement




public class Test{
  public static void main(String[] args){
    int num = 5;
    int mod = num %2;
    if (num ==0)
        System.out.println(num + "是零");
    else if (mod != 0)
        System.out.println(num + "是一個(gè)奇數(shù)");
    else
        System.out.println(num + "是一個(gè)偶數(shù)");
  }
}

result is:

5是一個(gè)奇數(shù)