Java Thread Interview Questions

THREADS INTERVIEW QUESTIONS AND ANSWERS JAVA

Q) What are the two types of multitasking ?
A)
a. Process-based.
b. Thread-based.

Q) What is a Thread ?
A)  A thread is a single sequential flow of control within a program.

Q) What are the two ways to create a new thread?
A)
a.Extend the Thread class and override the run() method.
b.Implement the Runnable interface and implement the run() method.

Q) If you have ABC class that must subclass XYZ class, which option will you use to      create a thread?
A)
I will make ABC implement the Runnable interface to create a new thread,     because ABC class will not be able to extend both XYZ class and Thread class.

Q) Which package contains Thread class and Runnable Interface?
A)
java.lang package

Q) What is the signature of the run() mehod in the Thread class?
A)
public void run()

Q) Which methods calls the run() method?
A)
start() method.

Q) Which interface does the Thread class implement?
A)
Runnable interface

Q) What are the states of a Thread ?
A)
Ready,Running,Waiting and Dead.

Q) Where does the support for threading lie?
A)
The thread support lies in java.lang.Thread, java.lang.Object and JVM.

Q) In which class would you find the methods sleep() and yield()?
A)
Thread class

Q) In which class would you find the methods notify(),notifyAll() and wait()?
A)
Object class

Q) What will notify() method do?
A)
notify() method moves a thread out of the waiting pool to ready state, but there is no guaranty which    thread will be moved out of the pool.

Q) Can you notify a particular thread?
A)
No.

Q) What is the difference between sleep() and yield()?
A)
When a Thread calls the sleep() method, it will return to its waiting state. When a Thread calls the yield()  method, it returns to the ready state.

Q) What is a Daemon Thread?
A)
Daemon is a low priority thread which runs in the backgrouund.

Q) How to make a normal thread as daemon thread?
A)
We should call setDaemon(true) method on the thread object to make a thread as       daemon thread.

Q) What is the difference between normal thread and daemon thread?
A)
Normal threads do mainstream activity, whereas daemon threads are used low       priority work. Hence daemon threads are also stopped when there are no normal       threads.

Q) Give one good example of a daemon thread?
A)
Garbage Collector is a low priority daemon thread.

Q) What does the start() method of Thread do?
A)
The thread’s start() method puts the thread in ready state and makes the thread      eligible to run. start() method automatically calls the run () method.

Q) What are the two ways that a code can be synchronised?
A)
a. Method can be declared as synchronised.
b. A block of code be sychronised.

Q) Can you declare a static method as synchronized?
A)
Yes, we can declare static method as synchronized. But the calling thread should      acquire lock on the class that owns the method.

Q) Can a thread execute another objects run() method?
A)
A thread can execute it’s own run() method or another objects run() method.

Q) What is the default priority of a Thread?
A)
NORM_PRIORITY

Java Exception Handling Questions

JAVA EXCEPTION HANDLING INTERVIEW QUESTIONS AND ANSWERS

Q) What package contains exception handling related classes?
A) java.lang

Q) what ar the two types of Exceptions?
A)
Checked Exceptions and Unchecked Exceptions

Q) What is the base class of all Exceptions?
A)
java.lang.Throwable.

Q) What is difference between an Exception and Error in java?
A)
Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that user program should catch. Error defines exceptions that are not excepted to be caught by the user program. Example is Stack Overflow.
( or )
Exception defines an abnormal termination of the program which can be handled at compile time using try catch finally mechanisum or by using the throws option
where as Error will be seen at runtime which cannot be handled.

Q) What is the difference between throw and throws?
A)
throw is used to explicitly raise a exception within the program, the statement would be throw new Exception(); throws clause is used to indicate the exceptions that are not handled by the method. It must specify this behavior so the callers of the method can guard against the exceptions. throws is specified in the method signature. If multiple exceptions are not handled, then they are separated by a comma. the statement would be as follows: public void doSomething() throws IOException

Q) What is the difference between Exception and Error in java?
A)
Exception and Error are the subclasses,MyException{}

Q) Differentiate between Checked Exceptions and Unchecked Exceptions?
A)
Checked Exceptions are those exceptions which should be explicitly handled by the calling method. Unhandled checked exceptions results in compilation error.
Unchecked Exceptions are those which occur at runtime and need not be explicitly handled. RuntimeException and it’s subclasses, Error and it’s subclasses fall under unchecked exceptions.

Q) What are User defined Exceptions?
A)
Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class.

Q) What is the importance of finally block in exception handling?
A)
Finally block will be executed whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally block will be executed. Finally is used to free up resources like database connections, IO handles, etc.

Q) Can a catch block exist without a try block?
A)
No. A catch block should always go with a try block.

Q) Can a finally block exist with a try block but without a catch?
A)
Yes. The following are the combinations try/catch or try/catch/finally or try/finally.

Q) What will happen to the Exception object after exception handling?
A)
Exception object will be garbage collected.

Q) The subclass exception should precede the base class exception when used within the catch clause. True/False?
A)
True.

Q) Exceptions can be caught or rethrown to a calling method. True/False?
A)
True.

Q) The statements following the throw keyword in a program are not executed. True/False?
A)
True.

Q) How does finally block differ from finalize() method?
A)
Finally block will be executed whether or not an exception is thrown. So it is used to free resoources. finalize() is a protected method in the Object class which is called by the JVM just before an object is garbage collected.

Q) What are the constraints imposed by overriding on exception handling?
A)
An overriding method in a subclass may only throw exceptions declared in the parent class or children of the exceptions declared in the parent class.

Java Basic Questions

Q. Can you help me debug my program?

A. If the problem you are having is not directly related to our software, we suggest that you use a Java development tool that helps you with debugging, and that you invest in some books or training to help you learn Java. There are many ways to build debugging into your program, and getting good training in Java programming is a good start to understanding how to do this.

Q. Where can I get help learning Java?

A. There are a lot of books and online references to Java. A good starting place is at the JavaSoft website documentation index, which has links to white papers and the Java Tutorial. You can find books on Java at any of the major online book shopping sites.

Q. Where do I get the JDK?

A. WebLogic 6.1 bundles JDK131. See our Platform support page for information about specific JDKs that we have tested and certified for use with WebLogic software.
Once you determine which version of the JDK you will be using, go to the JavaSoft website. Many platform vendors provide an optimized version of the JDK for their computers.

Q. How do I set up my CLASSPATH?

A. Setting up your CLASSPATH correctly depends on what you are trying to do. The most common tasks are described below:
-> Starting WebLogic Server. See Setting the Classpath Option in the Starting and Stopping WebLogic Servers section of the Administration Guide. In addition, your WebLogic distribution includes shell scripts that you can use to start the server. These scripts, which are located in the domain directories under the config directory of your WebLogic Server distribution, automatically set up the CLASSPATH variable in the shell before starting the server.
-> Compiling Application Classes or Using WebLogic Server Utilities. See Setting the Classpath for Compiling in the Developing WebLogic Server Components section of Developing WebLogic Server Applications.
-> Working With WebLogic Server Code Examples. See the WebLogic Server Examples Guide located at samples/examples/examples.html in your WebLogic Server distribution.

Q. Why won’t the examples work?

A. Usually problems with examples are related to your environment. Here are some troubleshooting hints:
1. If you are using a database, make sure you have run the utility utils.dbping to verify that your JDBC driver is correctly installed and configured.
2. Run the setEnv script to make sure your CLASSPATH is correctly set in the shell or DOS window in which you are running the examples. For more information, see Setting your development environment.
3. Check the instructions for the examples to make sure you have changed any user-specific variables in the code before compiling.
4. Verify that you are compiling with the -d option to direct the class files into the proper directory, as defined in the example instructions.
If the example is an applet, check the CODE and CODEBASE, and make sure WebLogic Server is running.

Q. Where can I get help with Java error messages?

A. Many questions we receive at BEA are related to generic Java error messages and are not specific to WebLogic Server. Here are some links that contain helpful information about Java error messages.
Source Description
Sun’s Java Developer Connection:-
This forum includes Questions and Answers on a wide variety of Java topics, including error messages. Use the Search box for fast results. For example, type “classpath error” in the Search box.
Compiler Error Messages:-
An extensive list of compiler error messages, including the infamous NoClassDefFoundError.
Sun’s Java APIs:-
Check the Java API to see if there is an exception description for the class you are using.

Q. Why did a client-server message generate a StackOverflowException?

A. If you are sending a particularly large data structure using java.io.Serialization, you may exceed the per-thread size limit for either the Java or native stack. You can increase the stack size by using the following command line options:
-ss Stacksize to increase the native stack size or
-oss Stacksize to increase the Java stack size,
where Stacksize is expressed as an integer followed by “k” or “m” for kbytes or mbytes. For example,
$java -ss156k (native)
$java -oss600k (Java)
The default native stack size is 128k, with a minimum value of 1000 bytes. The default java stack size is 400k, with a minimum value of 1000 bytes.

Q. Will a JIT make my Java application run faster?

A. A Just-In-Time compiler will make some Java applications run faster. A JIT works by storing generated machine code in memory and reusing it when possible. For example, if you execute the same operation 1000 times in a loop, a JIT will improve performance of this operation since the code will only be generated once. Applications with a lot of native methods will not see as much performance improvement as pure-Java applications.
If you use a JIT, you may want to turn off the JIT during debugging to facilitate stacktracing. If you are doing performance testing with a JIT, make sure that you execute the same test several times in the same invocation and then throw away the first result to get an idea of how long the transaction will take when your application is running in a steady state. The first time the code is executed, your test will take longer (the “code generation hit”).

Q. Can I redistribute the JDK that is bundled with WebLogic Server?

A. BEA Systems has the non-exclusive right to grant a third party, such as an independent software vendor (ISV), the right to redistribute the JDK that is bundled with WebLogic Server without any modifications of any kind. The following are caveats to this general statement:
-> The ISV cannot remove or alter any proprietary legends or notices contained in the JDK. The ISV shall not decompile, disassemble, decrypt, extract, or otherwise reverse engineer or modify the JDK. The JDK may not be leased or assigned in whole or in part.
-> The ISV must enter into a signed agreement with its distributors on terms substantially similar to those contained here in this redistribution policy explanation.
-> The ISV requires an end user license agreement with the product within which it embeds WebLogic Server.

-> The embedding of the JDK in ISV products does not include maintenance and support of the JDK by the JDK Provider. BEA Systems shall be solely responsible for providing maintenance and support for its ISVs and distributors. The ISV shall be solely responsible for providing maintenance and support for the end users of its products.
-> If an ISV wants to ship a JDK that is different from the JDK that BEA ships with WebLogic Server, that ISV needs to get those bundling rights directly from Sun or HP. For example:
Assume that BEA ships WebLogic Server 6.0 with JDK 1.3 only, that BEA ships WebLogic Server 5.1 with JDK 1.1 only, and that an ISV wants to ship JDK 1.1 with WebLogic Server 6.0 in an integrated product offered by that ISV. Unless BEA, for BEA business reasons, elects to make WebLogic Server 6.0 with JDK 1.1 generally available, the ISV couldn’t ship JDK 1.1 with WebLogic Server 6.0 in an integrated product offered by that ISV under BEA’s agreement with that ISV or under BEA’s agreement with Sun. The ISV could, however, obtain its own binary distribution agreement for the JDK from Sun and under that agreement bundle JDK 1.1 with its value added software solution consisting of the ISV applications and WebLogic Server 6.0 integrated.

Core Java Inteview Questions

Q:What are Checked and UnChecked Exception?

A: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream’s read() method•
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn’t force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String’s charAt() method• Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

Q:What is Overriding?

A: When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.
When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.

Q:What are different types of inner classes?

A: Nested top-level classes, Member classes, Local classes, Anonymous classes Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety.

Member classes – Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.

Local classes – Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.

Anonymous classes – Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

Q:Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?

A: Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbol
symbol : class ABCD
location: package io
import java.io.ABCD;

Q:Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?

A: No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it’s subpackage.

Q:What is the difference between declaring a variable and defining a variable?

A: In declaration we just mention the type of the variable and it’s name. We do not initialize it. But defining means declaration + initialization.
e.g String s; is just a declaration while String s = new String (”abcd”); Or String s = “abcd”; are both definitions.

Q:What is the default value of an object reference declared as an instance variable?

A: null unless we define it explicitly.

Q:Can a top level class be private or protected?

A: No. A top level class can not be private or protected. It can have either “public” or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the “modifier private is not allowed here”. This means that a top level class can not be private. Same is the case with protected.

Q:What type of parameter passing does Java support?

A:In Java the arguments are always passed by value .

Q:Primitive data types are passed by reference or pass by value?

A: Primitive data types are passed by value.

Q:Objects are passed by value or by reference?

A: Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object .