Java基础方面陷阱

来源:互联网 发布:链路状态协议网络拓扑 编辑:程序博客网 时间:2024/06/06 03:54
1判断是否是奇数
publicstaticboolean isOdd(inti){
         return i % 2 != 0;  //return i % 2 ==1(如果是负数这就错了)
    }
    public static void main(String[] args) {
        for(int i = -10; i <= 10; i++) {
            System.out.println(isOdd(i));
        }
    }

2.比较2个浮点数
public static void main(String[] args) {
        System.out.println(2.0-1.1);    //0.8999999999999999
        System.out.println(new BigDecimal("2.0").subtract(new BigDecimal("1.1"))); //0.9
        System.out.printf("%.1f", 2.0-1.1);  //0.9(格式化)
    }


3.长整型后面要加L
public static void main(String[] args) {
        final long MICROS_PER_DAY = 24L * 60 * 60 * 1000 * 1000;   
        final long MILLIS_PER_DAY = 24L * 60 * 60 * 1000;     
        System.out.println(MICROS_PER_DAY/MILLIS_PER_DAY);  //1000,如果不加L就是5
    }

4.交换数据
public static void main(String[] args) {
        int x = 1984;
        int y = 2001;
        /*y=(x^= (y^= x))^ y;
        System.out.println("x= " + x + "; y= " + y); */
        x=x^y;
        y=x^y;
        x=x^y;
        System.out.println("x= " + x + "; y= " + y);
        
    }

5.char类型会自动转为int
public static void main(String[] args) {
        System.out.println("H" + "a");    //Ha
        System.out.println('H' + 'a');   // 169

    }
6.和字符串拼接
public static void main(String[] args) {
      String letters = "ABC";
      char[] numbers = {'1', '2', '3'};
      System.out.println(letters + " easy as "+numbers);  //ABC easy as [C@15db9742
      System.out.println(numbers);  //123
    }



7.转义字符
public static void main(String[] args) {
        // \u0022 是双引号的 Unicode转义字符
        System.out.println("a\u0022.length() +\u0022b".length());  //2
        System.out.println("a".length() +"b".length());             //2
    }

8.打印输出类名
public static void main(String[] args) {
          System.out.println(
                  MyClass.class.getName().
                      replaceAll("\\.","/") + ".class");  //不加\\就是这样(///////////.class )no8/MyClass.class
    }

9.随机数问题
 private static Random rnd = new Random();
    public static void main(String[] args) {
         StringBuffer word = null;
         switch(rnd.nextInt(3)) { //是0~2之间
             case 1:  word = new StringBuffer("P");break; //如果是'p'会转为int那就是他的容量了
             case 2:  word = new StringBuffer("G");break;
             default: word = new StringBuffer("M");
         }
         word.append('a');
         word.append('i');
         word.append('n');
         System.out.println(word);  //如果'p'这种形式答案就是ain ,所以要加""
    }

10.无情的增量操作
public static void main(String[] args) {
        int j = 0;
        for (int i = 0; i < 100; i++){
            j= j++;
        }
        System.out.println(j);   //0
    }

11.整数边界的问题
public static final int END = Integer.MAX_VALUE;
    public static final int START = END - 100;
    public static void main(String[] args) {
          int count = 0;
          for (int i = START; i <END; i++)   //如果是i<=END 那就进入死循环了,MAX_VALUE会变为负数
              count++;
          System.out.println(count);  //100
    }

12  计数器的问题
public static void main(String[] args) {
      int minutes = 0;
      for (int ms = 0; ms < 60*60*1000; ms++)
          if (ms % 60*1000 == 0)
              minutes++;
      System.out.println(minutes);   //
    }

13  优柔寡断的返回值
public static void main(String[] args) {
          System.out.println(decision());
    }
    
    public static boolean decision() {
         try {
             return true;    //会捕获这个true并不会终止程序
         } finally {
             return false;     //false
         }
     } 

14  你好,再见
public static void main(String[] args) {
        try {
            System.out.println("Hello world");
            System.exit(0);     //Hello world,后面代码不会执行(虚拟机关闭了)
        } finally {
            System.out.println("Goodbye world");
        }
    }

15  到底关闭了吗
public static void main(String[] args) {
        
    }
    public static void copy(String src, String dest) throws IOException {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(src);
            out = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int n;
            while ((n = in.read(buf)) > 0)
                out.write(buf, 0, n);
        } finally {
            if (in != null) {
                try {
                    in.close();   //这个可以也会抛异常
                } catch (Exception e) {
                    in=null;
                }
            }
            if (out != null){
                try {
                    out.close();
                } catch (Exception e) {
                    out=null;
                }
                
            }
        } 
    }

16  所有的动物都是平等的。
public static void main(String[] args){
        final String pig = "length: 10";
        final String dog = "length: " + pig.length();
        System.out. println("Animals are equal: "
        + pig == dog);   //false  (先执行+,比较字符串用equals)
    
    }

17
public static void main(String[] args){
        char x = 'X';
        int i = 0;
        System.out.println(true ? x : 0);  //X
        System.out.println(false ? i : x); //88
    
    }
( • 如果第二个和第三个操作数具有相同的类型,那么它就是条件表达式的类
型。换句话说,你可以通过绕过混合类型的计算来避免大麻烦。
• 如果一个操作数的类型是 T,T 表示 byte、short 或 char,而另一个操作
数是一个 int 类型的常量表达式,它的值是可以用类型 T 表示的,那么条
件表达式的类型就是 T。
• 否则,将对操作数类型运用二进制数字提升,而条件表达式的类型就是第
二个和第三个操作数被提升之后的类型。
)


18
/**
* Generated by the IBM IDL-to-Java compiler, version 1.0
* from F:\TestRoot\apps\a1\units\include\PolicyHome.idl  (\u是个转义开始)
* Wednesday, June 17, 1998 6:44:40 o’clock AM GMT+00:00
*/
public class Demo1{
public static void main(String[] args){
System.out.print("Hell");
System.out.println("o world");
}
}//编译失败
(
(\u)表示的是一个 Unicode 转义字符的开始。遗憾
的是,这些字符后面没有紧跟四个十六进制的数字,因此,这个 Unicode 转义字
符是病构的,而编译器则被要求拒绝该程序。Unicode 转义字符必须是良构的,
即使是出现在注释中也是如此
)

19
public class Demo1 {
        private Demo1(Object o) {
            System.out.println("Object");
            }
            private Demo1(double[] dArray) {
            System.out.println("double array");
            }
            public static void main(String[] args) {
            new Demo1(null);
            }
}
( 构造器
Confusing(Object)可以接受任何传递给 Confusing(double[ ])的参数,因此
Confusing(Object)相对缺乏精确性。(每一个 double 数组都是一个 Object,
但是每一个 Object 并不一定是一个 double 数组。)因此,最精确的构造器就是
Confusing(double[ ]),这也就解释了为什么程序会产生这样的输出。
, 要想用一个 null 参数来调用 Confusing(Object)构造器,你需要这样写代码:
new Confusing((Object)null)。这可以确保只有 Confusing(Object)是可应用
的。更一般地讲,要想强制要求编译器选择一个精确的重载版本,需要将实际的
参数转型为形式参数所声明的类型。
)

原创粉丝点击