ImprovePrograming.......

近段时间在学习秦小波的《编写高质量代码》,写的一些东西对自己还是很有用的,大家也可以看看,了解一下。

package com.wangbiao.first;

public class TestFirst {

	// i其实是1,后面的是一个字母l,在编码过程中,“l”和“o”,尽量不要和数字搭配用,和容易造成混淆
	public static void test_first() {
		long i = 1L;// 长整型数据,务必用大写L,而如果是字母“o”,则加上注释说明
		System.out.println("i的值变成两倍" + (i + i));
	}

	// s是90,而str是90.0,所有输出为false.
	// 三目运算符的两个操作数类型不一样时,如果可以转换,则会转换,否则都返回Object类型
	public static void test_second() {
		int a = 80;
		String s = String.valueOf(a < 100 ? 90 : 100);
		String str = String.valueOf(a < 100 ? 90 : 100.0);
		System.out.println(s + "---" + str);
		System.out.println(s.equals(str));
	}

	// 结果是每次输出都是0,原因是在java中,temp++的原理是:
	// JVM将temp的值保存到临时变量区里面
	// temp的值加1
	// 将临时变量区里面的值返回,所以temp就是0
	public static void test_third() {
		int temp = 0;
		for (int i = 0; i < 10; i++) {
			// temp++;//这样的话,就会输出1~10
			// temp=temp+1;//这样的话,就会输出1~10
			// temp+=1;//这样的话,就会输出1~10

			temp = temp++;// 但是在C++里面,temp=temp++和temp++的效果是一样的。
			System.out.println(temp);
		}
		System.out.println(temp);
	}

	// instanceof用于对象的判断
	public static void test_four(){
		//boolean a='A' instanceof Character;//编译通不过,instanceof用于对象的判断
		boolean a="string" instanceof String;
		boolean b=new Object() instanceof String;
		boolean c=new String() instanceof Object;	
		boolean d=null instanceof Object;//null是万有类型,也可以说没有类型
		boolean e=(String)null instanceof String;//null是万有类型,也可以说没有类型	
		//boolean f=new Date() instanceof String;//编译通不过 Date与String没有继承关系
		System.out.println(a+"-"+b+"-"+c+"-"+d+"-"+e);
		
	}

    //边界问题,很经典
    public static void test_five(){
    	final int LIMIT=2000;
    	int count=1000;
    	int buy = 2147483647;//int最大范围
    	//看上去,这样判断没有什么问题,如果买的商品数目+1000小于2000的话,则才能购买,但是如果buy的值过大,加上1000后,超过了int的最大范围,
    	//则(buy+1000)称为了负数,如下面的例子为-2147482649。-2147482649也是小于2000的,所以购买成功。
    /*	if((buy+1000)<2000){
    		System.out.println("购买成功!"+(buy+1000));
    	}else{
    		System.out.println("购买失败!");
    	}*/
    	//正确的做法
    	if((buy+1000)>0 && (buy+1000)<2000){
    		System.out.println("购买成功!"+(buy+1000));
    	}else{
    		System.out.println("购买失败!");
    	}
    }
    
    //包装类型的大小比较
    //Integer的大小比较是intValue()的返回值比较,而其他包装类的大小比较是对应的value()值,如floatValue(),doubleValue()等
    public static void test_sex(){
    	Integer a=new Integer(100);
    	Integer b=new Integer(100);
    	System.out.println(a==b);
    	System.out.println(a>b);//比较的是intValue()的返回值,等效于a.intValue()>b.intValue()
    	System.out.println(a<b);
    }
    
	public static void main(String[] args) {
		// test_first();
		// test_second();
		//test_third();
		//test_four();
		//test_five();
		test_sex();
	}

}

你可能感兴趣的:(java)