介绍
如果您正在接受Java编程角色采访,那么您的编码技能可能会被测试,无论您是Java初学者还是专业程序员,本文都提供了一些常见的Java采访问题和答案,以帮助您做好准备。
1、如何在Java中翻译一个字符串?
但是,您可以从字符串创建一个字符串,然后从尾声开始重复它,您可以将这些字符附加到字符串构建程序,并最终返回扭曲的字符串。
下面的示例代码显示了一种方法来扭转一个字符串:
1public class StringPrograms {
2
3 public static void main(String[] args) {
4 String str = "123";
5
6 System.out.println(reverse(str));
7 }
8
9 public static String reverse(String in) {
10 if (in == null)
11 throw new IllegalArgumentException("Null is not valid input");
12
13 StringBuilder out = new StringBuilder();
14
15 char[] chars = in.toCharArray();
16
17 for (int i = chars.length - 1; i >= 0; i--)
18 out.append(chars[i]);
19
20 return out.toString();
21 }
22
23}
在方法中添加null
检查并使用StringBuilder
添加字符的奖金点. 请注意,Java中的索引从0开始,所以您需要在for
循环中从chars.length - 1
开始。
如何在Java中交换两个数字而不使用第三个变量?
在不使用第三个变量的情况下交换数字是一个三个步骤的过程,在代码中更好地可视化:
1b = b + a; // now b is sum of both the numbers
2a = b - a; // b - a = (b + a) - a = b (a is swapped)
3b = b - a; // (b + a) - b = a (b is swapped)
下面的示例代码显示了一种实现数字交换方法的方法:
1public class SwapNumbers {
2
3public static void main(String[] args) {
4 int a = 10;
5 int b = 20;
6
7 System.out.println("a is " + a + " and b is " + b);
8
9 a = a + b;
10 b = a - b;
11 a = a - b;
12
13 System.out.println("After swapping, a is " + a + " and b is " + b);
14 }
15
16}
输出显示整数值是交换的:
1[secondary_label Output]
2a is 10 and b is 20
3After swapping, a is 20 and b is 10
写一个Java程序来检查一个字符串是否存在。
下面的示例代码显示如何使用常规表达式来检查字符串是否包含语音:
1public class StringContainsVowels {
2
3 public static void main(String[] args) {
4 System.out.println(stringContainsVowels("Hello")); // true
5 System.out.println(stringContainsVowels("TV")); // false
6 }
7
8 public static boolean stringContainsVowels(String input) {
9 return input.toLowerCase().matches(".*[aeiou].*");
10 }
11
12}
4、写一个Java程序来检查给定的数字是否是数。
您可以编写一个程序来将给定的数n
分为2到n
/2的数,然后检查剩余的数,如果剩余的数是0,那么它不是一个主要数。
1public class PrimeNumberCheck {
2
3 public static void main(String[] args) {
4 System.out.println(isPrime(19)); // true
5 System.out.println(isPrime(49)); // false
6 }
7
8 public static boolean isPrime(int n) {
9 if (n == 0 || n == 1) {
10 return false;
11 }
12 if (n == 2) {
13 return true;
14 }
15 for (int i = 2; i <= n / 2; i++) {
16 if (n % i == 0) {
17 return false;
18 }
19 }
20
21 return true;
22 }
23
24}
考虑到,对于一个给定的数字N
,如果在2
到√N
之间有M
的总数(N的平方根),它均匀地分为它,那么N
不是一个总数。
写一个Java程序来打印一个Fibonacci序列使用回归。
一个Fibonacci序列是其中每个数字是前两个数字的总和。在这个例子中,序列以0
和1
开始,下面的示例代码显示如何使用for
循环来打印一个Fibonacci序列:
1public class PrintFibonacci {
2
3 public static void printFibonacciSequence(int count) {
4 int a = 0;
5 int b = 1;
6 int c = 1;
7
8 for (int i = 1; i <= count; i++) {
9 System.out.print(a + ", ");
10
11 a = b;
12 b = c;
13 c = a + b;
14 }
15 }
16
17 public static void main(String[] args) {
18 printFibonacciSequence(10);
19 }
20
21}
1[secondary_label Output]
20, 1, 1, 2, 3, 5, 8, 13, 21, 34,
您也可以使用回归来打印Fibonacci序列,因为Fibonacci数通过在序列中添加前两个数字来生成:
1F(N) = F(N-1) + F(N-2)
下面的示例类展示了如何使用回归来计算长达 10 个数字的 Fibonacci 序列:
1public class PrintFibonacciRecursive {
2
3 public static int fibonacci(int count) {
4 if (count <= 1)
5 return count;
6
7 return fibonacci(count - 1) + fibonacci(count - 2);
8 }
9
10 public static void main(String args[]) {
11 int seqLength = 10;
12
13 System.out.print("A Fibonacci sequence of " + seqLength + " numbers: ");
14
15 for (int i = 0; i < seqLength; i++) {
16 System.out.print(fibonacci(i) + " ");
17 }
18 }
19
20}
1[secondary_label Output]
2A Fibonacci sequence of 10 numbers: 0 1 1 2 3 5 8 13 21 34
如何检查Java中的整数列表是否只包含奇数?
您可以使用for
循环并检查每个元素是否奇怪:
1public static boolean onlyOddNumbers(List<Integer> list) {
2 for (int i : list) {
3 if (i % 2 == 0)
4 return false;
5 }
6
7 return true;
8}
如果列表大,则可以使用平行流进行更快的处理,如下示例代码所示:
1public static boolean onlyOddNumbers(List<Integer> list) {
2 return list
3 .parallelStream() // parallel stream for faster processing
4 .anyMatch(x -> x % 2 != 0); // return as soon as any elements match the condition
5}
要了解有关确定整数是否奇怪的数学的更多信息,请参阅 维基百科的Modulo操作。
如何在Java中检查一个字符串是否是一个 palindrome?
一个 palindrome 字符串是相同的字符串向后或向前。 要检查一个 palindrome,您可以逆转输入字符串并检查结果是否等于输入。
1boolean checkPalindromeString(String input) {
2 boolean result = true;
3 int length = input.length();
4
5 for (int i = 0; i < length/2; i++) {
6 if (input.charAt(i) != input.charAt(length - i - 1)) {
7 result = false;
8 break;
9 }
10 }
11
12 return result;
13}
8、如何在Java中从字符串中删除空格?
下面的示例代码显示了一种方法,可以使用 Character.isWhitespace()
方法从字符串中删除空格:
1String removeWhiteSpaces(String input) {
2 StringBuilder output = new StringBuilder();
3
4 char[] charArray = input.toCharArray();
5
6 for (char c : charArray) {
7 if (!Character.isWhitespace(c))
8 output.append(c);
9 }
10
11 return output.toString();
12}
了解有关删除空格和其他字符(/社区/教程/java-删除-字符串)的更多信息。
9.如何在Java中从字符串中删除引导和跟踪空间?
「String」类包含两种方法来删除引导和追溯白色空间:「trim()」和「strip()」。在Java 11中,被添加到「String」类的「strip()」方法使用了「Character.isWhitespace()」方法来检查字符是否是白色空间。
strip()
方法是删除白色空间的推荐方法,因为它使用的是 Unicode 标准。
1String s = " abc def\t";
2
3s = s.strip();
4
5System.out.println(s);
由于String
是不可变的,您必须将strip()
输出分配给字符串。
10、如何在Java中排序数组?
Arrays
实用类有许多过载的sort()
方法来排序原始数组和对象数组. 如果您正在按自然顺序排序原始数组,则可以使用Arrays.sort()
方法,如下示例所示:
1int[] array = {1, 2, 3, -1, -2, 4};
2
3Arrays.sort(array);
4
5System.out.println(Arrays.toString(array));
但是,如果你想排序一个对象组,那么对象必须执行比较
接口. 如果你想指定排序标准,那么你可以通过比较
来进行排序逻辑。 了解更多关于 Java 中的比较和比较。
11、如何在Java中编程创建僵局场景?
Deadlock 是多线程 Java 环境中的一个场景,其中两个或多个线程被永久封锁。
1public class ThreadDeadlock {
2
3 public static void main(String[] args) throws InterruptedException {
4 Object obj1 = new Object();
5 Object obj2 = new Object();
6 Object obj3 = new Object();
7
8 Thread t1 = new Thread(new SyncThread(obj1, obj2), "t1");
9 Thread t2 = new Thread(new SyncThread(obj2, obj3), "t2");
10 Thread t3 = new Thread(new SyncThread(obj3, obj1), "t3");
11
12 t1.start();
13 Thread.sleep(5000);
14 t2.start();
15 Thread.sleep(5000);
16 t3.start();
17 }
18
19}
20
21class SyncThread implements Runnable {
22
23 private Object obj1;
24 private Object obj2;
25
26 public SyncThread(Object o1, Object o2) {
27 this.obj1 = o1;
28 this.obj2 = o2;
29 }
30
31 @Override
32 public void run() {
33 String name = Thread.currentThread().getName();
34
35 System.out.println(name + " acquiring lock on " + obj1);
36 synchronized (obj1) {
37 System.out.println(name + " acquired lock on " + obj1);
38 work();
39 System.out.println(name + " acquiring lock on " + obj2);
40 synchronized (obj2) {
41 System.out.println(name + " acquired lock on " + obj2);
42 work();
43 }
44 System.out.println(name + " released lock on " + obj2);
45 }
46 System.out.println(name + " released lock on " + obj1);
47 System.out.println(name + " finished execution.");
48 }
49
50 private void work() {
51 try {
52 Thread.sleep(30000);
53 } catch (InterruptedException e) {
54 e.printStackTrace();
55 }
56 }
57
58}
所有三个线程都将能够在第一个对象上获得锁定,但它们正在使用共享资源,并以一种方式启动,以便它们将持续等待无限期地在第二个对象上获得锁定。
如何在Java中找到整数的因子数?
整数的因数是通过将从1的所有数字乘以给定的数字来计算的:
1F(n) = F(1)*F(2)...F(n-1)*F(n)
下面的示例代码显示如何使用回归来找到整数的因数:
1public static long factorial(long n) {
2 if (n == 1)
3 return 1;
4 else
5 return (n * factorial(n - 1));
6}
13、如何在Java中扭转链接列表?
LinkedList descendingIterator()
返回一个反转顺序对元素进行反转的迭代器. 下面的示例代码显示了如何使用该迭代器创建一个新的链接列表,其中元素列为反转顺序:
1LinkedList<Integer> ll = new LinkedList<>();
2
3ll.add(1);
4ll.add(2);
5ll.add(3);
6
7System.out.println(ll);
8
9LinkedList<Integer> ll1 = new LinkedList<>();
10
11ll.descendingIterator().forEachRemaining(ll1::add);
12
13System.out.println(ll1);
了解更多关于 [扭转链接列表]( / 社区 / 教程 / 扭转链接列表)从数据结构和算法的角度。
如何在Java中实现二进制搜索?
数组元素必须分类以实现二进制搜索,二进制搜索算法基于以下条件:
- 如果密钥小于中间元素,那么您现在只需要搜索数组的第一半部分
- 如果密钥大于中间元素,那么您只需要搜索数组的第二半部分
- 如果密钥等于数组中的中间元素,那么搜索结束
- 最后,如果在整个数组中没有找到密钥,那么它应该返回
-1
。
以下示例代码实现了二进制搜索:
1public static int binarySearch(int arr[], int low, int high, int key) {
2 int mid = (low + high) / 2;
3
4 while (low <= high) {
5 if (arr[mid] < key) {
6 low = mid + 1;
7 } else if (arr[mid] == key) {
8 return mid;
9 } else {
10 high = mid - 1;
11 }
12 mid = (low + high) / 2;
13 }
14
15 if (low > high) {
16 return -1;
17 }
18
19 return -1;
20}
写一个Java程序,说明 merge sort。
合并排序是最有效的排序算法之一. 它基于分割和征服
的原则工作。 它基于将列表分解为多个子列表,直到每个子列表由一个单一的元素组成,然后将这些子列表合并成一个排序列表。
1public class MergeSort {
2
3 public static void main(String[] args) {
4 int[] arr = { 70, 50, 30, 10, 20, 40, 60 };
5
6 int[] merged = mergeSort(arr, 0, arr.length - 1);
7
8 for (int val : merged) {
9 System.out.print(val + " ");
10 }
11 }
12
13 public static int[] mergeTwoSortedArrays(int[] one, int[] two) {
14 int[] sorted = new int[one.length + two.length];
15
16 int i = 0;
17 int j = 0;
18 int k = 0;
19
20 while (i < one.length && j < two.length) {
21 if (one[i] < two[j]) {
22 sorted[k] = one[i];
23 k++;
24 i++;
25 } else {
26 sorted[k] = two[j];
27 k++;
28 j++;
29 }
30 }
31
32 if (i == one.length) {
33 while (j < two.length) {
34 sorted[k] = two[j];
35 k++;
36 j++;
37 }
38 }
39
40 if (j == two.length) {
41 while (i < one.length) {
42 sorted[k] = one[i];
43 k++;
44 i++;
45 }
46 }
47
48 return sorted;
49 }
50
51 public static int[] mergeSort(int[] arr, int lo, int hi) {
52 if (lo == hi) {
53 int[] br = new int[1];
54 br[0] = arr[lo];
55
56 return br;
57 }
58
59 int mid = (lo + hi) / 2;
60
61 int[] fh = mergeSort(arr, lo, mid);
62 int[] sh = mergeSort(arr, mid + 1, hi);
63
64 int[] merged = mergeTwoSortedArrays(fh, sh);
65
66 return merged;
67 }
68
69}
16、你能在Java中创建一个字符金字塔吗?
模式程序是一个非常流行的采访主题,这种类型的问题被用来理解受访者的逻辑思维能力,请参阅 Pyramid Pattern Programs in Java以了解创建金字塔模式的不同方式。
写一个 Java 程序来检查两个数组是否包含相同的元素。
若要检查两个数组是否包含相同的元素,您需要先从两个数组创建一组元素,然后对这些组中的元素进行比较,以确定是否有没有在两组中存在的元素。
1import java.util.Arrays;
2import java.util.HashSet;
3import java.util.Set;
4
5public class ArraySameElements {
6
7 public static void main(String[] args) {
8 Integer[] a1 = {1,2,3,2,1};
9 Integer[] a2 = {1,2,3};
10 Integer[] a3 = {1,2,3,4};
11
12 System.out.println(sameElements(a1, a2));
13 System.out.println(sameElements(a1, a3));
14 }
15
16 static boolean sameElements(Object[] array1, Object[] array2) {
17 Set<Object> uniqueElements1 = new HashSet<>(Arrays.asList(array1));
18 Set<Object> uniqueElements2 = new HashSet<>(Arrays.asList(array2));
19
20 // if size is different, means there will be a mismatch
21 if (uniqueElements1.size() != uniqueElements2.size()) return false;
22
23 for (Object obj : uniqueElements1) {
24 // element not present in both?
25 if (!uniqueElements2.contains(obj)) return false;
26 }
27
28 return true;
29 }
30
31}
1[secondary_label Output]
2true
3false
如何在Java中获得整数数组中的所有元素的总和?
您可以使用for
循环重复数组元素,并添加它们以获得最终的总和:
1int[] array = { 1, 2, 3, 4, 5 };
2
3int sum = 0;
4
5for (int i : array)
6 sum += i;
7
8System.out.println(sum);
如何在Java中找到数组中的第二大数字?
有许多方法可以解决这个问题. 您可以以自然的上升顺序对数组进行排序,并采取第二个最后的值. 但是,排序是一种昂贵的操作. 您也可以使用两个变量在单次迭代中找到第二大值,如下示例所示:
1private static int findSecondHighest(int[] array) {
2 int highest = Integer.MIN_VALUE;
3 int secondHighest = Integer.MIN_VALUE;
4
5 for (int i : array) {
6 if (i > highest) {
7 secondHighest = highest;
8 highest = i;
9 } else if (i > secondHighest) {
10 secondHighest = i;
11 }
12
13 }
14 return secondHighest;
15}
问:如何在Java中编辑一个数组?
下面的示例代码展示了如何使用随机
类来生成随机索引号码,并模糊元素:
1int[] array = { 1, 2, 3, 4, 5, 6, 7 };
2
3Random rand = new Random();
4
5for (int i = 0; i < array.length; i++) {
6 int randomIndexToSwap = rand.nextInt(array.length);
7 int temp = array[randomIndexToSwap];
8 array[randomIndexToSwap] = array[i];
9 array[i] = temp;
10}
11
12System.out.println(Arrays.toString(array));
您可以在另一个for
循环中运行 shuffling 代码来 shuffle 多个回合。
21、如何在Java中找到文本文件中的字符串?
以下示例代码显示如何使用扫描器
类来读取文件内容的行后行,然后使用字符串包含()
方法来检查字符串是否存在于文件中:
1boolean findStringInFile(String filePath, String str) throws FileNotFoundException {
2 File file = new File(filePath);
3
4 Scanner scanner = new Scanner(file);
5
6 // read the file line by line
7 while (scanner.hasNextLine()) {
8 String line = scanner.nextLine();
9 if (line.contains(str)) {
10 scanner.close();
11 return true;
12 }
13 }
14 scanner.close();
15
16 return false;
17}
请注意,示例代码假定您在文件中搜索的字符串不包含新行字符。
如何在Java中以特定格式打印日期?
下面的示例代码显示如何使用SimpleDateFormat
类来格式化日期字符串:
1String pattern = "MM-dd-yyyy";
2SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
3
4String date = simpleDateFormat.format(new Date());
5System.out.println(date); // 06-23-2020
了解更多关于 Java SimpleDateFormat的信息。
如何在Java中合并两个列表?
下面的示例代码展示了如何使用addAll()
方法在Java中合并多个列表:
1List<String> list1 = new ArrayList<>();
2list1.add("1");
3List<String> list2 = new ArrayList<>();
4list2.add("2");
5
6List<String> mergedList = new ArrayList<>(list1);
7mergedList.addAll(list2);
8System.out.println(mergedList); // [1, 2]
写一个 Java 程序,按值排序 HashMap。
HashMap
不是一个有序的集合,以下示例代码显示了如何根据值来排序条目并将其存储在LinkedHashMap
中,以保持插入顺序:
1import java.util.ArrayList;
2import java.util.HashMap;
3import java.util.LinkedHashMap;
4import java.util.List;
5import java.util.Map;
6import java.util.Map.Entry;
7import java.util.Set;
8
9public class SortHashMapByValue {
10
11 public static void main(String[] args) {
12 Map<String, Integer> scores = new HashMap<>();
13
14 scores.put("David", 95);
15 scores.put("Jane", 80);
16 scores.put("Mary", 97);
17 scores.put("Lisa", 78);
18 scores.put("Dino", 65);
19
20 System.out.println(scores);
21
22 scores = sortByValue(scores);
23
24 System.out.println(scores);
25 }
26
27 private static Map<String, Integer> sortByValue(Map<String, Integer> scores) {
28 Map<String, Integer> sortedByValue = new LinkedHashMap<>();
29
30 // get the entry set
31 Set<Entry<String, Integer>> entrySet = scores.entrySet();
32 System.out.println(entrySet);
33
34 // create a list since the set is unordered
35 List<Entry<String, Integer>> entryList = new ArrayList<>(entrySet);
36 System.out.println(entryList);
37
38 // sort the list by value
39 entryList.sort((x, y) -> x.getValue().compareTo(y.getValue()));
40 System.out.println(entryList);
41
42 // populate the new hash map
43 for (Entry<String, Integer> e : entryList)
44 sortedByValue.put(e.getKey(), e.getValue());
45
46 return sortedByValue;
47 }
48
49}
25、如何在Java中从输入字符串中删除特定字符的所有发生?
「String」类没有删除字符的方法,下面的示例代码显示如何使用「replace()」方法创建新的字符串,而没有给定的字符:
1String str1 = "abcdABCDabcdABCD";
2
3str1 = str1.replace("a", "");
4
5System.out.println(str1); // bcdABCDbcdABCD
字符串在Java中是不可变的。所有字符串操作方法都返回一个新的字符串,这就是为什么你需要将它分配给另一个变量。 了解更多关于 删除字符从Java中的字符串。
26、如何在Java中在字符串中获得不同的字符及其计数?
您可以从字符串创建字符串,然后重复它并创建一个HashMap
,将字符作为密钥和其计数作为值。
1String str1 = "abcdABCDabcd";
2
3char[] chars = str1.toCharArray();
4
5Map<Character, Integer> charsCount = new HashMap<>();
6
7for (char c : chars) {
8 if (charsCount.containsKey(c)) {
9 charsCount.put(c, charsCount.get(c) + 1);
10 } else
11 charsCount.put(c, 1);
12}
13
14System.out.println(charsCount); // {a=2, A=1, b=2, B=1, c=2, C=1, d=2, D=1}
27、你能证明Java中的一个字符串
对象在程序上是不可变的吗?
下面的示例代码显示了如何证明一个字符串
对象是不可变的,并且代码中的评论解释了每个步骤:
1String s1 = "Java"; // "Java" String created in pool and reference assigned to s1
2
3String s2 = s1; //s2 also has the same reference to "Java" in the pool
4
5System.out.println(s1 == s2); // proof that s1 and s2 have the same reference
6
7s1 = "Python";
8//s1 value got changed above, so how String is immutable?
9
10//in the above case a new String "Python" got created in the pool
11//s1 is now referring to the new String in the pool
12//BUT, the original String "Java" is still unchanged and remains in the pool
13//s2 is still referring to the original String "Java" in the pool
14
15// proof that s1 and s2 have different reference
16System.out.println(s1 == s2);
17
18System.out.println(s2);
19// prints "Java" supporting the fact that original String value is unchanged, hence String is immutable
28、你能写一些代码来展示Java中的遗传吗?
下面的示例代码显示了如何使用扩展
关键字来创建类动物
的子类.新的类猫
将从动物
类继承变量,并添加更多只属于猫
类的代码。
1class Animal {
2 String color;
3}
4
5class Cat extends Animal {
6 void meow() {
7 System.out.println("Meow");
8 }
9}
如何在Java中显示多重继承的钻石问题?
当一个类从多个类继承时,钻石问题发生,当不清楚从哪个类执行哪种方法时,出现模糊性。
1interface I {
2 void foo();
3}
4class A implements I {
5 public void foo() {}
6}
7
8class B implements I {
9 public void foo() {}
10}
11
12class C extends A, B { // won't compile
13 public void bar() {
14 super.foo();
15 }
16}
30、你如何在Java中描述一个试着捕捉的例子?
下面的示例代码显示了一个试捕的例子:
1try {
2 FileInputStream fis = new FileInputStream("test.txt");
3} catch(FileNotFoundException e) {
4 e.printStackTrace();
5}
从Java 7开始,您也可以在单个捕获块中捕获多个例外,如下面的示例所示。
1public static void foo(int x) throws IllegalArgumentException, NullPointerException {
2 // some code
3}
4
5public static void main(String[] args) {
6 try {
7 foo(10);
8 } catch (IllegalArgumentException | NullPointerException e) {
9 System.out.println(e.getMessage());
10 }
11}
写一个Java程序来显示一个NullPointerException
。
如果您在null
上调用函数,它会投出NullPointerException
,如下示例代码所示:
1public static void main(String[] args) {
2 printString(null, 3);
3
4}
5
6static void printString(String s, int count) {
7 for (int i = 0; i < count; i++) {
8 System.out.println(s.toUpperCase()); // Exception in thread "main" java.lang.NullPointerException
9 }
10}
对于早期验证,您应该有 null 检查,如下示例代码所示:
1static void printString(String s, int count) {
2 if (s == null) return;
3 for (int i = 0; i < count; i++) {
4 System.out.println(s.toUpperCase());
5 }
6}
您还可以根据项目要求投放IllegalArgumentException
。
32、如何在Java中创建记录?
Records 被添加为 Java 16 中的标准功能。 Records 允许您创建一个 POJO 类,使用最少的代码。 Records 自动生成 hashCode()
、 equals()
、 getter 方法和 toString()
类的方法代码。 Records 是最终的,并且默认地扩展了 java.lang.Record
类。
1import java.util.Map;
2
3public record EmpRecord(int id, String name, long salary, Map<String, String> addresses) {
4}
了解更多關於 Java 記錄。 關於 POJO 的詳細信息,請參閱 Wikipedia 上的舊 Java 對象。
如何在Java中创建文本块?
Java 15 增加了文本块功能. 您可以使用文本块创建多行字符串. 多行字符串必须写在一对三倍引文中,如下示例所示:
1String textBlock = """
2 Hi
3 Hello
4 Yes""";
它就像创建一个字符串,例如Hi\\nHello\\nYes
。
显示 Java 中的交换表达式和多标签案例陈述的例子。
交换式表达式被添加为Java 14的标准功能。
1int choice = 2;
2
3int x = switch (choice) {
4 case 1, 2, 3:
5 yield choice;
6 default:
7 yield -1;
8};
9
10System.out.println("x = " + x); // x = 2
您也可以在交换式表达式中使用 lambda 表达式。
1String day = "TH";
2String result = switch (day) {
3 case "M", "W", "F" -> "MWF";
4 case "T", "TH", "S" -> "TTS";
5
6 default -> {
7 if (day.isEmpty())
8 yield "Please insert a valid day.";
9 else
10 yield "Looks like a Sunday.";
11 }
12};
13
14System.out.println(result); // TTH
35、如何从命令行编译和运行Java类?
这个例子指的是以下Java文件:
1public class Test {
2
3public static void main(String args[]) {
4 System.out.println("Hi");
5 }
6
7}
您可以使用您的终端中的下列命令编译它:
1javac Test.java
要运行该类,请在终端中使用以下命令:
1java Test
对于最近发布的版本,如果类文件不存在的话,java
命令也会编译程序,如果类在一个包中,如com.example
,那么它应该在文件夹中com/example
。
1java com/example/Test.java
如果您的类需要一些额外的 JAR 来编译和运行,您可以使用java -cp
选项。
1java -cp .:~/.m2/repository/log4j/log4j/1.2.17/log4j-1.2.17.jar com/example/Test.java
如何在Java中创建一个Enum?
以下示例代码显示如何创建基本enum:
1public enum ThreadStates {
2 START,
3 RUNNING,
4 WAITING,
5 DEAD;
6}
「ThreadStates」是固定常数字段「START」、「RUNNING」、「WAITING」和「DEAD」的字段。所有字段都暗示地扩展了「java.lang.Enum」类,并实施了「Serializable」和「Comparable」接口。Enum也可以有方法。 了解更多关于 enums in Java的信息。
如何在Java中使用forEach()
方法?
forEach()
方法提供了对可重复元素的所有元素执行操作的捷径,以下示例代码显示了如何重复列表元素并打印它们:
1List<String> list = new ArrayList<>();
2
3Iterator<String> it = list.iterator();
4
5while (it.hasNext()) {
6 System.out.println(it.next());
7}
您可以使用「forEach()」方法与 lambda 表达式来减少代码大小,如下示例代码所示:
1List<String> list = new ArrayList<>();
2
3list.forEach(System.out::print);
38、如何用默认
和静态
方法编写接口?
Java 8 在接口中引入了默认和静态方法,从而缩小了接口和抽象类之间的差距,以下示例代码显示了一种用默认
和静态
方法来编写接口的方法:
1public interface Interface1 {
2
3 // regular abstract method
4 void method1(String str);
5
6 default void log(String str) {
7 System.out.println("I1 logging::" + str);
8 }
9
10 static boolean isNull(String str) {
11 System.out.println("Interface Null Check");
12
13 return str == null ? true : "".equals(str) ? true : false;
14 }
15
16}
了解有关界面中的默认
和静态
方法的更多信息,请参阅 [Java 8 界面变化]( / 社区 / 教程 / java-8 界面变化 - 静态方法 - 默认方法)。
39、如何创建一个功能性界面?
具有完全一个抽象方法的接口称为功能接口.功能接口的主要好处是,您可以使用 lambda 表达式来实例化它们并避免使用大量的匿名类实现。
1@FunctionalInterface
2interface Foo {
3 void test();
4}
40. 显示在 Java 中使用 lambda 表达式的例子。
「Runnable」是功能界面的一个很好的例子,您可以使用lambda表达式创建一个可执行的,如下示例代码所示:
1Runnable r1 = () -> System.out.println("My Runnable");
顯示 Java 中的過載和過載的例子。
当一个类有两个或多个具有相同名称的方法时,它们被称为过载的方法。
1class Foo {
2 void print(String s) {
3 System.out.println(s);
4 }
5
6 void print(String s, int count) {
7 while (count > 0) {
8 System.out.println(s);
9 count--;
10 }
11 }
12
13}
当一个超级类方法在儿童类中也被执行时,它被称为overriding. 下面的示例代码显示了如何注明在两个类中实现的 printname()
方法:
1class Base {
2 void printName() {
3 System.out.println("Base Class");
4 }
5}
6
7class Child extends Base {
8 @Override
9 void printName() {
10 System.out.println("Child Class");
11 }
12}
了解更多关于 Java 中的过载和过载( / 社区 / 教程 / overriding-vs-overloading-in-java)。
第42章 猜测结果
通过猜测下列代码片段的输出来测试自己。
1String s1 = "abc";
2String s2 = "abc";
3
4System.out.println("s1 == s2 is:" + s1 == s2);
(详情输出)
1false
给定的表达式的输出是false
,因为+
运算器比==
运算器具有更高的优先级,因此给定的表达式被评估为s1 == s2 is:abc
== abc``,这就是
false`
1String s3 = "JournalDev";
2int start = 1;
3char end = 5;
4
5System.out.println(s3.substring(start, end));
(详情输出)
1ourn
给定的语句的输出是ourn
。第一个字符自动键入 cast 到int
。然后,因为第一个字符索引为0,它将从o
开始,并打印到n
。注意String substring
方法会创建一个始于start
索引的子字符,并扩展到end – 1
索引的字符。
1HashSet shortSet = new HashSet();
2
3 for (short i = 0; i < 100; i++) {
4 shortSet.add(i);
5 shortSet.remove(i - 1);
6}
7
8System.out.println(shortSet.size());
(详情输出)
1100
shortSet
的大小为100
。Java 中的 autoboxing 功能意味着具有原始类型short
的表达式i
转换为Short
对象。类似地,表达式i - 1
具有原始类型int
并自动化为Integer
对象。
1try {
2 if (flag) {
3 while (true) {
4 }
5 } else {
6 System.exit(1);
7 }
8} finally {
9 System.out.println("In Finally");
10}
[详细输出
没有输出. 如果旗帜是真
则此代码会产生无限循环,如果旗帜是假
则程序会存在。
1String str = null;
2String str1="abc";
3
4System.out.println(str1.equals("abc") | str.equals(null));
(详情输出)
1Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "<local1>" is null
给出的打印声明会投出一个java.lang.NullPointerException
,因为OR
逻辑运算器在返回结果之前对两个字母进行评估.因为str
是null
,所以.equals()
方法会投出一个例外。总是建议使用短路逻辑运算器,如``和&&
,这些运算器从左到右评估字母值。
1String x = "abc";
2String y = "abc";
3
4x.concat(y);
5
6System.out.print(x);
(详情输出)
1abc
x.concat(y)
创建一个新的字符串,但不分配给x
,因此x
的值不会改变
1public class MathTest {
2
3 public void main(String[] args) {
4 int x = 10 * 10 - 10;
5
6 System.out.println(x);
7 }
8
9}
(详情输出)
1Error: Main method is not static in class MathTest, please define the main method as:
2 public static void main(String[] args)
虽然这可能看起来像这个问题是关于数学运算符的执行顺序,但问题实际上是注意到( / 社区 / 教程 / 公共 - 静态 - 虚无 - 主字符串 - args - java - 主方法)没有被宣布为静态
1public class Test {
2
3 public static void main(String[] args) {
4 try {
5 throw new IOException("Hello");
6 } catch(IOException | Exception e) {
7 System.out.println(e.getMessage());
8 }
9 }
10}
(详情输出)
1Test.java:5: error: cannot find symbol
2 throw new IOException("Hello");
3 ^
4 symbol: class IOException
5 location: class Test
6Test.java:6: error: cannot find symbol
7 }catch(IOException | Exception e) {
8 ^
9 symbol: class IOException
10 location: class Test
112 errors
此代码导致编译时间错误. 例外IOException
已被替代的Exception
捕获
查找下面的代码片段中的5个错误。
1package com.digitalocean.programming-interviews;
2
3public class String Programs {
4
5 static void main(String[10] args) {
6 String s = "abc"
7 System.out.println(s);
8 }
9}
(详细解答)
- 包名不能有字符串
- 类名不能有空格
- 主要方法不是
公共
,所以它不会运行 - 主要方法参数不应该指定大小
- 字符串定义中缺少半色符号
( )
结论
这个50个Java编程面试问题集包括从初学者到专家级别的问题,以帮助您为面试做好准备。
推荐阅读:**