java data collection box

In my spare time, I read some Java knowledge points, and summed it up by the way, just in case.

1. Does the array have a length() method?

No, only the length attribute, no parentheses.

2. Does String have a length() method?

have.

3. Is String the most basic data type?

No, it is a reference data type.

Analysis: The memory space model is like a small grid arranged together. The memory space address is like a small house with a house number.

Memory usage in the program:

int a=1;
Double b=2.2;
String s="abc";
String ss="abc";

 S does not store abc directly, but stores a value.

The String type belongs to indirect storage, the address is stored first, and the content is stored in the target address, which belongs to the reference data type, and the reference is the address.

Int generates storage, direct storage, and is a basic data type.

4. Can the constructor be overridden?

cannot.

5. Can there be memory leaks in Java?

There will be memory leaks in Java. Memory leaks mean that the memory will not be released after the requested memory is not used.

6. Describe the MVC framework?

Model View Controller, namely model (model) - view (view) - controller (controller).

7. What is the difference between int and Integer?

Int is a basic data type, and integer is a relative reference type, which can be converted into each other.

Analysis: basic data types: byte, short, int, long (integer type), float, double, char, boolean;

Reference types: except primitive data types and enumeration types.

8. When an object is passed as a parameter to a method, the method can change the properties of the object and return the changed result. So is it passing by value or by reference?

Pass by reference. However, it is controversial. Answering by value is also possible. It needs to be explained clearly according to the facts. The address is also a value, so answering by reference and value is both possible.

9. Links to Java learning materials:

    Java World

    Oracle Technology Network | Java SE Technical Documentation

   MOOC

   ImportNew

   Code farm network

   java123

   Java learning website Daquan

  Official Java Documentation Index

  11 Favorite Websites for Java Developers

  Summary of the most refined JAVA knowledge points in history

  Super complete tutorial for Java learners

  40 Java Collections Interview Questions and Answers

  Summary of 21 technical points and knowledge points of Java 

  Top 10 Java Questions on Stackoverflow

  Difference between Array and ArrayList in Java

  Summary of 40 Java multithreading problems

  Ten common mistakes Java programmers make

   20 Very Useful Java Program Snippets

   25 Java Machine Learning Tools & Libraries

   9 Must-Read Books for Java Programmers

   Summary of in-depth research on Java virtual machine architecture

   10 Subtle Java Coding Best Practices

   Summary of common problems in Java programming

10. Two frameworks: SSH, SSM

SSH=Spring+Struts+Hibernate。
SSM=Spring+SpringMVC+MyBatis。

11. List 6 commonly used packages in JAVA

   java.lang;java.util;java.io;java.sql;java.awt;java.net;javax.swing

12. Which classes in the JDK cannot be inherited?

Classes that cannot be inherited are those that are decorated with the final keyword.

Generally, basic types or types that prevent extended classes from inadvertently destroying the implementation of the original method should be final.

13. Is String the most basic data type?

Basic data types include byte, int, char, long, float, double, boolean, and short.

So String does not belong to the category of basic data types, but String belongs to the most common reference type.

14. short s1 = 1; s1 = s1 + 1; what's wrong? short s1 = 1; s1 += 1; what's wrong?

For short s1 = 1; s1 = s1 + 1; since the type of the expression is automatically promoted when s1+1 is operated, the result is an int type, and when it is assigned to the short type s1, the compiler will prompt an error and the type needs to be cast .

For short s1 = 1; s1 += 1; Since += is an operator stipulated by the java language, the Java compiler will treat it specially, so it can be compiled correctly.

[Analysis] It mainly examines the operation of several basic data types. It will be automatically converted from low to high, and it will be forced to convert from high to low.

15. Java object initialization order?

There are two types, one is the initialization of this class, and the other is the initialization sequence of the parent class.

Let's break it down here:

The initialization order of this class is: static variable, static initialization block, variable, initialization block, constructor

The initialization order of inherited classes is: parent class static variable, parent class static initialization block, subclass static variable, subclass static initialization block, parent class variable, parent class initialization block, parent class constructor, subclass variable, subclass initialization Block, subclass constructor.

Explanation: In principle, if the answer is comprehensive, it should be a complete description of the initialization process of this class with inheritance. The following steps can be referred to:

1. When loading the program, the first thing to find is its base (parent) class. If there are multiple layers of base (parent) classes, it will search up one level at a time and finally find the root base (parent) class.

2. Execute the static initialization in the root base (parent) class, then execute the static in the next derived class, and so on, keeping this order.

3. At this point, the class has been loaded and the object is created. All basic data types will be set to their default values, and the object handle will be set to null

4. Call the construction method of the base (parent) class, and the construction of the base (parent) class adopts the same process as the construction method of the derived class.

5. After the construction method is initialized, initialize the variables.

6. Execute the rest of the constructor.

16. Write a few thread-safe classes, unsafe, class names that support sorting?

ØThread safety classes: Vector, Hashtable, Stack.

Ø Thread-unsafe classes: ArrayList, Linkedlist, HashSet, TreeSet, HashMap, TreeMap, etc.

ØClasses that support sorting include HashSet, LinkedHashSet, TreeSet, etc. (all implementations under the Set interface support sorting)

[Analysis] This question mainly examines the knowledge of the collection framework. In the collection framework, the Collection interface is the root type of the collection and provides common API methods for collection operations. Two sub-interfaces are derived from this interface, one is the List interface that does not support sorting, and the other is the Set interface with its own sorting, so answer sorting Reply with and without sorting from the implementation of the two interfaces. In terms of thread safety, the Vector class is earlier than the ArrayList that also belongs to the List interface. It is a thread-safe class. An asynchronous ArrayList class was launched after JDK1.2, which is more efficient than the Vector class. Similarly, Stack inherits from Vector and is also a thread-safe class. In addition, the implementation of the Map interface is also a thread-safe class in Hashtable.

17. Which methods can implement a thread?

One is to inherit Thread and rewrite the method run method of the Thread class; the other is to implement the runnable interface and implement the run method.

[Analysis] Let me add about the run method of the thread. To start a thread in the multi-thread API is to call the start() method, and the thread enters the ready state.

18. Why are stop() and suspend() deprecated?

stop() because it is not safe. It will release all locks acquired by the thread. When the stop() method is called on a thread object, the thread running on the thread object will stop immediately. If a thread is executing: synchronized void { x = 3; y = 4;} Since the method is synchronized, multiple threads can always guarantee that x and y are assigned at the same time, and if a thread is executing until x = 3;, the stop() method is called, even in the synchronization block , it simply stops, thus producing incomplete and disabled data. The most basic condition in multi-threaded programming is to ensure the integrity of the data, so please forget the stop method of the thread, and we will never say "stop the thread" in the future. And if objects are in an incoherent state, then other threads can inspect and modify them in that state.

The suspend() method is prone to deadlock. When suspend() is called, the target thread will stop, but still hold the lock acquired before that. At this time, no other thread can access the locked resource unless the "suspended" thread resumes operation. For any thread, if they want to resume the target thread while trying to use any locked resource, it will cause a deadlock. So you should not use suspend(), but you should put a flag in your Thread class to indicate whether the thread should be active or suspended. If the flag indicates that the thread should be suspended, it is ordered to enter the waiting state with wait(). If the flag indicates that the thread should be resumed, the thread is restarted with a notify().

19. What is the difference between "==" and the equals method?

The == operator is specially used to compare whether the values ​​of two variables are equal, that is, to compare whether the values ​​stored in the memory corresponding to the variables are the same, to compare whether two basic types of data or two reference variables are equal, Only the == operator can be used.

If the data pointed to by a variable is of object type, then two blocks of memory are involved at this time, the object itself occupies a block of memory (heap memory), and the variable also occupies a block of memory, for example Objet obj = new Object(); variable obj is a Memory, new Object() is another memory. At this time, the value stored in the memory corresponding to the variable obj is the first address of the memory occupied by the object. For variables that point to object types, if you want to compare whether two variables point to the same object, that is, to see whether the values ​​​​in the memory corresponding to the two variables are equal, then you need to use the == operator to compare.

The equals method is used to compare whether the contents of two independent objects are the same, just like comparing the appearance of two people. The two objects it compares are independent. For example, for the code below:

String a=new String("foo");

String b=new String("foo");

The two new statements create two objects, and then use the two variables a and b to point to one of the objects respectively. These are two different objects, and their first addresses are different, that is, the values ​​​​stored in a and b are not the same, so the expression a==b will return false, and the contents of the two objects are the same, so the expression a.equals(b) will return true.

In actual development, we often have to compare whether the passed string content is equal, for example, String input =…;input.equals("quit"), if a class does not define its own equals method, then it will inherit the Object class The equals method, the implementation code of the equals method of the Object class is as follows:

boolean equals(Object o){

return this==o;

}

This shows that if a class does not define its own equals method, its default equals method (inherited from the Object class) is to use the == operator, which is also to compare whether the objects pointed to by two variables are the same object. At this time, use equals and Using == will get the same result, but will always return false if two separate objects are compared. If the class you write wants to be able to compare whether the contents of the two instance objects created by the class are the same, then you must override the equals method, and write your own code to determine under what circumstances you can consider the contents of the two objects to be the same.

20. What is the difference between static variables and instance variables?

The difference in grammatical definition: the static keyword should be added before the static variable, but not before the instance variable.

The difference when the program is running: the instance variable belongs to the attribute of an object, the instance object must be created, the instance variable in it will be allocated space, and the instance variable can be used. Static variables do not belong to an instance object, but belong to a class, so they are also called class variables. As long as the program loads the bytecode of the class, there is no need to create any instance object, the static variable will be allocated space, and the static variable can be used. In short, instance variables must be created before they can be used through this object, and static variables can be directly referenced using the class name.

For example, for the following program, no matter how many instance objects are created, only one staticVar variable is always allocated, and every time an instance object is created, this staticVar will be incremented by 1; however, every time an instance object is created, an instanceVar will be allocated , that is, it is possible to allocate multiple instanceVar, and the value of each instanceVar is only added once.

public class VariantTest

{

public static int staticVar = 0;

public int instanceVar = 0;

public VariantTest()

{

staticVar++;

instanceVar++;

System.out.println(“staticVar=”+ staticVar +”,instanceVar=”+ instanceVar);

}

}

Remarks: In addition to clearly explaining the difference between the two, this answer also uses a specific application example to illustrate the difference between the two at the end, which reflects that I have a good ability to explain problems and design cases, and my thinking is quicker than that of ordinary programmers. , have the ability to write!

21. Can the name of the constructor be the same as the name of the class?

The name of the constructor must be the same as the class name.

[Analysis] The constructor or constructor is mainly used to initialize the member variables of the class, and is called when the class creates an instance.

22. Can a non-static method be called in a main method class?

can be called. Because Java's main method (main) method itself is also a static type method, a static type method, there is no problem initiating a call to another static method.

[Analysis] Static methods can call other static methods, but they cannot call non-static methods. This is like the relationship between class variables and instance variables in Java. Class variables are shared by all class members, while instance variables are only shared by the instance.

23. Can there be two public methods in a class?

Can. There are no restrictions on the number of public methods in Java, but there are restrictions on public classes. Only one class of public type can be defined in a Java source file.

24. What is GC and why is it used?

       GC means garbage collection (Gabage Collection). Memory handling is a place where programmers are prone to problems. Forgotten or wrong memory recovery will lead to instability or even crash of the program or system. The GC function provided by Java can automatically monitor whether the object exceeds Scope, so as to achieve the purpose of automatically reclaiming memory, the Java language does not provide an explicit operation method to release the allocated memory.

25. Talk about the principle of garbage collection, can it be recycled directly from memory?

      A notable feature of the Java language is the introduction of a garbage collection mechanism, which solves the most troublesome memory management problem for C++ programmers. It makes Java programmers no longer need to consider memory management when writing programs. Garbage collection can effectively prevent memory leaks and effectively use available memory. The garbage collector usually runs as a separate low-level thread. Under unpredictable circumstances, it clears and recycles objects that have died or have not been used for a long time in the memory heap. Programmers cannot call the garbage collector in real time. Objects or all objects are garbage collected, because the Java Language Specification does not guarantee that GC will be executed. The recycling mechanism includes generational copy garbage collection, marked garbage collection, and incremental garbage collection.

26. What are the types of exceptions in Java, and what are the differences?

    There are two categories, general exceptions and runtime exceptions. General exceptions, these exceptions are declared and thrown when defining the method, these exceptions must be thrown with try catch, or throws processing, if not handled, the program will fail to compile. For example: IOException, FileNotFoundException, SQLException, etc.

Runtime exceptions are exceptions that may be reported while the program is running. You can use try catch to grab it, or you don't need to do any processing. For example: NullPointerException is a relatively common runtime exception.

27. Can the switch statement act on byte, can it act on long, can it act on String?

     In switch (expression), the parenthesis expression can only be an integer expression or enumeration constant (larger font), and the integer expression can be int basic type or Integer packaging type, because byte, short, char can all be Implicit conversion to int, so these types and wrapper types for these types are also possible. Obviously, the long and String types do not conform to the syntax of switch, and cannot be implicitly converted to int type, so they cannot be used in the swtich statement.

28. What is the difference between Integer and int?

Int is one of the 8 primitive data types provided by java. In addition, Java provides encapsulation classes for each primitive type, and Integer is the encapsulation class provided by java for int. The default value of int is 0, and the default value of Integer is null, that is, Integer can distinguish the difference between unassigned and 0, while int cannot express unassigned.

29. What is Java Reflection?

JAVA reflection, Reflection is one of the characteristics of the Java program development language, which allows the running Java program to check itself, or "self-examination", and can directly manipulate the internal properties of the program.

30. Write the method names in several java.lang.Object classes.

There are mainly equals(), toString(), getClass(), hashCode(), clone(), notify(), wait(), notify() methods.

31. What is the output of the following code?

public class Example {
    String str = new String("good");
    char[] ch = {'a', 'b', 'c'};

    public static void main(String args[]) {
        Example ex = new Example();
        ex.change(ex, ex.str, ex.ch);
        System.out.print(ex.str + " and ");
        System.out.print(ex.ch);
        System.out.println("\n" + ex.str);// 输出依然是good
    }

    public void change(Example ex, String str, char ch[]) {
        System.out.println("同一个对象?" + (str == ex.str));
        // 字符串的操作只能是整个替换,所以对外面没有影响
        str = "test ok";
        // 址传递,指向的是同一个对象,这里改变了方法外面跟着变
        ch[0] = 'g';
        // 把ex整个替换掉,对外面没有影响
        Example temp = new Example();
        temp.str = "你猜猜";
        ex = temp;
    }
}

As can be seen from the above code, the response is the value transfer and reference transfer in Java

The result of running the above code.

 

Guess you like

Origin blog.csdn.net/jianshou6442/article/details/81624577