preface

I was on a Tube recently, hoping to see how people were making fun of Donald Trump, when I accidentally clicked on a video of a foreigner interviewing for Java. I was so nervous that I decided to check it out.

After all, it is not professional background development, so I decided to step back from the background knowledge in the interview, so as to avoid insult.

However, in view of my outstanding hand speed, fast record of the Java foundation, so ready to contribute, for everyone to enjoy.

In view of the topic is more, will be divided into two parts to sort out, mainly facing the foundation of Java, look at the foreigners interview questions and we have what difference.

Of course the question was asked by the foreigner and the answer was made up by me.

The body of the

What allocated memory is available in Java

The Java virtual machine divides memory into different data areas during program execution

  • Method Area – Method Area
    • The Method Area, like the Java heap, is an Area of memory shared by all threads.
    • Although the Java Virtual Machine specification describes the method area as a logical part of the Heap, it has a separate name, non-heap, which is supposed to be separate from the Java Heap.
    • The Runtime Constant Pool is part of the method area. The Class file has the exception of classesVersion/field/method/interfaceIn addition to the Constant Pool Table, the Constant Pool Table is used to store various files generated during compilationLiteral and symbolic references, which stores the class in the runtime constant pool in the method area after loading. It is also possible to put new constants into the pool at run time, a feature that is often used by developersString.intern()Methods. Thrown when the constant pool can no longer be allocated to memory due to method area memory limitationsOutOfMemoryErrorThe exception.
    • The size of the method area, like the heap space, can be fixed or extensible. The size of the method area determines how many classes the system can hold. If the system has too many classes, the method area will overflow, and the VIRTUAL machine will throw memory overflow errors
    • The method area is freed when the JVM is shut down
  • Heap – Heap Area
    • For most applications, the Java heap is the largest chunk of memory managed by the Java Virtual machine and is shared by all threads. The sole purpose of this memory area is to hold object instances, and almost all object instances and data are allocated in memory here.
    • The Java Virtual Machine specification states that the Java heap can be inPhysically discontinuous memory space, as long as it is logically contiguous, like disk space. When implemented, bothIt can be fixed size or extensible, mainstream virtual machines are extensible (through-Xmx-XmsControl), thrown if no instance allocation has been completed in the heap and the heap can no longer be extendedOutOfMemoryErrorThe exception.
  • Stack – Stack Area
    • The stack is a fast and efficient way to allocate storage, second only to program counters in access speed
    • The JVM has only two direct operations on the virtual machine stack: each method executes, followed by a push (push/push), and the method execution terminates the stack
    • There is no garbage collection problem in the stack
  • Program Counter Register
    • It’s a small, almost negligible amount of memory. It is also the fastest storage area
    • In the JVM specification, each thread has its own program counter, which is thread-private and has a lifetime consistent with that of the thread
    • There is only one method executing per thread at any one time, which is called the current method. If the current thread is executing a Java method, the program counter records the ADDRESS of the JVM bytecode instruction, or undefined if the native method is executing.
    • It is an indicator of program control flow, and basic functions such as branching, looping, jumping, exception handling, thread recovery, and so on rely on this counter
    • The bytecode interpreter works by changing the value of this counter to select the next bytecode instruction to execute
    • It is the only one that does not specify anything in the JVM specificationOutOfMemoryErrorArea of the situation
  • Native Method Stack Area
    • The Java virtual machine stack is used to manage the invocation of Java methods, and the local method stack is used to manage the invocation of local methods
    • The local method stack is also thread-private
    • Allows threads to be fixed orDynamically expandable memory size
      • If a thread request allocates more stack capacity than the maximum allowed by the local method stack, the Java virtual machine will throw oneStackOverflowErrorabnormal
      • If the native method stack can be dynamically extended, and when trying to extendFailed to allocate enough memoryOr when creating a new threadNot enough memoryTo create the corresponding local method stack, the Java virtual machine will throw oneOutofMemoryErrorabnormal
    • And what it does isMative Method StackNative methods were registered in Execution EngineLoading a local method library at runtime When a thread calls a local method, it enters a new andA world free of virtual machines. It has the same rights as the VIRTUAL machine.
    • Not all JVMS support native methods. Because the Java virtual Machine specification does not specify the language, implementation, data structure, and so on of the native method stack. If the JVM product does not intend to support native methods, you may not need to implement a native method stack
    • In Hotspot JVM, the local method stack and virtual machine stack are combined directly

If I say static public void main, will it still run?

When I first saw this topic, I was confused. I had never seen such a question in the domestic interview, so I was still not sure, so I hurried to search.

Modifiers in Java appear in the same order as Oracle prescribes FieldModifier, which is the custom order that forms the specification. Not following this convention has no technical impact, but reduces the readability of your code because most developers are accustomed to standard order.

So the program becomes static public void main() and can also run.

Only method modifiers are listed below:

What are the default values in local variables?

Local variables are not initialized in Java.

public class staticFactory {
    public static void main(String[] args) {
        inttemp; System.out.println(temp); }}Error:(10, 28) Java: The temp variable may not have been initialized
Copy the code

If a static variable is not assigned, the default value is 0

public class staticFactory {
    static int temp;
    public static void main(String[] args) { System.out.println(temp); }}// Prints a value of 0
Copy the code

If it’s a member variable

public class staticFactory {
    public static void main(String[] args) {
        LocalVariables obj = new LocalVariables();
        System.out.println("a="+obj.a);
        System.out.println("b="+obj.b);
        System.out.println("c="+obj.c);
        System.out.println("d="+obj.d); }}class LocalVariables {
    int a;
    char b;
    float c;
    String d;
}
/* Result: a=0 int Default value 0 b="" char default value "" c=0.0 float default value 0.0 d=null String Default value null */
Copy the code

How do I copy constructors in Java

The copy constructor in Java is a constructor that uses one object of the class to construct another object.

How do I create copy constructors

// To create a copy constructor, first declare a parameter constructor of the same type as this class:
public class Employee {
    private int id;
    private String name; 

    public Employee(Employee employee) {}}Copy the code
// Each attribute of the parameter object is then copied to the new instance.
public class Employee {
    private int id;
    private String name;
    
    public Employee(Employee employee) {
        this.id = employee.id;
        this.name = employee.name; }}Copy the code

The above is a shallow copy.

The attributes defined above are primitive and immutable (int and String), so copying before use is fine.

However, if the class contains mutable types, deep copy is implemented through this constructor.

To implement deep copy, we need to construct a new instance from the original mutable object type.

public class Employee {
    private int id;
    private String name;
    private Date startDate;
 
    public Employee(Employee employee) {
        this.id = employee.id;
        this.name = employee.name;
        this.startDate = newDate(employee.startDate.getTime()); }}Copy the code

What is a tagged interface

A tag interface is an interface without any methods or attributes, which simply indicates that its class belongs to a particular type, allowing other code tests to do something. And the markup interface is not unique to the Java language, but a universal design concept in computer science.

The sole purpose of using the tag interface is to enable type queries with Instanceof, for example:

if (obj instanceofCloneable) {...... }Copy the code

In Java, there is a commonly used tag interface class

  • Java.io.Serializable: Classes that do not implement this interface will not be able to serialize or deserialize any of their state. To ensure consistency of the serialVersionUID value across different Java compiler implementations, the serialized class must declare an explicit serialVersionUID value.
  • Java.lang.cloneable: Indicates that the object.clone () method can legally copy instances of this class by field. Classes implementing this interface should override Object.clone (which is protected) using a public method. If does not implement the Cloneable interface Object instance call clone method, will lead to throw CloneNotSupportedException anomalies.
  • Java.util. RandomAccess: used to indicate that it supports fast (usually fixed time) RandomAccess. The main purpose of this interface is to allow generic algorithms to change their behavior to provide good performance when applied to random or continuous access lists.
  • Java.rmi. Remote: The Remote interface identifies the interface whose methods can be invoked from a non-local virtual machine. Any remote object must implement this interface either directly or indirectly. Only the methods specified in the “Remote Interface” (an interface that extends java.rmi.remote) are available remotely.

Why isn’t Java fully object-oriented

What is a pure object-oriented language in the first place?

A pure or fully object-oriented language is a fully object-oriented language that supports or has the ability to treat everything in a program as an object. It does not support primitive data types (such as int, CHAR, float, bool, etc.). A programming language that meets seven criteria can be called a pure object-oriented language. They are:

  1. Encapsulation/data hiding
  2. inheritance
  3. polymorphism
  4. abstract
  5. All predefined types are objects
  6. All user-defined types are objects
  7. All operations performed on an object must be performed only through the methods exposed by the object

Why isn’t Java a pure object-oriented language?

Java supports attributes 1, 2, 3, 4, and 6, but not the 5 and 7 shown above. The Java language is not a pure object-oriented language because it contains the following attributes:

Primitive data types such as objects:

Smalltalk is a “pure” object-oriented programming language, unlike Java and C++, because there is no difference between values as objects and values as primitive types. In Smalltalk, primitive values such as integers, Bools, and characters are also objects. In Java, we treat predefined types as non-objects (primitives).

int a = 5;  
System.out.print(a);
Copy the code

Static keyword:

When we declare a class static, we can use it without using objects in Java.

These two points explain why Java is not fully object-oriented.

Can you implement Pointers in Java programs

The Java virtual machine is implicitly responsible for memory management. The main motto of Java is to keep programming simple. Therefore, it is not recommended to access memory directly through Pointers. So, Pointers have been eliminated in Java, there are no Pointers in Java.

Explain the Java String pool

In the Java heap memory space, there is an area for the Java string pool. When a new string needs to be created, the JVM first checks to see if the object exists in the string pool. If so, the referenced object points to the variable, and if not, a new object is created.

Since String instance objects cannot be modified, “multiple String instance reference variables reference the same String instance object” does not pose any problems while saving Java heap memory.

Direct assignment

Use the new way

  • At this point, it returns true if S1 == S2 is equal because they point to the same value.
  • Return false if S3 == S4 is equal because they are comparing the addresses of S3 and S4.

What happens when the main() method doesn’t live static?

Public static void main(String [] args); public static void main(String [] args); If the method is not found, NoSuchMethodError is raised :main terminates. The main() method must strictly follow its syntax, its signature must be public static void, and its arguments must be of string array type.

Of course, there are other meanings:

  • Because the main() method is static, the JVM does not need to create any instances that contain the main() method to call it.
  • C and C++ have similar main() methods as entry points for program execution.
  • If the main() method is not declared static, the JVM must create an instance of the main() class because the constructor can be overloaded and the JVM cannot determine which main() method to call.
  • Static methods and static data can be called directly when loaded into memory rather than after instance methods are created. If the main() method is static, it is loaded into the JVM context as an executable method.

conclusion

As can be seen above, the bias of the interview of foreigners and we still have some differences, half of these questions are not often asked in our interview, so learn from each other.