Pages

Subscribe Twitter Twitter

Monday, August 2, 2010

COREJAVA INTERVIEW QUESTIONS5

Method Overriding (Runtime polymorphism)
When a method in a subclass has the same name, return type and 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 super class 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 it's 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) Static
Static variables and 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.

 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 can’t be overriden to non-static methods.
 Static methods are 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” or “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 a instance of the class. To declare a class method uses 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.

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 methods cannot access instance variables why?
A) 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) 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.

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 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 frame work. 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”.
 Abstract class can have static, final method.
 An abstract method also declared private, native, final, synchronized, or strictfp.
 An abstract method declared in a non-abstract class
 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.

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

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;

 Interface can be extended, Interface can be 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.
 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.
 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?
 Abstract classes may have some executable methods and methods left unimplemented. Interface contains no implementation code.
 An abstract class can have nonabstract methods. All methods of an Interface are abstract.
 An abstract class can have instance variables. An Interface cannot.
 An abstract class can define constructor. An Interface cannot.
 An abstract class can have any visibility: public, private, protected. An Interface visibility must be public (or) none.

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).


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) Serializable & Externalizable
Serializable --> is an interface that extends serializable interface and sends data into streams in compressed format. It has 2 methods writeExternal (objectOutput out), readExternal (objectInput in).

Externalizable  is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal (ObjectOuput out) and readExternal (ObjectInput in).

Q) Internalisation & Localization
Internalisation -- Making a programme to flexible to run in any locale called internalisation.
Localization -- Making a programme to flexible to run in a specific locale called Localization.

Q) Serialization
Serialization is the process of writing the state of the object to a byte stream; this is useful when ever you want to save the state of your programme to a persistence storage area.

Q) Synchronization
Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. (Or) When 2 are more threads need to access the shared resources they need to some way ensure that the resources will be used by only one thread at a time. This process which is achieved is called synchronization.

(i) Ex: - Synchronizing a function:
public synchronized void Method1 () {
// Appropriate method-related code.
}

(ii) Ex: - Synchronizing a block of code inside a function:
public myFunction () {
synchronized (this) {
// Synchronized code here.
}
}

(iii) Ex: - public Synchronized void main (String args [])
But this is not the right approach because it means servlet can handle one request at a time.

Q) Different level of locking using Synchronization?
A) Class level, Object level, Method level, Block level

Q) Monitor
A monitor is a mutex, once a thread enters a monitor, all other threads must wait until that thread exist the monitor.

Q) Diff = = and .equals ()?
A) ==  Compare object references whether they refer to the same instance are not.
equals ()  method compare the characters in the string object.

Q) Marker Interfaces (or) Tagged Interfaces :-
An Interface with no methods. Is called marker Interfaces, eg., Serializable, SingleThread Model, Cloneable.

Q) URL Encoding & URL Decoding
URL Encoding is the method of replacing all the spaces and other extra characters into their corresponding Hex Characters and URL Decoding is the reverse process converting all Hex Characters back their normal form.

Q) URL & URLConection

URL is to identify a resource in a network, is only used to read something from the network.
URL url = new URL (protocol name, host name, port, url specifier)

URLConnection can establish communication between two programs in the network.
URL hp = new URL (“www.yahoo.com”);
URLConnection con = hp.openConnection ();

Q) Runtime class
Runtime class encapsulate the run-time environment. You cannot instantiate a Runtime object. You can get a reference to the current Runtime object by calling the static method Runtime.getRuntime ()

Runtime r = Runtime.getRuntime ()
Long mem1;
mem1 = r.freeMemory ();
mem1 = r.totalMemory ();

Q) Execute other programs
You can use java to execute other heavy weight process on your multi tasking operating system, several form of exec () method allows you to name the programme you want to run.
Runtime r = Runtime.getRuntime ();
Process p = null;
try{
p = r.exce (“notepad”);
p.waiFor ()
}

Q) System class
System class hold a collection of static methods and variables. The standard input, output, error output of the java runtime are stored in the in, out, err variables.

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) Native Methods
Native methods are used to call subroutine that is written in a language other than java, this subroutine exist as executable code for the CPU.

Q) Cloneable Interface
Any class that implements the cloneable interface can be cloned, this interface defines no methods. It is used to indicate that a class allow a bit wise copy of an object to be made.

Q) Clone
Generate a duplicate copy of the object on which it is called. Cloning is a dangerous action.

Q) Comparable Interface
Classes that implements comparable contain objects that can be compared in some meaningful manner. This interface having one method compare () the invoking object with the object. For sorting comparable interface will be used.
Ex: - int compareTo (Object obj)

Q) Class
Encapsulate the run time state of an object (or) interface. You cannot explicitly declare a class object, by using getClass () method you can do that.
Class a = x.getClass ();

Methods>> getClasses (), getConstructor (), getInterface (), getMethods (), getSuperclass (), getName ().

Q) java.lang.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 an “.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.

0 comments:

Post a Comment