源代码如下:
public class Demo { public static void main(String[] args) { //整数拓展 进制 二进制0b 十进制 八进制0 十六进制 0x int i1 = 0b10; int i2 = 10; int i3 = 010; int i4 = 0x10; System.out.println("0b10 = " + i1); System.out.println("10 = " + i2); System.out.println("010 = " + i3); System.out.println("0x10 = " + i4); } }
输出结果如下:
详见 https://www.cnblogs.com/gaizai/p/4233780.html
先看代码及运行结果
案例1:
public class Demo { public static void main(String[] args) { double d = 0.1d; float f = 0.1f; System.out.println(d); System.out.println(f); System.out.println(d == f); } }
输出结果:
咦?是不是很奇怪,同样都是0.1,为什么比较相等时是false?
原因就是 : double和float的数据类型不同 占用的位数不一样
接下来看案例2
public class Demo { public static void main(String[] args) { float f1 = 23322222222561561f; float f2 = 23322222222561561f + 1; System.out.println(f1 == f2); } }
很明显f2比f1大1,输出结果应该为false,事实上确实如此吗?我们来看输出结果
我的天,竟然和我们想象的不一样!!!这是怎么回事?
原来浮点数是有限的,刚刚的数字太大超过了范围,其次浮点数是离散的,有舍入误差,接近但是不等于
结论: 最好完全避免使用浮点数进行比较!!!
那么问题来了,当银行业务表示钱的数量的时候怎么办呢?
哈哈哈,不用慌,有一个类可以用来表示,是一个数学工具类 BigDecimal,以后学习的路上会讲解的
先看代码:
public class Demo { public static void main(String[] args) { char c1 = ‘a‘; char c2 = ‘中‘; System.out.println(c1); System.out.println((int)c1); System.out.println(c2); System.out.println((int)c2); } }
运行结果
这里用到了强制转换(以后会说)
所有的字符本质都是数字,这里会有一个编码的概念
Unicode,中文又称万国码、国际码、统一码、单一码,是计算机科学领域里的一项业界标准。它对世界上大部分的文字系统进行了整理、编码,使得电脑可以用更为简单的方式来呈现和处理文字。
\t: 制表符
\n: 换行符
...............
代码:
public class Demo { public static void main(String[] args) { String s1 = new String("Hello World"); String s2 = new String("Hello World"); System.out.println(s1 == s2); String s3 = "Hello World"; String s4 = "Hello World"; System.out.println(s3 == s4); } }
输出结果
为什么会出现这种情况呢?先留一个悬念,等到学习对象的时候,再来解释这个问题,嘿嘿嘿
在使用if条件比较时可以对代码进行精简,如下代码所示:
public class Demo { public static void main(String[] args) { boolean flag = true; //老手写法 if (flag){ System.out.println("Hello World"); } //新手写法 if (flag == true){ System.out.println("Hello World"); } } }
两种写法中if中的条件都表示当flag为true时输出Hello World 但是第一种显然比第二种要更加精简
原文:https://www.cnblogs.com/SunJunchen/p/14042231.html