Translate

Wednesday, January 2, 2013

Core Java Interview Question Part-7


Q) Class

            Class encapsulate the run-time state of an object or interface. Methods in this class are

static Class forName(String name) throws ClassNotFoundException
getClass()
getClassLoader()
getConstructor()
getField()
getDeclaredFields()
getMethods()
getDeclearedMethods()
getInterface()
getSuperClass()

Q) java.jlang.Reflect (package)

            Reflection is the ability of software to analyse it self, to obtain information about the field, constructor, methods & modifier of class. You need this information to build software tools that enables you to work with java beans components.

Q) InstanceOf

            Instanceof means by which your program can obtain run time type information about an object.
Ex:- A a = new A();
       a.instanceOf A;
 
Q) Java pass arguments by value are by reference?
A) By value
 
Q) Java lack pointers how do I implements classic pointer structures like linked list?
A) Using object reference.
 
Q) java. Exe

Micro soft provided sdk for java, which includes “jexegentool”. This converts class file into a “.Exec”  form. Only disadvantage is user needs a M.S java V.M installed.

Q) Bin & Lib in jdk?

Bin contains all tools such as javac, appletviewer and awt tool.
Lib contains API and all packages.


  
Collections Frame Work


Q)        
Collection classes
Collection Interfaces
Legacy classes
Legacy interface
Abstract collection
Collection
Dictionary
Enumerator
Abstract List
List
Hash Table

Abstract Set
Set
Stack

Array List
Sorted Set
Vector

Linked List
Map
Properties

Hash set
Iterator


Tree Set



Hash Map



Tree Map



Abstract Sequential List



           
Collection Classes

      Abstract collection à Implements most of the collection interfaces.
     
      Abstract List à Extends Abstract collection & Implements List Interface. A.L allow “random access”.

Methods>> void add (int index, Object element), boolean add(Object o), boolean addAll(Collection c), boolean addAll(int index, Collection c), Object remove(int index), void clear(), Iterator iterator().

      Abstract Set à Extends Abstract collection & Implements Set interface.

Array List à Array List extends AbstractList and implements the List interface. ArrayList is a variable length    of array of object references, ArrayList support dynamic array that grow as needed. A.L allow rapid random access to element but slow for insertion and deletion from the middle of the list. It will allow duplicate elements. Searching is very faster.
A.L internal node traversal from the start to the end of the collection is significantly faster than Linked List traversal.
      à A.L is a replacement for Vector.
     
Methods>>void add (int index, Object element), boolean add(Object o), boolean addAll(Collection c), boolean addAll(int index, Collection c), Object remove(int index), void clear(), object get(int index), int indexOf(Object element),  int latIndexOf(Object element), int size(), Object [] toArray(). 

Linked List à Extends AbstactSequentialList and implements List interface. L.L provide optimal sequence access, in expensive insertion and deletion from the middle of the list, relatively slow for random access. When ever there is a lot of insertion & deletion we have to go for L.L. L.L is accessed via a reference to the first node of the list. Each subsequent node is accessed via a reference to the first node of the list. Each subsequent node is accessed via the link-reference number stored in the previous node.
     
Methods>> void addFirst(Object obj), addLast(Object obj), Object getFirst(), Object getLast(),void add (int index, Object element), boolean add(Object o), boolean addAll(Collection c), boolean addAll(int index, Collection c), Object remove(int index), Object remove(Object o), void clear(), object get(int index), int indexOf(Object element), int latIndexOf(Object element), int size(), Object [] toArray(). 

Hash Set à Extends AbstractSet & Implements Set interface, it creates a collection that uses HashTable for storage, H.S does not guarantee the order of its elements, if u need storage go for TreeSet. It will not allow duplicate elements
     
      Methods>>boolean add(Object o), Iterator iterator(), boolean remove(Object o), int size().

Tree Set à Extends Abstract Set & Implements Set interface. Objects are stored in sorted, ascending order. Access and retrial times are quite fast. It will not allow duplicate elements
     
Methods>> boolean add(Object o), boolean addAll(Collection c), Object first(), Object last(), Iterator iterator(), boolean remove(Object o).

Hash Map à Extends Abstract Map and implements Map interface. H.M does not guarantee the order of elements, so the order in which the elements are added to a H.M is not necessary the order in which they are ready by the iterate. H.M permits only one null values in it while H.T does not
     
      à HashMap is similar to Hashtable.
     
Tree Map à implements Map interface, a TreeMap provides an efficient means of storing key/value pairs in sorted order and allow rapid retrieval.
    
      Abstract Sequential List à Extends Abstract collection; use sequential access of its elements.

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();
}
}