Java(數據類型)基礎面試
1 String s1 = "Java";
String s2 = "Java";
String s3 = "Ja" + "va";
String ss1 = "Ja";
String ss2 = "va";
String s4 = ss1+ss2;
System.out.println(s1==s2);
System.out.println(s1==s3);
System.out.println(s1==s4);
求輸出結果,並說明為什麽?
true true false
原因:java中String對常亮具有緩存,並且對常量之間的“+”操作與常量等同。然變量之間的“+”操作是生成新的對象。
2 double a = 0.0;
int b = 0;
double a1 = a/a,a2=a/a;
System.out.println(a1==a2);
System.out.println(6.2/a==129.3/a);
System.out.println(-8/a);
System.out.println(-8/b);
輸出是什麽,為什麽?
false a1=NaN a2=NaN 0/0.0 = NaN 且NaN與NaN不相等
true 6.2/a = Infinity=129.3/a (正數/0.0= Infinity)
-Infinity (負數/0.0= -Infinity)
java.lang.ArithmeticException
3 byte b = 5;
(1)b = b + 5;
(2)b += 5;
(1)和(2)有什麽區別?
(1)報錯,類型不一致
(2)不報錯,b=10
4 Integer e = 100,f = 100;
System.out.println(e==f);
Integer g = 200,h = 200;
System.out.println(g==h);
Integer i = new Integer(100);
Integer j = new Integer(100);
System.out.println(i==j);
System.out.println(i.equals (j));
問輸出結果,說明為什麽。
true
false
false (內存比較)
true (值比較)
Integer 在(-128,127)範圍內是,能夠直接翻譯為 Integer a = Integer.valueOf(i); 自動拆箱操作
JDK中valueOf的源碼如下:
1 public static Integer valueOf(int i) { 2 assert IntegerCache.high >= 127; 3 if (i >= IntegerCache.low && i <= IntegerCache.high) 4 return IntegerCache.cache[i + (-IntegerCache.low)]; 5 return new Integer(i); 6 }
因此兩個都是非new出來的Integer,如果數在-128到127之間,則是true,否則為false (緩存操作)
int和integer(無論new否)比,都為true,因為會把Integer自動拆箱為int再去比。
5 Collection c = new ArrayList<String>();
c.add(“123”);
c.add(“345”);
c.add(“456”);
boolean b = c.contains(123);
System.out.println(b);
問輸出是什麽,為什麽?
false 數據類型不匹配
6 看程序寫出運行結果:
1 List<String> list = new ArrayList<>();
2 list.add("a1");
3 list.add("a2");
4 list.add("a3");
5 list.add("a4");
6 list.add("a5");
7 Iterator<String> it = list.iterator();
8 while(it.hasNext()){
9 String s = it.next();
10 if(s.equals("a3")){
11 list.add("ABC");
12 }
13 System.out.println(s);
14 }
輸出結果是什麽,為什麽
第1行 報錯,應補齊泛型
結果:
a1
a2
Exception in thread "main" a3
java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819)
at java.util.ArrayList$Itr.next(ArrayList.java:791)
at light.mvc.controller.base.Demo.main(Demo.java:18)
原因:list集合Iterator遍歷的過程中,不能進行add、remove操作。
7 System.out.println(0.09 + 0.01);
System.out.println(1.0 - 0.32);
System.out.println(1.015 * 100);
System.out.println(1.301 / 100);
結果為:
0.09999999999999999
0.6799999999999999
101.49999999999999
0.013009999999999999
為什麽,會造成什麽後果,該怎麽解決。
對於不需要任何準確計算精度的數字可以直接使用float或double,但是如果需要精確計算的結果,則必須使用BigDecimal類,而且使用BigDecimal類也可以進行大數的操作。
Java(數據類型)基礎面試