【01】Java面试----基础方面的陷阱
发布日期:2021-06-29 15:42:18 浏览次数:2 分类:技术文章

本文共 2103 字,大约阅读时间需要 7 分钟。

什么是陷阱

简洁的定义

陷阱,是指那些能够正常编译,但是在执行时却产生事与愿违的,有时候甚至是灾难性后果的程序代码。
广义的定义

任何可能导致程序员把大量的时间浪费在开发工具的使用上而不是最终软件的进展上的语言特性、API或系统,都可以称呼为陷阱。

NO.1  找奇数

解析:当输入负数时,结果输出不正确。

正确:

public class OddTest {	public static boolean isOdd(int i){ 		 return i % 2 != 0; 	}	public static void main(String[] args) {		for(int i = -10; i <= 10; i++) {			System.out.println(isOdd(i));		}	}}

NO.2  浮点数相减

解析:解析结果为0.8999999999999999

正确:

public class DoubleMinus {	public static void main(String[] args) {		System.out.println(new BigDecimal("2.0").subtract(new BigDecimal("1.1")));		System.out.printf("%.1f", 2.0-1.1);			}}

NO.3  长整除

解析:输出结果为5,由于int的范围

正确:

public class LongDivision {	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); 	}}

NO.4  互换内容

解析:x= 0; y= 1984

正确:

public class Swap {	public static void main(String[] args) {		int x = 1984; 		int y = 2001; 		y=(x^= (y^= x))^ y; 		System.out.println("x= " + x + "; y= " + y); 	}}

NO.5  字符串和字符

解析:Ha

169

NO.6  字符数组

解析:CharArray.java

正确:

public class CharArray {	public static void main(String[] args) {	  String letters = "ABC"; 	  char[] numbers = {'1', '2', '3'}; 	  System.out.print(letters + " easy as "); 	  System.out.print(numbers);	}}

NO.7  随机数的问题

解析:ain

正确:

public class RandomTest {   private static Random rnd = new Random(); 	public static void main(String[] args) {	     StringBuffer word = null; 	     switch(rnd.nextInt(3)) { 	         case 1:  word = new StringBuffer("P");break; 	         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); 	}}

NO.8  无情的增量操作

解析:0

正确:

public class ForTest {	public static void main(String[] args) {        int j = 0;         for (int i = 0; i < 100; i++){           j = ++j;         }        System.out.println(j); 	}}

NO.9  整数边界的问题

解析:死循环,超出了int的范围

NO.10  计数器的问题

解析:60000

正确:

NO.11  优柔寡断的返回值

解析:false

NO.12  你好,再见

解析:Hello world

转载地址:https://codingchaozhang.blog.csdn.net/article/details/80961017 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:排序算法整合
下一篇:Windows平台下kafka环境的搭建

发表评论

最新留言

不错!
[***.144.177.141]2024年04月29日 06时38分10秒