Translate

Thursday, December 27, 2012

Core Java Interview Question Part-6


Q) When we use Abstract class?
A) Let us take the behaviour of animals, animals are capable of doing different things like flying, digging,
Walking. But these are some common operations performed by all animals, but in a different way as well. When an operation is performed in a different way it is a good candidate for an abstract method.

Public Abstarctclass Animal{
  Public void eat(food food)  {
  }
  public void sleep(int hours) {
  }
  public abstract void makeNoise()
}

public Dog extends Animal
{
   public void makeNoise()  {
            System.out.println(“Bark! Bark”);
    }
}

public Cow extends Animal
{
   public void makeNoise() {
            System.out.println(“moo! moo”);
    }
}
 
Q) Interface
            Interface is similar to class but they lack instance variable, their methods are declared with out any body. Interfaces are designed to support dynamic method resolution at run time. All methods in interface are implicitly
abstract, even if the abstract modifier is omitted. Interface methods have no implementation;

Interfaces are useful for?
a) Declaring methods that one or more classes are expected to implement
b) Capturing similarities between unrelated classes without forcing a class relationship.
c) Determining an object's programming interface without revealing the actual body of the class.

Why Interfaces?
“ one interface multiple methods “ signifies the polymorphism concept.

à Interface has visibility public.
à Interface can be extended & implemented.
à An interface body may contain constant declarations, abstract method declarations, inner classes and inner interfaces.
à All methods of an interface are implicitly Abstract, Public, even if the public modifier is omitted.
à An interface methods cannot be declared protected, private, strictfp, native or synchronized.
à All Variables are implicitly final, public, static fields.
à A compile time error occurs if an interface has a simple name the same as any of it's enclosing classes or interfaces.
à An Interface can only declare constants and instance methods, but cannot implement default behavior.
à top-level interfaces may only be declared public, inner interfaces may be declared private and protected but only if they are defined in a class.

à A class can only extend one other class.
à A class may implements more than one interface.
à Interface can extend more than one interface.

Interface A
{
            final static float pi = 3.14f;
}

class B implements A
{
            public float compute(float x, float y) {
                        return(x*y);
            }
}

class test{
public static void main(String args[])
{
            A a = new B();
            a.compute();
}
}
           
Q) Diff Interface & Abstract Class?
à A.C may have some executable methods and methods left unimplemented. Interface contains no implementation code.
à An A.C can have nonabstract methods. All methods of an Interface are abstract.
à An A.C can have instance variables. An Interface cannot.
à An A.C must have subclasses whereas interface can't have subclasses
à An A.C can define constructor. An Interface cannot.
à An A.C can have any visibility: public, private, protected. An Interface visibility must be public (or) none.
à An A.C can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior.

Q) What is the difference between Interface and class?
à A class has instance variable and an Interface has no instance variables.
à Objects can be created for classes where as objects cannot be created for interfaces.
à All methods defined inside class are concrete. Methods declared inside interface are without any body.

Q) What is the difference between Abstract class and Class?
à Classes are fully defined. Abstract classes are not fully defined (incomplete class)
à Objects can be created for classes; there can be no objects of an abstract class.

Q) What are some alternatives to inheritance?
A) Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass). 

Core Java Interview Questions Part-5


Q) Static methods cannot access instance variables why?
 Static methods can be invoked before the object is created; Instance variables are created only when the new object is created. Since there is no possibility to the static method to access the instance variables. Instance variables are called called as non-static variables.

Q) String & StringBuffer
            String is a fixed length of sequence of characters, String is immutable.
           
            StringBuffer represent growable and writeable character sequence, StringBuffer is mutable which means that its value can be changed. It allocates room for 16-addition character space when no specific length is specified. Java.lang.StringBuffer is also a final class hence it cannot be sub classed. StringBuffer cannot be overridden the equals() method.

Q) Conversions
   String to Int Conversion: -
   int I   = integer.valueOf(“24”).intValue();
                           int x  = integer.parseInt(“433”);
                           float f = float.valueOf(23.9).floatValue();
           
    Int to String Conversion :-
                          String arg = String.valueOf(10);

Q) Super()
            Super() always calling the constructor of immediate super class, super() must always be the first statements executed inside a subclass constructor.

Q) What are different types of inner classes?
A) Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. e.g., outer.inner. Top-level inner classes implicitly have access only to static variables. There can also be inner interfaces. All of these are of the nested top-level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a more publicly available interface. Because local classes are not members the modifiers public,  protected, private and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

à Inner class inside method cannot have static members or blocks

Q) Which circumstances you use Abstract Class & Interface?
--> If you need to change your design make it an interface.
--> Abstract class provide some default behaviour, A.C are excellent candidates inside of application framework. A.C allow single inheritance model, which should be very faster.

Q) Abstract Class
Any class that contain one are more abstract methods must also be declared as an abstract, there can be no object of an abstract class, we cannot directly instantiate the abstract classes. A.C can contain concrete methods.
àAny sub class of an Abstract class must either implement all the abstract methods in the super class or be declared itself as Abstract.
à Compile time error occur if an attempt to create an instance of an Abstract class.
à You cannot declare “abstract constructor” and “abstract static method”.
à An “abstract method” also declared private, native, final, synchronized, strictfp, protected.
à Abstract class can have static, final method (but there is no use).
à Abstract class have visibility public, private, protected.
à By default the methods & variables will take the access modifiers is , which is accessibility as package.
à An abstract method declared in a non-abstract class.
à An abstract class can have instance methods that implement a default behavior.
à A class can be declared abstract even if it does not actually have any abstract methods. Declaring such a class abstract indicates that the implementation is somehow incomplete and is meant to serve as a super class for one or more subclasses that will complete the implementation.
à A class with an abstract method. Again note that the class itself is declared abstract, otherwise a compile time error would have occurred.

Abstract class A{
            Public abstract callme();
            Void callmetoo(){
            }
}

class B extends A(
            void callme(){
            }
}

class AbstractDemo{
public static void main(string args[]){
            B b = new B();
            b.callme();
            b.callmetoo();
}
}

Core Java Interview Questions part-4


Q) Overloading & Overriding?
Overloading (Compile time polymorphism)
 Define two or more methods within the same class (or) subclass that share the same name and their number of parameter, order of parameter & return type are different then the methods are said to be overloaded.
· Overloaded methods do not have any restrictions on what return type of Method (Return type are different) (or) exceptions can be thrown. That is something to worry about with overriding.
· Overloading is used while implementing several methods that implement similar behavior but for different data types.

Overriding (Runtime polymorphism)
When a method in a subclass has the same name, return type & parameters as the method in the super class then the method in the subclass is override the method in the super class.

à The access modifier for the overriding method may not be more restrictive than the access modifier of the superclass method.

· If the superclass method is public, the overriding method must be public.
· If the superclass method is protected, the overriding method may be protected or public.
· If the superclass method is package, the overriding method may be packagage, protected, or public.
· If the superclass methods is private, it is not inherited and overriding is not an issue.
· Methods declared as final cannot be overridden.

à The throws clause of the overriding method may only include exceptions that can be thrown by the superclass method, including its subclasses.
  
à Only member method can be overriden, not member variable     

            class Parent{
    int i = 0;
    void amethod(){
                System.out.println("in Parent");
                }
             }         
class Child extends Parent{
    int i = 10;
    void amethod(){
                System.out.println("in Child");
    }
}          
class Test{
public static void main(String[] args){
Parent p = new Child();
Child  c = new Child();
System.out.print("i="+p.i+" ");
p.amethod ();
System.out.print("i="+c.i+" ");
c.amethod();
}
}

O/p: - i=0 in Child     i=10 in Child

Q) Final variable
            Once to declare a variable as final it cannot occupy memory per instance basis.

Q) Static block
            Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to  the main method the static block will execute.

Q) Static variable & Static method
Static variables & methods are instantiated only once per class. In other words they are class variables,   not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class.
Static methods can be referenced with the name of the class. It may not access the instance variables of that class, only its static variables. Further it may not invoke instance (non-static) methods of that class unless it provides them with some object.

à When a member is declared a static it can be accessed before any object of its class are created.
à Instance variables declared as static are essentially global variables.
à If you do not specify an initial value to an instance & Static variable a default value will be assigned   automatically.
à Methods declared as static have some restrictions they can access only static data, they can only call other            static data, they cannot refer this or super.
à Static methods cant be overriden to non-static methods.
à Static methods is called by the static methods only, an ordinary method can call the static methods, but static methods cannot call ordinary methods.
à Static methods are implicitly "final", because overriding is only done based on the type of the objects
à They cannot refer “this” are “super” in any way.

Q) Class variable & Instance variable  & Instance methods  & class methods
Instance variable à variables defined inside a class are called instance variables with multiple instance of class, each instance has a variable stored in separate memory location.

Class variables à you want a variable to be common to all classes then we crate class variables. To create a class variable put the “static” keyword before the variable name.

Class methods à we create class methods to allow us to call a method without creating instance of the class. To declare a class method use the “static” key word .

Instance methods à we define a method in a class, in order to use that methods we need to first create objects of the class. 

Core Java Interview Questions part-3


Q) Can I have multiple main methods in the same class?

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

Q) Constructor
            The automatic initialization is performed through the constructor, constructor has same name has class name. Constructor has no return type not even void. We can pass the parameters to the constructor. this() is used to invoke a constructor of the same class. Super () is used to invoke a super class constructor. Constructor is called immediately after the object is created before the new operator completes.

à Constructor can use the access modifiers public, protected, private or have no access modifier
à Constructor can not use the modifiers abstract, static, final, native, synchronized or strictfp
à Constructor can be overloaded, we cannot override.
à You cannot use this() and Super() in the same constructor.

Class A(
A(){
     System.out.println(“hello”);
}}

Class B extends A {
B(){
     System.out.println(“friend”);
}}

Class print {
Public static void main (String args []){
B b = new B();
}
o/p:- hello friend

Q) Diff Constructor & Method

Constructor
Method
Use to instance of a class
Grouping java statement
No return type
Void (or) valid return type
Same name as class name
As a name except the class method name, begin with lower case.
“This” refer to another constructor in the same class
Refers to instance of class
“Super” to invoke the super class constructor
Execute an overridden method in the super class
Inheritance” cannot be inherited
Can be inherited
We can “overload” but we cannot “overridden
Can be inherited
Will automatically invoke when an object is created
Method has called explicitly

Q) Garbage collection
G.C is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program cann't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use, calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. Garbage collection is a low-priority thread.

G.C is a low priority thread in java, G.C cannot be forced explicitly. JVM may do garbage collection if it is running short of memory. The call System.gc() does NOT force the garbage collection but only suggests that the JVM may make an effort to do garbage collection.

Q) How an object becomes eligible for Garbage Collection?
A) An object is eligible for garbage collection when no object refers to it, An object also becomes eligible when its reference is set to null. The objects referred by method variables or local variables are eligible for garbage collection when they go out of scope.
Integer i = new Integer(7);
i =
null;
Q) Final, Finally, Finalize
Final: - When we declare a sub class a final the compiler will give error as “cannot subclass final class” Final to prevent inheritance and method overriding. Once to declare a variable as final it cannot occupy memory per instance basis.
     à  Final class cannot have static methods   
     à  Final class cannot have abstract methods (Because of final class never allows any class to inherit it)
     à  Final class can have a final method.

Finally: - Finally create a block of code that will be executed after try catch block has completed. Finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also execute.
                       
    Using System.exit() in try block will not allow finally code to execute

Finalize: - some times an object need to perform some actions when it is going to destroy, if an object holding some non-java resource such as file handle (or) window character font, these resources are freed before the object is going to destroy.

Q) Can we declare abstract method in final class?
A) It indicates an error to declare abstract method in final class. Because of final class never allows any class to inherit it.

Q) Can we declare final method in abstract class?
A) If a method is defined as final then we can’t provide the reimplementation for that final method in it’s derived classes i.e overriding is not possible for that method. We can declare final method in abstract class suppose of it is abstract too, then there is no used to declare like that.

Q) Superclass & Subclass
            A super class is a class that is inherited whereas subclass is a class that does the inheriting

Q) How will u implement 1) polymorphism 2) multiple inheritance 3) multilevel inheritance in java?
A) Polymorphism           – overloading and overriding
    Multiple inheritances  – interfaces.
    Multilevel inheritance – extending class.