第三章笔记《Thinkinng in JAVA》

第三章 操作符

3.3 优先级

+、-、*、/、()

3.4 赋值

方法调用中的别名问题

import static net.mindview.until.Print.*

class Letter {
    char c;
}
public class PassObject {
    static void f(Letter y) {
        y.c = 'z';
    }
    public static void main(String[] args) {
        Letter x = new Letter();
        x.c = 's';
        print("1:x.c:"+x.c);
        f(x);
        print("1:x.c:"+x.c); 
    }
}
/* Output:
1:x.c:s
2:x.c:z
*/

代码行y.c = 'z';改变的是f()之外的对象。

3.6 自动递增和递减

++a或--a,先执行运算再生成值
a++或a--,先生成值再执行运算

import static net.mindview.until.Print.*

public class AutoInc {
    public static void main (String[] args) {
        int i =1;
        print("i:" + i);
        print("++i:" + ++i);
        i = 1;
        print("i++:" + i++);
    }
}
/*
Output:
i:1
++i:2
i++:1
*/

3.7 关系操作符

、<、<=、>=、==、!=

//: operators/Equivalence.java

public class Equivalence {
  public static void main(String[] args) {
    Integer n1 = new Integer(47);
    Integer n2 = new Integer(47);
    System.out.println(n1 == n2);
    System.out.println(n1 != n2);
  }
} /* Output:
false
true
*///:~
  • 尽管内容相同,但是对象的引用不同,==和=!比较的是对象的引用。
//: operators/EqualsMethod.java

public class EqualsMethod {
  public static void main(String[] args) {
    Integer n1 = new Integer(47);
    Integer n2 = new Integer(47);
    System.out.println(n1.equals(n2));
  }
} /* Output:
true
*///:~
  • equals()
    比较的是2个对象的内容是否一致,限对象操作,默认行为是比较引用。不适用于基本类型
//: operators/EqualsMethod2.java
// Default equals() does not compare contents.

class Value {
  int i;
}

public class EqualsMethod2 {
  public static void main(String[] args) {
    Value v1 = new Value();
    Value v2 = new Value();
    v1.i = v2.i = 100;
    System.out.println(v1.equals(v2));
  }
} /* Output:
false
*///:~

3.8 逻辑运算符

“与”(&&)、“或”(||)、“非”(!)

3.8.1 短路

3.10 按位操作符

&、|、^、~

3.11 移位操作符

左移位操作符(<<)、右移位操作符(>>)、>>=、<<=、无符号右移(>>>=)

  • 左移在后面补0
  • 右移在前面补符号位相同的
  • 无符号右移在前面补0

3.15 类型转换操作符

JAVA 允许我们把任何基本数据类型转换成别的数据类型,但布尔型除外。

3.16 JAVA没有sizeof

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容