JAVA Interview Questions

This blog is meant for the professional who are in java platform or interested to work on java platform. This is my small attempt to gather some useful questions generally asked in the java interviews. If anybody finds some errors in the answer please do mail me and give ur useful comments which helps me to improve this blog and make it error free.

My Photo
Name:
Location: Bhubaneswar, Orissa, India

Nothing on this planet is more powerful than a person who has made a decision to achieve something.

October 15, 2006

CORE JAVA RELATED QUESTIONS

Q. What is the difference between an abstract class and an interface?
A. An abstract class allows its subclasses to override the methods defined in it. It is never instantiated and a class can inherit from a single class, as Java doesn’t support for Multiple Inheritance. It may contain both abstract and non-abstract methods. An interface has public, abstract methods and may have public, static and final variables (read only). It introduces multiple inheritance by a class implementing several interfaces.
An example:
interface Movable { abstract move ();} abstract class Mammal{ void getHeight(float height){ ... } abstract eat();} abstract class Vehicle{ void getSizeofSeat(float seatSize){ ... } abstract engineType();} class Student extends Mammal implements Move{ ...... getheight(height); void eat(){ ....... } void move();}class Car extends Vehicle implements Move{ ...... getSizeofSeat(float seatSizevoid engineTypr(){ ....... } void move();}

Hence Student and Car is not related but they can still implement the Move interface.
Q. What is a user-defined exception?
A. For every project you implement you need to have a project dependent exception class so that objects of this type can be thrown so in order to cater this kind of requirement the need for user defined exception class is realized.
for example:
class MyException extends Exception{ public MyException(){};public MyException(String msg){ super(msg);} }
Q. What do you know about the garbage collector?
A. In Java, memory management is done automatically by JVM.A programmer is free of this responsibility of handling memory. A garbage collector is a part of JVM responsible for removing objects from heap, which is no longer in use. The garbage collector typically runs in a background thread, periodically scanning the heap, identifying discardable objects, and releasing the memory they occupy so that the memory is available for future objects.
Q. What is the difference between C++ and Java?
A. Java is a platform independent, pure object oriented language while C++ is having some of its features from C, which is a procedural language so it is not pure object oriented. Pointers are supported in C++ while not in Java. The memory management is done automatically with help of part of JVM called Garbage Collector. Multiple inheritance is not supported in Java but supported in C++. There are no structures, unions or enumeration in Java. There is no scope resolution operator in Java (::). There are no destructors in Java like C++. There is no virtual keyword in Java because all non-static method use dynamic binding.
Q. What is the difference between process and threads?
A. A thread is part of a process; a process may contain several different threads. Two threads of the same process share a good deal of state and are not protected against one another, whereas two different processes share no state and are protected against one another. Two threads of the same process have different values of the program counter; different stacks (local variables); and different registers. The program counter, stack pointer, and registers are therefore saved in the thread table. Two threads share open files and memory allocation; therefore, file information and memory information (e.g. base/limit register or page table) is stored in the process table.
Q. What is a JAR file?
A. A JAR file is a Java Archive file and is an assembly of class files, resource files and a manifest files bundled together.
Q. What is the use of interface?
A. An interface is a collection of public abstract methods and read only i.e. public, static and final variables.The concept of interfaces in Java makes Multiple Inheritance a reality. Two or more non-related classes can implement the same interface. A class can implement multiple interfaces.
Q. What is polymorphism/late binding/dynamic binding?
A. When an object is sent a message then it does not know itself what type it is, the runtime environment will decide about function calling over an object. This feature of connecting an object with its associated message at runtime is known as Polymorphism or Late binding or Dynamic binding.
Q. What is Collection?
A. A Collection is an object, which represents an assembly of objects called elements. e.g. Vector class.
Q. Why Java does not support multiple inheritance?
A. In designer’s view Multiple Inheritance poses many problems and confusions than it solves.e.g. famous Diamond problemThe diamond problem is an ambiguity that can occur when a class multiply inherits from two classes that both descend from a common super class.In such scenarios assuming if Java implements multiple inheritance then it would be difficult to know which method is to be called by an inheriting class object of two of the super classes In Java, interfaces solve all these ambiguities caused by the diamond problem. Through interfaces, Java allows multiple inheritance of interface but not of implementation. Implementation, which includes instance variables and method implementations, is always singly inherited. As a result, confusion will never arise in Java over which inherited instance variable or method implementation to use.
Q. What is serializable interface?
A. In java.io package there is an interface called java.io.Serializable, which is a syntactic way of serializing objects. This interface does not define any method. The purpose of serialization is persistence, communication over sockets or RMI. In Object serialization an object can be converted into byte stream and vice versa.
Q. Why we use OOPS concepts what are its adv?
A. In OOPS everything is expressed in terms of Objects and Classes. e.g. a ‘man’ is considered an object of ‘human’ class. This approach helps in designing complex real time systems with ease. In OOP domain objects communicate with each other through message passing. The features that OOPS provide are Data Abstraction and Encapsulation, Inheritance and Polymorphism. Advantages:ReusabilityModular approach towards problem solvingBetter MaintainabilityBetter Performance
Q. Why Java is not 100% pure OOP language?
A. It does not support Multiple Inheritance.
Q. What is exception?
A. An exception is an abnormal behavior existing during a normal execution of a program. For example: When writing to a file if there does not exist required file then an appropriate exception will be thrown by java code.
Q. What are the ways you can handle exception?
A. In Java exceptions are handled in try, catch, throw and finally blocks. It says try a block of Java code for a set of exception/s catch an exception if it appears in a catch block of code separate from normal execution of code. It clearly segregates errors from a block of code in an effective and efficient manner. The exceptions, which are caught, thrown using throw keyword. A finally block is called in order to execute clean up activities for any mess caused during abnormal execution of program.
Q. Checked and Unchecked exception.
A. A checked exception is one, which a block of code is likely to throw, and represented by throws clause. In Java it is expected that a method ‘throws’ an exception which is a checked exception.
Q. What is finally in Exception handling?
A. ‘finally’ is a part of try-catch-throw and finally blocks for exception handling mechanism in Java.’finally‘ block contains snippet which is always executed irrespective of exception occurrence. The runtime system always executes the statements within the finally block regardless of what happens within the try block. The cleanup code is generally written in this part of snippet e.g. dangling references are collected here.
Q. Difference between ArrayList and Vector class?
A. From an API perspective, the two classes are very similar. Vectors are synchronized. Any method that touches the Vector's contents is thread safe. ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe. With that difference in mind, using synchronization will incur a performance hit. So if you don't need a thread-safe collection, use the ArrayList. Internally, both the ArrayList and Vector hold onto their contents using an Array. You need to keep this fact in mind while using either in your programs. When you insert an element into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. Depending on how you use these classes, you could end up taking a large performance hit while adding new elements. It's always best to set the object's initial capacity to the largest capacity that your program will need. By carefully setting the capacity, you can avoid paying the penalty needed to resize the internal array later. If you don't know how much data you'll have, but you do know the rate at which it grows, Vector does possess a slight advantage since you can set the increment value.
Q. What is a Vector class?
A. A Vector class is an important class of java.util.* package responsible for keeping the objects within it.This implements Cloneable, Collection, List, RandomAccess, Serializable interfaces. java.lang.Object
java.util.AbstractCollection
java.util.AbstractList
java.util.Vector
This is a class of growing array objects. The objects can be accessed using integer indexing. The size of a Vector can grow dynamically. Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. The capacity is always at least as large as the vector size; it is usually larger because as components are added to the vector, the vector's storage increases in chunks the size of capacityIncrement. An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation. Vector is Synchronized or Thread Safe.
Q. Two types of multitasking?
A. Co-operativeIn case of co-operative multitasking applications consume resources i.e. memory and CPU cycle and once it is completed with its execution of set of instructions, it returns control back to the OS. The scheme depends on the application co-operating and so is known as co-operative multitasking. In cases where the application entered an endless loop and never reached the code which handed control back to the operating system, the whole machine became locked up.
An example is Windows 3.1
Pre –emptiveIn this technique the operating system allocates resources to an application. This will enable it to execute. Rather than wait for the application to give the resources up, the operating system is activated at certain time intervals and may take the resources back from the executing application and allocate them to another application that is waiting.Example: Unix, Windows NT, and 32 bit programs running under Windows '95
Q. Two ways of creating thread
A. Threads can be created in the following ways : Instantiating a class extending java.lang.Thread class and calling start() method Creating a java.lang.Thread and passing a reference of a class implementing Runnable interface.Then calling start() method on this object. Q. What is Synchronization?
A. In Java, JVM takes care of thread synchronization. Java support multithreading and data is shared along multiple threads. Inside the Java virtual machine, each thread is awarded a Java stack, which contains data no other thread can access, including the local variables, parameters, and return values of each method the thread has invoked. The data on the stack is limited to primitive types and object references. In the JVM, it is not possible to place the image of an actual object on the stack. All objects reside on the heap.There is only one heap inside the JVM, and all threads share it. The heap contains nothing but objects. There is no way to place a solitary primitive type or object reference on the heap -- these things must be part of an object. Arrays reside on the heap, including arrays of primitive types, but in Java, arrays are objects too. Besides the Java stack and the heap, the other place data may reside in the JVM is the method area, which contains all the class (or static) variables used by the program. The method area is similar to the stack in that it contains only primitive types and object references. Unlike the stack, however, the class variables in the method area are shared by all threads.Object and class locks As described above, two memory areas in the Java virtual machine contain data shared by all threads. These are: The heap, which contains all objects The method area, which contains all class variables If multiple threads need to use the same objects or class variables concurrently, their access to the data must be properly managed. Otherwise, the program will have unpredictable behavior. To coordinate shared data access among multiple threads, the Java virtual machine associates a lock with each object and class. A lock is like a privilege that only one thread can "possess" at any one time. If a thread wants to lock a particular object or class, it asks the JVM. At some point after the thread asks the JVM for a lock -- maybe very soon, maybe later, possibly never -- the JVM gives the lock to the thread. When the thread no longer needs the lock, it returns it to the JVM. If another thread has requested the same lock, the JVM passes the lock to that thread. Class locks are actually implemented as object locks. When the JVM loads a class file, it creates an instance of class java.lang.Class. When you lock a class, you are actually locking that class's Class object. Threads need not obtain a lock to access instance or class variables. If a thread does obtain a lock, however, no other thread can access the locked data until the thread that owns the lock releases it. Monitors The JVM uses locks in conjunction with monitors. A monitor is basically a guardian in that it watches over a sequence of code, making sure only one thread at a time executes the code. Each monitor is associated with an object reference. When a thread arrives at the first instruction in a block of code that is under the watchful eye of a monitor, the thread must obtain a lock on the referenced object. The thread is not allowed to execute the code until it obtains the lock. Once it has obtained the lock, the thread enters the block of protected code. When the thread leaves the block, no matter how it leaves the block, it releases the lock on the associated object.
Q. What is memory leak?
A. A memory leak occurs when all references (pointers) to a piece ofallocated memory are overwritten, cleared, or pass out of scope. The result is thatthe program simply “forgets” about that particular piece of memory.Unfortunately, the operating environment (usually an OS) is not aware of theapplication’s amnesia. That memory is treated by the outside world as though itstill belongs to the application. The memory is therefore completely unavailable;it has “leaked”. (In the worst case, the memory can become unavailable to allapplications in the system, even if the application that created the leak isterminated. The memory can only be reclaimed by rebooting the system.)
Q. public static void main explain?
A. It is the main entry point of a java file. Every java file has just single copy of main method from where main thread is invoked and that’s why main method is static. This method can be overloaded but JVM will distinguish public static void main from rest of the overloaded main methods.
Q. If you have static block, constructor and main method in Java file then what will be the sequence of method calls?
A. Sequence will be:
1. static
2. main
3. constructor
Q. What are the command line arguments?
A. Whenever a java file is executed it is done by java command given as below:java Usage: java [-options] class [args...] (to execute a class) or java -jar [-options] jarfile [args...] (to execute a jar file)when some arguments are also passed with execution command then these arguments are called command line arguments as they are taken as an array of String as a parameter in main method.
Q. Explain 3-tier architecture?
A. In 3-tier architecture an application’s logic is segregated in three layers:• Client side View Logic/Presentation Logic• Middleware centric Business Logic• Database end Data LogicThis approach has an essence of dividing responsibilities of overall application in order to achieve better performance, reusability and scalability.
Q. Difference between String and StringBuffer?
A. String objects are immutable. It means any method like concat, substring, replace called upon an existing String object will return a new String object i.e. updations of an existing String object will not be reflected in the same object rather a new String object will be created. A StringBuffer implements a mutable sequence of characters, which can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. The principal operations on a StringBuffer are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer. The append method always adds these characters at the end of the buffer; the insert method adds the characters at a specified point.
Q. What are Wrapper classes? Is String a Wrapper Class?
A. The Wrapper classes in Java are those classes which wrap primitive data i.e. char, int, float, double correspond to Character, Integer, Float, Double wrapper classes. String is not a wrapper class but a final class which provides immutable objects which can be shared.
Q. What are the restrictions for static method?
A. Whenever you say something is static that means data or method is not associated with an object instance of that class. Only a single copy of that will be created for that class. So even if you have never created an object of a class you an always access static data and method of that class. A static method cannot access non static data. An abstract method cannot be static.
Q. How does thread synchronization occurs inside a monitor?
A. In multithreaded environment where many a threads are trying to access a piece of code then a thread will first acquire a lock on the object and then execute code related with it. Once a thread is free then lock will be free for rest of the threads vying to have an access over the code. In Java this mechanism is obtained over a method or a block of code mentioned as synchronize.
Q. What is a Daemon thread?
A. A ‘‘daemon’’ thread is one that is supposed to provide a general service in the background as long as the program is running, but is not part of the essence of the program. Thus, when all of the nondaemon threads complete the program is terminated. Conversely, if there are any non-daemon threads still running the program doesn’ t terminate.
Q. How can a dead thread be started?
A. There is no mechanism for starting a dead thread.
Q. Can Applet have a constructor?
A. An applet can have constructor calling a constructor of its base class i.e. java.awt.Applet but it will not be overridden. The init() method, which works much like a constructor, handles whatever initialization your applet requires. The browser or applet viewer automatically calls it to perform applet initialization each time the applet is loaded. In light of this, we recommend that applets do not have constructors because an applet is not guaranteed to have a full environment until its init() method has been called. For example, let's say you want to perform applet image loading inside of an applet constructor. This simply will not work, and should be performed inside the init() method instead. To sum up, an applet constructor is the constructor of the applet, which has been subclassed from the Applet class. Moreover, this constructor can not be overridden. Therefore, because it is not very useful to define an applet constructor, we advise that you employ an overridden init() method for all initialization.
Q. Explain StreamTokenizer?
A. The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time. The parsing process is controlled by a table and a number of flags that can be set to various states. The stream tokenizer can recognize identifiers, numbers, quoted strings, and various comment styles. Each byte read from the input stream is regarded as a character in the range '\u0000' through '\u00FF'. The character value is used to look up five possible attributes of the character: white space, alphabetic, numeric, string quote, and comment character. Each character can have zero or more of these attributes. In addition, an instance has four flags. These flags indicate: Whether line terminators are to be returned as tokens or treated as white space that merely separates tokens. Whether C-style comments are to be recognized and skipped. Whether C++-style comments are to be recognized and skipped. Whether the characters of identifiers are converted to lowercase. A typical application first constructs an instance of this class, sets up the syntax tables, and then repeatedly loops calling the nextToken method in each iteration of the loop until it returns the value TT_EOF.
Q. What are the types of access modifiers?
A. public :A variable with public access modifier can be accessed by any class.
private: A variable with private access modifier can be accessed within that class only.
protected: A variable with protected access modifier can be accessed within subclasses of a
class having protected variables.default
Q. Is synchronized a modifier?
A. It is a keyword for making a method or a block of code thread safe. Only and only one thread can access a synchronized block or method at a time.
Q. What is method overloading?
A. A method with changed formal parameters will lead to implementing method overloading. int calculateSum(int i,int j)float calculateSum(float i,int j)double calculateSum(double i,int j)float calculateSum(int i,float j)
Q. What is method overriding?
A. The method with same signature but with changed implementation lead to method overriding and that can occur in a parent child relation of classes.A method defined in parent class can be overridden in its child class with different implementation from its base class.
Q. Does java support multi dimensional arrays?
A. Java supports an array of arrays rather multidimensional arrays.

0 Comments:

Post a Comment

<< Home