Summary of wrong questions in Java special exercises

1. GC garbage collection mechanism

Error : In Java, for memory resources that are no longer used, such as methods that call completion, the "garbage collector" will automatically release them. ( )

When the method is called, a stack frame will be created on the stack, and the program will be automatically released from the stack after the call, instead of being released by gc.

JVM memory can be simply divided into three areas:
1. Heap area (heap): used to store all objects, shared by threads (Note: arrays also belong to objects)
2. Stack area (stack): used to store basic data types The data and object references are private to the thread (divided into: virtual machine stack and local method stack)
3. Method area (method): used to store class information, constants, static variables, compiled bytecode, etc. It is shared by threads (also known as non-heap, namely None-Heap)
Java's garbage collector (GC) is mainly for the heap area

insert image description here
1. New generation: (1) All objects are created in the Eden area of ​​the new generation. When the Eden area is full, the Minor GC of the new generation is triggered, and the surviving objects in the Eden area and the non-idle Survivor area are copied to another free Survivor area. . (2) To ensure that a Survivor area is empty, the new generation Minor GC is to copy surviving objects between the two Survivor areas until the Survivor area is full.
2. Old generation: When the Survivor area is full, the object is copied to the old generation through Minor GC. If the old generation is also full, Full GC will be triggered to perform garbage collection on the entire heap (including the new generation, old generation, and permanent generation).
3. Persistent generation: If the permanent generation is full, Full GC will be triggered.

2. Multithreaded start(), run()

public static void main(String args[]) {
    
    
    Thread t = new Thread() {
    
    
        public void run() {
    
    
            pong();
        }
    };
    t.run();
    System.out.print("ping");
}
static void pong() {
    
    
    System.out.print("pong");
}

When the output pongping
is on the 7th line, the t.run(); method is called, and the call to the run method is just a normal method call, so it must first execute pong() and then execute System.out.print("ping ");
If the 7th line is replaced by the t. Continue to execute, or the new thread may execute first.

3. null is a keyword, NULL is not a keyword, NULL can be used as an identifier

4. list.remove()

If a list is initialized as {5, 3, 1}, after executing the following code, the result is ()? [4, 3, 1, 6]
nums.add(6);
nums.add(0,4);
nums.remove(1);

nums.remove(1); Delete the element at index 1.
The list has two forms of remove(), one is to delete list.remove(index) according to the index, and the other is to delete list.remove(obj) according to the matching degree of the storage object.

Assume num has been created as an ArrayList object and initially contains the following integer values: [0, 0, 4, 2, 5, 0, 3, 0]. Execute the following method numQuest(), what is the final output?

private List<Integer> nums;

//precondition: nums.size() > 0
//nums contains Integer objects
public void numQuest() {
    
    
int k = 0;
Integer zero = new Integer(0);
while (k < nums.size()) {
    
    
	if (nums.get(k).equals(zero))
		nums.remove(k);
		k++;
	}
}

[0, 4, 2, 5, 3]
Note that deleting an element in this method will cause the subscript to change. After deleting an element, the subsequent element will adjust its position.

5. Five areas of JVM memory

insert image description hereinsert image description here

6. About byte variable operation

1. byte a1 = 2, a2 = 4, a3;
2. short s = 16;
3. a2 = s;
4. a3 = a1 * a2; 

If char, byte, and short are involved in operations in java, these values ​​will be automatically converted to int types and then operated. Here a1 and a2 are automatically converted to int type, and the result is also of type Int. Assigning an int type to byte requires conversion.

7. About the properties in the interface body

Which of the following field declarations is legal within the body of an interface? ()

private final static int answer = 42;
public static int answer = 42;
final static answer = 42;
int answer;

In the interface, the attributes are all modified by default public static final, so:
A (wrong): cannot be modified with private;
B (correct): in the interface, the attribute defaults to public static final, these three keywords can be omitted;
C (Error): The type of the attribute is not written;
D (Error): The attribute modified by final must be assigned a value;
the attribute in the interface does not belong to the object, but belongs to the class (interface), because the static modification is used by default.

8. & the &&

& is a non-short-circuit logical AND in a logical operation, and a bitwise AND
&& in a bit operation Logical operation: logical and

9. System.out.println(true ? false : true == true ? false : true);

output false.

true == true ? false : true is dead code (Dead Code)
I already know the answer, why execute it later?
insert image description here

10. Build package

If you want to create a java.scut.computer package,
you only need to add a "package java.scut.computer;" statement in the code, and it must be placed in the first line of the code

11. Literals and variables

int i = -5;
i = ++(i++);

The answer is a compilation error.
The compilation error of this question lies in this sentence: i = ++(i++);
++() must be a variable inside the brackets, and i ++ is a literal.

12. main

There can be multiple named main methods in a JAVA program. correct.
There can be multiple overloaded main methods in java, only public static void main(String[] args){} is the function entry

13. Array Subscript

The subscript of an array element in the java language always starts from 0, and the subscript can be an integer or an integer expression, correct.
for(int i=0;i<10;i++){ a[i+1]=a[i] } This i+1 is an integer expression.


14. Abnormal

The caught exception can not only be handled in the current method, but also can be thrown to the upper level method that called it for processing.

Compile-time exceptions must be handled explicitly, and runtime exceptions are handed over to the virtual machine.
Runtime exceptions may not be handled. When such an exception occurs, the virtual machine always takes over. For example, none of us has ever dealt with Null Pointer Exception, it is a runtime exception, and this exception is one of the most common exceptions. After a runtime exception occurs, the system will throw the exception to the upper layer until it encounters the processing code. If there is no processing block, go to the top layer, if it is multi-threaded, it will be thrown by Thread.run(), if it is single-threaded, it will be thrown by main(). After throwing, if it is a thread, the thread will also exit. If the exception is thrown by the main program, the entire program will exit. Runtime exception is a subclass of Exception, and it also has the characteristics of general exception, which can be handled by Catch block. It's just that it's often not dealt with. That is to say, if the runtime exception is not handled, then after the runtime exception occurs, either the thread is terminated or the main program is terminated.

15. javac.exe等

javac.exe is to compile.java file
java.exe is to execute the compiled class file
javadoc.exe is to generate Java documentation
jdb.exe is a Java debugger
javaprof.exe is a profiling tool

16. About exceptions

checked exception: Refers to compile-time exceptions. This type of exception needs to be handled by this function. Use try and catch to handle it, or use throws to throw an exception, and then hand it over to the caller to handle the exception.
runtime exception: Refers to the runtime exception, this type of exception does not have to be handled by this function, of course it can also be handled.
Both Thread.sleep() and Object.wait() can throw InterruptedException. This exception cannot be ignored because it is a checked exception

17. Expansion of ArrayList

The default array size of Arraylist is 10, and the size after expansion is 1.5 times that before expansion.
If the newly created collection has an initial value, the default is the size passed in, and the capacity will not be expanded.

18. About try-catch-finally

  1. Only try and report an error.
  2. try-catch, correct.
  3. try-finally, correct.
  4. try-catch-finally, correct.
public void test() {
    
    
	try {
    
    
		throw new NullPointerException();
	}finally {
    
    
		
	}
}

19. File class

The File class is a class that operates on the entire file or file attributes, such as creating a file, deleting a file, checking whether a file exists, etc., and cannot manipulate the file content; the file content is operated by IO stream.

20. Java has 5 ways to create objects:

Use the new keyword (most commonly used): ObjectName obj = new ObjectName();
use the newInstance() method of the Class class that uses reflection: ObjectName obj = ObjectName.class.newInstance();
use the newInstance() method of the Constructor class that reflects: ObjectName obj = ObjectName.class.getConstructor.newInstance();
Use object clone clone() method: ObjectName obj = obj.clone();
Use deserialization (ObjectInputStream) readObject() method: try (ObjectInputStream ois = new ObjectInputStream (new FileInputStream(FILE_NAME))) { ObjectName obj = ois. readObject(); }

21. Code blocks

public class B
{
    
    
    public static B t1 = new B();
    public static B t2 = new B();
    {
    
    
        System.out.println("构造块");
    }
    static
    {
    
    
        System.out.println("静态块");
    }
    public static void main(String[] args)
    {
    
    
        B t = new B();
    }
}

Building Blocks Building Blocks Static Blocks Building Blocks

22. return in try-catch

public boolean returnTest()
{
    
    
    try
    {
    
    
        return true;
    }
    catch (Exception e)
    {
    
    
 
    }
    finally
    {
    
    
        return false;
    }
}

output false

23. String final related

String StringBuffer are all modified by final. means that it cannot be inherited. Both are implemented by a character array, where the character array is modified by final, which means it cannot be modified.

String s = "asdf";
s = "qaz";

Cannot be modified does not mean that it cannot be reassigned.

24. ASCII

Space 32
characters 0 48
letters a 97
letters A 65

25. The subclass must explicitly call the superclass constructor

class Base{
    
    
    public Base(String s){
    
    
        System.out.print("B");
    }
}
public class Derived extends Base{
    
    
    public Derived (String s) {
    
    
        System.out.print("D");
    }
    public static void main(String[] args){
    
    
        new Derived("C");
    }
}

26. Static methods & static

public class Test
{
    
    
    public int x;
    public static void main(String []args)
    {
    
    
        System. out. println("Value is" + x);
    }
}

Non-static variables cannot be referenced by static methods

public class Test {
    
     
    public int aMethod(){
    
    
        static int i = 0;
        i++; 
        return i;
    } 
public static void main(String args[]){
    
    
    Test test = new Test(); 
    test.aMethod(); 
    int j = test.aMethod();
    System.out.println(j);
    } 
}

Compilation error, static variables in Java can only be defined in the class body, not in the method. Static variables are owned by the class and not by the method.

27. Implement inter-thread notification and wakeup

Object.wait/notify/notifyAll is the method Condition.await/signal/signalAll in the Object class
; Condition only appeared in java 1.5, and it is used to replace the traditional wait() and notify() of Object to realize inter-thread communication Collaboration, compared to using Object's wait() and notify(), it is safer and more efficient to use Condition's await() and signal() to achieve inter-thread collaboration.

28. Realize the conversion of GBK encoded byte stream to UTF-8 encoded byte stream:

The operation steps are to decode first and then encode.
Use new String(src,"GBK") to decode to get a string.
Use getBytes("UTF-8") to get UTF8 encoded byte array
byte[] src,dst;
dst=new String(src, "GBK").getBytes("UTF-8")

29. Static fields

public class B
{
    
    
    public static B t1 = new B();
    public static B t2 = new B();
    {
    
    
        System.out.println("构造块");
    }
    static
    {
    
    
        System.out.println("静态块");
    }
    public static void main(String[] args)
    {
    
    
        B t = new B();
    }
}

Output: Construction block construction block Static block construction block
It is not the static block that is initialized first, but the static field. (BM: Ah! What a painful realization!) The
static field contains static variables, static blocks and static methods, which require The initialization is a static variable and a static block. The initialization order of the two of them is determined by their positions!
So!
The initialization order is t1 t2 static block

30. Array copy related

Which of the following array copy methods in the java language is the most efficient?
Summary:
(1) In terms of speed: System.arraycopy > clone > Arrays.copyOf > for
(2) The reason why the speed of for is the slowest is that the subscript notation searches from the starting point to the specified subscript every time (Modern compilers should optimize it and change it to a pointer). In addition, it must judge whether the maximum length of the array is reached every time it loops, and perform an additional addition operation to record the subscript value.
(3) Looking at the source code of Arrays.copyOf, we can find that it actually calls System.arraycopy in essence. The reason why the time gap is relatively large is that a large part of the overhead is spent on the Math.min function.

Briefly talk about it:
System.arraycopy(): native method + JVM handwritten function, the fastest pre-written in JVM
clone(): native method, but not handwritten, requires JNI conversion, second in speed
Arrays.copyof() : The essence is to call the method of 1
for(): it is all deep copy, and it is not an encapsulation method, the slowest is justifiable

31. A variable of any data type can be assigned to a variable of Object type.

As the old saying goes, everything in Java is an object, and Object is the root class of all classes!

32. Inheritance

public class Demo {
    
    
  class Super {
    
    

    int flag = 1;

    Super() {
    
    
      test();
    }

    void test() {
    
    
      System.out.println("Super.test() flag=" + flag);
    }
  }
  class Sub extends Super {
    
    

    Sub(int i) {
    
    
      flag = i;
      System.out.println("Sub.Sub()flag=" + flag);
    }
    void test() {
    
    
      System.out.println("Sub.test()flag=" + flag);
    }
  }
  public static void main(String[] args) {
    
    
    new Demo().new Sub(5);
  }
}

Output:
Sub.test() flag=1
Sub.Sub() flag=5

33. import java.util.*

Can access all classes in the java/util directory, but cannot access all classes in the java/util subdirectory

34. Conversion rules for ternary operator types

1. If the two operands are not convertible, no conversion will be performed, and the return value will be Object type.
2. If the two operands are expressions of a clear type (such as variables), they will be converted according to normal binary numbers, int type conversion It is long type, long type is converted to float type, etc.
3. If one of the two operands is a number S and the other is an expression, and its type is marked as T, then if the number S is within the range of T, it will be converted to the T type; if S exceeds the T type range, T is converted to S type.
4. If both operands are literal numbers, the return value type is the one with a larger range

Object a = true ? new Boolean(false) : new Character('1').getClass(); // java.lang.Boolean
Object b = true ? new Byte((byte) 1) : new Character('1'); // java.lang.Integer
Object c = true ? new Byte((byte) 1) : new Short((short) 1); // java.lang.Short

byte b = 1;
char c = 1;
short s = 1;
int i = 1;

// 三目,一边为byte另一边为char,结果为int
// 其它情况结果为两边中范围大的。适用包装类型
i = true ? b : c; // int
b = true ? b : b; // byte
s = true ? b : s; // short

// 表达式,两边为byte,short,char,结果为int型
// 其它情况结果为两边中范围大的。适用包装类型
i = b + c; // int
i = b + b; // int
i = b + s; // int

// 当 a 为基本数据类型时,a += b,相当于 a = (a) (a + b)
// 当 a 为包装类型时, a += b 就是 a = a + b
b += s; // 没问题
c += i; // 没问题

// 常量任君搞,long以上不能越
b = (char) 1 + (short) 1 + (int) 1; // 没问题
// i = (long) 1 // 错误

35. Self comprehension

insert image description here

36. switch

The control expression after the switch statement can only be short, char, int integer type and enumeration type, not long, float, double and boolean type. The String type is supported by java7.
a. Basic type byte char short Reason: These basic digital types can be automatically converted to int, but actually int is still used.
b. Basic type packaging classes Byte, Short, Character, Integer Reason: Java’s automatic unboxing mechanism can see that these objects are automatically converted to basic types
c, String Type Reason: The string.hashCode value of the actual switch comparison is an int type
d. Reason for enum type: The actual comparison is the ordinal value of enum (indicating the order of enumeration values), which is also an int type, so it can also be said that the switch statement only supports int type

37. HashMap 与HashTable 、Map

HashMap implements the Map interface which allows any type of key and value objects and allows NULL to be used as key or value.
In Hashtable, neither Key nor Value can be null.

Hashtable:
(1) Hashtable is a hash table that stores key-value pairs (key-value) mappings.
(2) Hashtable functions are synchronized, which means it is thread-safe. Its key and value cannot be null.
(3) HashTable directly uses the hashCode of the object.
HashMap:
(1) Composed of array + linked list, it is implemented based on a hash table. The array is the main body of HashMap, and the linked list mainly exists to resolve hash conflicts.
(2) Not thread-safe, HashMap can accept null key (key) and value (value). Null can be used as a key, and there is only one such key; there can be one or more keys corresponding to null values
​​(3) HashMap recalculates the hash value
(4) HashMap instances have two parameters that affect their performance: "Initial capacity" and filling factor
(5) The key-value in HashMap is stored in Entry
(6) HashMap uses the zipper method to resolve hash conflicts.
The default size of the hash array in HashTable is 11, and the increase method is old*2+1 . The default size of the hash array in HashMap is 16, and it must be an index of 2

Hashtable, HashMap, Properties inheritance relationship is as follows:

public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, java.io.Serializable

public class HashMap<K,V>extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable  

The Properties class inherits the Hashtable class, and the Hashtable class inherits the Dictionary class

TreeMap is a class that implements the Map interface through a red-black tree. The key cannot be null, and a NullPointerException will be reported, and the value can be null.
insert image description hereinsert image description here

38. Flow

According to whether the flow is directly connected to a specific place (such as disk, memory, device, etc.), it is divided into two types: node flow and processing flow.

Node stream: data can be read and written from or to a specific place (node). Such as FileReader.
Processing stream: It is the connection and encapsulation of an existing stream, and the data is read and written through the function call of the encapsulated stream. Such as BufferedReader. The constructor for processing streams always takes another stream object as a parameter. A stream object has been wrapped multiple times by other streams, which is called a stream link.
Node streams commonly used in JAVA:

File FileInputStream FileOutputStream FileReader FileWriter Node stream for file processing.
String StringReader StringWriter A stream of nodes that process strings.
Array ByteArrayInputStream ByteArrayOutputStream CharArrayReader CharArrayWriter Node stream for processing arrays (corresponding to no longer a file, but an array in memory).
Pipeline PipedInputStream PipedOutputStream PipedReaderPipedWriter The node stream that processes the pipeline.
Common processing flow (closing the processing flow uses closing the node flow inside)

Buffered stream: BufferedInputStrean BufferedOutputStream BufferedReader BufferedWriter Add buffering function to avoid frequent reading and writing of hard disk.
Conversion stream: InputStreamReader OutputStreamReader realizes the conversion between byte stream and character stream.
Data stream DataInputStream DataOutputStream, etc. - provide basic data types to be written into the file, or read out. The
closing sequence of the stream
is generally: open first and then close, and then close first
Another case: see dependencies , if stream a depends on stream b, stream a should be closed first, and then stream b should be closed. For example, if processing flow a depends on node flow b, you should close processing flow a first, and then close node flow b. You
can only close the processing flow without closing the node flow. When the processing flow is closed, the closing method of the node flow it processes will be called.

39. Serialization

public class DataObject implements Serializable{
    
    
    private static int i=0;
    private String word=" ";
    public void setWord(String word){
    
    
        this.word=word;
    }
    public void setI(int i){
    
    
        Data0bject. i=I;
     }
}

DataObject object=new Data0bject ( );
object.setWord("123");
object.setI(2);
Serialize this object into a file, and read the file in another JVM for deserialization, what is the time The values ​​of word and i in the read Data0object object are respectively:
"123", 0

Serialization saves the state of the object, and static variables belong to the state of the class. Therefore, serialization does not save static variables. So i is unchanged.
Java will not instantiate static variables and variables modified by transient during serialization, because static represents the members of the class, and transient represents the temporary data of the object. It is declared that these two types of data members cannot be serialized

40. Transaction Concurrency and Consistency Issues

Non-repeatable read, dirty read, phantom read, lost modification
LeetBook

41. Lock

There are also links above

Guess you like

Origin blog.csdn.net/qq_43709785/article/details/119295305