Chinese Soft international Java written test questions

Source: Internet
Author: User
Tags throw exception

1, class loading There are several cases, how to load class

Answer:

Ways to load classes on virtual machines:

1, dog dog = new Dog ();
This action causes the constant pool to parse, and the dog class is implicitly loaded.
If the current ClassLoader cannot find the dog, the Noclassdeffounderror is thrown.

2, Class clazz = Class.forName ("Dog");
Object dog =clazz.newinstance ();
Load a type by reflection and create an object instance
If the dog cannot be found, the classnotfoundexception is thrown.

3, Class clazz = Classloader.loadclass ("Dog");
Object dog =clazz.newinstance ();
Load a type by reflection and create an object instance
If the dog cannot be found, the classnotfoundexception is thrown.

So what is the difference between 1 and 2 and 3? What are the conditions for each?

The class loaders used by 1 and 2 are the same and are the current class loaders. (ie: this.getClass.getClassLoader).
3 The class loader is specified by the user.

If you need to look for a class outside of the current classpath, you can only use the 3rd way. The 3rd way the class is loaded is a different namespace from the current class.
The current class loader namespace is not visible to it. Of course, if the superclass of the loaded class is visible to the current class namespace, you can make a forced transition.

The 1th and 2nd cases differ little. If the dog class is not available at compile time, the 2nd method is used.

In addition, the 1th and 2nd will cause the class to be initialized, that is, to execute static initialization statements for the class, and the 3rd case does not.
Also note that the 1th throws the error, the 2nd, 3 kinds of throw exception, they belong to different exception/fault branches.

-----------------------------

Object Instantiation Method:
1, new Dog ();
2, Clazz.newinstance (); or Clazz.getconstructor (... ). Newinstance (... );
3, Object.clone ();//Copy by local method
4. Deserialization

2. What are the runtime exceptions and compile-time exceptions?

Answer

Java exceptions can be divided into 3 types:

(1) Compile-time exception: Java.lang.Exception

(2) Run-time exception: Java.lang.RuntimeException

(3) Error: Java.lang.Error

Java.lang.Exception and Java.lang.Error inherit from Java.lang.Throwable;

Java.lang.RuntimeException inherits from Java.lang.Exception.

Compile-time Exception: The program is correct, but because the external environment conditions do not meet the trigger. For example: User error and I/O problem----program tries to open a remote socket port that does not exist. This is not a logic error for the program itself, but it is probably a remote machine name error (user spelling error). For commercial software systems, program developers must consider and address this issue. The Java compiler enforces the requirement to handle such exceptions, and if such exceptions are not caught, the program cannot be compiled.

Run-time exception: This means that there is a bug in the program, such as array out of bounds, 0 is removed, the entry parameter does not meet the specification ..... Such exceptions require a change of program to avoid, and the Java compiler enforces the requirement to handle such exceptions.

ClassCastException (class conversion exception)

Indexoutofboundsexception (array out of bounds)

NullPointerException (null pointer)

Arraystoreexception (data store exception, type inconsistency when manipulating arrays)

There are also bufferoverflowexception exceptions for IO operations

3. How can I make a subclass unable to inherit the method of the parent class

With final decoration

4. What are thread synchronization and thread Asynchrony, and how are threads implemented?

Thread-synchronous, asynchronous concepts

1) multithreaded concurrency, when multiple threads simultaneously request the same resource, it is inevitable that the data of this resource is not secure, a thread modifies the processing data of the B thread, and the B thread modifies the math of a thread processing. Obviously this is due to global resources, and sometimes in order to solve this problem, prioritize the use of local variables, fallback to use synchronous code block, for such a security consideration must sacrifice the system processing performance, plus in multi-threaded concurrency when the most intense resources, this implementation of thread synchronization mechanism

Synchronization: A thread to request a resource, but this resource is being used by the B thread, because the synchronization mechanism exists, a thread request is not, what to do, a thread can only wait to continue

Async: A thread wants to request a resource, but this resource is being used by a B thread because there is no synchronization mechanism present, a thread is still requested, a thread does not have to wait

Obviously, synchronization is the safest and most insured. and asynchronous insecure, easy to lead to deadlock, so that a thread dead will cause the entire process to crash, but there is no synchronization mechanism exists, performance will be improved

Implementing Multithreading in Java

1) inherit thread, rewrite the Run method inside

2) Implement Runnable interface

Doug Lea preferred the latter, first, Java does not have a single inheritance limit second, you can also isolate code

Thread pool

It is necessary to know that any resource creation, including threads, in a computer consumes system resources. In a Web service, the response to the Web server must be as fast as possible, and it is not necessary to create a thread service every time the user submits the request button. In order to reduce the waiting time of the user, the thread must be pre-created, put in the threads pool, and the thread pool can be implemented with Hashtable data structure, see the source code of Apach HTTP server's thread pool, use is hashtable,key with thread object, value Using controlrunnable,controlrunnable is the only thread in the thread pool that can work, and is the thread that it assigns to the thread pool to serve.

For security reasons, the thread pool of the Apach HTTP server is synchronized. I heard that WebLogic has asynchronous implementation, not studied, not sure

5, what is the business, talk about your understanding of the business

A transaction is a sequence of operations that accesses a database, and the database application system accesses the database through a transaction set.   The proper execution of a transaction causes the database to transition from one state to another state. Transactions must be subject to the ACID principles established by ISO/IEC. Acid is an abbreviated transaction of atomicity (atomicity), consistency (consistency), isolation (isolation), and persistence (durability) that must be subject to the acid principle established by ISO/IEC. Acid is an abbreviation for atomicity (atomicity), consistency (consistency), isolation (isolation), and persistence (durability).
    • Atomic Nature . That is, the transaction is either fully executed or not executed at all. If all the child transactions of a transaction are committed successfully, all database operations are committed, the database state is transformed, and if there is a child transaction failure, the database operations of the other child transactions are rolled back, that is, the database returns to the state before the transaction execution, and no state transitions occur.
    • consistency or can be strung . The execution of a transaction causes the database to transition from a correct state to another correct state.
    • isolation . Before a transaction is properly committed, it is not allowed to make any changes to the data to any other transaction, that is, before the transaction is committed correctly, its possible results should not be displayed to any other transaction.

Durability . After the transaction is committed correctly, the result is persisted in the database, and the transaction results are saved even if there are other failures after the transaction commits.

6. Tell me about your understanding of the set mechanism

You need to use a collection class when you don't know the number of data to store beforehand, or if you need a more flexible method than the array subscript access mechanism.



Understanding Collection Classes

The collection class is stored in the Java.util package.
The collection class holds the object's reference, not the object itself, and for the convenience of expression, we say that the object in the collection refers to the reference to the object in the collection (reference).
There are 3 main types of collections: Set (Set), list (listing), and map (map).
http://www.backboneitgroup.cn
(1) Set
Set (set) is the simplest collection of objects that are not sorted in a particular way, but simply add objects to the collection as if they were placed in a pocket.
Access to and operations on a centralized member are made through a reference to a centralized object, so the set cannot have duplicate objects.
The set also has multiple variants that can be implemented such as TreeSet, which adds objects to a set of actions that are inserted into an ordered sequence of objects according to a comparison rule. It implements the SortedSet interface, which is the method of adding object comparisons. By iterating over the objects in the set, we can get an ascending set of objects.

(2) List
The main feature of a list is that its objects are stored in a linear manner, without a specific order, with only one beginning and one end, and of course, it is different from a set that has no order at all.
The list is represented in the data structure as: array and vector, linked list, stack, queue.
The collection class for the implementation list is often used in our daily work and will be described in detail in the notes that are behind it.

(3) Mapping
Mappings differ significantly from sets or lists, and each item in the map is paired. Each object stored in the map has an associated keyword (key) object that determines where the object is stored in the map, and must be supplied with the corresponding keyword when retrieving the object, as if looking up a word in the dictionary. The keyword should be unique.
The keyword itself does not determine where the object is stored, it needs to be processed over a hashing (hashing) technique, producing an integer value called a hash code, which is usually used as a bias, relative to the starting position of the memory region assigned to the map. This determines where the keyword/object pair is stored. Ideally, hash processing should result in a uniformly distributed value within a given range, and each keyword should have a different hash code.

Introduction to collection Classes
Java.util There are 13 classes that can be used to manage collection objects, which support collections such as sets, lists, or mappings, and the following are brief descriptions of these classes

Set:
HashSet: The implementation of a set using HashMap. Although the set is defined as unordered, there must be some way to find an object fairly efficiently. Storage and retrieval operations that use an HashMap object implementation set are implemented in a fixed time period.
TreeSet: The implementation of a set that sorts objects in ascending order. This means that getting the first iterator from a TreeSet object will provide the object in ascending order. The TreeSet class uses a treemap.
List:
Vector: Implements an array-like table that automatically increases capacity to accommodate the elements you need. Using subscripts to store and retrieve objects is just like in a standard array. You can also use an iterator to retrieve objects from a vector. Vector is the only synchronization container class?? Performance is also good when two or more threads are accessed at the same time.
Stsck: This class derives from the vector and adds a method implementation stack?? A last-in-first-out storage structure.
LinkedList: Implement a linked list. A linked list defined by this class can also be used as a stack or as a queue.
ArrayList: Implements an array that is variable in size and can be accessed like a linked list. It provides the * * * to resemble a vector class but is out of sync.

Mapping:
HashTable: To implement an image, all keys must be non-empty. In order to work efficiently, the class defining the key must implement the Hashcode () method and the equal () method. This class is an inheritance of the previous Java implementation and is usually better used in other classes that implement the image.
HashMap: Implements an image that allows an empty object to be stored, and allows the key to be empty (since the key must be unique, of course there can be only one).
Weakhashmap: Implements such an image: Usually if a key is no longer referenced to an object, the key/object pair is discarded. This is in contrast to the HashMap, where the key in the image maintains the life cycle of the key/object pair, although the program using the image no longer has a reference to the key, and therefore cannot retrieve the object.
TreeMap: To implement such an image, the object is the key in ascending order.

Both set and list are extended by the public interface collection, so they can all be referenced using a variable of type collection. This means that any collection of lists or sets can be referenced in this way, except for the mapping class (but not completely excluded, because a list can be obtained from the map.) So, the standard way to pass a list or set to a method is to use the collection type parameter.

Vector or ArrayList, which one is better, why?
To answer this question can not be generalize, sometimes using vectors better, sometimes ArrayList, sometimes these two are not the best choice. You don't expect to get a simple affirmative answer, because it depends on what you do with them. Here are 4 things to consider:

(1) Api

(2) Synchronous processing

(3) Data growth

(4) Usage mode

Here are one by one discussions on these 4 areas

Api
This is described in the book "Java Programming Language" (Addison-wesley, June 2000), authored by Ken Arnold, which resembles the ArrayList. All of these two classes are very similar from the API point of view. But there are still some major differences between them.

Synchronization of

The vectors are synchronized. Some of the methods in this class ensure that the objects in the vector are thread-safe. The ArrayList is asynchronous, so objects in ArrayList are not thread-safe. Because the requirements of synchronization affect the efficiency of execution, it is a good choice to use ArrayList if you do not need a thread-safe collection, which avoids unnecessary performance overhead due to synchronization.

Data growth

From an internal implementation mechanism, both ArrayList and vectors use arrays to control the objects in the collection. When you add elements to both types, if the number of elements exceeds the current length of the internal array, they all need to extend the length of the internal array, and vector automatically grows the array length by default, ArrayList is the original 50%. So in the end you get this collection that takes up more space than you actually need. So if you're going to save a lot of data in a collection then there are some advantages to using vectors, because you can avoid unnecessary resource overhead by setting the initialization size of the collection.

Usage patterns

In ArrayList and vectors, it takes the same amount of time to find the data from a specified location (through an index) or to add or remove an element at the end of the collection, as shown in O (1). However, if an element is added or removed elsewhere in the collection, the time spent will grow linearly: O (n-i), where n represents the number of elements in the collection, and I represents the index position at which the element is incremented or removed. Why is that? It is assumed that all elements after the first and second elements of the collection will perform the operation of the displacement. What does all this mean?

This means that you just look for elements in a particular location or only add and remove elements at the end of the collection, so you can use either a vector or a ArrayList. If this is another operation, you might want to choose a different collection operation class. For example, the Linklist collection class takes the same amount of time to add or remove elements from any position in the collection as-O (1), but it is less slow to use an element in the index-O, Where I is the location of the index. It's also easy to use ArrayList because you can simply use an index instead of creating an iterator object. Linklist also creates objects for each inserted element, all of which you have to understand that it also brings additional overhead.

Finally, in the book Practical Java, Peter Haggar suggests using a simple array instead of a vector or ArrayList. This is especially true for programs with high efficiency requirements. Because the use of arrays (array) avoids synchronization, additional method calls, and unnecessary reallocation of space operations

7. Read the Code

public class A {

public int SayHello (int i) {
SYSTEM.OUT.PRINTLN (i + "is int");
return i;
}

Public Char SayHello (char i) {
SYSTEM.OUT.PRINTLN (i + "is char");
return i;
}

Public short SayHello (short i) {
SYSTEM.OUT.PRINTLN (i + "is short");
return i;
}

public static void Main (string[] args) {
A = new A ();
String s = "Wo";
A.sayhello (s);
System.out.println ("--" + A.sayhello (s));
}

}

What is the final output?

You can try to add this code to the compilation software and you will find it wrong.

8. Given an array (not sorted), write a bubbling sort, arranged from small to large

Two

1, last year's Today is which day (do not know this question what meaning, later also forgot to ask)

2, database table establishment and query, employee list EMP ID, name,salary,dept_id, Department dept Id,name

Find out the number of employees owned by each department, if none, then show 0

3, Struts1 and Struts2, write their implementation methods, at least three ways

4, Struts1, STRUTS2 is thread-safe?

5. The difference between Struts1 and struts2

Chinese Soft international Java written test questions

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.