Java Interview Questions/Java面试题

 
1           What is transient variable?
Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.
 
2           Name the containers which uses Border Layout as their default layout?
Containers which use Border Layout as their default ones are, window, Frame and Dialog classes.
 
3           What do you understand by Synchronization?
Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.
 
E.g. Synchronizing a function:
public synchronized void Method1 () {
     // Appropriate method-related code.
}
 
E.g. Synchronizing a block of code inside a function:
public myFunction (){
    synchronized (this) {
            // Synchronized code here.
         }
}
 
4           What is Collection API?
The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.
Collection
----Set
--------HashSet
--------TreeSet
--------LinkedList
----List
--------ArrayList
--------Vector
 
Map
----Hashtable
----HashMap
 
5           Is Iterator a Class or Interface? What is its use?
Iterator is an interface which is used to step through the elements of a Collection.
 
6           What is similarities/difference between an Abstract class and Interface?
6.1          Similarities
6.1.1      They can be used to implement the polymorphism.
6.1.2      Both of them can not be instantiated.
6.2          Differences
6.2.1      Interface can be used to implement the multiple inheritances while the abstract can not. Because the Java only provides the single inheritance.
6.2.2      There is no implementation in the interfaces. But in abstract class, you can implement some common logic.
6.2.3      In interface, there can be only public methods and public static fields.
6.2.4      The efficiency with interface is lower than abstract class. (If it refer to the overrode function)
 
7           How to define an Interface?
7In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.
Emaple of Interface:
 
public interface sampleInterface {
    public void functionOne();
 
    public static long CONSTANT_ONE = 1000;
}
 
8           Explain the user defined Exceptions?
8User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.
 
Example:
class myCustomException extends Exception {
     // The class simply has to exist to be an exception
}
 
9           Explain the new Features of JDBC 2.0 Core API?
The JDBC 2.0 API includes the complete JDBC API, which includes both core and Optional Package API, and provides inductrial-strength database computing capabilities.
 
New Features in JDBC 2.0 Core API:
9.1           Scrollable result sets - using new methods in the ResultSet interface allows programmatically move the to particular row or to a position relative to its current position. The methods is ResultSet.relative(…).
9.2           JDBC 2.0 Core API provides the Batch Updates functionality to the java applications.
9.3           Java applications can now use the ResultSet.updateXXX methods.
9.4           New data types - interfaces mapping the SQL3 data types
9.5           Custom mapping of user-defined types (UTDs)
9.6           Miscellaneous features, including performance hints, the use of character streams, full precision for java.math.BigDecimal values, additional security, and support for time zones in date, time, and timestamp values. 
 
10       Explain garbage collection?
Garbage collection is one of the most important feature of Java. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program cann't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.
 
11       How you can force the garbage collection?
Garbage collection automatic process and can't be forced. 
 
12       What is OOPS?
OOP is the common abbreviation for Object-Oriented Programming.   
 
13       Describe the principles of OOPS.
There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation. 
 
14       Explain the Encapsulation principle.
14Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper. 
 
15       Explain the Inheritance principle.
15Inheritance is the process by which one object acquires the properties of another object. 
 
16       Explain the Polymorphism principle.
16.1        One name many forms.
16.2        One interface multiple implementations.
 
The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as "one interface, multiple methods". 
 
17       Explain the different forms of Polymorphism.
From a practical programming viewpoint, polymorphism exists in three distinct forms in
 
Java:
Method overloading
Method overriding through inheritance
Method overriding through the Java interface
 
18       Access specifiers are keywords that determine the type of access to the member of a class.
Public
Protected
Defaults(Package)
Private
 
19       Describe the wrapper classes in Java.
Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.
Following table lists the primitive types and the corresponding wrapper classes:
 
Primitive
Wrapper
boolean
  java.lang.Boolean
byte
  java.lang.Byte
char
  java.lang.Character
double
  java.lang.Double
float
  java.lang.Float
int
  java.lang.Integer
long
  java.lang.Long
short
  java.lang.Short
void
  java.lang.Void
 
20       Read the following program:
public class test {
public static void main(String [] args) {
    int x = 3;
    int y = 1;
   if (x = y)
     System.out.println("Not equal");
 else
    System.out.println("Equal");
 }
}
 
What is the result?
   A. The output is “Equal”
  B. The output in “Not Equal”
   C. An error at " if (x = y)" causes compilation to fall.
   D. The program executes but no output is show on console.
 
Answer: C
 
21       what is the class variables ?
When we create a number of objects of the same class, then each object will share a common copy of variables. That means that there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class, but mind it that it should be declared outside outside a class. These variables are stored in static memory. Class variables are mostly used for constants, variable that never change its initial value. Static variables are always called by the class name. This variable is created when the program starts i.e. it is created before the instance is created of class by using new operator and gets destroyed when the programs stops. The scope of the class variable is same a instance variable. The class variable can be defined anywhere at class level with the keyword static. It initial value is same as instance variable. When the class variable is defined as int then it's initial value is by default zero, when declared boolean its default value is false and null for object references. Class variables are associated with the class, rather than with any object. 
 
22       What is the difference between the instanceof and getclass, these two are same or not ?
Instanceof is a operator, not a function while getClass is a method of java.lang.Object class. Consider a condition where we use
 
if(o.getClass().getName().equals("java.lang.Math")){ }
 
This method only checks if the classname we have passed is equal to java.lang.Math. The class java.lang.Math is loaded by the bootstrap ClassLoader. This class is an abstract class.This class loader is responsible for loading classes. Every Class object contains a reference to the ClassLoader that defines. getClass() method returns the runtime class of an object. It fetches the java instance of the given fully qualified type name. The code we have written is not necessary, because we should not compare getClass.getName(). The reason behind it is that if the two different class loaders load the same class but for the JVM, it will consider both classes as different classes so, we can't compare their names. It can only gives the implementing class but can't compare a interface, but instanceof operator can.
 
The instanceof operator compares an object to a specified type. We can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface. We should try to use instanceof operator in place of getClass() method. Remember instanceof opeator and getClass are not same. Try this example, it will help you to better understand the difference between the two.
 
Interface one{
}
Class Two implements one {
}
Class Three implements one {
}
 
public class Test {
public static void main(String args[]) {
One test1 = new Two();
One test2 = new Three();
System.out.println(test1 instanceof one); //true
System.out.println(test2 instanceof one); //true
System.out.println(Test.getClass().equals(test2.getClass())); //false
}
}
 
23       Is “abc” a primitive value?
The String literal “abc” is not a primitive value. It is a String object.
 
24       What restrictions are placed on the values of each case of a switch statement?
During compilation, the values of each case of a switch statement must evaluate to a value     that can be promoted to an int value.
 
25       What modifiers may be used with an interface declaration? –
An interface may be declared as public or abstract.
 
26       What is the difference between a while statement and a do statement?
A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.
 
27       What modifiers can be used with a local inner class?
A local inner class may be final or abstract.
 
28       What is the purpose of the File class?
The File class is used to create objects that provide access to the files and directories of a local file system.
 
29       Can an exception be rethrown?
Yes, an exception can be rethrown.
 
30       When does the compiler supply a default constructor for a class?
The compiler supplies a default constructor for a class if no other constructors are provided.
 
31       If a method is declared as protected, where may the method be accessed?
A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.
 
32       Which non-Unicode letter characters may be used as the first character of an identifier?
The non-Unicode letter characters $ and _ may appear as the first character of an identifier
 
33       What restrictions are placed on method overloading?
Two methods may not have the same name and argument list but different return types.
 
34       What is casting?
There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.
 
35       What is the return type of a program’s main() method?
A program’s main() method has a void return type.
 
36       What class of exceptions are generated by the Java run-time system?
The Java runtime system generates RuntimeException and Error exceptions.
 
37       What class allows you to read objects directly from a stream?
The ObjectInputStream class supports the reading of objects from input streams.
 
38       What is the difference between a field variable and a local variable?
A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method.
 
39       How are this() and super() used with constructors?
this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
 
40       What is the relationship between a method’s throws clause and the exceptions that can be thrown during the method’s execution?
A method’s throws clause must declare any checked exceptions that are not caught within the body of the method.
 
41       Why are the methods of the Math class static?
So they can be invoked as if they are a mathematical code library.
 
42       What are the legal operands of the instanceof operator?
The left operand is an object reference or null value and the right operand is a class, interface, or array type.
 
43       What are E and PI?
E is the base of the natural logarithm and PI is mathematical value pi. They are defined in the Math class.
 
44       Are true and false keywords?
The values true and false are not keywords. Both are the constant values like 0, 1, 2.
 
45       What is the difference between the File and RandomAccessFile classes?
The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.
 
46       What happens when you add a double value to a String?
The result is a String object.
 
47       What is your platform’s default character encoding?
If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1.
 
48       Which package is always imported by default?
The java.lang package is always imported by default.
 
49       What interface must an object implement before it can be written to a stream as an object?
An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.
 
50       How can my application get to know when a HttpSession is removed?
Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method. Create an instance of that class and put that instance in HttpSession.
 
51       What’s the difference between notify() and notifyAll()?
notify() is used to unblock one waiting thread; notifyAll() is used to unblock all of them. Using notify() is preferable (for efficiency) when only one blocked thread can benefit from the change (for example, when freeing a buffer back into a pool). notifyAll() is necessary (for correctness) if multiple threads should resume (for example, when releasing a “writer” lock on a file might permit all “readers” to resume).
 
52       Why can’t I say just abs() or sin() instead of Math.abs() and Math.sin()?
The import statement does not bring methods into your local name space. It lets you abbreviate class names, but not get rid of them altogether. That’s just the way it works, you’ll get used to it. It’s really a lot safer this way.
 
However, there is actually a little trick you can use in some cases that gets you what you want. If your top-level class doesn’t need to inherit from anything else, make it inherit from java.lang.Math. That *does* bring all the methods into your local name space. But you can’t use this trick in an applet, because you have to inherit from java.awt.Applet. And actually, you can’t use it on java.lang.Math at all, because Math is a “final” class which means it can’t be extended.
 
53       Why are there no global variables in Java?
Global variables are considered bad form for a variety of reasons: Adding state variables breaks referential transparency (you no longer can understand a statement or expression on its own: you need to understand it in the context of the settings of the global variables), State variables lessen the cohesion of a program: you need to know more to understand how something works. A major point of Object-Oriented programming is to break up global state into more easily understood collections of local state, When you add one variable, you limit the use of your program to one instance. What you thought was global, someone else might think of as local: they may want to run two copies of your program at once. For these reasons, Java decided to ban global variables.
 
54       What does it mean that a class or member is final?
A final class can no longer be subclassed. Mostly this is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. Methods may be declared final as well. This means they may not be overridden in a subclass. Fields can be declared final, too. However, this has a completely different meaning. A final field cannot be changed after it’s initialized, and it must include an initializer statement where it’s declared. For example, public final double c = 2.998; It’s also possible to make a static field final to get the effect of C++’s const statement or some uses of C’s #define, e.g. public static final double c = 2.998;
 
55       What does it mean that a method or class is abstract?
An abstract class cannot be instantiated. Only its subclasses can be instantiated. You indicate that a class is abstract with the abstract keyword like this:
public abstract class Container extends Component {
Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in the current class. It exists only to be overridden in subclasses. It has no body. For example,
public abstract float price();
Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or itself be declared abstract.
 
56       What is a transient variable?
Transient variable is a variable that may not be serialized.
 
57       How are Observer and Observable used?
Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.
 
58       Can a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object.
 
59       What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.
 
 
60       What is the difference between the >> and >>> operators?
The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.
 
61       Is sizeof a keyword?
The sizeof operator is not a keyword.
 
62       Does garbage collection guarantee that a program will not run out of memory?
Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection
 
63       Can an object’s finalize() method be invoked while it is reachable?
An object’s finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object’s finalize() method may be invoked by other objects.
64       What value does readLine() return when it has reached the end of a file?
The readLine() method returns null when it has reached the end of a file.
 
65       Can a for statement loop indefinitely?
Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;
 
66       To what value is a variable of the String type automatically initialized?
The default value of an String type is null.
 
67       What is a task’s priority and how is it used in scheduling?
A task’s priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks. Please see the method public final void setPriority(int newPriority) in class Thread.
 
68       What is the range of the short type?
The range of the short type is -(2^15) to 2^15 - 1.
 
69       What is the purpose of garbage collection?
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused.
 
70       What do you understand by private, protected and public?
These are accessibility modifiers. Private is the most restrictive, while public is the least restrictive. There is no real difference between protected and the default type (also known as package protected) within the context of the same package, However the protected keyword allows visibility to a derived class in a different package.
 
71       What is Downcasting?
Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy
 
72       Can a method be overloaded based on different return type but same argument type ?
No, because the methods can be called without using their return type in which case there is ambiquity for the compiler
 
73       What happens to a static var that is defined within a method of a class ?
Can’t do it. You’ll get a compilation error
 
74       How many static init can you have ?
As many as you want, but the static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope.
 
75       What is the difference amongst JVM Spec, JVM Implementation, JVM Runtime ?
The JVM spec is the blueprint for the JVM generated and owned by Sun. The JVM implementation is the actual implementation of the spec by a vendor and the JVM runtime is the actual running instance of a JVM implementation
 
76       Describe what happens when an object is created in Java?
Several things happen in a particular order to ensure the object is constructed properly: Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data. The instance variables of the objects are initialized to their default values. The constructor for the most derived class is invoked. The first thing a constructor does is call the consctructor for its superclasses. This process continues until the constrcutor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.
 
77       Why does it take so much time to access an Applet having Swing Components the first time?
Because behind every swing component are many Java objects and resources. This takes time to create them in memory. JDK 1.3 from Sun has some improvements which may lead to faster execution of Swing applications.
 
78       What is Action Class?
78The Action is part of the controller. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. There should be no database interactions in the action. The action should receive the request, call business objects (which then handle database, or interface with J2EE, etc) and then determine where to go next. Even better, the business objects could be handed to the action at runtime (IoC style) thus removing any dependencies on the model.    The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.
 
79       Write code of any Action Class?
79 Here is the code of Action Class that returns the ActionForward object.
 
TestAction.java
 
package  roseindia.net;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class TestAction extends Action
{
  public ActionForward execute(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception{
      return mapping.findForward("testAction");
  }
}
 
80       What is ActionForm?
80An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.
 
81       What is Struts Validator Framework?
81Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class. 
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值