PDA

View Full Version : Java Interview Questions


masterstroke
23-12-2009, 05:54 AM
Q) What is explicit casting?

Explicit casting in the process in which the complier are specifically informed to about transforming the object.

Example

long i = 700.20;

int j = (int) i; //Explicit casting

masterstroke
23-12-2009, 05:56 AM
Access specifiers are keywords that determine the type of access to the member of a class. These keywords are for allowing privileges to parts of a program such as functions and variables. These are:

Public : accessible to all classes
Protected : accessible to the classes within the same package and any subclasses.
Private : accessible only to the class to which they belong
Default : accessible to the class to which they belong and to subclasses within the same package

masterstroke
23-12-2009, 05:57 AM
Object class is the superclass of every class.

masterstroke
23-12-2009, 05:58 AM
The 8 primitive types are byte, char, short, int, long, float, double, and boolean.

masterstroke
23-12-2009, 06:00 AM
A static variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static variables i.e. 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. These are declared outside a class and stored in static memory. Class variables are mostly used for constants.

Static variables are always called by the class name.

This variable is created when the program starts and gets destroyed when the programs stops.

The scope of the class variable is same an instance variable. Its initial value is same as instance variable and gets a default value when its not initialized corresponding to the data type.

Similarly, a static method is a method that belongs to the class rather than any object of the class and doesn’t apply to an object or even require that any objects of the class have been instantiated.

Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object.

A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final.

However, you can’t override a static method with a non-static method. In other words, you can’t change a static method into an instance method in a subclass.

Non-static variables take on unique values with each object instance.

masterstroke
23-12-2009, 06:02 AM
If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the && operator is a short cut operator.

When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. If the first operand evaluates to false, the evaluation of the second operand is skipped.

masterstroke
23-12-2009, 06:02 AM
Program compiles and runs properly.

masterstroke
23-12-2009, 06:03 AM
In declaration we only mention the type of the variable and its name without initializing it.

Defining means declaration + initialization.

E.g. String str; is just a declaration

while String str = new String (”abhi”); Or String str = “abhi”; are both definitions.

masterstroke
23-12-2009, 06:04 AM
In Java the arguments (primitives and objects) are always passed 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.

masterstroke
23-12-2009, 06:05 AM
Encapsulation 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. Objects allow procedures to be encapsulated with their data to reduce potential interference. 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.

masterstroke
23-12-2009, 06:07 AM
The Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integral and floating-point operations may take place.

In the numerical promotion process the byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.

masterstroke
23-12-2009, 06:08 AM
The process of converting one data type to another is called Casting. There are two types of casting in Java; these are implicit casting and explicit casting.

Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not work for all scenarios.

Example

int i = 1000;

long j = i; //Implicit casting


Explicit casting in the process in which the complier are specifically informed to about transforming the object.

Example

long i = 700.20;

int j = (int) i; //Explicit casting

masterstroke
23-12-2009, 06:09 AM
Print array.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print array.length.

masterstroke
23-12-2009, 06:11 AM
We can have multiple overloaded main methods but there can be only one main method with the following signature :

public static void main(String[] args) {}

No the program fails to compile. The compiler says that the main method is already defined in the class.

masterstroke
23-12-2009, 06:11 AM
JVM is an abstract computing machine like any other real computing machine which first converts .java file into .class file by using Compiler (.class is nothing but byte code file.) and Interpreter reads byte codes.

masterstroke
23-12-2009, 06:12 AM
Add two variables and assign the value into First variable. Subtract the Second value with the result Value. and assign to Second variable. Subtract the Result of First Variable With Result of Second Variable and Assign to First Variable. Example:

int a=5,b=10;a=a+b; b=a-b; a=a-b;

An other approach to the same question

You use an XOR swap.

for example:

int a = 5; int b = 10;
a = a ^ b;
b = a ^ b;
a = a ^ b;

masterstroke
23-12-2009, 06:13 AM
Encapsulation may be used by creating ‘get’ and ’set’ methods in a class (JAVABEAN) which are used to access the fields of the object. Typically the fields are made private while the get and set methods are public. Encapsulation can be used to validate the data that is to be stored, to do calculations on data that is stored in a field or fields, or for use in introspection (often the case when using javabeans in Struts, for instance). Wrapping of data and function into a single unit is called as data encapsulation. Encapsulation is nothing but wrapping up the data and associated methods into a single unit in such a way that data can be accessed with the help of associated methods. Encapsulation provides data security. It is nothing but data hiding.

masterstroke
23-12-2009, 06:14 AM
Reflection is the process of introspecting the features and state of a class at runtime and dynamically manipulate at run time. This is supported using Reflection API with built-in classes like Class, Method, Fields, Constructors etc. Example: Using Java Reflection API we can get the class name, by using the getName method.

masterstroke
23-12-2009, 06:14 AM
Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the OS heap or the heap maintained by the JVM? Why

Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to those objects are on the STACK.

masterstroke
23-12-2009, 06:15 AM
A StringTokenizer is utility class used to break up string.

Example:

StringTokenizer str = new StringTokenizer(”Hello World”);

while (str.hasMoreTokens()) {

System.out.println(str.nextToken());

}

Output:

Hello

World

masterstroke
23-12-2009, 06:18 AM
No. It is by default loaded internally by the JVM. The java.lang package is always imported by default.

masterstroke
23-12-2009, 06:18 AM
One can import the same package or same class multiple times. Neither compiler nor JVM complains anything about it. And the JVM will internally load the class only once no matter how many times you import the same class.

masterstroke
23-12-2009, 06:20 AM
Does importing com.abhi.* also import com.abhi.pgr.*?

No you will have to import the sub packages explicitly. Importing com.abhi.* will import classes in the package abhi only. It will not import any class in any of its sub packages.

masterstroke
23-12-2009, 06:20 AM
A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces.

Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.

For example: The Java API is grouped into libraries of related classes and interfaces; these libraries are known as package.

masterstroke
23-12-2009, 06:21 AM
e.g. will the code containing an import such as java.lang.abhi compile?

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, cannot resolve symbol.

masterstroke
23-12-2009, 06:24 AM
String objects are immutable whereas StringBuffer objects are not. StringBuffer unlike Strings support growable and modifiable strings.

sunita
25-12-2009, 07:01 AM
null unless we define it explicitly.

sunita
25-12-2009, 07:01 AM
A constructor is a member function of a class that is used to create objects of that class, invoked using the new operator. It has the same name as the class and has no return type. They are only called once, whereas member functions can be called many times. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator. Constructor will be automatically invoked when an object is created whereas method has to be called explicitly.

super.method(); is used to call a super class method from a sub class. To call a constructor of the super class, we use the super(); statement as the first line of the subclass constructor.

sunita
25-12-2009, 07:03 AM
Java does support multiple inheritance via interface implementation.

sunita
25-12-2009, 07:03 AM
Private constructor can be used if you do not want any other class to instantiate the class. This concept is generally used in Singleton Design Pattern. The instantiation of such classes is done from a static public method.

sunita
25-12-2009, 07:05 AM
this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

shilpa
02-01-2010, 09:56 AM
How many methods in the Serializable interface? Which methods of Serializable interface should I implement?

There is no method in the Serializable interface. It is an empty interface which does not contain any methods. The Serializable interface acts as a marker, telling the object serialization tools that the class is serializable. So we do not implement any methods.

shilpa
02-01-2010, 09:57 AM
What is the difference between Serializalble and Externalizable interface? How can you control over the serialization process i.e. how can you customize the seralization process?

When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class’s serialization process. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.

shilpa
02-01-2010, 09:58 AM
An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object. The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.

shilpa
02-01-2010, 09:59 AM
The serialization is a kind of mechanism that makes a class or a bean persistent by having its properties or fields and state information saved and restored to and from storage. That is, it is a mechanism with which you can save the state of an object by converting it to a byte stream. Whenever an object is to be sent over the network or saved in a file, objects are serialized.

shilpa
02-01-2010, 10:00 AM
A transient variable is a variable that may not be serialized i.e. the value of the variable can't be written to the stream in a Serializable class. If you don’t want some field to be serialized, you can mark that field transient or static. In such a case when the class is retrieved from the ObjectStream the value of the variable is null.

Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.

rajesh
06-01-2010, 07:00 AM
Iterator enables us to cycle through a collection in the forward direction only, for obtaining or removing elements whereas ListIterator extends Iterator, allow bidirectional traversal of list and the modification of elements

rajesh
06-01-2010, 07:01 AM
A Set stores elements in an unordered way and does not contain duplicate elements, whereas a list stores elements in an ordered way but may contain duplicate elements.

rajesh
06-01-2010, 07:02 AM
The Collections API is a set of classes and interfaces that support operations on collections of objects.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

rajesh
06-01-2010, 07:02 AM
We can access the elements of a collection using the following ways:
1.Every collection object has get(index) method to get the element of the object. This method will return Object.
2.Collection provide Enumeration or Iterator object so that we can get the objects of a collection one by one.

rajesh
06-01-2010, 07:03 AM
The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements. The Map interface is used associate keys with values.

rajesh
06-01-2010, 07:05 AM
1. Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. An abstract class can contain no abstract methods also i.e. abstract class may contain concrete methods. A Java Interface can contain only method declarations and public static final constants and doesn’t contain their implementation. The classes which implement the Interface must provide the method definition for all the methods present.

2. Abstract class definition begins with the keyword “abstract” keyword followed by Class definition. An Interface definition begins with the keyword “interface”.

3. Abstract classes are useful in a situation when some general methods should be implemented and specialization behavior should be implemented by subclasses. Interfaces are useful in a situation when all its properties need to be implemented by subclasses

4. All variables in an Interface are by default - public static final while an abstract class can have instance variables.

5. An interface is also used in situations when a class needs to extend an other class apart from the abstract class. In such situations its not possible to have multiple inheritance of classes. An interface on the other hand can be used when it is required to implement one or more interfaces. Abstract class does not support Multiple Inheritance whereas an Interface supports multiple Inheritance.

6. An Interface can only have public members whereas an abstract class can contain private as well as protected members.

7. A class implementing an interface must implement all of the methods defined in the interface, while a class extending an abstract class need not implement any of the methods defined in the abstract class.

8. The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement those method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass

9. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast

10.Interfaces are often used to describe the peripheral abilities of a class, and not its central identity, E.g. an Automobile class might
implement the Recyclable interface, which could apply to many otherwise totally unrelated objects.

rajesh
06-01-2010, 07:07 AM
An Interface are implicitly abstract and public. Interfaces with empty bodies are called marker interfaces having certain property or behavior.

Examples : java.lang.Cloneable,java.io.Serializable,java.util .EventListener. An interface body can contain constant declarations, method prototype declarations, nested class declarations, and nested interface declarations.

Interfaces provide support for multiple inheritance in Java. A class that implements the interfaces is bound to implement all the methods defined in Interface.

rajesh
06-01-2010, 07:09 AM
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 exception may be thrown. Checked exceptions must be caught at compile time. Example: IOException.

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.
Example: ArrayIndexOutOfBoundsException. Errors are often irrecoverable conditions.