标签:des style blog http io os ar java for
(1) OOP and Design Patterns
(1.1) Please explain difference among class, interface and abstract class. When you would use it rather than other?
Feature |
Interface |
Abstract class |
Multiple inheritance |
A class may implement multiple interfaces. |
A class may inherit only one abstract class. |
Default implementation |
An interface cannot provide any code, just the signature. |
An abstract class can provide complete, default code and/or just the details that have to be overridden. |
Access Modifiers |
The only permissible access modifier is public, which is also the default one. |
An abstract class can contain access modifiers for the methods and properties. |
Core vs. Peripheral |
Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a Movable interface. |
An abstract class defines the core identity of a class and therefore it is used for objects of the same type. |
Homogeneity |
If various implementations only share method signatures then it is better to use Interfaces. |
If various implementations are of the same kind and use common behavior or status then abstract class is better to use. |
Speed |
Previously used to require more time to find the actual method implementation while going through the table or interfaces of a class. |
Previously used to be faster. The today’s dynamic compilation eliminates the difference. |
Adding functionality (Versioning) |
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. |
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly. |
Fields and Constants |
Only public static final field can be defined. Fields are public, static, and final by default. |
An abstract class can have any fields with any modifiers. |
Static methods |
Static methods are not allowed. Static methods cannot be overridden because they are resolved at compile time. Official proposal for Java 7 was dropped for unforeseen complications. |
Static methods are allowed. |
Abstractness |
The keyword “abstract” is default for all methods. Method body is not allowed. |
The class must be declared with the keyword “abstract”. Abstract methods with no body must use the keyword “abstract”. |
Nested interface = interface inside another interface or class. Example: defining the callback interface as nested.
(1.2) Please explain the overloaded, overridden methods? Constructors can be overloaded, overridden?
Overloading: picking a method signature at compile time based on the number and type of the arguments. Return type is not part of the signature and so it can’t be used to distinguish between the overloaded methods, not even in Java 7 or ever J
Overriding: picking a method implementation at run time based on the actual type of the target object. As of Java 5, the overriding implementation in subclass may return a subclass of the type returned by the overridden implementation in the super class (covariant return type).
Constructors can be overloaded.
Constructors cannot be overridden because they are not inherited. Each subclass constructor has to chain either to another constructor within the subclass or to a constructor in the superclass. No argument constructors and default constructors chain automatically to the no argument constructor of the parent.
(1.3) What is a marker interface? What is purpose? Some examples.
Marker interface is an interface with no methods. It is used to mark, that instances of the marked class support “some functionality”. The marker interface can be checked using “instanceof”.
Recently, marker interfaces are often being replaced by annotations.
Examples:
Cloneable: Discouraged. Does not contain the method clone(). Just marks that instances may be cloned. Implementers of clone() should call super.clone(). If class is not marked Cloneable, Object.clone() will throw CloneNotSupportedException.
Serializable: ObjectOutputStream, ObjectInputStream. NotSerializableException.
(1.4) Please pick any design pattern and describe it. Could you mention some usage of patterns in JDK?
Creational Patterns
Abstract Factory
Builder
Factory method
Prototype
Singleton
Structural Patterns
Adapter
Bridge
Composite
Decorator
Facade
Flyweight
Proxy
Behavioral Patterns
Chain of responsibility
Command
Interpreter
Iterator
Mediator
Memento
Observer (or Publish/Subscribe)
State
Strategy
Template method
Visitor
(1.5) What is the multiple inheritance? Have you heard the term Diamond problem? Is it possible to have multiple inheritance in Java? Could you propose some solution how to achieve it? How you would achieve class is of more types?
(1.6) What is the difference between deep and shallow copy?
(1.7) What is the concept of access modifiers? How many access modifiers do we have in Java?
Class level
Member level
Modifier |
Class |
Package |
Subclass |
World |
public |
Y |
Y |
Y |
Y |
protected |
Y |
Y |
Y |
N |
(default / package private) |
Y |
Y |
N |
N |
private |
Y |
N |
N |
N |
(1.8) What are inner class and anonymous class? Can an anonymous class implement an interface?
Every class in Java must implement and/or extend some other class (java.lang.Object by default). This applies for anonymous classes as well and the syntax for implementing and extending is identical.
(1.9) Please describe the basics of dependency injection mechanism? Can you mention some pros & cons? Do you know some frameworks implementing this? Have you used any?
Inversion of Control (Hollywood principle) = the framework calls the application code, not the other way round
Dependency Injection = The framework calls the application code and sets dependencies.
Pros:
Cons:
Frameworks: Spring, Google Guice, Pico Container, CDI
(2) Java Core and Libraries
(2.1) What is passing by value and passing by reference, and what is the situation in Java/C?
Java is by definition pass-by-value, references to non-primitive types are passed by value.
Primitive data types: byte, short, int, long, float, double, boolean, char.
(2.2) What is serialization? What I need to do to serialize an object? How I can remove some instance property from serialization? How the transient field could be reconstructed during the de-serialization phase? Do you know some frameworks used for serialization?
The keyword “transient” excludes given member variable from serialization.
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{
in.defaultReadObject();
// reconstruct transient variables
}
Serialization frameworks:
(2.3) If you override the equals() method what other methods would you also need to consider and why? Why is important to override the equals() method?
You must override hashCode() in every class that overrides equals(), because equal objects must have equal hash codes.
The default implementations satisfy the contract but are often not very efficient.
(2.4) What do you know about Collections framework? Why do we have eg. more implementation of List interface. Provide some examples and pros/cons.
Efficiency depends on the way the collection implementation is used (fast read / slow write etc).
(2.5) What is the difference between final, finally and finalize? What do you understand by the java final keyword?
final
finally – try/catch/finally
finalize – called on an object when it is garbage collected. Nobody knows when and if it will be called.
(2.6) What is reflection API? Pros/Cons? What is the purpose?
Pros
Cons
(2.7) Checked and Unchecked exception? What is the difference? What do you prefer in your app?
Checked exceptions
Unchecked exceptions
(2.8) What is the difference between an error and an exception?
Errors are abnormal conditions, which should not be caught.
AnnotationFormatError, AssertionError, LinkageError, VirtualMachineError, StackOverflowError.
(2.9) What is a mutable object and immutable object? Why is it important to distinguish them?
It is not possible to change state of an immutable object.
Effective Java: “Classes should be immutable unless there‘s a very good reason to make them mutable....If a class cannot be made immutable, limit its mutability as much as possible.”
How to implement:
(2.10) What are generics in java and what is the benefit of using them?
Customize a "generic" method or class to whatever type you‘re working with.
Advantages:
(2.11) What is an annotation? Do you know any Java built-in annotations?
Annotations are a form of syntactic metadata that can be added to the source code.
Classes, methods, variables, parameters and packages may be annotated.
Checking for annotations is done via reflection API.
Built-in annotations:
Usage:
(2.12) What is the StackOverflowError? What could be the root cause of this error?
StackOverflowError is an error and thus should not be handled.
StackOverflowError is mostly caused by infinite recursion (invalid or missing termination condition).
(2.13) Which methods can you call on every instance in Java?
(2.14) What are enums? Describe them. Can be inherited? Is it allowed to define a constructor for an enum?
An enum type is a special data type that enables for a variable to be a set of predefined constants.
Enums cannot inherit from each other, because each enum type already implements from java.lang.Enum and there’s no multiple inheritance in Java.
Enums can implement interfaces though.
Enums can contain constructors, methods and fields.
The individual constants are like instances of the enum class.
(2.15) Is it possible to change the content of a String instance? Can you mention some other classes for manipulating Strings?
String is immutable (and also final). Why?
StringBuffer (synchronized), StringBuilder (is not synchronized). Clear by calling setLength(0).
(3) Advanced Java/J2EE
(3.1) What is the reflection API? Pros/Cons? What is its purpose?
(This is a duplicate question – same as (2.6))
(3.2) What is a servlet? What is the life cycle of a servlet?
A Servlet is an interface in Java EE (javax.servlet) that conforms to the Java Servlet API, a protocol by which a Java class may respond to HTTP requests.
Servlet# service(ServletRequest req, ServletResponse res)
Servlet# init(ServletConfig config)
Servlet# destroy()
HttpServlet# doGet(HttpServletRequest req,
HttpServletResponse resp)
HttpServlet# doPost(HttpServletRequest req, HttpServletResponse resp)
(3.3) What is a classloader and what are its responsibilities? What is a classloader hierarchy?
Java is a dynamically compiled language. Unlike C++, the linking process is performed by the JVM at runtime. Classes are loaded into the JVM on an ‘as needed‘ basis. Static initializers are run when the class is being loaded.
Each classloader in the hierarchy first queries its parent. Only when the parent is not able to load the class, the classloader tries itself.
(3.4) What is JMS, what are the two basic models?
Java Messaging Service, part of Java EE.
Two basic models:
(3.5) What is point-to-point messaging?
In point-to-point messaging system, messages are routed to an individual consumer which maintains a queue of "incoming" messages. This messaging type is built on the concept of message queues, senders, and receivers. Each message is addressed to a specific queue, and the receiving clients extract messages from the queues established to hold their messages. While any number of producers can send messages to the queue, each message is guaranteed to be delivered, and consumed by one consumer. Queues retain all messages sent to them until the messages are consumed or until the messages expire. If no consumers are registered to consume the messages, the queue holds them until a consumer registers to consume them.
(3.6) What is a managed bean?
EJB = POJO that is treated as managed component by the Java EE container.
(3.7) What is a web service? Could you explain terms SOAP, WSDL.
Web Service is a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format (specifically WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standards.
SOAP = Simple Object Access Protocol = protocol for Web Services.
(3.8) What are two basic approaches of how to design web service?
REST
SOAP
(3.9) What is a two-phase commit?
2PC is a distributed algorithm that coordinates all the processes that participate in a distributed atomic transaction on whether to commit or roll back the transaction.
Commit request phase (= voting phase)
Commit phase (success)
Commit phase (failure)
(3.10) What is JDBC? What is ORM. Do you know any implementations? What is lazy-loading/fetching?
JDBC (Java Database Connectivity) is part of JDK since JDK 1.1. Packages java.sql.* and javax.sql.*.
JDBC is oriented towards relational databases.
A JDBC-to-ODBC bridge enables connections to any ODBC-accessible data source in the JVM host environment.
Usage
Four types of drivers
Object Relational Mapping (ORM)
(4) Multithreading and Synchronization
(4.1) How can you create new threads in Java? What is the thread lifecycle in Java? Is there difference between J2SE and J2EE world?
Create new thread:
(4.2) How JVM performs thread synchronization? Explain terms Monitor, critical section, deadlock, volatile.
Keyword “synchronized”
Atomic access
wait(), notify(), notifyAll()
Immutable object are inherently thread safe.
join() on multiple threads
for (Thread thread : threads) {
thread.join();
}
(4.3) What‘s the difference between the methods sleep() and wait()?
(4.4) What does java.util.concurrent package provide?
High level concurrency package introduced with Java SE 5.
java.util.concurrent.locks
Interface |
Implementation |
Lock
|
ReentrantLock ReentrantReadWriteLock.ReadLock ReentrantReadWriteLock.WriteLock |
ReadWriteLock
|
ReentrantReadWriteLock
|
Executor, ThreadPool
Concurrent collections
Atomic variables
(4.5) How do you synchronize a collection?
We can use synchronized wrappers. The following factory methods return thread-safe objects:
(4.6) Can a thread deadlock itself?
By definition, there should be at least two threads for a deadlock. However the following two lines product a thread-hang that almost looks like a thread deadlocking itself:
lock.readLock().lock();
lock.writeLock().lock();
(5) Databases
(5.1) Can you explain what transactions are? How are they used and why? What ACID stands for? Can you describe isolation levels?
ACID – core properties of a DBMS
Isolation levels
Serializable |
|
Repeatable reads |
|
Read committed |
|
Read uncommitted |
|
(5.2) What is the difference between inner and outer join?
(5.3) What is an index? What are pros/cons? What is a clustered and non-clustered, bitmap index?
Pros:
Cons:
Clustered index = The actual table (rows) is reorganized according to the index. Increases performance of sequential access. Only one clustered-index per table.
Bitmap index = index data stored in bit arrays. Useful for columns with small domains (for example gender).
(5.4) What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?
Scrollable cursor = can be positioned anywhere in the result set.
Cursor “with hold” = not released at commit.
Disadvantages:
(5.5) What is a database view? What is a materialized view?
(5.6) What are database constraints? What are pros/cons?
Disadvantages:
(5.7) What is normalization? What are the benefits?
Normalization – process of enforcing / increasing the Normal Form (NF) of the database.
NF1 - Table faithfully represents a relation, primarily meaning it has at least one candidate key.
NF2 - No non-prime attribute in the table is functionally dependent on a proper subset of any candidate key.
NF3 - Every non-prime attribute is non-transitively dependent on every candidate key in the table. The attributes that do not contribute to the description of the primary key are removed from the table. In other words, no transitive dependency is allowed.
标签:des style blog http io os ar java for
原文地址:http://www.cnblogs.com/chayu3/p/4060164.html