Java interview questions, java questions

Source: Internet
Author: User

Java interview questions, java questions
1. simple principles and applications of the Exception Handling Mechanism in C ++ or Java. 
When a JAVA program violates the JAVA Semantic Rules, the JAVA Virtual Machine will indicate an error as an exception. There are two types of violation of Semantic Rules. One is the built-in semantic check of the JAVA class library. For example, if the array subscript is out of the range, IndexOutOfBoundsException is triggered. When a null object is accessed, NullPointerException is thrown. Another scenario is that JAVA allows programmers to extend this semantic check. programmers can create their own exceptions and choose when to use the throw keyword to cause exceptions. All exceptions are subclasses of java. lang. Thowable.
2. the similarities and differences between Java interfaces and C ++ virtual classes. 
Because Java does not support multi-inheritance, it is possible that a class or object must use methods or attributes in several classes or objects respectively. The existing single Inheritance Mechanism cannot meet the requirements. Compared with inheritance, interfaces are more flexible because they do not have any implementation code. After a class implements an interface, this class implements all the methods and attributes in the interface, and the attributes in the interface are under the default state are public static, and all methods are public by default. A class can implement multiple interfaces.
3. Advantages and principles of garbage collection. Two recovery mechanisms are also considered.
A notable feature of Java is the introduction of the garbage collection mechanism, which helps c ++ programmers solve the most troublesome memory management problems, it makes memory management unnecessary for Java programmers when writing programs. Because of the garbage collection mechanism, objects in Java do not have the concept of "Scope", and only objects can be referenced with "Scope ". Garbage collection can effectively prevent memory leakage and effectively use available memory. The garbage collector is usually used as a separate low-level thread to clear and recycle objects that have been killed in the memory heap or are not used for a long time, programmers cannot call the Garbage Collector to recycle an object or all objects in real time. The collection mechanism involves generational replication, garbage collection, marking, and incremental garbage collection.

4. Please state the thread synchronization method you know.

Wait (): puts a thread in the waiting state and releases the lock of the object it holds.
Sleep (): It is a static method that calls a running thread to capture InterruptedException exceptions.
Y (): Wake up a thread in the waiting state. Note that when this method is called, it cannot actually wake up a thread in the waiting state, instead, the JVM determines which thread to wake up, not by priority.
Allnotity (): Wake up all threads in the wait state. Note that it is not a lock for all wake-up threads but a lock for them to compete.
5. Describe the usage and functions of destructor and virtual functions. 
6. What is the difference between Error and Exception?
Error indicates system-level errors and exceptions that the program does not need to handle,
Exception indicates the exceptions that need to be captured or processed by the program.
7. In java, a class is declared as the final type. What does it mean? 
Indicates that the class cannot be inherited. It is a top-level class.
8. Describe your most common programming style.

9. What is the difference between heap and stack.

Stack is a linear set. The operations for adding and deleting elements should be completed in the same segment. The stack is processed as follows.
Heap is an element of stack.

10. If the system needs to use an extra large integer (beyond the long length range), Please design a Data Structure to store this super large number and design an algorithm to implement the extra large integer addition operation ).

public class BigInt() { int[] ArrOne = new ArrOne[1000]; String intString=""; public int[] Arr(String s) { intString = s; for(int i=0;i<ArrOne.leght;i++) {
11. If you want to design a graphic system, please design basic graphical components (Point, Line, Rectangle, Triangle) for simple implementation

First, let's talk about the differences between final, finally, and finalize.

Final is used to declare attributes. Methods and classes indicate that attributes are unchangeable, methods cannot be overwritten, and classes cannot be inherited. Finally is a part of the structure of the exception handling statement, indicating that it is always executed. Finalize is a method of the Object class. This method is called when the garbage collector is executed. It can overwrite this method to collect other resources during garbage collection, for example, close a file.

Second, can Anonymous Inner Class (Anonymous internal Class) be extends (inherited) other classes, or implements (implemented) interface (interface )?
It can inherit other classes or complete other interfaces. This method is often used in swing programming.

Third, the difference between Static Nested Class and Inner Class is that the more you say, the better (the more general the interview questions are ).

Static Nested Class is an internal Class declared as static. It can be instantiated without relying on external Class instances. In general, internal classes must be instantiated before they can be instantiated.

Fourth, the difference between & and.

& Is a bitwise operator that represents bitwise and OPERATION, & is a logical operator that represents logic and (and ).

Fifth, the difference between HashMap and Hashtable.
HashMap is a lightweight Implementation of Hashtable (non-thread-safe implementation). They all complete the Map interface. The main difference is that HashMap allows null key values ), because of non-thread security, the efficiency may be higher than that of Hashtable.

Sixth, the difference between Collection and Collections.

Collection is the upper-level interface of the Collection class. Its inherited interfaces include Set and List. collections is a help class for collection classes. It provides a series of static methods for searching, sorting, thread security, and other operations on various sets.

7. When to use assert.
1.4 new keywords (syntax) are used to test the boolean expression status and can be used to debug programs. If the expression is true, the following statement is executed. Otherwise, AssertionError is thrown. In addition, assert <boolean expression>: indicates that if the expression is true, the subsequent expression is ignored. Otherwise, the value of the subsequent expression is used as the construction parameter of AssertionError. Note that the-source 1.4 parameter must be added during compilation; otherwise, an error is returned.] Add the-ea parameter during running; otherwise, the assert row is ignored.

Eighth, what is GC? Why does GC exist?

GC is the meaning of garbage Collection (Gabage Collection). Memory Processing is a place where programmers are prone to problems. Forgetting or wrong memory Collection can lead to instability or even crash of programs or systems, the GC function provided by Java can automatically monitor whether the object exceeded the scope to automatically recycle the memory. the Java language does not provide a display operation to release the allocated memory.

Ninth, String s = new String ("xyz"); how many String objects are created?


10. How much is Math. round (11.5? Math. round (-11.5) and so on?
Math. round (11.5) = 12Math. round (-11.5) =-11round method returns a long integer closest to the parameter. After the parameter is added to 1/2, ask for its floor.

11th, short s1 = 1; s1 = s1 + 1; what is the error? Short s1 = 1; s1 + = 1; what is the error?

Short s1 = 1; s1 = s1 + 1; (s1 + 1 is an int type and requires forced conversion) short s1 = 1; s1 + = 1; (can be compiled correctly)

12th. What is the difference between sleep () and wait?
Sleep is a Thread method, which causes the Thread to suspend the execution for a specified time and give the execution opportunity to other threads. However, the monitoring status remains unchanged and will be automatically restored after the time. Calling sleep does not release the object lock. Wait is an Object-class method. Calling the wait method for this Object causes this thread to discard the Object lock and enter the waiting lock pool for this Object. Only the notify method (or notifyAll) is issued for this Object) then this thread enters the object lock pool and prepares to get the object lock and enters the running state.


Multithreading is used to synchronize multiple tasks, not to provide operation efficiency, but to improve system efficiency by improving resource usage efficiency. threads are implemented when multiple tasks need to be completed at the same time.

You can run the program at the same time, but the results of running the program are different even though they are running at the same time.

Because multithreading has one feature: randomness.

Cause: the CPU continuously switches to process various threads in an instant.

It can be understood that multiple threads are scrambling for cpu resources.


2. Comparison of threads and processes

A thread has many characteristics of a traditional Process. It is also known as a Light-Weight Process or a Process element;

The traditional Process is called a Heavy Process (Heavy-Weight Process), which is equivalent to a task with only one thread. In the operating system where threads are introduced, a process usually has several threads and requires at least one thread.


Differences between processes and threads:

1. The process has an independent process space, and the data storage space (heap space and stack space) in the process is independent.

2. The thread heap space is shared, the stack space is independent, and the resources consumed by the thread are smaller than those consumed by the process, which can affect each other.


13th. Does Java have a goto?

There are no 13 questions. If any interview asks this question, I suggest you stay away from the company.

14th, does the array have the length () method? Does String have the length () method?
The array does not have the length () method. It has the length attribute.
String has the length () method.

15th, the difference between Overload and Override. Can the Overloaded method change the type of the returned value?

Overriding and Overloading are different manifestations of Java polymorphism. Overriding is a manifestation of the polymorphism between the parent class and the Child class, and Overloading is a manifestation of the polymorphism in a class. If a subclass defines a method with the same name and parameter as its parent class, we say this method is overwritten ). When a subclass object uses this method, it calls the definition in the subclass. For it, the definition in the parent class is "blocked. If multiple methods with the same name are defined in a class, they may have different numbers of parameters or have different parameter types, it is called Overloading ). The Overloaded method can change the type of the returned value.

16th. The elements in the Set cannot be repeated. How can we identify whether the elements are repeated or not? Is = or equals () used ()? What are their differences?

The elements in the Set cannot be repeated, so the iterator () method is used to identify whether the elements are repeated or not. Equals () is used to determine whether two sets are equal.
The equals () and = Methods Determine whether the reference value points to the same object equals () is overwritten in the class, in order to return the true value when the content and type of the two separated objects match.

17th. Give me the most common runtime exception.

Refer to the following:

18th, what is the difference between error and exception?

Error indicates that recovery is not a serious problem that is impossible but difficult. For example, memory overflow. It is impossible to expect the program to handle such a situation.
Exception indicates a design or implementation problem. That is to say, it indicates that if the program runs normally, it will never happen.

19th, List, Set, and Map are inherited from the Collection interface?

List, Set is
Map is not

20th. What is the difference between abstract class and interface?

The class that declares a method rather than implementing it is called abstract class. It is used to create a class that reflects some basic behaviors and declare a method for this class, however, this class cannot be implemented in this class. You cannot create an abstract instance. However, you can create a variable whose type is an abstract class and point it to an instance of a specific subclass. Abstract constructors or abstract static methods are not allowed. The subclasses of Abstract classes provide implementation for all Abstract methods in their parent classes. Otherwise, they are also Abstract classes. Instead, implement this method in the subclass. Other classes that know their behavior can implement these methods in the class.
An interface is a variant of an abstract class. All methods in the interface are abstract. Multi-inheritance can be achieved by implementing such an interface. All methods in the interface are abstract, and none of them have a program body. The interface can only define static final member variables. The implementation of an interface is similar to that of a subclass, except that the implementation class cannot inherit behaviors from the interface definition. When a class implements a special interface, it defines (to be given by the program body) all the methods of this interface. Then, it can call the interface method on any object that implements the interface class. Because there is an abstract class, it allows the interface name as the type of the referenced variable. Normally, dynamic Association editing will take effect. The reference can be converted to the interface type or from the interface type. The instanceof operator can be used to determine whether the class of an object implements the interface.

21st can abstract methods be both static, native, and synchronized?

22nd. Can an interface inherit an interface? Can an abstract class implement the (implements) interface? Can an abstract class inherit a concrete class )?
Interfaces can inherit interfaces. Abstract classes can be implemented (implements) interfaces, and whether abstract classes can inherit object classes, provided that object classes must have clear constructors.

23rd. Is run () or start () used to start a thread ()?

When a thread is started, the start () method is called to make the virtual processor represented by the thread in a running state, which means that it can be scheduled and executed by JVM. This does not mean that the thread will run immediately. The run () method can generate the exit sign to stop a thread.

24th. Can Constructor be overwritten?

Constructor cannot be inherited, so Overriding cannot be overwritten, but Overloading can be overloaded.

25th. Can I inherit the String class?

The String class is a final class, so it cannot be inherited.

26th. After a thread enters a synchronized method of an object, can other threads access other methods of this object?
No. One synchronized Method of an object can only be accessed by one thread.

27th, there is a return statement in try {}, so will the code in finally {} following this try be executed? When will it be executed, before or after return?

Will be executed, before return.

28th. Programming question: how many equals 2x8 in the most efficient way?

Programmers with a C background are particularly fond of asking such questions.
2 <3

29th, the two objects have the same value (x. equals (y) = true), but different hash codes are available, right?

No. It has the same hash code.

30th. After an object is passed as a parameter to a method, this method can change the attributes of the object and return the changed result, so is it a value transfer or a reference transfer?
Is the value transfer. The Java programming language only transmits parameters by values. When an object instance is passed as a parameter to a method, the parameter value is a reference to the object. The object content can be changed in the called method, but the object reference will never change.

31st. Does swtich work on byte, long, and String?

In switch (expr1), expr1 is an integer expression. Therefore, the parameters passed to the switch and case statements should be int, short, char, or byte. Long and string cannot apply to swtich.

32nd programming question: Write a Singleton.

The Singleton mode ensures that only one instance of a Class exists in a Java application.
The Singleton mode generally has several forms:
The first form: defines a class. Its constructor is private. It has a static private class variable. When the class is initialized, use a public getInstance method to obtain its reference, and then call the method.

Public class Singleton {
Private Singleton (){}
// Define your own instance internally. Isn't it strange?
// Note that this is private for internal calls only
Private static Singleton instance = new Singleton ();
// Here is a static method for external access to this class, which can be accessed directly.
Public static Singleton getInstance (){
Return instance;

Second form:

Public class Singleton {
Private static Singleton instance = null;
Public static synchronized Singleton getInstance (){
// This method is better than above. You don't need to generate objects every time. It's just the first time.
// Generate instances during use, improving efficiency!
If (instance = null)
Instance = new Singleton ();
Return instance ;}
Other forms:
Defines a class. Its constructor is private and all methods are static.
It is generally considered that the first form is more secure.

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: 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.