博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【01】Java面试----基础方面的陷阱
阅读量:1887 次
发布时间:2019-04-26

本文共 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

你可能感兴趣的文章
表单重复提交
查看>>
Filter
查看>>
微服务架构实施原理详解
查看>>
必须了解的mysql三大日志-binlog、redo log和undo log
查看>>
Uniform Grid Quadtree kd树 Bounding Volume Hierarchy R树 搜索
查看>>
局部敏感哈希Locality Sensitive Hashing归总
查看>>
图像检索中为什么仍用BOW和LSH
查看>>
图˙谱˙马尔可夫过程˙聚类结构----by林达华
查看>>
深度学习读书笔记之AE(自动编码AutoEncoder)
查看>>
深度学习读书笔记之RBM
查看>>
深度学习word2vec笔记之基础篇
查看>>
法国INRIA Data Sets & Images 数据集和图像库
查看>>
训练自己haar-like特征分类器并识别物体(1)
查看>>
Github系列之二:开源 一行代码实现多形式多动画的推送小红点WZLBadge(iOS)
查看>>
iOS容易造成循环引用的三种场景,就在你我身边!
查看>>
有一个会做饭的女友是一种怎样的体验?
查看>>
Storm入门之第一章
查看>>
java提高篇之数组(1):认识JAVA数组
查看>>
java提高篇之数组(2)
查看>>
浅析数据一致性
查看>>