Java interview question for experienced and Core Java Interview Questions and Answers




Java interview question for experienced and Core Java Interview Questions and Answers

Core java interview questions 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 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. This is a chicken-and-egg situation.
  • 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 between Choice and list are following:
  • 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 following:
  • 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 following:
  • 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 interfaces with no field or methods. Uses of Mark Interfaces are following:
  • We use Marker interface to tell java complier to add special behavior to the class implementing it.
  • Java marker interface has no members in it.
  • It is implemented by classes in 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.


Core java interview questions for experienced 




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 { c() { int q; System.out.println("inside"); }; 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 Collections.sort(list); • // 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); Collections.reverse(list);


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 canbe said 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, if we will run 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 is not having 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:

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



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

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

• java.lang.Comparable

• java.lang.Comparable compares another object with itself .



Differentiate between final, finally and finalize.

• The keyword is final.

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 file


JAR files:

• JAR files is the acronym stands for Java ARchive fles.

• JAR files allow aggregating many files into one,

• JAR is usually used to hold Java classes in a library.



WAR files:

• WAR files is the acronym stands for Web ARchive fles.

• WAR stores XML, java classes, and JavaServer pages

• WAR is mainly used for Web Application purposes.`



In a 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"));

System.setErr(x);

System.Out(x); 

Previous
Next Post »