Myblog's Blog

February 19, 2010

Garbage Collection

Filed under: Garbage Collection — technospider @ 10:14 pm

What is difference between C++ Destructor and Java Finalize method ?

November 17, 2009

Filed under: Inner Classes — technospider @ 6:58 pm
Q1) What is an inner class?

Ans) Inner class is a class defined inside other class and act like a member of the enclosing class.
Q2) What are the different types of inner classes?

Ans) There are two main types of inner classes –

  • Static member class
  • Inner class
    • Member class
    • Anonymous class
    • Local class
Q3) What is static member class?

Ans) A static member class behaves much like an ordinary top-level class, except that it can access the static members of the class that contains it. The static nested class can be accessed as the other static members of the enclosing class without having an instance of the outer class. The static class can contain non-static and static members and methods.public class InnerClass {

static class StaticInner {

static int i = 9;
int no = 6;

private void method() {}

public void method1() {}

static void method2() {}

final void method3() {}

}
}

The static inner class can be accessed from Outer Class in the following manner:
InnerClass.StaticInner staticObj= new InnerClass. StaticInner ();

No outer class instance is required to instantiate the nested static class because the static class is a static member of the enclosing class.

Q4) What are non static inner classes?

Ans)
Non – static inner classes – classes associated with the object of the enclosing class.
Member class – Classes declared outside a function (hence a “member”) and not declared “static”.
The member class can be declared as public, private, protected, final and abstract. E.g.public class InnerClass {

class MemberClass {

public void method1() { }

}
}

Method local class – The inner class declared inside the method is called method local inner class. Method local inner class can only be declared as final or abstract. Method local class can only access global variables or method local variables if declared as final

public class InnerClass {

int i = 9;

public void method1() {

final int k = 6;
class MethodLocal {
MethodLocal() {
System.out.println(k + i);
}
}
}
}Anonymous inner class – These are local classes which are automatically declared and instantiated in the middle of an expression.  Also, like local classes, anonymous classes cannot be public, private, protected, or static. They can specify arguments to the constructor of the superclass, but cannot otherwise have a constructor. They can implement only one interface or extend a class.
Anonymous class cannot define any static fields, methods, or classes, except for static final constants.
Also, like local classes, anonymous classes cannot be public, private, protected, or static

Some examples:
public class MyFrame extends JFrame {

JButton btn = new JButton();
MyFrame() {
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
}
}

Anonymous class used with comparator

List<Parent> l = new ArrayList<Parent>();
l.add(new Parent(2));
l.add(new Parent(3));
Collections.sort(l, new Comparator() {
public int compare(Object o1, Object o2) {
Parent prt1 = (Parent) o1;
Parent prt2 = (Parent) o2;

if (prt1.getAge() > prt2.getAge()) {

return -1;
}else if(prt1.getAge()<prt2.getAge()) {

return 1;
} else {

return 0;
}
}
});

 

Q5) Does a static nested class have access to the enclosing class’ non-static methods or instance variables?

Ans) No .
Q6) What are the advantages of Inner classes?

Ans) The embedding of inner class into the outer class in the case when the inner class is to be used only by one class i.e. the outer class makes the package more streamlined. Nesting the inner class code where it is used (inside the outer class) makes the code more readable and maintainable.

The inner class shares a special relationship with the outer class i.e. the inner class has access to all members of the outer class and still have its own type is the main advantages of Inner class. Advantage of inner class is that they can be hidden from the other classes in the same package and still have the access to all the members (private also) of the enclosing class. So the outer class members which are going to be used by the inner class can be made private and the inner class members can be hidden from the classes in the same package. This increases the level of encapsulation.

If a class A is written requires another class B for its own use, there are two ways to do this. One way is to write a separate class B or to write an inner class B inside class A. Advantage of writing the inner class B in the class A is you can avoid having a separate class. Inner classes are best used in the event handling mechanism and to implement the helper classes. The advantage of using inner class for event handling mechanism is that the use of if/else to select the component to be handled can be avoided. If inner classes are used each component gets its own event handler and each event handler implicitly knows the component it is working for. e.g.

Button btn1 = new Button(“Submit”);
Btn.addActionListener(new ActionListener(){/br>

Public void actionPerformed(ActionEvent ae){ submitClicked(); }

} );
The advantage of using static nested class is that to instantiate a static nested class you need not create an instance of the enclosing class which reduces the number of objects the application creates at runtime.

Q7)What are disadvantages of using inner classes?

Ans)
1. Using inner class increases the total number of classes being used by the application. For all the classes created by JVM and loaded in the memory, jvm has to perform some tasks like creating the object of type class. Jvm may have to perform some routine tasks for these extra classes created which may result slower performance if the application is using more number of inner classes.
2. Inner classes get limited support of ide/tools as compared to the top level classes, so working with the inner classes is sometimes annoying for the developer.
Q8) What are different types of anonymous classes?

Ans 1) Plain old anonymous class type one
e.g.
class superClass{
void doSomething() {
System.out.println(“Doing something in the Super class”);
}
}

class hasAnonymous{
superClass anon = new superClass(){
void doSomething() {
System.out.println(“Doing something in the Anonymous class”);
}
};
Here anon is the reference which is of type superClass which is the class extended by the anonymous class i.e. superclass of the anonymous class. The method doSomething() is the super class method overridden by the anonymous class.
2) Plain old anonymous class type two

interface Eatable{
public void prepareSweets();
}
class serveMeal{
Eatable food = new Eatable(){
public void prepareSweets(){ //come implementation code goes here }
};
}
food is reference variable of type Eatable interface which refers to the anonymous class which is the implementer of the interface Eatable. The anonymous implementer class of the interface Eatable implements its method prepareSweets() inside it.
3) Argument defined anonymous class – e.g.

interface Vehicle {
void getNoOfWheels();
}
class Car {
void getType(Vehical v) { }
}
class BeautifulCars {
void getTheBeautifilCar() {
Car c = new Car ();
c.getType (new Vehicle () {
public void getNoOfWheels () {
System.out.println(“It has four wheels”);
}
});
}
}
Anonymous class is defined as the argument of the method getTheBeautifilCar(), this anonymous class is the implementer of the interface Vehicle. The method of class Car getTheBeautifilCar() expects the argument as an object of type Vehicle. So first we create an object of Car referenced by the variable ‘c’. On this object of Car we call the method getTheBeautifilCar() and in the argument we create an anonymous class in place which is the implementer of interface Vehicle hence of type Vehicle.

Q9) If you compile a file containing inner class how many .class files are created and what are all of them accessible in usual way?

Ans) If a inner class enclosed with an outer class is compiled then one .class file for each inner class an a .class file for the outer class is created. e.g.
class EnclosingOuter {
class Inner{ }
}
If you compile the above code with command
% javac EnclosingOuter.java
Two files
EnclosingOuter.class
EnclosingOuter$Inner.class

will be created. Though a separate inner class file is generated, the inner class file is not accessible in the usual way like,
% java EnclosingOuter$Inner
Q10) How to access the inner class from code within the outer class?

Ans) The inner class is instantiated only through the outer class instance.
class EnclosingOuter {
private int noInnerClass = 1;
public void getNoOfInnerClasses(){
Inner in = new Inner();
System.out.println(“No Of Inner classes is : “+ in.getNoOfClassesFromOuter());
}
class Inner{

public int getNoOfClassesFromOuter(){ return noInnerClass; }

}
Here the method getNoOfInnerClasses() is called on the outer class’s instance through this outer class instance the inner class instance in is created.

Q11) How to create an inner class instance from outside the outer class instance code?

Ans) To create an instance of the inner class you must have the instance of its enclosing class.
e.g. class EnclosingOuter {
class Inner{ }
}
To create the instance of inner class from class other than the enclosing class.
1) class OtherThanOuter{
EnclosingOuter out = new EnclosingOuter();
EnclosingOuter.Inner in = out.new Inner();
}

2) class OtherThanOuter{
EnclosingOuter.Inner out = new EnclosingOuter.Inner (); }

Q12) How to refer to the outer this i.e. outer class’s current instance from inside the inner class?

Ans) The outer this reference i.e. the outer class’ current instance’ reference can be refered using ‘OuterClassName.this’. E.g
class EnclosingOuter {
class Inner{
System.out.println(“Inner class reference is “ + this); // inner class instance

System.out.println(“Outer class reference is “ + EnclosingOuter.this); //outer class instance
}
}

To reference the inner class reference from within the inner class use this.

Q13) Which modifiers can be applied to the inner class?

Ans) Following are modifiers that can be applied to the inner:
public
private
abstract
final
protected
strictfp
static – turns the inner class into static nested class.
Q14) Can the method local inner class object access method’s local variables?

Ans) No, a method local inner class object can not access the method local variable.
Reason: The local variables are not guaranteed to live as long as the local inner class object. The method local variable live on stack and exist only till the method lives, their scope is limited only code inside the method they are declared in. But the local inner class object created within the method lives on heap and it may exist even after the method ends if in case the reference of this local inner class is passed into some other code and is stored in an instance variable. So we can not be sure that the local variables will live till the method local inner class object lives, therefore the method local inner class object can not access the method local variable. To access the method local variables, the variable has to be declared as final.
Q15) Can a method local inner class access the local final variables?Why?

Ans) Yes. Because the final variables are stored on heap and they live as long as the method local inner class object may live.
Q16) Which modifiers can be applied to the method local inner class?

Ans) Only abstract or final keyword isallowed.
Q17) Can a local class declared inside a static method have access to the instance members of the outer class?

Ans) No. There is no this reference available in the static method .The static method class can not have access to any members of the outer class other than static members.
Q18) Can a method which is not in the definition of the superclass of an anonymous class be invoked on that anonymous class reference?

Ans) No. Compilation will fail.As the reference variable type of the anonymous class will be of superclass which will not know of any method defined inside the anonymous class the compilation will fail.
e.g. class SuperClass{
void doSomething() {
System.out.println(“In the Super class”);
}
}
class hasAnonymous{
SuperClass anon = new SuperClass(){
void doSomething() {
System.out.println(“In the Anonymous class”);
}
void doStuff() {
System.out.println(“An Anonymous class method not present in superClass”);
}
};

public void doIt(){
anon.doSomething(); // legal superClass has this method
anon.doStuff(); // Not legal }
}
The above code does not compile as the superClass does not know about the anonymous class method doStuff().

Q19) Can an anonymous class define method of its own?

Ans) Yes. But there will be no way by which the methods defined in the anonymous class which are not present in its superclass be invoked. As only those methods which are defined in the suprclass which the anonymous class extends be invoked defining the methods in the anonymous class will be of no use
Q20) Can an anonymous class implement multiple interfaces directly?

Ans) No. An anonymous class can implement only one interface. If the anonymous class is extending a class then it becomes the implementer of all the interfaces implemented by its superclass automatically.
Q21) Can an anonymous class implement an interface and also extend a class at the same time?

Exceptions

Filed under: Exceptions — technospider @ 6:53 pm
Q1) What is an Exception?

Ans) The exception is said to be thrown whenever an exceptional event occurs in java which signals that something is not correct with the code written and may give unexpected result. An exceptional event is a occurrence of condition which alters the normal program flow. Exceptional handler is the code that does something about the exception.

Q2) Exceptions are defined in which java package?

Ans)All the exceptions are subclasses of java.lang.Exception

Q3) How are the exceptions handled in java?

Ans)When an exception occurs the execution of the program is transferred to an appropriate exception handler.The try-catch-finally block is used to handle the exception.
The code in which the exception may occur is enclosed in a try block, also called as a guarded region.
The catch clause matches a specific exception to a block of code which handles that exception.
And the clean up code which needs to be executed no matter the exception occurs or not is put inside the finally block

Q4) Explain the exception hierarchy in java.

Ans) The hierarchy is as follows:

Exception

Throwable is a parent class off all Exception classes. They are two types of Exceptions: Checked exceptions and UncheckedExceptions. Both type of exceptions extends Exception class.

Q5) What is Runtime Exception or unchecked exception?

Ans) Runtime exceptions represent problems that are the result of a programming problem. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small. Runtime exceptions need not be explicitly caught in try catch block as it can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program’s clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can). The solution to rectify is to correct the programming logic where the exception has occurred or provide a check.

Q6) What is checked exception?

Ans) Checked exception are the exceptions which forces the programmer to catch them explicitly in try-catch block. It is a subClass of Exception. Example: IOException.

Q7) What is difference between Error and Exception?

Ans) An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime.Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable.

While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.)

Q8) What is difference between ClassNotFoundException and NoClassDefFoundError?

Ans) A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader in the CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader and hence the class from the child classloader is not visible.

Consider if NoClassDefFoundError occurs which is something like

java.lang.NoClassDefFoundError

src/com/TestClass

does not mean that the TestClass class is not in the CLASSPATH. It means that the class TestClass was found by the ClassLoader however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that’s not found by the ClassLoader. So to find the culprit, view the source of the class in question (TestClass in this case) and look for code using static blocks or static members.

Q9) What is throw keyword?

Ans) Throw keyword is used to throw the exception manually. It is mainly used when the program fails to satisfy the given condition and it wants to warn the application.The exception thrown should be subclass of Throwable.

public void parent(){
try{
child();
}catch(MyCustomException e){ }
}

public void child{
String iAmMandatory=null;
if(iAmMandatory == null){
throw (new MyCustomException(“Throwing exception using throw keyword”);
}
}

Q10) What is use of throws keyword?

Ans) If the function is not capable of handling the exception then it can ask the calling method to handle it by simply putting the throws clause at the function declaration.

public void parent(){
try{
child();
}catch(MyCustomException e){ }
}

public void child throws MyCustomException{
//put some logic so that the exception occurs.
}

Q11) What are the possible combination to write try, catch finally block?

Ans)

 

1) try{

//lines of code that may throw an exception

}catch(Exception e){

//lines of code to handle the exception thrown in try block

}finally{

//the clean code which is executed always no matter the exception occurs or not.

}

2 try{

}finally{}

3 try{

}catch(Exception e){

//lines of code to handle the exception thrown in try block

}

The catch blocks must always follow the try block. If there are more than one catch blocks they all must follow each other without any block in between. The finally block must follow the catch block if one is present or if the catch block is absent the finally block must follow the try block.

Q12) How to create custom Exception?

Ans) To create you own exception extend the Exception class or any of its subclasses.

e.g.

1 class New1Exception extends Exception { } // this will create Checked Exception

2 class NewException extends IOExcpetion { } // this will create Checked exception

3 class NewException extends NullPonterExcpetion { } // this will create UnChecked exception

Q13) When to make a custom checked Exception or custom unchecked Exception?

Ans) If an application can reasonably be expected to recover from an exception, make it a checked exception. If an application cannot do anything to recover from the exception, make it an unchecked exception.

Q14)What is StackOverflowError?

Ans) The StackOverFlowError is an Error Object thorwn by the Runtime System when it Encounters that your application/code has ran out of the memory. It may occur in case of recursive methods or a large amount of data is fetched from the server and stored in some object. This error is generated by JVM.

e.g. void swap(){

swap();

}

Q15) Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope?

Ans) Any Exception that can be thrown by a method is part of the method’s public programming interface. Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them. These exceptions are as much a part of that method’s programming interface as its parameters and return value.

Q16) Once the control switches to the catch block does it return back to the try block to execute the balance code?

Ans) No. Once the control jumps to the catch block it never returns to the try block but it goes to finally block(if present).

Q17) Where is the clean up code like release of resources is put in try-catch-finally block and why?

Ans) The code is put in a finally block because irrespective of try or catch block execution the control will flow to finally block. Typically finally block contains release of connections, closing of result set etc.

Q18) Is it valid to have a try block without catch or finally?

Ans) NO. This will result in a compilation error. The try block must be followed by a catch or a finally block. It is legal to omit the either catch or the finally block but not both.

e.g. The following code is illegal.

try{
int i =0;
}
int a = 2;
System.out.println(“a = “+a);

Q19) Is it valid to place some code in between try the catch/finally block that follows it?

Ans) No. There should not be any line of code present between the try and the catch/finally block.

e.g. The following code is wrong.

try{}
String str = “ABC”;
System.out.println(“str = “+str);
catch(Exception e){}

Q20) What happens if the exception is never caught and throws down the method stack?

Ans) If the exception is not caught by any of the method in the method’s stack till you get to the main() method, the main method throws that exception and the JVM halts its execution.

Q21) How do you get the descriptive information about the Exception occurred during the program execution?

Ans) All the exceptions inherit a method printStackTrace() from the Throwable class. This method prints the stack trace from where the exception occurred. It prints the most recently entered method first and continues down, printing the name of each method as it works its way down the call stack from the top.

Q22) Can you catch more than one exceptions in a single catch block?

Ans)Yes. If the exception class specified in the catch clause has subclasses, any exception object that is a subclass of the specified Exception class will be caught by that single catch block.

E.g..

try {

// Some code here that can throw an IOException

}

catch (IOException e) {

e.printStackTrace();

}

The catch block above will catch IOException and all its subclasses e.g. FileNotFoundException etc.

Q23)Why is not considered as a good practice to write a single catchall handler to catch all the exceptions?

Ans) You can write a single catch block to handle all the exceptions thrown during the program execution as follows :

try {

// code that can throw exception of any possible type

}catch (Exception e) {

e.printStackTrace();

}

If you use the Superclass Exception in the catch block then you will not get the valuable information about each of the exception thrown during the execution, though you can find out the class of the exception occurred. Also it will reduce the readability of the code as the programmer will not understand what is the exact reason for putting the try-catch block.

Q24) What is exception matching?

Ans) Exception matching is the process by which the the jvm finds out the matching catch block for the exception thrown from the list of catch blocks. When an exception is thrown, Java will try to find by looking at the available catch clauses in the top down manner. If it doesn’t find one, it will search for a handler for a supertype of the exception. If it does not find a catch clause that matches a supertype for the exception, then the exception is propagated down the call stack. This process is called exception matching.

Q25) What happens if the handlers for the most specific exceptions is placed above the more general exceptions handler?

Ans) Compilation fails. The catch block for handling the most specific exceptions must always be placed above the catch block written to handle the more general exceptions.

e.g. The code below will not compile.

1 try {

// code that can throw IOException or its subtypes

} catch (IOException e) {

// handles IOExceptions and its subtypes

} catch (FileNotFoundException ex) {

// handle FileNotFoundException only

}

The code below will compile successfully :-

try {
// code that can throw IOException or its subtypes
} catch (FileNotFoundException ex) {
// handles IOExceptions and its subtypes
} catch (IOException e){
// handle FileNotFoundException only
}

Q26) Does the order of the catch blocks matter if the Exceptions caught by them are not subtype or supertype of each other

Ans) No. If the exceptions are siblings in the Exception class’s hierarchy i.e. If one Exception class is not a subtype or supertype of the other, then the order in which their handlers(catch clauses) are placed does not matter.

Q27) What happens if a method does not throw an checked Exception directly but calls a method that does? What does ‘Ducking’ the exception mean?

Ans) If a method does not throw an checked Exception directly but calls a method that throws an exception then the calling method must handle the throw exception or declare the exception in its throws clause. If the calling method does not handle and declares the exception, the exceptions is passed to the next method in the method stack. This is called as ducking the exception down the method stack.

e.g. The code below will not compile as the getCar() method has not declared the CarNotFoundException which is thrown by the getColor () method.

void getCar() {

getColor();

}

void getColor () {

throw new CarNotFoundException();

}

Fix for the above code is

void getCar() throws CarNotFoundException {

getColor();

}

void getColor () {

throw new CarNotFoundException();

}

Q28) Is an empty catch block legal?

Ans) Yes you can leave the catch block without writing any actual code to handle the exception caught.

e.g. The code below is legal but not appropriate, as in this case you will nt get any information about the exception thrown.

try{

//code that may throw the FileNotFoundException

}catch(FileNotFound eFnf){

//no code to handle the FileNotFound exception

}

 

Q29)Can a catch block throw the exception caught by itself?

KeyWords

Filed under: Basic — technospider @ 6:51 pm
Q1) What are different types of access modifiers in Java?

Ans) There are four different types of modifiers:

Modifer Accessible in the same package Accessible in different package
Private No No
Protected Yes Yes, only if the class extends the main class
Default Yes No
Public Yes Yes
Q2) What is the use of final keyword?

Ans) The final keyword can be assigned to

  1. Class level variable
  2. method
  3. class
  4. Objects

If a final is assigned to a variable, the variable behaves as a constant. It means that the value of variable once set cannot be changed.

final int i=1;
i =5; // error

If a final is assigned to a method then it cannot be overridden in its child class.

class Parent {

public final void print(){System.out.println(“Inside”);

}

}

class Child extends Parent{

public final void print(){             // error cannot override final method

System.out.println(“Inside”);
}

}

If a class is made as final, then no other class can extend it and make it as parent class. E.g. String Class.

Final objects are instantiated only once. i.e

final Map map = new HashMap();

map.put(“key”,”value”);

map = new HashMap();  // error

Q3) What is use of synchronized keyword?

Ans) This keyword is used to prevent concurrency. Synchronized keyword can be applied to static/non-static methods or a block of code. Only one thread at a time can access synchronized methods and if there are multiple threads trying to access the same method then other threads have to wait for the execution of method by one thread. Synchronized keyword provides a lock on the object and thus prevents race condition. E.g.

public void synchronized method(){}
public void synchronized staticmethod(){}
public void myMethod(){

synchronized (this){             // synchronized keyword on block of  code
}

}

Q4) What is volatile keyword?

Ans) In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable in the other thread. But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a method is called for a given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased. In this case the count variable is declared as volatile. The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time from the main memory. The volatile variable also have performance issues.

Q5) What is a transient variable?

Ans) If some of the properties of a class are not required to be serialized then the varaibles are marked as transient. When an object is deserialized the transient variables retains the default value depending on the type of variable declared and hence lost its original value.

Q6) What is a strictfp modifier?

Ans) Strictfp is used with variable only . It is used to restrict floating point calculations ( fp ) to ensure portability ( platform Independent ). When this modifier is specified, the JVM adheres to the Java specifications ( IEEE-754 floating-point specification ) and returns the consistent value independent of the platform. That is, if you want the answers from your code (which uses floating point values) to be consistent in all platforms, then you need to specify the strictfp modifier.

Q7) What is a static variable?

Ans) Static keyword can be used with the variables and methods but not with the class but there are static class. Anything declared as static is related to class and not objects.

Static variable : Multiples objects of a class shares the same instance of a static variable.Consider the example:

public class Counter{

private static int count=0;

private int nonStaticcount=0;

public void incrementCounter(){

count++;

nonStaticcount++;

}

public int getCount(){

return count;

}

public int getNonStaticcount(){

return nonStaticcount;

}

 

public static void main(String args[]){

Counter countObj1 = new Counter();

Counter countObj2 = new Counter();

countObj1.incrementCounter();

countObj1.incrementCounter();

System.out.println(“Static count for Obj1: “+countObj1.getCount());

System.out.println(“NonStatic count for Obj1: “+countObj1.getNonStaticcount());

System.out.println(“Static count for Obj2: “+countObj2.getCount())

System.out.println(“NonStatic count for Obj2: “+countObj2.getNonStaticcount())

}

Output

Static count for Obj1: 2

NonStatic count for Obj1: 2

Static count for Obj2: 2

NonStatic count for Obj2: 0

In the above program obj1 and obj2 share the same instance of static variable count hence if the value is incremented by one object , the incremented value will be reflected across the other objects

Q8) What is a static method?

Ans)A method defined as static is called static method. A static method can be accessed without creating the objects. Just by using the Class name the method can be accessed.

Static method can only access static variables and not local or global non-static variables. For eg:

public class Test{
public static void printMe(){
System.out.println(“Hello World”);
}
}
public class MainClass{
public static void main(String args[]){
Test.printMe()

}
}
OutPut:
Hello World

Also static method can call only static methods and not non static methods. But non-static methods can call static mehtods.

Q9) Why static methods cannot access non static variables or methods?

Ans) A static method cannot access non static variables or methods because static methods doesnt need the object to be accessed. So if a static method has non static variables or non static methods which has instantiated variables they will no be intialized since the object is not created and this could result in an error.

Q10) What is static class?

Ans) A class cannot be declared static. But a class can be said a static class if all the variables and methods of the class are static and the constructor is private. Making the constructor private will prevent the class to be instantiated. So the only possibility to access is using Class name only

Q9) What is throw keyword?

Ans) Throw keyword is used to throw the exception manually. It is mainly used when the program fails to satisfy the given condition and it wants to warn the application.The exception thrown should be subclass of Throwable.

public void parent(){
try{
child();
}catch(MyCustomException e){ }
}

public void child{
String iAmMandatory=null;
if(iAmMandatory == null){
throw (new MyCustomException(“Throwing exception using throw keyword”);
}
}

Q10) What is use of throws keyword?

Filed under: Collections — technospider @ 6:45 pm
Q1) What is difference between ArrayList and vector?

Ans: )

1) Synchronization – ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.

2) Data growth – Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted 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.

Q2) How can Arraylist be synchronized without using Vector?

Ans) Arraylist can be synchronized using:

Collection.synchronizedList(List list)

Other collections can be synchronized:

Collection.synchronizedMap(Map map)

Collection.synchronizedCollection(Collection c)

Q3) If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the basis of the employeeID of Employee class. What are the steps?

Ans) 1) Implement Comparable interface for the Employee class and override the compareTo(Object obj) method in which compare the employeeID

2) Now call Collections.sort() method and pass list as an argument.

Now consider that Employee class is a jar file.

1) Since Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object obj1) method .

2) Call Collections.sort() on the list and pass comparator as an argument.

Q4)What is difference between HashMap and HashTable?

Ans) Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are

1. Hashmap is not synchronized in nature but hshtable is.

2. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t.
Fail-safe – “if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException”

3. HashMap permits null values and only one null key, while Hashtable doesn’t allow key or value as null.

Q5) What are the classes implementing List interface?

Ans)
There are three classes that implement List interface:
1) ArrayList : It is a resizable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe.

2) Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.

3) LinkedList: the LinkedList also implements Queue interface and provide FIFO(First In First Out) operation for add operation. It is faster if than ArrayList if it performs insertion and deletion of elements from the middle of a list.

Q6) Which all classes implement Set interface?

Ans) A Set is a collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. HashSet,SortedSet and TreeSet are the commnly used class which implements Set interface.

SortedSet – It is an interface which extends Set. A the name suggest , the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface.

TreeSet – It is the implementation of SortedSet interface.This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized.

HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets

Q7) What is difference between List and a Set?

Ans)
1) List can contain duplicate values but Set doesnt allow. Set allows only to unique elements.
2) List allows retrieval of data to be in same order in the way it is inserted but Set doesnt ensures the sequence in which data can be retrieved.(Except HashSet)
Q8) What is difference between Arrays and ArrayList ?

Ans) Arrays are created of fix size whereas ArrayList is of not fix size. It means that once array is declared as :

      1. int [] intArray= new int[6];
      2. intArray[7]   // will give ArraysOutOfBoundException.

Also the size of array cannot be incremented or decremented. But with arrayList the size is variable.

  1. Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be added and deleted at runtime.

List list = new ArrayList();
list.add(1);
list.add(3);
list.remove(0) // will remove the element from the 1st location.

  1. ArrayList is one dimensional but array can be multidimensional.

int[][][] intArray= new int[3][2][1];   // 3 dimensional array

  1. To create an array the size should be known or initalized to some value. If not initialized carefully there could me memory wastage. But arrayList is all about dynamic creation and there is no wastage of memory.
Q9) When to use ArrayList or LinkedList ?

Ans)  Adding new elements is pretty fast for either type of list. For the ArrayList, doing  random lookup using “get” is fast, but for LinkedList, it’s slow. It’s slow because there’s no efficient way to index into the middle of a linked list. When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is fast, because deletion can be done simply by changing a couple of links. So an ArrayList works best for cases where you’re doing random access on the list, and a LinkedList works better if you’re doing a lot of editing in the middle of the list.

Source : Read More – from java.sun

Q10) Consider a scenario. If an ArrayList has to be iterate to read data only, what are the possible ways and which is the fastest?

Ans) It can be done in two ways, using for loop or using iterator of ArrayList. The first option is faster than using iterator. Because value stored in arraylist is indexed access. So while accessing the value is accessed directly as per the index.

Q11) Now another question with respect to above question is if accessing through iterator is slow then why do we need it and when to use it.

Ans) For loop does not allow the updation in the array(add or remove operation) inside the loop whereas Iterator does. Also Iterator can be used where there is no clue what type of collections will be used because all collections have iterator.

Q12) Which design pattern Iterator follows?

Ans) It follows Iterator design pattern. Iterator Pattern is a type of behavioral pattern. The Iterator pattern is one, which allows you to navigate through a collection of data using a common interface without knowing about the underlying implementation. Iterator should be implemented as an interface. This allows the user to implement it anyway its easier for him/her to return data. The benefits of Iterator are about their strength to provide a common interface for iterating through collections without bothering about underlying implementation.

Example of Iteration design pattern – Enumeration The class java.util.Enumeration is an example of the Iterator pattern. It represents and abstract means of iterating over a collection of elements in some sequential order without the client having to know the representation of the collection being iterated over. It can be used to provide a uniform interface for traversing collections of all kinds.

Q13) Why is it preferred to declare: List<String> list = new ArrayList<String>(); instead of ArrayList<String> = new ArrayList<String>();

Ans) It is preferred because:

  1. If later on code needs to be changed from ArrayList to Vector then only at the declaration place we can do that.
  2. The most important one – If a function is declared such that it takes list. E.g void showDetails(List list);
    When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector,LinkedList making the function more flexible
Q14) What is difference between iterator access and index access?

Ans) Index based access allow access of the element directly on the basis of index. The cursor of the datastructure can directly goto the ‘n’ location and get the element. It doesnot traverse through n-1 elements.

In Iterator based access, the cursor has to traverse through each element to get the desired element.So to reach the ‘n’th element it need to traverse through n-1 elements.

Insertion,updation or deletion will be faster for iterator based access if the operations are performed on elements present in between the datastructure.

Insertion,updation or deletion will be faster for index based access if the operations are performed on elements present at last of the datastructure.

Traversal or search in index based datastructure is faster.

ArrayList is index access and LinkedList is iterator access.

Q15) How to sort list in reverse order?

Ans) To sort the elements of the List in the reverse natural order of the strings, get a reverse Comparator from the Collections class with reverseOrder(). Then, pass the reverse Comparator to the sort() method.

List list = new ArrayList();

Comparator comp = Collections.reverseOrder();

Collections.sort(list, comp)

Q16) Can a null element added to a Treeset or HashSet?

Ans) A null element can be added only if the set contains one element because when a second element is added then as per set defination a check is made to check duplicate value and comparison with null element will throw NullPointerException.
HashSet is based on hashMap and can contain null element.

Q17) How to sort list of strings – case insensitive?

Ans) using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

Q18) How to make a List (ArrayList,Vector,LinkedList) read only?

Ans) A list implemenation can be made read only using Collections.unmodifiableList(list). This method returns a new list. If a user tries to perform add operation on the new list; UnSupportedOperationException is thrown.

Q19) What is ConcurrentHashMap?

Ans) A concurrentHashMap is thread-safe implementation of Map interface. In this class put and remove method are synchronized but not get method. This class is different from Hashtable in terms of locking; it means that hashtable use object level lock but this class uses bucket level lock thus having better performance.

Q20) Which is faster to iterate LinkedHashSet or LinkedList?

Ans) LinkedList.

Q21) Which data structure HashSet implements

Ans) HashSet implements hashmap internally to store the data. The data passed to hashset is stored as key in hashmap with null as value.

Q22) Arrange in the order of speed – HashMap,HashTable, Collections.synchronizedMap,concurrentHashmap

Ans) HashMap is fastest, ConcurrentHashMap,Collections.synchronizedMap,HashTable.

Q23) What is identityHashMap?

Ans) The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.

Q24) What is WeakHashMap?

Threads

Filed under: Threads — Tags: , , , , , , — technospider @ 6:43 pm

1. Write a Java program to create three threads namely A, B, C and make them run one after another. (C has to run after B completes, B has to run after A completes).
2. What happens when a thread calls notify() but no thread(s) is waiting?
3. How will you declare a timer variable that will be accessed by multiple threads very frequently?
4. How will you synchronize static variables?

5. What happens when threads are waiting, but never being notified?

//
//

ANSWERS:

1. Many ways to do it. I prefer join(). When a thrad A calls b.join(), then A runs only after thread b completes. So, for this problem, C has to call b.join() and B has to call a.join()
2. Actually…, nothing :) the notify() call simply returns.
3. Declare the variable as volatile. Every thread caches a copy of instance variable, work with local copy, and then sync it with master copy. But, threads do not cache a copy of volatile instance variable.
4. Obtain class level lock. synchronized( obj.getClass()) {……..}
5. Leaving the answer to readers! :)

Java Performance interview questions

Filed under: JAVA — technospider @ 3:59 pm
  1. You have to write a java program that can read files of varying sizes, ranging from 100 KB (very small) to few GBs (large size).
  2. You have to use JDBC (type 4 driver) to retrieve some values from two different tables in database. As you have to use join operation in this case, will you consider using join in the sql query level or in the program level?
  3. How will you plan your optimization strategy for a given J2EE (or Java) application?
  4. Give some strategy to optimize web tier (JSP/Servlets)?
  5. How will you tune the Data base tier?
  6. Answers

  1. The for loop iterates only once, not 100 times. So the running time is 10 millisecond. Because, the loop evaluates to a constant result ( that is, k = 20 * 100 will yield same result for 100 times) . So, jvm is smart enough, runs the for() loop once and saves time. I just mention this, because the developer should not worry about expression level optimization, which is taken care by the jvm itself.
  2. You can write an intelligent program in this case :) . If the file size is smaller, then read the whole file content in one-go. Read an example program given here. But, what if the file size is big? In this case, the program can’t read the whole file in one shot, as it would run out of memory. So, you can write the program in such a way that it reads the file content in byte arrays for several iterations. In this case, the running time of the program will depend on the size of byte array. So, how will you smartly determine the size of byte array?You can use Runtime.getRuntime().freeMemory() to find the freely available heap size. Based on this available memory, your program can create smaller or larger byte arrays at runtime. The larger the byte arrays, the lesser the response time.
  3. You have to move the join operation to query level. Never try to do (joining, sorting, aggregating, grouping and etc) such things application level, unless otherwise it is required. Because, SQL processor may optimize the join and prepare the better execution plan than you!
  4. It is too vast topic for discussion. In short,
    • Use profiler tools (there are so many.. example is JProfiler), monitoring tools and generate reports. From the report, analyze the response time of each component.
    • First, you have to analyze the response time of read/write tasks such as: I/O, Database access. Because, that is where most of the time spent.
    • Look for poor code that doesn’t release database connection or doesn’t close files and etc.
    • Minimize the repeated interaction with components as much as possible.
  5. Again, a vast topic!
    • Clearly identify static and dynamic portion of the web components. Enable client browser-level-cache for static web resource to save the network roundtrip.
    • Don’t dump all the data in session object, because that may lead your server running out of space at sometime.
    • Enable <load-on-startup> for all sticky servlet (servlets that are accessed many times).
    • Analyze whether you can zip and transfer some of the content.
  6. It is really really a big topic and hence, leaving it to the readers end! :)

Java servlet interview questions

Filed under: JAVA — technospider @ 3:57 pm
  1. After hitting submit button, a JSP page processes a database transaction. You have accidentally closed the browser window. Will the database transaction continue or will get over?
  2. What is the difference between http GET and POST methods ?
  3. There are 10 servlets in your web application, and they are frequently used (sticky Servlet). How will you optimize their loading?
  4. How will you communicate across Servlets? (or, how will you achieve Inter Servlet communication?)
  5. Hope, you know the difference between RequestDispatcher.forward() and RequestDispatcher.sendRedirect(). So, which one is desirable to use?
  6. What is the class path hierarchy for a Servlet?
  7. You can’t read files (located out of tomcat directory) from JSP and Servlets for security purpose. But, how will you access those files from JSP or Servlets, in case if you need them?

Javascript interview questions

Filed under: JAVA — technospider @ 3:49 pm

1. cssfloat property

2. what are the different ways to hide content on a page (style.display = “none”, style.visibility = “hidden”, table with height = 0)

3. setTimeout

4. setInterval and how to clear the interval

5. window object

6. prototype

Java-Trick interview Questions

Filed under: JAVA — technospider @ 3:45 pm
  1. Give the use and an example of the scenario where you would use serialVersionUID in a your Java class?
  2. Design a Employee class with name, empId, age and address fields.
    • Any two Employee objects are compared based on their age.
    • The empId is the unique id for Employee class. The Employee class can be used in Collections and HashMap.
  3. Explain what goes in a HashMap or Hashtable, when you store the objects with same hashcode values. Explain your answer in very depth.
  4. In JVM Memory, where the private, public, protected, static, String literal and object references are stored?
  5. How will you store your exception stack trace in a file? (you should not redirect the console output)
  6. What is the use of Weak, Soft, Phantom references in Garbage Collection of java? Give scenarios.
  7. How will you keep an object alive for ever in the JVM memory? (trick: use finalize() method)
Older Posts »

Theme: Silver is the New Black. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.