class Number { int i; } public class Assignment { public static void main(String[] args) { Number n1 = new Number(); Number n2 = new Number(); n1.i = 9; n2.i = 47; System.out.println("1: n1.i: " + n1.i + ", n2.i: " + n2.i); n1 = n2; System.out.println("2: n1.i: " + n1.i + ", n2.i: " + n2.i); n1.i = 27; System.out.println("3: n1.i: " + n1.i + ", n2.i: " + n2.i); } }
输出结果为
1: n1.i: 9, n2.i: 47 2: n1.i: 47, n2.i: 47 3: n1.i: 27, n2.i: 27
这种现象成为别名现象
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 = 'a'; System.out.println("1: x.c: " + x.c); f(x); System.out.println("2: x.c: " + x.c); } }
输出结果为
1: x.c: a 2: x.c: z
f()方法表面上似乎要在方法的作用域内制作自己的自变量Letter y的一个副本。
但同样地,实际传递的是一个句柄。
2.对象的内容相同,句柄却是不同的,而==和!=比较的正好就是对象句柄。
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); } }
结果是
true false
要创建自己的对象类,如果要比较的话,需要自己先实现equal方法才能比较,否则比较的还是句柄。
3.三元运算符
布尔表达式 ? 值0:值1
4.字面值
class Literals { char c = 0xffff; // max char hex value byte b = 0x7f; // max byte hex value short s = 0x7fff; // max short hex value int i1 = 0x2f; // Hexadecimal (lowercase) int i2 = 0X2F; // Hexadecimal (uppercase) int i3 = 0177; // Octal (leading zero) // Hex and Oct also work with long. long n1 = 200L; // long suffix long n2 = 200l; // long suffix long n3 = 200; //! long l6(200); // not allowed float f1 = 1; float f2 = 1F; // float suffix float f3 = 1f; // float suffix 74 float f4 = 1e-45f; // 10 to the power float f5 = 1e+9f; // float suffix double d1 = 1d; // double suffix double d2 = 1D; // double suffix double d3 = 47e47d; // 10 to the power } ///:~ /** 十六进制(Base 16)——它适用于所有整数数据类型——用一个前置的0x或0X指示。并在后面跟随采用大 写或小写形式的0-9以及a-f。若试图将一个变量初始化成超出自身能力的一个值(无论这个值的数值形式 如何),编译器就会向我们报告一条出错消息。注意在上述代码中,最大的十六进制值只会在char,byte以 及short身上出现。若超出这一限制,编译器会将值自动变成一个int,并告诉我们需要对这一次赋值进行 “缩小造型”。这样一来,我们就可清楚获知自己已超载了边界。 八进制(Base 8)是用数字中的一个前置0以及0-7的数位指示的。在C,C++或者Java中,对二进制数字 没有相应的“字面”表示方法。 字面值后的尾随字符标志着它的类型。若为大写或小写的L,代表long;大写或小写的F,代表float;大写 或小写的D,则代表double。 指数总是采用一种我们认为很不直观的记号方法:1.39e-47f。在科学与工程学领域,“e”代表自然对数的 基数,约等于2.718(Java一种更精确的double值采用Math.E的形式)。它在象“1.39×e的-47次方”这 样的指数表达式中使用,意味着“1.39×2.718的-47次方”。然而,自FORTRAN语言发明后,人们自然而然 地觉得e代表“10多少次幂”。这种做法显得颇为古怪,因为FORTRAN最初面向的是科学与工程设计领域。 理所当然,它的设计者应对这样的混淆概念持谨慎态度(注释①)。但不管怎样,这种特别的表达方法在 C,C++以及现在的Java中顽固地保留下来了。所以倘若您习惯将e作为自然对数的基数使用,那么在Java 中看到象“1.39e-47f”这样的表达式时,请转换您的思维,从程序设计的角度思考它;它真正的含义是 “1.39×10的-47次方”。 */