Java常见的面试题(一)
生活随笔
收集整理的這篇文章主要介紹了
Java常见的面试题(一)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
一、判斷是否是奇數
二、浮點數相減
三、字符串相加和字符相加
四、字符數組
五、增量問題
六、異常處理問題1
七、異常處理問題2
八、長整除
九、隨機數的問題
十、整數邊界的問題
public class Demo01_是否是奇數 {public static void main(String[] args) {for (int i = -5; i < 5; i++) {System.out.println(i + ":" + isOdd(i));}}//容易把負數的情況遺漏public static boolean isOdd(int num) {return num % 2 != 0;} }
二、浮點數相減
public class Demo02_浮點數相減 {public static void main(String[] args) {//會出現丟失精度的問題System.out.println(2.0 - 1.1);//0.8999999999999999} }三、字符串相加和字符相加
public class Demo03_字符串和字符相加 {public static void main(String[] args) {System.out.println("H" + "e");//He//字符相加會先轉換為int類型在相加System.out.println('H' + 'e');//173 } }四、字符數組
public class Demo04_字符數組 {public static void main(String[] args) {char[] chs = {'a', 'b', 'c'};//char數組直接打印會輸出char數組的值 println(char[] chars)System.out.println(chs);//abc//和字符串相加會調用println的重載方法 println(String s)System.out.println("hello" + chs);//hello[C@49e4cb85} }五、增量問題
public class Demo05_增量問題 {public static void main(String[] args) {int j = 0;for (int i = 0; i < 100; i++) {j = j++;}System.out.println(j);//0} }六、異常處理問題1
public class Demo06_異常處理問題 {public static void main(String[] args) {try {System.out.println("hello");System.exit(0);} finally {System.out.println("world");}//會輸出hello。exit方法會強制終止程序} }七、異常處理問題2
public class Demo07_異常處理問題2 {public static void main(String[] args) {//程序會最終執行finally里面的語句System.out.println(panDuan());//false}public static boolean panDuan() {try {return true;} finally {return false;}} }八、長整除
public class Demo08_長整除 {public static void main(String[] args) {final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000;final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;//24*60*60...是int類型相乘,會發生數據精度丟失System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);//5System.out.println("----------------");final long MICROS_PER_DAY1 = 24l * 60 * 60 * 1000 * 1000;final long MILLIS_PER_DAY1 = 24l * 60 * 60 * 1000;//應該先轉換為long類型在相乘System.out.println(MICROS_PER_DAY1 / MILLIS_PER_DAY1);//1000} }九、隨機數的問題
public class Demo09_隨機數的問題 {public static void main(String[] args) {Random r = new Random();StringBuilder sb = null;switch (r.nextInt(2)) {case 1:sb = new StringBuilder('H');case 2:sb = new StringBuilder('E');default:sb = new StringBuilder('L');}sb.append("l");sb.append("o");System.out.println(sb);//問題1:r.nextInt(2)取不到2這個值//問題2:case 1和case 2后面沒有加break;//問題3:new StringBuilder('H')里面參數傳的是字符類型,會自動轉為int,調用的構造方法為指定// 容器大小的方法} }十、整數邊界的問題
public class Demo10_整數邊界問題 {public static void main(String[] args) {int end = Integer.MAX_VALUE;int start = end - 100;int count = 0;//會造成死循環,當i等于end時在+1會變成-2147326492,永遠小于endfor (int i = start; i <= end; i++) {count++;System.out.println(i);}System.out.println(count);} }?
總結
以上是生活随笔為你收集整理的Java常见的面试题(一)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: List、Set
- 下一篇: Java Optional 的 orEl