Core Java Interview Questions and Answers for Experienced

Why we preferred event-delegation model over earlier event-inheritance model?

The event-delegation model has two advantages over the event-inheritance model.

- Event-delegation helps in event handling by objects other than those who generate the events.
- Help in differentiating between component design and its use.
- Event-delegation performs much better in applications where generation of events takes place.
- Event-delegation model does not repeatedly process unhandled events, which cause improvement in the performance.

How is Java source code files named?

Java source code file takes the name of a public class or interface that is defined by the programmer while coding within the file. Source code file may contain maximum one public class or interface in the file. Two cases me occur while naming of the java source code file:

- When public class or interface is defined within a source code file then the java source code file must take the name of the public class or interface defined while coding.

- When no public class or interface is defined inside a source code file, then the java source code file take a name that is different than its classes and interfaces. Source code files use the .java extension.

What are the advantages of Java layout managers?

In Java Button, Checkbox, Lists, Scrollbars, Text Fields and Text Area etc. are positioned by the default layout manager. Using algorithm layout manager automatically arranges the controls within a window. In Windows environment, we can control layout manually. But we do not do it manual because of following two reasons:

- It is very tedious to manually lay out a large number of components.
- Sometimes the width and height information is not available when you need to arrange some control, because the native toolkit components have not been realized.

Java uses layout managers to lay out components in a consistent manner across all windowing platforms.

What is the difference between a Choice and a List?

The difference between Choice and List are as follows:

- Choice class presents a pop-up menu of choices whereas List is a collection of different visible item.
- Choice is displayed in a compact form, to see the list of available choices we need to scroll down whereas list displays the entire available items.
- Choice allows selecting only one items but List supports the selection of one or more List items.
- Lists typically allow duplicate elements selection. List allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all.

What is the difference between the event model and the event-delegation model?

Difference between event model and event-delegation are as follows:

- The event-delegation model eliminates the processing required to support in the handling of unhandled events.
- Event delegation model allow components to handle their own events. When components are unable to handle a particular event, then event is inherited by the component container.
- In the event-delegation model, specific objects are designated as event handlers for GUI components. These objects implement event-listener interfaces.
- The JDK 1.02 event model uses an event inheritance.

What restrictions are placed on method overriding?

The restrictions on method overloading are the signature of the method.

- Signature is number, type, and order of the arguments passed to a method.
- Overridden methods must have the same name, argument list, and return type.
- Any method which has the same name cannot have the same signature.
- They can have the same return types in the same scope.
- The compiler uses the signature to detect which overloaded method to refer when an overloaded method is called.
- If two methods have the same name and signature the compiler will throw a runtime error.

What is numeric promotion?

Numeric promotions are used for the conversion of the operands of a numeric operator into a common type. This conversation is performed so that we can easily perform the calculation on it.

- It is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations can be performed over it.
- In this byte, char, and short values are converted to int values.
- The int values are also converted to long values. The long and float values are converted to double values.

Can you compare SWING and AWT?

Swing components operate same as AWT components, the only differences are that Swing provides a number of new event types.

- Few Swing components don't have an AWT counterpart.
- Swing is an extension of AWT. It is not the replacement for the AWT.
- The advantages of Swing components is components are not rendered on the screen by the operating system, the look and feel of a component does not change when application is running on different platform using different versions.
- It is possible to cause Swing components to mimic the look and feel of a specific platform no matter what platform the program is running on. This is known as pluggable look and feel.

Does networking is support in Java ?

Yes, Java supports two types of classes:

- Low-Level Classes: provide support for socket programming like Socket, DatagramSocket, and ServerSocket classes.
- High-Level Classes: provide web programming URL, URLEncoder, and URLConnection classes.

Networking programming classes ease the programming of network applications. Java networking like anything else in Java is platform-independent.

Describe java's security model.

The Java security model was introduced in Java 2. It is divided into two pieces:

- User Adjustable Security Manager: checks various API operations like file access
- Byte Code Verifier: that asserts the validity of compiled byte code.

Public abstract class SecurityManager java.lang. SecurityManager is an abstract class which helps to different applications subclass to implement a particular security policy. It allows an application to determine whether or not a particular operation will generate a security exception.

What is Race condition?

Race Condition: It is the situation when two threads raise the request for the same resource allocation, but the manner in which resources are allocated are significant, is called race conditions.

- Race condition is created in program in order to run the parallel execution of program by using multiple threads in a same period.
- A race condition occurs when two threads operate on same object without proper synchronization and there operation interleaves on each other.
- The risk of Race condition is higher in Java.

What is difference between StringBuffer and StringBuilder in Java?

The difference between StringBuffer and StringBuilder are as follows:

- StringBuffer is uses mutable String, all public methods are synchronized which makes it thread-safe but same time slow but In JDK 5 they provided StringBuilder which is copy of StringBuffer without synchronization.
- StringBuilder is compatible with StringBuffer, but synchronization property is may not compatible.
- StringBuilder is a little faster than StringBuffer.

What is Marker Interface?

Marker interface in Java is interface with no field or methods. Uses of Marker Interfaces are following:

- We use Marker interface to tell java compiler to add special behavior to the class implementing it.
- Java marker interface has no members in it.
- It is implemented by classes to get some functionality.

Example: When we want to save the state of an object then we implement serializable interface.

What is the main difference between shallow cloning and deep cloning of objects?

The differences between shallow cloning and deep cloning are:

- Java supports shallow cloning of objects by default when a class implements the java.lang. Cloneable interface where as Deep cloning is faster to develop and easier to maintain but carries a performance overhead.
- A shallow is a copy of the collection structure whereas Deep cloning copies duplicate everything.
- In Shallow copy, individual elements can be shared between two collection but in case of deep cloning two collections with all of the elements is the original collection duplicate.

What are the difference between throw and throws?

The differences are between throw and throws are:

- Throw is used to trigger an exception where as throws is used in declaration of exception.
- Without throws, Checked exception cannot be handled where as checked exception can be propagated with throws.
- Throw is used inside the method where as throws is used with the method signature.
- Throw is followed by an instance but throws is followed by class.

What is difference between preemptive scheduling and time slicing?

Differences between preemptive and time scheduling are:

- In Preemptive scheduling the highest priority task executes until it enters the waiting or dead stated or a higher priority task comes into existence.
- Time slicing, a task executes for a predefined time period and then the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factor.

What differences are between submit and execute method with ThreadPoolExecutor?

The difference between submit and execute method with ThreadPoolExecutor are:

- When our tasks throw an exception and if it was submitted with execute this exception will go to the uncaught exception handler. If you submitted the task with submit any thrown exception, checked or not, is then part of the task return status.

What is the difference between final, finally and finalize methods in Java?

Final – a key word to define constants.

- After declaring a class as final we cannot divide it into subclasses.
- When a method is marked final, it cannot be overridden by the subclass.
- When a field is marked final, its value once set, cannot be reset.

Finally – The finally block is always used with try and catch blocks, except that, when try block uses System.exit(0) call.

- It is ensured for unexpected error, the finally block do the execution which is mention in last clause of a try catch block.
- It is a block of statements that is executed irrespective if or if not an exception was caught in the preceding try block.

Finalize() – This method is linked with garbage collection.

- This method is invoked automatically, just before the collection of garbage value.

What are the types of 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, like 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.

Describe what happens when an object is created in Java.

Several things happen in a particular order to ensure the object is constructed properly:

1. Memory allocation: To hold all instance variables and implementation-specific data of the object and its super classes.
2. Initialization: the objects are initialized to their default values.
3. Constructor: Constructors call the constructors for its super classes. This process continues until the constructor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java.
4. Execution: Before the body of the constructor is executed all instance variable initializes and initialization blocks must get executed. Then the body of the constructor is executed.

Can an inner class be built in an Interface?

- Yes,an inner class may be built an Interface
Example :
public interface xyz
   static int p=0;
   void m();
   class c
           int q;

public static void main(String c[])
   System.out.println("inside ");

Why is explicit object casting needed?

In order to assign a superclass object in a variable to a subclass,one needs to do explicit casting.

For example:
Person person;
Man man;
man = (Man)person;
An automatic casting takes place when we typecast a object in subclass as parent class object.

Define Externalizable.

Externalizable is coined as an Interface
- It extends the Serializable Interface.
- It also sends data into the Streams.
- Externalizable sends data in a Compressed Format.
- Externalizable is having two methods, for e.g. writeExternal(ObjectOuput out) & readExternal(ObjectInput in)

How can a collection object be sorted?

- // Sort

- // Sort case-insensitive
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

- // SortReverse-order
Collections.sort(list, Collections.reverseOrder ());

- // Reverse-order sort case-insensitive
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

Define local, member and a class variable.

- Within a method variables declared are called “local” variables.

- Variables declared in the class i.e not in any methods are “member” variables (global variables).

- Variables declared in the class i.e not in any methods and are called as “static” are class variables

Name the different identifier states of a Thread.

Different types of identifiers of a Thread are:

- R - Running or runnable thread
- S - Suspended thread
- CW - Thread waiting on a condition variable
- MW - Thread waiting on a monitor lock
- MS - Thread suspended waiting on a monitor lock

Define Vector class. Differentiate the Vector and ArrayList.

- Vector can be termed a legacy class which has been introduced to implement the List interface since Java 2 platform v1.2
- Vector is always synchronized but ArrayList is not.
- When Vector class is synchronized, while running in multithreading environment we've to use ArrayList with Collections.
- Vector has a default size i.e 10 while arrayList has no default size .
- ArraayList does not any method returning Enumerations where as vector list is having.

Differentiate between Enumeration and Iterator interface

- In java.util package the Enumeration and Iterator are available.
- The Enumeration interface is replicated by the Iterator interface.
- In preference to Enumeration new implementations should consider using Iterator.

The difference of Iterators from enumerations are:

Enumeration has 2 methods namely hasMoreElements() & nextElement() where the Iterator contained three methods namely hasNext(), next(),remove().

An optional remove operation is added in Iterator,and has shorter method names. We Use remove() to delete the objects but the Enumeration interface does not support this feature.

The legacy classes use Enumeration interface .Vector.elements() & Hashtable.elements() method results Enumeration. All Java Collections Framework classes returns iterator. java.util.Collection.iterator() method returning an instance of Iterator.

What are the alternatives to inheritance?

- Delegation is an alternative to inheritance.

- Delegation denotes that you include an instance of any class as an instance variable, and forward messages to the instance.

- It is safer than inheritance because it ceases you to think about forwarded message , because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense.

- On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

Number the bits, used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?

- Unicode requires 16 bits

- ASCII require 7 bits. but it is usually represented as 8 bits.

- UTF-8 represents characters using 8, 16, and 18 bit patterns.

- UTF-16 uses 16-bit and larger bit patterns.
Define reflection

- Reflection allows program related access to information about the fields, methods and constructors of loaded classes

- It use reflected fields, methods, and constructors

- It helps to operate on their underlying counterparts on objects,

- It operates within security restrictions.

What is RMI and how it is useful?

- Remote method invocation is called RMI.

- One can work with remote object using RMI .

- It gives a impression that you are working with a object that resides within your own JVM though it is somewhere.

- The protocol used by RMI is RMI-IIOP

Define a Collection API.

- The set of classes and interfaces supporting the operation on collections of objects is the Collection API .

- Than the vectors, arrays, and hashtables if effectively replaces, these classes and interfaces are more flexible, more powerful, and more regular

- class examples: HashSet, TreeMap, ArrayList, LinkedList,HashMap and TreeMap.

- interface examples: Set,List ,Collection and Map.

How many forms of Polymorphism are there?

Polymorphism exists in three different forms in Java:

- Method overloading.
- Method overriding through inheritance.
- Method overriding through the Java interface.

Define the wrapper classes in Java and name a few.

- Wrapper class is wraps around the primitive data type.

- List of the primitive types and the corresponding wrapper classes:

1. Primitive Wrapper
2. boolean java.lang.Boolean
3. byte java.lang.Byte
4. char java.lang.Character
5. double java.lang.Double
6. float java.lang.Float
7. int java.lang.Integer
8. long java.lang.Long
9. short java.lang.Short
10 .void java.lang.Void

Differentiate between JDK, JRE & JVM

- JDK stands for Java Development Kit.
It is the most widely used Java Software Development Kit.

- JRE stands for Java Runtime Environment
It is an implementation of the Java Virtual Machine which executes Java programs

- JVM stands for Java Virtual Machine
It is an interpreter.

Why will you use Comparator and Comparable interfaces?

- java.util.Comparator
It compares some other class’s instances,

- java.lang.Comparable
It compares another object with itself .

Differentiate between final, finally and finalize.

- The keyword is final.sss
It is used for declaring a constant
It prevents a class from producing subclasses.

- finally is a code.
It always executes when the try block is finished,
Unless System.exit() has been called.

- finalize() is a method,
Before discarding by the garbage collector it is invoked .

Differentiate JAR and WAR files

JAR files
- JAR files stands for Java Archive Files.
- JAR files allow aggregating many files into one,
- JAR is usually used to hold Java classes in a library.

WAR files
- WAR files stands for Web Archive Files.
- WAR stores XML, java classes, and JavaServer pages
- WAR is mainly used for Web Application purposes.`

In Java, how can you send program messages on the system console, but error messages to a file?

- The class System has a variable out that denotes the standard output,
- The standard error device represents the variable err .
- Naturally, they both point at the system console.

In this way, the standard output can be sent to the file:
Stream x = new Stream(new FileOutputStream("error.txt"));
Define class and object. Explain them with an example using java
Class and object - Class: A class is a program construct which encapsulates data and operations on data. In object oriented programming, the class can be viewed as a blue print of an object...
What is a method? Provide several signatures of the methods
What is a method? - A java method is a set of statements to perform a task. A method is placed in a class...
Difference between instance variable and a class variable
Difference between instance variable and a class variable - An instance variable is a variable which has one copy per object / instance. That means every object will have one copy of it...
Post your comment
Discussion Board
Comment on this article
Its nice and help for interviews
C.V.S.REDDY 11-27-2012