Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit punch card activity, click to seeEvent details.
👨🎓 author: Java Academic Conference
🏦 Storage: Github, Gitee
✏️ blogs: CSDN, Nuggets, InfoQ, Cloud + Community
💌 public account: Java Academic Party
🚫 special statement: the original is not easy, shall not be reproduced or copied without authorization, if you need to reproduce can contact xiaobian authorization.
🙏 Copyright notice: part of the text or pictures in the article come from the Internet and Baidu Encyclopedia, if there is infringement, please contact xiaobian as soon as possible. Wechat search public Java academic party contact xiaobian.
☠️ Daily toxic chicken Soup: this society is unfair, do not complain, because it is useless! People always make progress in introspection!
👋 Hello! I am your old friend Java academic Party, it is the best time of the year to find a job, have you got the offer? Based on the requirements of most of the fans, let the small compilation sort out some interview questions, as long as the fans have demand, it must meet, from today I will continue to update the interview questions, which covers: Java foundation, multi-threading, IO, high concurrency, collection framework, database, framework and distributed technology. Updated continuously
32. Difference between int and Integer
Integer is the packaging type of int, which is automatically converted during unpacking and packing. Int is a basic type that stores values directly; And an INTEGER is an object, and you point to that object with a reference.
Because an Integer is an object, it requires a data structure to describe it in the JVM and takes up more memory than an int.
String s = new String(” ABC “) creates several String objects
One or two, if the constant pool already has “ABC”, create only one, otherwise create two
34. Are you familiar with intern() of String objects?
Intern () in String is a Native method that first looks for a String in the constant pool. If it doesn’t, it creates a String in the constant pool. Otherwise, it returns a reference to a String that already exists in the constant pool. Such as:
String s1="aa";
String s2=s1.intern();
System.out.print(s1==s2);
Copy the code
The above code returns true. Because “aa” is determined at compile time and placed in the JVM’s string constant pool, s1 and S2 end up referring to the same string constant object. See the comments for the intern method in String.
35. What are the common methods of String
- IndexOf () : returns the indexOf the specified character.
- CharAt () : Returns the character at the specified index.
- Replace () : string replacement.
- Trim () : Removes whitespace at both ends of a string.
- Split () : Split string, returns an array of split strings.
- GetBytes () : Returns a byte array of strings.
- Length () : Returns the length of the string.
- ToLowerCase () : converts the string toLowerCase.
- ToUpperCase () : converts the string toUpperCase letters.
- Substring () : intercepts characters.
- Equals () : String comparison.
36. What are the common methods of Files
- Files.exists() : checks whether a file path exists.
- Files.createfile () : Creates a file. Files.createdirectory () : Creates a folder.
- Files.delete() : Deletes a file or directory.
- Files.copy() : copies Files.
- Files.move() : moves a file.
- Files.size() : Displays the number of Files.
- Files.read() : Reads Files.
- Files.write() : writes Files.
37. Java IO vs. NIO
NIO stands for New IO, and this library was introduced in JDK1.4. NIO and IO have the same function and purpose, but the implementation method is different. NIO mainly uses blocks, so NIO is much more efficient than IO. Two sets of NIOS are provided in the Java API, one for standard INPUT and output NIO and the other for network programming NIO.
38. Talk about IO streams in Java
There are several types of IO flows in Java
- According to the flow direction, it can be divided into input flow and output flow.
- According to operation unit, it can be divided into byte stream and character stream.
- Flows are divided into node flows and processing flows according to their roles.
Java I/O flows involve more than 40 classes. These classes look messy but are actually very regular and closely related to each other. More than 40 classes of Java I/O flows are derived from the following four abstract base classes.
- InputStream/Reader: The base class for all input streams, which are byte input streams and character input streams.
- OutputStream/Writer: Base class for all output streams, byte output streams and character output streams.
39. Java reflection works
Definition 1.
The reflection mechanism is that, at runtime, all properties and methods of any given class are known; For any object, you can call any of its methods. In Java, given the name of a class, all information about the class can be obtained through reflection.
This ability to dynamically retrieve information and invoke methods on objects becomes the reflection mechanism of the Java language
2. Where is reflection used
JDBC is a typical reflection mechanism.
40. Weird interview questions
1. The first line
What does the following Java program print?
Public class Test {public static void main(String[] args){system.out.println (math.min (double.min_value, 0.0d)); }}Copy the code
Unlike integers, where MINVALUE is negative, Double’s MAXVALUE and MIN_VALUE are both positive numbers. MINVALUE is 2 ^ (-1074), a Double constant whose size is the smallest of all Double values. So, contrary to the obvious answer, this program will print 0.0 because double-.minvalue is greater than 0.
Public static final double MIN_VALUE = 0x0.0000000000001p-1022; / / 4.9 e-324Copy the code
Posed this question to Java developers with three to five years of experience, it was surprising that nearly 70% of the candidates got it wrong.
2. The name of the second
What happens if you place a return statement or system.exit () on a try or catch block? Will it end up blocking enforcement?
This is a very popular and tricky Java problem, and it’s tricky because many programmers think that the fiFinally block will always execute no matter what. This problem challenges this concept by placing a return statement in a try or catch block or calling system.exit () from a try or catch block. The answer to this tricky question in Java is that even if you put a return statement inside a try or catch block, the finally block will execute, but if you call system.exit () from a try or catch block, the last block will not run.
3. The third way
Can you override private live static methods in Java?
Method coverage is a great topic to address if you want to ask technical questions in Java. However, you cannot override private or static methods in Java, and if you create a similar method in a subclass with the same return type and the same method parameters, it will hide superclass methods, which is called method hiding. Similarly, you cannot override a private method in a subclass because it is not accessible there; what you do is create another private method in the subclass with the same name.
4. The fourth
What will the expression 1.0/0.0 return? Does he throw an exception? Any compile-time errors?
While Java developers are aware of Double primitive types and Double classes, they don’t pay enough attention to double-.infinity, NaN, and -0.0, among other rules, to control the arithmetic calculations involving them when doing floating-point operations. The simple answer to this problem is that it doesn’t throw ArithmeticExcpetion and return Double.INFINITY.
Also, note that even if x itself is NaN, comparing x == double-.nan is always evaluated to false. To test whether x isNaN, you should use the method call double.isnan (x) to check whether a given number isNaN. If you know SQL, it’s pretty close to NULL.
5. The fifth
Does Java support multiple inheritance?
If C ++ can support direct multiple inheritance, then why isn’t Java a parameter that Your Interviewer often gives you? The answer to this question is more subtle than it seems, because Java supports multiple inheritance of Type by allowing interfaces to extend other interfaces, where Java does not support multiple implementation inheritance. This distinction is blurred by the fact that Java 8’s default methods now provide for multiple behavioral inheritance in Java.
6. 6
What does the following Java program print
public class Test { public static void main(String[] args) throws Exception { char[] chars = new char[] {'\u0097'}; String str = new String(chars); byte[] bytes = str.getBytes(); System.out.println(Arrays.toString(bytes)); }}Copy the code
The crux of the problem is how character encoding and string-to-byte array conversions work. In this program, we first create a String from a character array, which has only one character ‘\ u0097’, then we get the byte array from the String and print the bytes. Since \ u0097 is within the 8-bit range of the basic byte type, it is reasonable to guess that the str.getBytes () call will return a byte array containing an element with a value of -105 ((byte) 0x97).
However, this is not program-printed, which is why the problem is tricky. In fact, the output of the program is operating system and loop dependent. On Windows XP with a US locale, the above program prints [63] and gets a different value if you run the program on Linux or Solaris.
To answer this question correctly, you need to understand how Unicode characters are represented in Java String values and Java strings, and the role of character encodings in String.getBytes().
In simple terms, converting a string to a byte array, Java iterates over all the characters represented by the string, converting each character into multiple bytes, and finally putting the bytes together. The rule that maps each Unicode character to a byte array is called character encoding. Therefore, if the same character encoding is not used during encoding and decoding, the retrieved value may be incorrect. When we call str.getBytes() without specifying a character encoding scheme, the JVM uses the platform’s default character encoding to get the job done.
The default encoding scheme is operating system and locale dependent. On Linux, it is UTF-8, with American locale on Windows, and the default encoding is Cp1252. This explains the output we get from running this program on a Windows machine with an American locale. Regardless of the character encoding scheme used, Java always converts Unicode characters whose encoding is not recognized to 63, which represents the character U + 003F in all encodings.
The seventh
What are the following problems with implementing the compareTo() method in Java
public int compareTo(Object o){ Employee emp = (Employee) o; //id is int return this.id -emp. id; }Copy the code
Where ID is an integer. Well, before you guarantee that ids are always heads, there’s nothing wrong with three of these Java problems. This Java problem becomes tricky when you can’t guarantee that the ID is positive or negative. The tricky part is that if the ID becomes negative, the subtraction may overflow and produce incorrect results.
Eighth,
How do you ensure that N threads can access N resources without deadlocks?
If you’re not familiar with writing multithreaded code, this can be a tricky problem for you. This Java problem is tricky even for experienced senior programmers who don’t really face deadlocks and race conditions. The key here is sorting, which prevents deadlocks if you acquire resources in a particular order and release them in the opposite order.
Consider the following Java code snippet, which initializes two variables and neither is volatile, and two threads, T1 and T2, are modifying these values, as shown below, both out of sync
int x = 0;
boolean bExit = false;
Thread 1 (not synchronized) x = 1;
bExit = true;
Thread 2 (not synchronized)
if (bExit == true)
System.out.println("x=" + x);
Copy the code
The answer to this question is yes, thread T2 might print x = 0. Why is that? Since there are no instructions to the compiler, such as synchronized or volatile, bExit = true may appear before x = 1 in the compiler’s reordering. Also, x =1 May not be visible in thread 2, so thread 2 will load x = 0. Now, how do you solve it?
When asked this question, several programmers responded differently, with one suggesting that two threads synchronize on a common mutex, and another saying that both variables are mutable. Both are true because it prevents reordering and guarantees visibility. But the best answer is you just need to make bExit volatile, and then thread 2 can only print “x = 1”. X need not be volatile, because when bExit is volatile, x cannot be reordered after bExit = true.
If you need all Java eight-part articles, click planet for free accessplanet(Github address) If you don’t have a Github partner. You can follow my wechat official account:Java academic lie prone, send the eight-part document, the first time to get all clearance eight-part document. Finally: I wish everyone can get a satisfactory offer, a bright future