3. 操作符
对象内部称之为引用,(C中的指针),使用时要小心引用.
class Tank{ int level; } public class Assignment { public static void main(String[] args) { Tank t1 = new Tank(); Tank t2 = new Tank(); t1.level = 9; t2.level = 47; System.out.println("1:t1.level:" + t1.level + ",t2.level :" + t2.level); //1:t1.level:9,t2.level :47 t1 = t2;// 都指向了同一个对象 System.out.println("2:t1.level:" + t1.level + ",t2.level :" + t2.level); //2:t1.level:47,t2.level :47 t1.level = 27; //两个引用指向的是同一块内存,所以都被改变 System.out.println("3:t1.level:" + t1.level + ",t2.level :" + t2.level); ////3:t1.level:27,t2.level :27 } }
基本 类型转化.具体原理是由各个基本类型的位数决定的.
//: operators/Casting.java public class Casting { public static void main(String[] args) { int i = 200; long lng = (long) i; lng = i; // 高类型得到低类型的值,不需要强转 i = lng; // 报错Type mismatch: cannot convert from long to int i = 'c'; //char 可以向上转为int,所以这语句正确,i = 99('c'的ASCII码值) } //出现这个问题的原因在于: //long 8个字节 -9223372036854775808 -> 9223372036854775807 //int 4个字节 -2147483648 -> 2147483648 //简单说就是long可以存下int,所以编译器不担心,但int有可能存不下long,编译器小心起见,需要程序员确认. }
+=,-=,*=,/=,&=,|=,^= 这些语句都是合法的
如何得到各种基本类型的最大值和最小值?
public class Exponents { public static void main(String[] args) { double maxDouble = Double.MAX_VALUE; float maxFloat = Float.MAX_VALUE; int maxInt = Integer.MAX_VALUE; int minInt = Integer.MIN_VALUE; // short s = Short.MAX_VALUE; // byte b = Byte.MAX_VALUE; // long l = Long.MAX_VALUE; // char c = Character.MAX_VALUE; //以上都成立 System.out.println("maxDouble = " + maxDouble +'\n' + "maxFloat = " + maxFloat); System.out.println("int的取值范围是:" + minInt + "-->" + maxInt); } /** * maxDouble = 1.7976931348623157E308 maxFloat = 3.4028235E38 * int的取值范围是:-2147483648-->2147483647 */ }
切记 i=0; i = i++; //i依然==0
public class exp { public static void main(String[] args) { int i = 0; while(i<1) { i = i++; //i = 0; (i++不起作用了) System.out.println(i); //无限输出0 } } }
if(x = y) //在java 中一般会报错:编译时异常,除非x,y都是boolean 值
public class exp { public static void main(String[] args) { int x=0; int y=0; if(x=y) {//编译错误: Type mismatch: cannot convert from int to boolean } boolean x2 = false; boolean y2 = true; if(x2 = y2) { //成功,并且表达式的值由y2,也就是右值决定. } } }
4. 控制执行流程
主要就是for,while,dowhile,有意思的大概也就java中的goto语句了.
java中不提供 goto 语句,但是保留 goto 关键字
break 和 continue 语句已经含有 goto 功能, 可以直接将goto 原有的lable 放在 break/continue 之后.
主要是用来控制多重循环.
public class LabeledFor { public static void main(String[] args) { int i = 0; outer: while (true) { inner: for (; i < 10; i++) { if (i == 2) { System.out.println("continue"); continue; } if (i == 3) { System.out.println("break"); i++; break; } if (i == 7) { System.out.println("continue outer"); i++; continue outer; } if (i == 8) { System.out.println("break outer"); break outer; } for (int k = 0; k < 5; k++) { if (k == 3) { System.out.println("continue inner"); continue inner; } } } } } } /* continue inner continue inner continue break continue inner continue inner continue inner continue outer break outer */