Java Fundamentals 30 Q

Source: Internet
Author: User

Java Basics 30 Q 1. Object-oriented and process-oriented differentiation-oriented processes

Advantages: The performance is higher than object-oriented, because the class calls need to instantiate, the cost is relatively large, compared to consume resources, such as SCM, embedded development, Linux/unix and other general use of process-oriented development, performance is the most important factor.

Cons: no object-oriented easy to maintain, easy to reuse, easy to expand

Object oriented

Advantages: Easy to maintain, easy to reuse, easy to expand, due to the object-oriented packaging, inheritance, polymorphism characteristics, can design a low-coupling system, making the system more flexible and easier to maintain

Cons: performance is less than process-oriented

2. What are the features of the Java language?
    1. Simple and easy to learn;

    2. Object-oriented (encapsulation, inheritance, polymorphism);

    3. Platform Agnostic (the Java Virtual Machine realizes platform independence);

    4. Reliability

    5. Security

    6. Support Multithreading (c + + language does not have a built-in multithreading mechanism, so you must call the operating system multithreading capabilities for multithreaded programming, while the Java language provides multi-threaded support);

    7. Supports network programming and is convenient (the Java language itself is designed to simplify network programming, so the Java language not only supports network programming and is very convenient);

    8. Compilation and interpretation coexist;

3. What is a JDK? What is a JRE? What is a JVM? The connection and difference between the three

These are very basic things in Java, but I believe there must be a lot of people do not understand! Why is it? Because most of the time we're using out-of-the-box build tools and environments, we don't think about these things.

JDK: As the name implies, it's a development toolkit for developers, and it's for program developers. It includes a full JRE (Java Runtime Environment), a Java runtime environment, and other toolkits for developers to use.

JRE: Normal user and only need to install JRE (Java Runtime Environment) to run Java programs. The program developer must install the JDK to compile and debug the program.

JVM: When we run a program, the JVM is responsible for converting bytecode into specific machine code, and the JVM provides memory management/garbage collection and security mechanisms. This is independent of the hardware and operating system, which is why Java programs can write multiple executions at once.

Difference and Contact:

    1. JDK for development, JRE for running Java programs;

    2. The JVM is included in both the JDK and the JRE;

    3. The JVM is the core of the Java programming language and has platform independence.

4. What is a byte code? What are the biggest benefits of byte-code adoption? Let's look at the compilers and interpreters in Java:

The concept of virtual machines is introduced in Java, which is to add a layer of abstract virtual machines between the machine and the compiler program. This virtual machine provides a common interface to the compiler on any platform.

The compiler only needs to target the virtual machine, generate code that the virtual machine can understand, and then be executed by the interpreter to convert the virtual machine code to the machine code of the particular system. In Java, this code for the virtual machine is called 字节码 (that is .class , the file with the extension) and it is not intended for any particular processor, but only for virtual machines.

The interpreter for each platform is different, but the virtual machines that are implemented are the same. The Java source program is compiled by the compiler into bytecode, the bytecode is interpreted by the virtual machine, the virtual machine sends each byte code to be executed to the interpreter, the interpreter translates it into machine code on a particular machine, and then runs on a particular machine. This explains the coexistence of Java's compilation and interpretation.

Java source code----> Compiler---->JVM executable Java bytecode (i.e. virtual instructions)---->JVM---->JVM Interpreter-----> Machine executable binary machine code----> program runs.

The benefits of using byte codes:

In the way of bytecode, the Java language solves the problem of inefficient execution of traditional interpretive language in a certain degree, while preserving the portability of interpretive language. So Java programs run more efficiently, and because bytecode is not specific to a particular machine, Java programs can run on many different computers without recompiling.

5. The difference between Java and C + +

I know a lot of people have not learned C + +, but the interviewer is nothing like to take us Java and C + + than Ah! No way!!! Even if you have not learned C + +, write it down!

    • are object-oriented languages that support encapsulation, inheritance, and polymorphism

    • Java does not provide pointers to directly access memory, program memory is more secure

    • Java classes are single-inheritance, and C + + supports multiple inheritance, although Java classes are not multiple-inheritance, but interfaces can inherit more.

    • Java has an automatic memory management mechanism that does not require programmers to manually release useless memory

6. What is the main class of Java programs? What is the difference between the main class of the application and the applet?

There can be multiple classes in a program, but only one class is the main class. In a Java application, this main class refers to the class that contains the main () method. In the Java applet, the main class is a subclass that inherits from the system class JApplet or applets. The main class of the application does not necessarily require the public class, but the main class requirement for the applet must be the public class. The main class is the entry point for Java program execution.

7. What are the differences between Java applications and applets?

Simply put, the application starts from the main thread (that is, the main () method). Applet applets do not have the main method, mainly embedded in the browser page run (call the init () thread or run () to start), embedding the browser is similar to flash games.

8. Differences between character constants and string constants
    1. Form : A character constant is a single quote that is caused by a char string constant is a number of characters caused by double quotation marks

    2. meaning: A character constant is equivalent to an integer value (an ASCII value), which can participate in an expression-arithmetic string constant that represents an address value (the string is stored in memory)

    3. Memory Size: character constants account for only one byte string constant takes up a number of bytes (at least one character end flag)

9. Whether the constructor constructor can be override

When it comes to inheritance, we know that the private properties and construction methods of the parent class cannot be inherited, so constructor cannot be override, but can be overload, so you can see the case where there are multiple constructors in a class.

10. The difference between overloading and rewriting

overloading: occurs in the same class, the method name must be the same, the parameter type is different, the number is different, the order is different, the method return value and the access modifier can be different, occurs at compile time.

override: occurs in a parent-child class, the method name, the argument list must be the same, the return value range is less than or equal to the parent class, the range of exceptions thrown is less than the parent class, the access modifier scope is greater than or equal to the parent class, and if the parent method access modifier is private, the subclass cannot override the method.

One. Java object-oriented programming three main features: encapsulation, inheritance, polymorphic encapsulation

Encapsulation to privatize the properties of an object, while providing some of the methods that can be accessed by the outside world, if you do not want to be outside the method, we do not have to provide methods for external access. But if a class does not provide access to the outside world, then this class is meaningless.

Inherited

Inheritance is the technique of building a new class using the definition of an existing class, and the definition of a new class can add new data or new functionality, or it can use the functionality of the parent class, but not selectively inherit the parent class. By using inheritance we are able to reuse the previous code very easily.

Please remember the following 3 points about inheritance:

    1. Subclasses have properties and methods that are not private to the parent class.

    2. Subclasses can have their own properties and methods, that is, subclasses can extend the parent class.

    3. Subclasses can implement methods of the parent class in their own way. (Introduction later).

Polymorphic

The so-called polymorphism refers to the specific type of reference variable defined in the program and the method call issued by the reference variable is not determined during programming, but is determined during the program's run, that is, a reference to which the variable bottom will point to which class of the instance object, the reference variable emitted by the method call is the method implemented in the class, Must be determined by the time the program is running.

There are two forms in Java that can be polymorphic: inheritance (overriding of multiple subclasses to the same method) and interfaces (implementing interfaces and overwriting the same method in the interface).

What is the difference between string and StringBuffer, StringBuilder? Why is the string immutable?

Variability 

The string class uses a character array to hold strings, private final char value[], so the string object is immutable. Both StringBuilder and StringBuffer inherit from the Abstractstringbuilder class, and in Abstractstringbuilder are also saved with a character array, Char[]value, Both of these objects are mutable.

Thread Safety

The object in string is immutable and can be understood as constant, thread-safe. Abstractstringbuilder is the common parent of StringBuilder and StringBuffer, and defines some basic operations for strings, such as expandcapacity, append, insert, indexof, and other public methods. StringBuffer is thread-safe because it adds a synchronous lock to a method or a synchronous lock on a method that is called. StringBuilder does not have a synchronous lock on the method, so it is non-thread safe.

Performance

Each time a string type is changed, a new string object is generated, and the pointer is then pointed to the new string object. Instead of generating a new object and changing the object reference, StringBuffer will operate on the StringBuffer object itself every time. Using Stirngbuilder in the same situation can only achieve a performance gain of around 10%~15% compared to using StringBuffer, but at the risk of multi-threading insecurity.

for a summary of the three uses:

If you want to manipulate a small amount of data with the = string single-threaded operation string buffer, manipulate a large amount of data = StringBuilder multithreading operation string buffers to manipulate large amounts of data = StringBuffer

13. Automatic box packing and unpacking

Boxing : wrapping the base types with their corresponding reference types;

unpacking : Converting the wrapper type to the base data type;

14. Why is it illegal to invoke a non-static member within a static method?

Because static methods can be called without objects, other non-static variables cannot be called in a static method, and non-static variable members cannot be accessed.

15. Defining a construction method that does not work and has no parameters in Java

Before a Java program executes a subclass's construction method, if the parent class-specific constructor method is not invoked with super (), the "constructor without parameters" in the parent class is called. Therefore, if the parent class only defines the constructor method with parameters, and the constructor method in the subclass does not use super () to invoke a particular constructor method in the parent class, an error will occur at compile time because the Java program cannot find a constructor in the parent class that has no parameters to execute. The solution is to add a construction method that does not work and has no parameters in the parent class.

What is the difference between import Java and javax?

At first, the JAVAAPI required package was the Java start package, Javax was just an extension API package to use. Over time, however, Javax gradually expanded to become part of the Java API. However, moving the extension from the Javax package to the Java package will be too cumbersome and will eventually break a heap of existing code. Therefore, the final decision Javax package will become part of the standard API.

So, there's actually no difference between Java and javax. It's all a name.

17. What is the difference between an interface and an abstract class?
    1. The method of the interface is public by default, all methods cannot be implemented in the interface, abstract classes can have non-abstract methods

    2. The instance variable in the interface is the final type by default, and not necessarily in the abstract class.

    3. A class can implement multiple interfaces, but can only implement an abstract class at most

    4. When a class implements an interface, all methods of the interface are implemented, and abstract classes do not necessarily

    5. Interfaces cannot be instantiated with new, but can be declared, but must refer to an object that implements the interface from the design level, abstraction is the abstraction of a class, a template design, an interface is an abstraction of behavior, and a specification of behavior.

18. What is the difference between a member variable and a local variable?
    1. From the syntactic form, the member variable belongs to the class, while the local variable is the variable or the parameter of the method defined in the method, and the member variable can be modified by the modifier such as public,private,static, while the local variable cannot be modified by the access control modifier and static; Both the member variable and the local variable can be modified by the final;

    2. From the way variables are stored in memory, member variables are part of the object, and objects exist in heap memory, local variables exist in stack memory

    3. From the time the variable is in memory, the member variable is part of the object, it exists as the object is created, and the local variable disappears automatically as the method is called.

    4. If the member variable is not assigned an initial value, the value is automatically assigned as the default for the type (a member variable with the exception of the final decoration but not the static modifier must be assigned to the value), and the local variable is not automatically assigned.

19. What operators are used to create an object? What is the difference between an object entity and an object reference?

New operator, new creates an object instance (the object instance is in heap memory), and the object reference points to an object instance (the object reference resides in the stack memory). An object reference can point to 0 or 1 objects (a rope can be either a balloon or a balloon); An object can have n references to it (you can tie a balloon with n ropes).

20. What is the return value of a method? What is the function of the return value in the method of the class?

The return value of the method is the result of the execution of the code in the body of a method we have obtained! (provided that the method may produce a result). The function of the return value: To receive the result, so that it can be used for other operations!

21. What is the function of the construction method of a class? If a class does not declare the constructor method, can the program execute correctly? Why?

The main function is to complete the initialization of the class object. can be executed. Because a class can have a default constructor without arguments, even if there is no declaration of a constructor method.

22. What are the characteristics of the construction method?
    1. The name is the same as the class name;

    2. There is no return value, but the constructor cannot be declared with void;

    3. Automatically executes when an object of the class is generated, without calling it.

23. What is the difference between static and instance methods?
    1. When you call a static method externally, you can use the "class name. Method Name" way, or you can use the "object name. Method Name" way. The instance method is only in the following way. That is, calling a static method eliminates the need to create an object.

    2. When a static method accesses members of this class, it only allows access to static members (that is, static member variables and static methods), not to instance member variables and instance methods, and the instance method does not.

24. What is the difference between an object's equality and a reference to them?

objects are equal compared to whether the contents of the memory are equal and reference equality comparisons are whether the memory addresses they point to are equal.

25. A constructor method that does not have parameters is called before the subclass constructor is called, and the purpose is to do so?

Help subclasses do initialization work.

26. = = with equals (important)

= = : Its function is to determine whether the address of two objects is equal. That is, two objects are judged to be not the same object. (Basic data Type = = Compares values, reference data type = = Compares memory addresses)

equals () : Its function is also to determine whether two objects are equal. However, it is generally used in two different situations:

    • Scenario 1: The class does not overwrite the Equals () method. Comparing the two objects of the class with Equals () is equivalent to comparing the two objects by "= =".

    • Scenario 2: Class overrides the Equals () method. Generally, we all override the Equals () method to equal the contents of two objects, and if their contents are equal, return True (that is, the two objects are considered equal).

As an example:

  1. public class test1 {

  2.    public static void main(String[] args) {

  3.        String a = new String("ab"); // a 为一个引用

  4.        String b = new String("ab"); // b为另一个引用,对象的内容一样

  5.        String aa = "ab"; // 放在常量池中

  6.        String bb = "ab"; // 从常量池中查找

  7.        if (aa == bb) // true

  8.            System.out.println("aa==bb");

  9.        if (a == b) // false,非同一对象

  10.            System.out.println("a==b");

  11.        if (a.equals(b)) // true

  12.            System.out.println("aEQb");

  13.        if (42 == 42.0) { // true

  14.            System.out.println("true");

  15.        }

  16.    }

  17. }

Description

    • The Equals method in string is overridden because the Equals method of object is the memory address of the object being compared, and the Equals method of string compares the value of the object.

    • When creating an object of type string, the virtual opportunity looks in the constant pool for an object that already exists and has the same value to be created, and assigns it to the current reference if there is one. If not, recreate a string object in the constant pool.

Hashcode and equals (important)

The interviewer may ask you: "Have you rewritten hashcode and equals, why you must override the Hashcode method when you rewrite equals?" ”

Hashcode () Introduction

The function of Hashcode () is to obtain a hash code, also known as a hash code; it actually returns an int integer. The purpose of this hash code is to determine the index position of the object in the hash table. Hashcode () is defined in the Object.java of the JDK, which means that any class in Java contains a hashcode () function.

A hash table stores a key-value pair (Key-value), which is characterized by the ability to quickly retrieve the corresponding "value" according to the "key". This is the use of the hash code! (You can quickly find the object you want)

Why should there be hashcode

We use the example of "hashset How to check for repetition" to illustrate why there are hashcode:

When you add an object to HashSet, HashSet calculates the object's Hashcode value to determine where the object is joined, and also compares the hashcode values of the other objects that have been added, and if there is no corresponding hashcode, HashSet will assume that the object does not recur. However, if an object with the same hashcode value is found, then the Equals () method is called to check if the Hashcode equality object is actually the same. If the two are the same, HashSet will not let the join operation succeed. If it is different, it will be re-hashed to another location. (The Java Initiation Book "Head fist Java" Second edition). This allows us to significantly reduce the number of equals, thus greatly improving the execution speed.

Hashcode () and Equals () related provisions
    1. If two objects are equal, then hashcode must be the same

    2. Two objects are equal, and each of the two objects is called by the Equals method to return True

    3. Two objects have the same hashcode value, and they are not necessarily equal

    4. Therefore, the Equals method is overwritten, and the Hashcode method must also be overwritten

    5. The default behavior of Hashcode () is to create unique values on the objects on the heap. If Hashcode () is not overridden, the class's two objects are not equal in any way (even if the two objects point to the same data)

Value passing and reference passing in Java

value passing means that an object is passed by value, meaning that a copy of the object is passed, even if the copy is changed, and the source object is not affected. (Because when a value is passed, it is actually a copy of the value of the argument to the parameter.) )

reference passing means that an object is passed by reference, meaning that it is not the actual object, but the reference to the object. As a result, external changes to the referenced object are reflected on all objects. (because when a reference is passed, it is actually a copy of the address value of the argument to the parameter.) )

You can view this article for me in detail:

The most common Java face question summary-the first week of 29. Briefly describes the basic concepts of threading, procedures, and processes. And what is the relationship between them?

A thread is similar to a process, but a thread is a smaller execution unit than a process. A process can produce multiple threads during its execution. Unlike processes, where multiple threads share the same block of memory space and a set of system resources, the burden is much smaller than the process when the system is generating a thread or switching between threads, and because of this, the thread is also called a lightweight process.

A program is a file containing instructions and data that is stored in a disk or other data storage device, which means that the program is static code.

A process is a process of execution of a program and is the basic unit of the system's running program, so the process is dynamic. The system runs a program that is a process from creation, run to extinction. In a nutshell, a process is an executing program that executes in a single instruction on a computer, while each process also occupies certain system resources such as CPU time, memory space, files, files, input, and so on. In other words, when the program executes, it will be loaded into memory by the operating system. A thread is a smaller unit of work that the process divides into. The biggest difference between threads and processes is that the processes are essentially independent, while threads are not necessarily, because threads in the same process are highly likely to interact with each other. From another point of view, the process is the scope of the operating system, mainly in the same period of time, can execute more than one program, while the thread is in the same program almost simultaneously execute more than one program segment.

30. What are the basic statuses of threads? How are these states defined?
    1. NEW: A new Thread object was created.

    2. runnable: After the thread object is created, other threads (such as the main thread) call the object's start () method. The thread in this state is in a pool of running threads, waiting for the thread to be dispatched to get the CPU right.

    3. Run (running): The thread that can run the state (runnable) obtains the CPU time slice (TimeSlice) and executes the program code.

    4. Block: Blocking state refers to a thread that, for some reason, abandons the use of the CPU, letting the CPU TimeSlice and temporarily stop running. Until the thread enters the operational (runnable) state, there is a chance to get the CPU TimeSlice again to the run (running) state. There are three types of blocking: (i). Wait for blocking: the thread that runs (running) executes the o.wait () method, and the JVM puts the thread into the wait queue (the waitting queues). (b). Synchronous blocking: When a thread running (running) acquires a synchronization lock on an object, if the synchronization lock is occupied by another thread, the JVM puts the thread into the lock pool. (iii). Other blocking: The thread that runs (running) executes the thread.sleep (long ms) or T.join () method, or when an I/O request is made, the JVM will place the thread in a blocked state. When the sleep () state time-out join () waits for the thread to terminate or time out, or the I/O process finishes, the thread is re-transferred to the operational (runnable) state.

    5. death (Dead): The thread Run (), the main () method finishes executing, or the run () method exits because of an exception, the thread ends the life cycle. The thread of death cannot be resurrected again.

Note: You can use the early morning subway to describe the process:

Not up yet: sleeping

Get up and pack up, you can always take the subway departure: Runnable

Wait for the subway to: waiting

The subway is coming, but I have to line up. Metro: I/O blocking

On the subway, found that there is no seat: synchronized blocked

Seats found on the subway: Running

Arrival Destination: Dead

Java Fundamentals 30 Q

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.