博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java面试编程面试题_Java编程面试的前50个问题
阅读量:2530 次
发布时间:2019-05-11

本文共 36863 字,大约阅读时间需要 122 分钟。

java面试编程面试题

Java Programming Interview Questions are always the deciding factor in any Java interview. Whether you are a beginner in Java or an expert programmer, you will be tested for your coding skills in the interview. So, it’s a good idea to brush up your coding skills before you face the interview.

Java编程面试问题始终是任何Java面试的决定因素。 无论您是Java的初学者还是专家程序员,都将在面试中测试您的编码技能。 因此,在面试之前提高自己的编码技能是一个好主意。

Java编程面试问题 (Java Programming Interview Questions)

I am providing 50+ Java programming questions to test your coding skills. It’s good for beginners as well as experienced Java developers. The best part is that some of the questions are from the latest releases (Java 14). If you can write Java programs using the latest features, it means you keep yourself up to date, which will work in your favor.

我提供了50多个Java编程问题来测试您的编码技能。 对于初学者和有经验的Java开发人员来说都非常好。 最好的部分是一些问题来自最新版本(Java 14)。 如果您可以使用最新功能编写Java程序,则意味着您可以保持最新状态,这将对您有利。

1.如何在Java中反转字符串? (1. How to reverse a String in Java?)

It might be surprising, but there is no reverse() utility method in the String class. But, it’s a very simple task. We can create a character array from the string and then iterate it from the end to start. We can append the characters to a string builder and finally return the reversed string.

可能令人惊讶,但是String类中没有反向()实用程序方法。 但是,这是一个非常简单的任务。 我们可以从字符串创建一个字符数组,然后从头开始迭代它。 我们可以将字符附加到字符串生成器,最后返回反转的字符串。

public class StringPrograms {	public static void main(String[] args) {		String str = "123";		System.out.println(reverse(str));	}	public static String reverse(String in) {		if (in == null)			throw new IllegalArgumentException("Null is not valid input");		StringBuilder out = new StringBuilder();		char[] chars = in.toCharArray();		for (int i = chars.length - 1; i > 0; i--)			out.append(chars[i]);		return out.toString();	}}

Bonus Points: Adding null check in the method and using StringBuilder for appending the characters.

优点 :在方法中添加null检查,并使用StringBuilder附加字符。

Easy to Miss: The indexing in Java starts from 0. So, we have to start at “chars.length – 1” in the for loop.

容易错过 :Java中的索引从0开始。因此,我们必须在for循环中从“ chars.length – 1”开始。

2.如何在不使用第三个变量的情况下交换两个数字? (2. How to swap two numbers without using a third variable?)

It’s a slightly tricky question. It’s a three steps process. It’s better visualized in code.

这是一个有点棘手的问题。 这是一个三步过程。 用代码更好地可视化。

int a = 10;int b = 20;b = b + a; // now b is sum of both the numbersa = b - a; // b - a = (b + a) - a = b (a is swapped)b = b - a; // (b + a) - b = a (b is swapped)

We can’t return multiple variables in Java. Since Java is Pass-by-Value and these are primitive data types, their values won’t change. For example, below swap function will not change the input integer values.

我们无法在Java中返回多个变量。 由于Java是“按值传递”并且它们是原始数据类型,因此它们的值不会更改。 例如,下面的swap函数将不会更改输入整数值。

public static void swapNumbers(int a, int b) {    b = b + a;	a = b - a;	b = b - a;}public static void main(String[] args) {	int a = 10;	int b = 20;	swapNumbers(a, b);	System.out.printf("a is %d, b is %d", a, b); // a is 10, b is 20}

3. Java程序检查字符串中是否存在元音? (3. Java Program to check if a vowel is present in the string?)

We can use regular expression to check if the string contains vowels or not.

我们可以使用正则表达式来检查字符串是否包含元音。

public class StringContainsVowels {	public static void main(String[] args) {		System.out.println(stringContainsVowels("Hello")); // true		System.out.println(stringContainsVowels("TV")); // false	}	public static boolean stringContainsVowels(String input) {		return input.toLowerCase().matches(".*[aeiou].*");	}}

4. Java程序检查给定数字是否为Prime? (4. Java program to check if the given number is Prime?)

We can write a simple program to divide the given number “n” from 2 to n/2 and check the remainder. If the remainder is 0, then it’s not a prime number.

我们可以编写一个简单的程序将给定的数字“ n”从2除以n / 2,然后检查余数。 如果余数为0,则它​​不是质数。

public class PrimeNumberCheck {	public static void main(String[] args) {		System.out.println(isPrime(19)); // true		System.out.println(isPrime(49)); // false	}	public static boolean isPrime(int n) {		if (n == 0 || n == 1) {			return false;		}		if (n == 2) {			return true;		}		for (int i = 2; i <= n / 2; i++) {			if (n % i == 0) {				return false;			}		}		return true;	}}

But, this is not very memory and time-efficient. For a given number N, if there is a prime number M between 2 to √N (square root of N) that evenly divides it, then N is not a prime number.

但是,这不是很节省内存和时间。 对于给定的数N,如果在2到√N(N的平方根)之间有一个质数M对其进行均分,则N不是质数。

You can read more about it .

您可以了解更多信息。

5.使用递归的斐波那契数列 (5. Fibonacci Series using recursion)

We can use a for loop to print fibonacci series.

我们可以使用for循环来打印斐波那契数列。

public static void printFibonacciSeries(int count) {	int a = 0;	int b = 1;	int c = 1;	for (int i = 1; i <= count; i++) {		System.out.print(a + ", ");		a = b;		b = c;		c = a + b;	}}

The fibonacci number is generated by adding the previous two numbers – F(N) = F(N-1) + F(N-2). We can use recursion to print fibonacci series.

斐波那契数是通过将前两个数相加而得出的-F(N)= F(N-1)+ F(N-2)。 我们可以使用递归来打印斐波那契数列。

public class FibonacciNumbers {	public static int fibonacci(int n) {		if (n <= 1)			return n;		return fibonacci(n - 1) + fibonacci(n - 2);	}	public static void main(String args[]) {		int n = 10;		System.out.println(fibonacci(n));	}}

6.检查整数列表是否仅包含奇数? (6. Check if a List of integers contains only odd numbers?)

We can use for loop and check each element one by one if they are odd or not.

我们可以使用for循环并逐个检查每个元素是否为奇数。

public static boolean onlyOddNumbers(List
list) { for (int i : list) { if (i % 2 == 0) return false; } return true;}

If the list is huge, we can use parallel stream for faster processing.

如果列表很大,我们可以使用并行流进行更快的处理。

public static boolean onlyOddNumbers(List
list) { return list .parallelStream() // parallel stream for faster processing .anyMatch(x -> x % 2 != 0); // return as soon as any elements match the condition}

7.回文检查 (7. Palindrome Check)

A palindrome string is one whose reverse is also the same string. So we can reverse the input string and check if both strings are equal or not. We can also use the String charAt(int index) method to check for palindrome string.

回文字符串是反向字符串也相同的字符串。 因此,我们可以反转输入字符串,并检查两个字符串是否相等。 我们还可以使用String charAt(int index)方法检查回文字符串。

boolean checkPalindromeString(String input) {	boolean result = true;	int length = input.length();	for(int i=0; i < length/2; i++) {		if(input.charAt(i) != input.charAt(length-i-1)) {			result = false;			break;		}	}	return result;}

8.如何从字符串中删除空格 (8. How to remove Whitespaces from String)

We can use Character.isWhitespace() method to remove whitespaces from the string.

我们可以使用Character.isWhitespace()方法从字符串中删除空格。

String removeWhiteSpaces(String input){	StringBuilder output = new StringBuilder();		char[] charArray = input.toCharArray();		for(char c : charArray) {		if (!Character.isWhitespace(c))			output.append(c);	}		return output.toString();}

9.如何从字符串中删除开头和结尾的空格? (9. How to remove leading and trailing whitespaces from a string?)

Java String class contains two methods to remove leading and trailing whitespaces – trim(), and strip(). The strip() method was added to the String class in Java 11. However, the strip() method uses Character.isWhitespace() method to check if the character is a whitespace. This method uses Unicode code points whereas the trim() method identifies any character having codepoint value less than or equal to ‘U+0020’ as a whitespace character.

Java String类包含两种删除开头和结尾空格的方法– trim()和strip()。 strip()方法已添加到Java 11中的String类中。但是,strip()方法使用Character.isWhitespace()方法来检查字符是否为空格。 此方法使用Unicode代码点,而trim()方法将代码点值小于或等于'U + 0020'的任何字符标识为空白字符。

The strip() method is the recommended way to remove whitespaces because it uses the Unicode standard.

推荐使用strip()方法删除空格,因为它使用Unicode标准。

String s = "  abc  def\t";		s = s.strip();		System.out.println(s);

Since String is immutable, we have to assign the strip() output to the string.

由于String是不可变的,因此我们必须将strip()输出分配给字符串。

10.用Java排序数组? (10. Sorting an array in Java?)

This question requires a deep understanding of sorting in Java. If you look at the Arrays utility class, there are many overloaded sort() methods to sort primitive as well as to object arrays.

这个问题需要对Java排序有深入的了解。 如果您看一下Arrays实用程序类,有很多重载的sort()方法可以对基元和对象数组进行排序。

If you are sorting a primitive array in the natural order, then it’s very simple. Just use the Arrays.sort() method.

如果您要按自然顺序对原始数组进行排序,那么这很简单。 只需使用Arrays.sort()方法即可。

int[] array = {1, 2, 3, -1, -2, 4};Arrays.sort(array);System.out.println(Arrays.toString(array));

But, if you want to sort an array of Objects, then the object must implement Comparable interface. If you want to specify the sorting criteria, then you can pass the Comparator for the sorting logic. You should read more about them at – .

但是,如果要对对象数组进行排序,则该对象必须实现Comparable接口。 如果要指定排序条件,则可以将比较器传递给排序逻辑。 您应该在– 阅读有关它们的更多信息。

11.如何以编程方式创建死锁方案? (11. How to Create a Deadlock Scenario Programatically?)

Deadlock is a special scenario in the multi-threaded environment where two or more threads are blocked forever. The deadlock situation arises with at least two threads and two or more threads. Let’s write a simple program to create a deadlock.

死锁是多线程环境中的一种特殊情况,在这种情况下,两个或更多线程将永远被阻塞。 至少有两个线程以及两个或更多线程会出现死锁情况。 让我们编写一个简单的程序来创建死锁。

public class ThreadDeadlock {    public static void main(String[] args) throws InterruptedException {        Object obj1 = new Object();        Object obj2 = new Object();        Object obj3 = new Object();            Thread t1 = new Thread(new SyncThread(obj1, obj2), "t1");        Thread t2 = new Thread(new SyncThread(obj2, obj3), "t2");        Thread t3 = new Thread(new SyncThread(obj3, obj1), "t3");                t1.start();        Thread.sleep(5000);        t2.start();        Thread.sleep(5000);        t3.start();            }}class SyncThread implements Runnable{    private Object obj1;    private Object obj2;    public SyncThread(Object o1, Object o2){        this.obj1=o1;        this.obj2=o2;    }    @Override    public void run() {        String name = Thread.currentThread().getName();        System.out.println(name + " acquiring lock on "+obj1);        synchronized (obj1) {         System.out.println(name + " acquired lock on "+obj1);         work();         System.out.println(name + " acquiring lock on "+obj2);         synchronized (obj2) {            System.out.println(name + " acquired lock on "+obj2);            work();        }         System.out.println(name + " released lock on "+obj2);        }        System.out.println(name + " released lock on "+obj1);        System.out.println(name + " finished execution.");    }    private void work() {        try {            Thread.sleep(30000);        } catch (InterruptedException e) {            e.printStackTrace();        }    }}

All the three threads will be able to acquire a lock on the first object. But, they are using the shared resources and started in such a way that they will keep on waiting indefinitely to acquire the lock on the second object. We can use the java thread dump to detect the deadlocks. Read more at .

这三个线程都将能够获得第一个对象的锁。 但是,他们使用共享资源并以一种方式启动,即他们将无限期地等待获取第二个对象的锁。 我们可以使用java线程转储来检测死锁。 阅读更多内容。

12.查找整数的阶乘? (12. Find factorial of an integer?)

The factorial of an integer is calculated by multiplying all the numbers from 1 to the given number.

整数的阶乘是通过将所有数字从1乘以给定数字来计算的。

F(n) = F(1)*F(2)…F(n-1)*F(n).

F(n)= F(1)* F(2)... F(n-1)* F(n)。

We can use recursion to find the factorial of an integer.

我们可以使用递归来查找整数的阶乘。

public static long factorial(long n) {	if (n == 1)		return 1;	else		return (n * factorial(n - 1));}

13.回顾链接列表? (13. Revese a Linked List?)

LinkedList descendingIterator() returns an iterator that iterates over the element in the reverse order. We can use this iterator to create a new Linked List with elements in the reverse order.

LinkedListDescendingIterator()返回一个迭代器,该迭代器以相反的顺序迭代元素。 我们可以使用此迭代器来创建一个新的链表,其中的元素顺序相反。

LinkedList
ll = new LinkedList<>();ll.add(1);ll.add(2);ll.add(3);System.out.println(ll);LinkedList
ll1 = new LinkedList<>();ll.descendingIterator().forEachRemaining(ll1::add);System.out.println(ll1);

If you are looking from the data structures and algorithms perspective, read .

如果您从数据结构和算法的角度看,请阅读 。

14.如何实现二进制搜索? (14. How to implement Binary Search?)

The array elements must be sorted for implementing binary search. The binary search algorithm is based on the following conditions.

必须对数组元素进行排序才能实现二进制搜索。 二进制搜索算法基于以下条件。

If the key is less than the middle element, then we now need to search only in the first half of the array.

If the key is greater than the middle element, then we need to only search in the second half of the array.
And if the key is equal to the middle element in the array, then the search ends.
Finally, if the key is not found in the whole array, then it should return -1. This indicates that the element is not present.

如果键小于中间元素,那么我们现在只需要在数组的前半部分搜索。

如果键大于中间元素,那么我们只需要在数组的后半部分搜索即可。
如果键等于数组中的中间元素,则搜索结束。
最后,如果在整个数组中找不到键,则它应该返回-1。 这表明该元素不存在。

public static int binarySearch(int arr[], int low, int high, int key) {	int mid = (low + high) / 2;	while (low <= high) {		if (arr[mid] < key) {			low = mid + 1;		} else if (arr[mid] == key) {			return mid;		} else {			high = mid - 1;		}		mid = (low + high) / 2;	}	if (low > high) {		return -1;	}	return -1;}

15.合并Java排序? (15. Merge Sort in Java?)

Merge sort is one of the most efficient sorting algorithms. It works on the principle of Divide and Conquers. It is based on the idea of breaking down a list into several sub-lists until each sublist consists of a single element. Then merging those sublists in a manner that results in a sorted list.

合并排序是最有效的排序算法之一。 它遵循分而治之的原则。 它基于以下思想:将一个列表分解为几个子列表,直到每个子列表包含一个元素。 然后以导致排序列表的方式合并这些子列表。

public class MergeSort {	public static void main(String[] args) {		int[] arr = { 70, 50, 30, 10, 20, 40, 60 };		int[] merged = mergeSort(arr, 0, arr.length - 1);		for (int val : merged) {			System.out.print(val + " ");		}	}	public static int[] mergeTwoSortedArrays(int[] one, int[] two) {		int[] sorted = new int[one.length + two.length];		int i = 0;		int j = 0;		int k = 0;		while (i < one.length && j < two.length) {			if (one[i] < two[j]) {				sorted[k] = one[i];				k++;				i++;			} else {				sorted[k] = two[j];				k++;				j++;			}		}		if (i == one.length) {			while (j < two.length) {				sorted[k] = two[j];				k++;				j++;			}		}		if (j == two.length) {			while (i < one.length) {				sorted[k] = one[i];				k++;				i++;			}		}		return sorted;	}	public static int[] mergeSort(int[] arr, int lo, int hi) {		if (lo == hi) {			int[] br = new int[1];			br[0] = arr[lo];			return br;		}		int mid = (lo + hi) / 2;		int[] fh = mergeSort(arr, lo, mid);		int[] sh = mergeSort(arr, mid + 1, hi);		int[] merged = mergeTwoSortedArrays(fh, sh);		return merged;	}}

16.用Java创建字符金字塔吗? (16. Create a Pyramid of Characters in Java?)

Pattern programs are used a lot in interviews to understand the logical thinking abilities of the interviewee. Pyramid patterns are very popular and once we get the logic on the way it’s created, writing code to achieve the same is an easy task.

访谈中经常使用模式程序来了解受访者的逻辑思维能力。 金字塔模式非常流行,一旦我们了解了创建方式的逻辑,编写代码即可实现这一目标很容易。

I have written an extensive post for different kind of pyramid patterns examples, read it .

我为各种不同的金字塔图案示例撰写了广泛的文章,请在阅读。

17.检查两个数组是否包含相同的元素? (17. Check if two arrays contains same elements?)

We will first create a set of elements from both the arrays. Then compare the elements in these sets to find if there is an element that is not present in both the sets?

我们将首先从这两个数组创建一组元素。 然后比较这些集合中的元素以查找两个集合中都不存在的元素?

package com.journaldev.programminginterviews;import java.util.Arrays;import java.util.HashSet;import java.util.Set;public class ArraySameElements {	public static void main(String[] args) {		Integer[] a1 = {1,2,3,2,1};		Integer[] a2 = {1,2,3};		Integer[] a3 = {1,2,3,4};				System.out.println(sameElements(a1, a2));		System.out.println(sameElements(a1, a3));	}	static boolean sameElements(Object[] array1, Object[] array2) {		Set uniqueElements1 = new HashSet<>(Arrays.asList(array1));		Set uniqueElements2 = new HashSet<>(Arrays.asList(array2));				// if size is different, means there will be a mismatch		if(uniqueElements1.size() != uniqueElements2.size()) return false;				for(Object obj : uniqueElements1) {			// element not present in both?			if (!uniqueElements2.contains(obj)) return false;		}				return true;	}}

18.整数数组中所有元素的总和? (18. Sum of all elements in integer array?)

It’s a very simple program. We can use for loop to iterate over the array elements and add them to get the final sum.

这是一个非常简单的程序。 我们可以使用for循环遍历数组元素并将其相加以获得最终总和。

int[] array = { 1, 2, 3, 4, 5 };int sum = 0;for (int i : array)	sum += i;System.out.println(sum);

19.查找数组中的第二大数字吗? (19. Find second largest number in an array?)

There are many ways to solve this problem. We can sort the array in natural ascending order and take the second last value. But, sorting is an expensive operation.

有很多方法可以解决此问题。 我们可以按自然升序对数组进行排序,并取倒数第二个值。 但是,分类是一项昂贵的操作。

We can also use two variables to find the second largest value in a single iteration.

我们还可以使用两个变量在一次迭代中找到第二个最大值。

private static int findSecondHighest(int[] array) {	int highest = Integer.MIN_VALUE;	int secondHighest = Integer.MIN_VALUE;	for (int i : array) {		if (i > highest) {			secondHighest = highest;			highest = i;		} else if (i > secondHighest) {			secondHighest = i;		}	}	return secondHighest;}

20.如何用Java随机播放数组? (20. How to Shuffle an Array in Java?)

We can use Random class to generate random index numbers and shuffle the elements.

我们可以使用Random类来生成随机索引号并改组元素。

int[] array = { 1, 2, 3, 4, 5, 6, 7 };Random rand = new Random();for (int i = 0; i < array.length; i++) {	int randomIndexToSwap = rand.nextInt(array.length);	int temp = array[randomIndexToSwap];	array[randomIndexToSwap] = array[i];	array[i] = temp;}System.out.println(Arrays.toString(array));

We can run the shuffling code inside another for loop to shuffle multiple rounds.

我们可以在另一个for循环中运行改组代码以改组多个回合。

21.如何查找文本文件中是否存在字符串? (21. How to find if a string is present in a text file?)

We can use Scanner class to read the file contents line by line. Then use String contains() method to check if the string is present in the file or not.

我们可以使用Scanner类逐行读取文件内容。 然后使用String contains()方法检查文件中是否存在该字符串。

boolean findStringInFile(String filePath, String str) throws FileNotFoundException {	File file = new File(filePath);	Scanner scanner = new Scanner(file);	// read the file line by line	while (scanner.hasNextLine()) {		String line = scanner.nextLine();		if (line.contains(str)) {			scanner.close();			return true;		}	}	scanner.close();	return false;}

The above code assumes that the string we are searching for in the file doesn’t contain newline characters.

上面的代码假定我们在文件中搜索的字符串不包含换行符。

22.如何以特定格式打印日期? (22. How to print date in specific format?)

We can use SimpleDateFormat class to get the date string into specific formatting.

我们可以使用SimpleDateFormat类将日期字符串转换为特定格式。

String pattern = "MM-dd-yyyy";SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);String date = simpleDateFormat.format(new Date());System.out.println(date); // 06-23-2020

Recommended Reading: .

推荐读物: 。

23.如何在Java中合并两个列表? (23. How to merge two lists in java?)

We can use the addAll() method to merge multiple lists in Java.

我们可以使用addAll()方法合并Java中的多个列表。

List
list1 = new ArrayList<>();list1.add("1");List
list2 = new ArrayList<>();list2.add("2");List
mergedList = new ArrayList<>(list1);mergedList.addAll(list2);System.out.println(mergedList); // [1, 2]

24.如何按值对HashMap排序? (24. How to Sort HashMap by values?)

HashMap is not an ordered collection. So, sorting its entries doesn’t make any sense. But, we can sort the entries based on value and store into LinkedHashMap. LinkedHashMap maintains the order of insertion.

HashMap不是有序集合。 因此,对条目进行排序没有任何意义。 但是,我们可以基于值对条目进行排序并将其存储到LinkedHashMap中。 LinkedHashMap保持插入顺序。

package com.journaldev.programminginterviews;import java.util.ArrayList;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.Set;public class SortHashMapByValue {	public static void main(String[] args) {		Map
scores = new HashMap<>(); scores.put("David", 95); scores.put("Jane", 80); scores.put("Mary", 97); scores.put("Lisa", 78); scores.put("Dino", 65); System.out.println(scores); scores = sortByValue(scores); System.out.println(scores); } private static Map
sortByValue(Map
scores) { Map
sortedByValue = new LinkedHashMap<>(); // get the entry set Set
> entrySet = scores.entrySet(); System.out.println(entrySet); // create a list since the set is unordered List
> entryList = new ArrayList<>(entrySet); System.out.println(entryList); // sort the list by value entryList.sort((x, y) -> x.getValue().compareTo(y.getValue())); System.out.println(entryList); // populate the new hash map for (Entry
e : entryList) sortedByValue.put(e.getKey(), e.getValue()); return sortedByValue; }}

25.从输入String中删除所有出现的给定字符? (25. remove all occurrences of a given character from input String?)

String class doesn’t have any method to remove characters. We can use the replace() method to create a new string without the given character.

字符串类没有任何删除字符的方法。 我们可以使用replace()方法创建一个不带给定字符的新字符串。

String str1 = "abcdABCDabcdABCD";		str1 = str1.replace("a", ""); System.out.println(str1); // bcdABCDbcdABCD

The string is immutable in Java. All the string manipulation methods return a new string. So, it’s necessary that we assign it to another variable.

该字符串在Java中是不可变的。 所有的字符串操作方法都返回一个新的字符串。 因此,有必要将其分配给另一个变量。

26.如何在字符串中获取不同的字符及其数量? (26. How to get distinct characters and their count in a String?)

We can create the character array from the string. Then iterate over it and create a HashMap with the character as key and their count as value.

我们可以从字符串创建字符数组。 然后对其进行迭代,并创建一个HashMap,将字符作为键,并将其计数作为值。

String str1 = "abcdABCDabcd";char[] chars = str1.toCharArray();Map
charsCount = new HashMap<>();for(char c : chars) { if(charsCount.containsKey(c)) { charsCount.put(c, charsCount.get(c)+1); }else charsCount.put(c, 1);}System.out.println(charsCount); // {a=2, A=1, b=2, B=1, c=2, C=1, d=2, D=1}

27.如何通过编程证明String是不可变的? (27. How to prove String is immutable programatically?)

String s1 = "Java"; // "Java" String created in pool and reference assigned to s1String s2 = s1; //s2 is also having the same reference to "Java" in the poolSystem.out.println(s1 == s2); // proof that s1 and s2 have same references1 = "Python"; //s1 value got changed above, so how String is immutable?//well, in the above case a new String "Python" got created in the pool//s1 is now referring to the new String in the pool //BUT, the original String "Java" is still unchanged and remains in the pool//s2 is still referring to the original String "Java" in the pool// proof that s1 and s2 have different referenceSystem.out.println(s1 == s2); System.out.println(s2); // prints "Java" supporting the fact that original String value is unchanged, hence String is immutable

28.编写一个程序来展示继承? (28. Write a Program to showcase inheritance?)

class Animal {	String color;}class Cat extends Animal {	void meuw(){		System.out.println("Meuw");	}}

29.编写一个程序来显示具有多重继承的钻石问题? (29. Write a Program to Show Diamond Problem with Multiple Inheritance?)

Java doesn’t allow extending multiple classes. It’s to keep it simple and avoid diamond problem.

Java不允许扩展多个类。 为了保持简单,避免出现钻石问题。

interface I {	void foo();}class A implements I{	public void foo() {}}class B implements I{	public void foo() {}}class C extends A, B { // won't compile	public void bar() {		super.foo();	}}

In above example, if Java would have allowed multiple class inheritance, then which super foo() method should get called? There could be a mechanism to fix this, but Java language developers thought it’s better to keep it simple by not allowing multiple inheritance.

在上面的示例中,如果Java将允许多个类继承,那么应该调用哪个super foo()方法? 可能有一种机制可以解决此问题,但是Java语言开发人员认为最好通过不允许多重继承来保持简单。

30.编写一个程序来显示尝试捕获示例? (30. Write a Program to show try catch example?)

Let’s look at a simple try-catch block code.

让我们看一个简单的try-catch块代码。

try {	FileInputStream fis = new FileInputStream("test.txt");}catch(FileNotFoundException e) {	e.printStackTrace();}

From Java 7 onwards, We can also catch multiple exceptions in a single catch block. It’s useful when we have the same code in all the catch blocks.

从Java 7开始,我们还可以在单​​个catch块中捕获多个异常。 当我们在所有catch块中都有相同的代码时,这很有用。

public static void foo(int x) throws IllegalArgumentException, NullPointerException {	// some code}public static void main(String[] args) {	try {		foo(10);	} catch (IllegalArgumentException | NullPointerException e) {		System.out.println(e.getMessage());	}}

31.编写代码以显示NullPointerException (31. Write a code to show NullPointerException)

If we are calling a function on the “null”, it will throw NullPointerException.

如果我们在“ null”上调用一个函数,它将抛出NullPointerException。

public static void main(String[] args) {	printString(null, 3);	}static void printString(String s, int count){	for (int i = 0 ; i < count; i++) {		System.out.println(s.toUpperCase()); // Exception in thread "main" java.lang.NullPointerException	}}

That’s why it’s better to have null check in place for early validation.

这就是为什么最好设置null检查以进行早期验证的原因。

static void printString(String s, int count){	if(s == null) return;	for (int i = 0 ; i < count; i++) {		System.out.println(s.toUpperCase());	}}

We can also throw IllegalArgumentException based on the project requirements.

我们还可以根据项目要求抛出IllegalArgumentException

32.如何用Java创建记录? (32. How to Create a Record in Java?)

Records is a preview feature introduced in Java 14. Records allow us to create a POJO class with minimal code. It automatically generates hashCode(), equals(), getter methods, and toString() method code for the class. Records are final and implicitly extends java.lang.Record class.

Records是Java 14中引入的预览功能。Records使我们可以使用最少的代码来创建POJO类。 它会自动为该类生成hashCode(),equals(),getter方法和toString()方法代码。 记录是最终的,并且隐式扩展了java.lang.Record类。

import java.util.Map; public record EmpRecord(int id, String name, long salary, Map
addresses) {}

Read more at .

中的阅读更多内容。

33.如何用Java创建文本块? (33. How to create Text Blocks in Java?)

Java 13 added text blocks as a preview feature. We can create multiline strings using text blocks.

Java 13添加了文本块作为预览功能。 我们可以使用文本块创建多行字符串。

The multiline string has to be written inside a pair of triple-double quotes.

多行字符串必须写在一对三重双引号内。

String textBlock = """		Hi		Hello		Yes""";

It’s same as creating a string as “Hi\nHello\nYes”.

与创建字符串“ Hi \ nHello \ nYes”相同。

34.显示开关表达式和多标签case语句的示例 (34. Show example of switch expressions and multi-label case statements)

The switch expressions were added as a preview feature in Java 12. It became a standard feature in Java 14 release. The below examples show switch expressions as well as multi-label case statements.

开关表达式是在Java 12中作为预览功能添加的。它已成为Java 14发行版中的标准功能。 以下示例显示了开关表达式以及多标签case语句。

int choice = 2;int x = switch (choice) {case 1, 2, 3:	yield choice;default:	yield -1;};System.out.println("x = " + x); // x = 2

We can also use lambda expressions in switch expressions.

我们还可以在开关表达式中使用lambda表达式。

String day = "TH";String result = switch (day) {case "M", "W", "F" -> "MWF";case "T", "TH", "S" -> "TTS";default -> {	if (day.isEmpty())		yield "Please insert a valid day.";	else		yield "Looks like a Sunday.";}};System.out.println(result); // TTH

35.如何从命令行编译和运行Java类? (35. How to Compile and Run a Java Class from Command Line?)

Let’s say we have a class as below.

假设我们有一个如下的类。

public class Test {public static void main(String args[]) {		System.out.println("Hi");	}}

We can compile it using the following code.

我们可以使用以下代码对其进行编译。

javac Test.java

For running the class, we can run the following command.

为了运行该类,我们可以运行以下命令。

java Test

From the recent releases, java command will take care of compilation also if the class file is not present.

从最新发行版开始,如果没有类文件,java命令也将负责编译。

If the class is in a package com.journaldev, then it should be inside the folder com/journaldev. The command to compile and run will be as follows.

如果该类在com.journaldev包中,则它应该在com/journaldev文件夹中。 编译和运行命令如下。

java com/journaldev/Test.java

If our class requires some additional JARs to compile and run, we can use the -cp java option.

如果我们的类需要一些其他的JAR来编译和运行,则可以使用-cp java选项。

java -cp .:~/.m2/repository/log4j/log4j/1.2.17/log4j-1.2.17.jar  com/journaldev/Test.java

36.如何用Java创建枚举? (36. How to create Enum in Java?)

Let’s look at a simple Enum.

让我们看一个简单的枚举。

public enum ThreadStates {	START,	RUNNING,	WAITING,	DEAD;}

ThreadStates is the enum with fixed constants fields START, RUNNING, WAITING, and DEAD.

ThreadStates是具有固定常量字段START,RUNNING,WAITING和DEAD的枚举。

All Enum implicitly extends java.lang.Enum class and implements Serializable and Comparable interfaces.

所有Enum隐式扩展java.lang.Enum类,并实现Serializable和Comparable接口。

Enum can have methods also, read more at .

Enum也可以有方法,有关更多信息,请中的 。

37.如何使用forEach()方法? (37. How to use forEach() method?)

The forEach() method provides a shortcut to perform an action on all the elements of an iterable. Let’s say we have to iterate over the list elements and print it.

forEach()方法提供了对可迭代对象的所有元素执行操作的快捷方式。 假设我们必须遍历列表元素并进行打印。

List
list = new ArrayList<>();Iterator
it = list.iterator();while (it.hasNext()) { System.out.println(it.next());}

We can use forEach() method with lambda expression to reduce the code size.

我们可以使用带有lambda表达式的forEach()方法来减少代码大小。

List
list = new ArrayList<>();list.forEach(System.out::print);

38.用默认和静态方法编写一个接口? (38. Write an interface with default and static method?)

Java 8 introduced default and static methods in interfaces. This has bridged the gap between interfaces and abstract classes.

Java 8在接口中引入了默认方法和静态方法。 这弥合了接口和抽象类之间的鸿沟。

public interface Interface1 {		// regular abstract method	void method1(String str);		default void log(String str){		System.out.println("I1 logging::"+str);	}		static boolean isNull(String str) {		System.out.println("Interface Null Check");		return str == null ? true : "".equals(str) ? true : false;	}}

Read more at .

在了解更多信息。

39.我们如何创建功能界面? (39. How do we create a Functional interface?)

An interface with exactly one abstract method is called Functional Interface. @FunctionalInterface annotation is added so that we can mark an interface as functional interface.

具有唯一一种抽象方法的接口称为功能接口。 添加了@FunctionalInterface批注,以便我们可以将接口标记为功能接口。

The major benefit of java 8 functional interfaces is that we can use lambda expressions to instantiate them and avoid using bulky anonymous class implementation.

Java 8功能接口的主要好处是我们可以使用lambda表达式实例化它们,并避免使用笨重的匿名类实现。

@FunctionalInterfaceinterface Foo {	void test();}

Further Reading: .

进一步阅读: 。

40.显示在Java中使用lambda表达式的示例 (40. Show an example of using lambda expressions in Java)

Runnable is an excellent example of a functional interface. We can use lambda expressions to create a runnable.

Runnable是功能界面的一个很好的例子。 我们可以使用lambda表达式创建可运行对象。

Runnable r1 = () -> System.out.println("My Runnable");

You can learn everything about lambda expressions in .

您可以在学习有关lambda表达式的所有信息。

41.显示Java重载和重写的示例 (41. Show examples of overloading and overriding in Java)

When a class have two or more methods with the same name, they are called overloaded methods.

当一个类具有两个或更多个同名的方法时,它们称为重载方法。

class Foo {	void print(String s) {		System.out.println(s);	}	void print(String s, int count) {		while (count > 0) {			System.out.println(s);			count--;		}	}}

Recommended Reading: .

推荐读物: 。

When a superclass method is also implemented in the child class, it’s a case of overriding.

如果在子类中也实现了超类方法,则这是重载的情况。

class Base {	void printName(){		System.out.println("Base Class");	}}class Child extends Base{	@Override	void printName(){		System.out.println("Child Class");	}}

Recommend Readings: and .

推荐读物: 以及 。

42-49。 猜测代码段的输出 (42-49. Guess the Output of Code Snippets)

Let’s look at 8 code snippets and guess their output.

让我们看一下8个代码段并猜测它们的输出。

  1. String s1 = "abc";String s2 = "abc";System.out.println("s1 == s2 is:" + s1 == s2);

    Output: false

    Explanation: The given statements output will be “false” because in java + operator precedence is more than == operator. So the given expression will be evaluated to “s1 == s2 is:abc” == “abc” i.e false.

    输出:假

    说明:给定的语句输出将为“ false”,因为在Java +运算符中,优先级大于==运算符。 因此,给定的表达式将被评估为“ s1 == s2 is:abc” ==“ abc”,即false。

  2. String s3 = "JournalDev";int start = 1;char end = 5;System.out.println(start + end);System.out.println(s3.substring(start, end));

    Output: ourn

    Explanation: The given statements output will be “ourn”. First character will be automatically type caste to int. After that since in java first character index is 0, so it will start from ‘o’ and print till ‘n’. Note that in String substring function it leaves the end index.

    输出:ourn

    说明:给定的语句输出将为“ ourn”。 第一个字符将自动将等级转换为int。 之后,由于在Java中第一个字符索引为0,因此它将从“ o”开始并打印到“ n”。 请注意,在String子字符串函数中,它保留结束索引。

  3. HashSet shortSet = new HashSet();for (short i = 0; i < 100; i++) {	shortSet.add(i);	shortSet.remove(i - 1);}System.out.println(shortSet.size());

    Output: 100

    Explanation: The size of the shortSet will be 100. Java Autoboxing feature has been introduced in JDK 5, so while adding the short to HashSet<Short> it will automatically convert it to Short object. Now “i-1” will be converted to an int while evaluation and after that it will autoboxed to Integer object but there is no Integer object in the HashSet, so it will not remove anything from the HashSet and finally its size will be 100.

    输出:100

    说明:shortSet的大小将为100。JDK 5中引入了Java自动装箱功能,因此,在将short添加到HashSet <Short>时,它将自动将其转换为Short对象。 现在,“ i-1”将在求值时转换为int,然后将其自动装箱为Integer对象,但HashSet中没有Integer对象,因此它将不会从HashSet中删除任何内容,最终其大小将为100。

  4. What will be the boolean “flag” value to reach the finally block?
    try {	if (flag) {		while (true) {		}	} else {		System.exit(1);	}} finally {	System.out.println("In Finally");}

    Explanation: The finally block will never be reached here. If flag will be TRUE, it will go into an infinite loop and if it’s false it’s exiting the JVM. So finally block will never be reached here.

    说明:在这里永远不会到达finally块。 如果flag为TRUE,它将进入无限循环,如果为false,则退出JVM。 因此,最终将永远无法到达这里。

  5. String str = null;String str1="abc";System.out.println(str1.equals("abc") | str.equals(null));

    Output: NullPointerException

    Explanation: The given print statement will throw java.lang.NullPointerException because while evaluating the OR logical operator it will first evaluate both the literals and since str is null, .equals() method will throw exception. Its always advisable to use short circuit logical operators i.e “||” and “&&” which evaluates the literals values from left and since the first literal will return true, it will skip the second literal evaluation.

    输出:NullPointerException

    说明:给定的print语句将引发java.lang.NullPointerException,因为在评估OR逻辑运算符时,它将首先评估两个文字,并且由于str为null,.equals()方法将引发异常。 始终建议使用短路逻辑运算符,即“ ||” 和“ &&”从左开始评估文字值,由于第一个文字将返回true,因此它将跳过第二个文字评估。

  6. String x = "abc";String y = "abc";x.concat(y);System.out.print(x);

    Output: abc

    Explanation: The x.concat(y) will create a new string but it’s not assigned to x, so the value of x is not changed.

    输出:abc

    说明:x.concat(y)将创建一个新字符串,但是未将其分配给x,因此x的值不会更改。

  7. public class MathTest {	public void main(String[] args) {				int x = 10*10-10;				System.out.println(x);	}}

    Output: Runtime error

    Explanation: This is a tricky question, it looks like the test is about the order of execution of the mathematical operators and will get overlooked. It will produce Runtime error because main method is not , something like below.

    public class MathTest {	public void main(String[] args) {				int x = 10*10-10;				System.out.println(x);	}}

    输出:运行时错误

    说明:这是一个棘手的问题,看起来测试似乎是关于数学运算符的执行顺序, 将被忽略。 由于main方法不是 ,因此将产生运行时错误,如下所示。

  8. public class Test {	public static void main(String[] args) {		try {			throw new IOException("Hello");		}catch(IOException | Exception e) {			System.out.println(e.getMessage());		}	}}

    Output: Compile-Time Error

    Explanation: It will be a compile time error as The exception IOException is already caught by the alternative Exception.

    输出:编译时错误

    说明:这将是一个编译时错误,因为替代Exception已捕获IOException异常。

UPDATE: Head over to some more .

更新:转到其他一些 。

50.在下面的代码片段中找到5个错误 (50. Find 5 mistakes in the following code snippet)

package com.journaldev.programming-interviews;public class String Programs {	static void main(String[10] args) {		String s = "abc"		System.out.println(s);	}}
  1. Package name can’t have hyphens.

    软件包名称不能带有连字符。
  2. Class name can’t have whitespaces.

    类名不能包含空格。
  3. The main method is not public, so it won’t run.

    主要方法不是公开的,因此不会运行。
  4. The main method argument shouldn’t specify the size.

    main方法参数不应指定大小。
  5. The semicolon is missing in the string definition.

    字符串定义中缺少分号。

结论 (Conclusion)

I have tried my best to include easy as well as slightly complex programming questions in this tutorial. Also, I have added code snippets and questions related to recent changes in the Java features.

我已尽力在本教程中包括一些简单的程序问题以及一些稍微复杂的编程问题。 另外,我还添加了代码片段和与Java功能的最新更改有关的问题。

翻译自:

java面试编程面试题

转载地址:http://zoozd.baihongyu.com/

你可能感兴趣的文章
精通ASP.NET Web程序测试
查看>>
vue 根据不同属性 设置背景
查看>>
51Nod1601 完全图的最小生成树计数 Trie Prufer编码
查看>>
Codeforces 1110D. Jongmah 动态规划
查看>>
android驱动在win10系统上安装的心酸历程
查看>>
优雅的程序员
查看>>
oracle之三 自动任务调度
查看>>
Android dex分包方案
查看>>
ThreadLocal为什么要用WeakReference
查看>>
删除本地文件
查看>>
FOC实现概述
查看>>
base64编码的图片字节流存入html页面中的显示
查看>>
这个大学时代的博客不在维护了,请移步到我的新博客
查看>>
GUI学习之二十一——QSlider、QScroll、QDial学习总结
查看>>
nginx反向代理docker registry报”blob upload unknown"解决办法
查看>>
gethostbyname与sockaddr_in的完美组合
查看>>
kibana的query string syntax 笔记
查看>>
旋转变换(一)旋转矩阵
查看>>
thinkphp3.2.3 bug集锦
查看>>
[BZOJ 4010] 菜肴制作
查看>>