Questions and answers for Java programmers

Source: Internet
Author: User

Some questions that are frequently asked during interviews with Java programmers on the Internet, although a little old, are still worth reading.

1. Let's talk about the differences between final, finally, and finalize.

Final? Modifier (keyword) If a class is declared as final, it means that it cannot generate a new subclass and cannot be inherited as a parent class. Therefore, a class cannot be declared both abstract and final. Declare variables or methods as final to ensure that they are not changed during use. Variables declared as final must be declared with an initial value, which can only be read and cannot be modified in future references. Methods declared as final can only be used, but cannot be used to reload finally? Finally blocks are provided for troubleshooting. If an exception is thrown, the matched catch clause is executed, and the control enters finally.
Block (if any ).

Finalize? Method Name. Java technology allows you to use the finalize () method to clear objects from the memory before the Garbage Collector clears them. This method is called by the garbage collector when it determines that this object is not referenced. It is defined in the object class, so all classes inherit it. Subclass overwrites the finalize () method to sort system resources or perform other cleanup tasks. The finalize () method is called before the Garbage Collector deletes an object.

2. Can anonymousinner class (anonymous internal class) be extends (inherited) other classes, or implements (implemented) interface (Interface )?

An anonymous internal class is an internal class without a name. It cannot be extends (inherited) other classes, but an internal class can be used as an interface and implemented by another internal class.

3. The difference between staticnested class and innerclass indicates that the more you speak, the better. (some of the questions are general ).

Nested class (generally C ++) and innerclass (generally Java ). The biggest difference between Java internal classes and C ++ Nested classes is whether there are external references. For details, see http: // www.frontfree.net/articles/services/view.asp? Id = 704 & page = 1

Note: The static internal class (innerclass) means 1 to create a static internal class object without an external Class Object. 2 to access an external class object from an object of a static internal class

4. The difference between & and.

& Is a bitwise operator. & Is a Boolean logical operator.

5. Differences between hashmap and hashtable.

All belong to the map interface class, which maps the unique key to a specific value.

The hashmap class is not classified or sorted. It allows a null key and multiple null values.

Hashtable is similar to hashmap, but does not allow null keys and null values. It is also slower than hashmap because it is synchronized.

6. Differences between collection and collections.

Collections is a Java. util class that contains various static methods related to set operations.

Collection is an interface under java. util. It is the parent interface of various collection structures.

7. When to use assert.

An assertion is a statement that contains a Boolean expression. When executing this statement, it is assumed that the expression is true. If the expression is calculated as false, the system reports an assertionerror. It is used for debugging purposes:

Assert (a> 0); // throws anassertionerror if a <= 0

There are two types of assertions:

Assertexpression1;

Assertexpression1: expression2;

Expression1 should always generate a Boolean value.

Expression2 can be any expression that generates a value. This value is used to generate a string message that displays more debugging information.

Assertions are disabled by default. To enable assertions during compilation, use the source 1.4 flag:

Javac-source 1.4 test. Java

To enable assertions at run time, you can use-enableassertions or-ea flag.

To disable assertions during running, use the-da or-disableassertions flag.

To enable assertions in the system class, you can use the-ESA or-DSA tag. You can also enable or disable Assertion Based on the package.

You can place assertions on any location that is not expected to arrive normally. Assertions can be used to verify parameters passed to private methods. However, assertions should not be used to verify the parameters passed to the public method, because public methods must check their parameters whether or not assertions are enabled. However, you can use assertions to test the post-condition either in a public method or in a non-public method. In addition, assertions should not change the state of the program in any way.

8. What is GC? Why does GC exist? (Basic ).

GC is the garbage collector. Java Programmers don't have to worry about memory management, because the Garbage Collector automatically manages. To request garbage collection, you can call one of the following methods:

System. GC ()

Runtime. getruntime (). GC ()

9, string S = newstring ("XYZ"); how many stringobjects are created?

Two objects, one being "xyx" and the other being referenced object s pointing to "xyx.

10. What is the value of math. Round (11.5? What is math. Round (-11.5) equal?

Math. Round (11.5) returns (long) 12, math. Round (-11.5) returns (long)-11;

11, short S1 = 1; S1 = S1 + 1; what is the error? Required S1 = 1; S1 + = 1; what is the error?

Short S1 = 1; S1 = S1 + 1; error: S1 is short type, S1 + 1 is int type, cannot be converted to short type explicitly. It can be changed to S1 = (short) (S1 + 1 ). Short S1 = 1; S1 + = 1 is correct.

12. What is the difference between sleep () and wait? Thread favorites

The sleep () method is used to stop a thread for a period of time. After the sleep interval expires, the thread may not resume execution immediately. This is because at that time, other threads may be running and not scheduled to give up the execution, unless (a) the "Awake" thread has a higher priority, (B) the running thread is blocked for other reasons.

When wait () is a thread interaction, if the thread sends a wait () call to a synchronization object X, the thread will pause the execution and the called object will enter the waiting state, wait until the wake-up or wait time is reached.

13. Does Java have a goto?

Goto? Reserved Words in Java, which are not currently used in Java.

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

15. Differences 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 different parameter types, it is called overloading ). The overloaded method can change the type of the returned value.

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

17. Give me the most common runtimeexception.

Arithmeticexception, arraystoreexception, except, failed, cannotredoexception, cannotundoexception, classcastexception, cmcmexception, concurrentmodificationexception, domexception, emptystackexception, failed, failed, illegalpathstateexception,
Illegalstateexception, imagingopexception, exceptions, missingresourceexception, exceptions, exceptions, nullpointerexception, profiledataexception, providerexception, rasterformatexception, securityexception, systemexception, expiration, unmodifiablesetexception, unsupportedoperationexception

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

19. Does list, set, and map inherit from the collection interface?

List, set is

Map is not

20. What is the difference between abstractclass and interface?

The class that declares a method rather than implementing it is called an 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 staticfinal 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.

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

None

22. Can an interface inherit the interface? Can an abstract class implement the (implements) interface? Can an abstract class inherit the concreteclass )?

Interfaces can inherit interfaces. Abstract classes can be implemented (implements) interfaces. abstract classes can inherit object classes, provided that the object classes must have clear constructors.

23. Do I use run () or start () 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.

24. Can constructor be overwritten?

Constructor cannot be inherited, so overriding cannot be overwritten, but overloading can be overloaded.

25. Can I inherit the string class?

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

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

27. 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 and executed before return.

28. Programming question: How can I calculate 2 by 8 in the most efficient way?

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

2 <3

29. The two objects have the same value (X. Equals (y) = true), but different hashcodes are available. Is this correct?

No. It has the same hash code.

30. After an object is passed as a parameter to a method, this method can change the attributes of this 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.

31. Can the switch function 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 act on the switch.

32. Programming question: Write a singleton.

The Singleton mode ensures that only one instance of a class exists in a Java application.

Generally, Singleton mode has several forms:

The first form: defines a class. Its constructor is private. It has a static private class variable and is instantiated during class initialization, use a public getinstance method to obtain its reference, and then call the method.

Publicclass Singleton {

Privatesingleton (){}

// Define your own instance internally. Isn't it strange?

// Note that this is private for internal calls only

Privatestatic Singleton instance = newsingleton ();

// Here is a static method for external access to this class, which can be accessed directly.

Publicstatic Singleton getinstance (){

Returninstance;

}

}

Second form:

Publicclass Singleton {

Privatestatic Singleton instance = NULL;

Publicstatic synchronized singletongetinstance (){

// 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 = newsingleton ();

Returninstance ;}

}

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.

33, hashtable and hashmap

Hashtable inherits from the dictionary class, while hashmap is an implementation of mapinterface introduced by java1.2. Hashmap allows null as the key or value of an entry, whereas hashtable does not. In addition, hashmap removes the hashtable contains method and changes it to containsvalue and containskey. The contains method is easy to misunderstand.

The biggest difference is that the hashtable method is synchronize, but hashmap is not. When multiple threads access hashtable, they do not need to implement synchronization for their own methods, hashmap must provide external synchronization for it.

The hash/rehash algorithms used by hashtable and hashmap are roughly the same, so there is no big difference in performance.

 

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.