Tuesday 5 April 2016

CORE JAVA Interview Questions & Answers.

Q) What is difference between Java and C++?

A) (i) Java does not support pointers. Pointers are inherently insecure and troublesome. Since pointers do not exist in Java.
(ii) Java does not support operator overloading.
(iii) Java does not perform any automatic type conversions that result in a loss of precision
 (iv) All the code in a Java program is encapsulated within one or more classes. Therefore, Java does not have global variables or global functions.
(v) Java does not support multiple inheritance.

Java does not support destructors, but rather, add the finalize() function.
(vi) Java does not have the delete operator.
(vii) The << and >> are not overloaded for I/O operations

Q) Opps concepts

Polymorphism

Ability to take more than one form, in java we achieve this using Method Overloading (compile time polymorphism), Method overriding (runtime polymorphism)

Inheritance

Is the process by which one object acquires the properties of another object. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses.

Encapsulation

Wrapping of data and function into a single unit called encapsulation. Ex:- all java programs.

(Or)

Nothing but data hiding, like the variables declared under private of a particular class are accessed only in that class and cannot access in any other the class. Or Hiding the information from others is called as Encapsulation. Or Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse.

Abstraction

Nothing but representing the essential futures without including background details.

Dynamicbinding

Code associated with a given procedural call is not known until the time of the call at runtime. Dynamic binding is nothing but late binding.

Q) class & object?

class à class is a blue print of an object Object à instance of class.

Q)  Object creation?

Object is constructed either on a memory heap or on a stack.

Memory heap

generally the objects are created using the new keyword. Some heap memory is allocated to this newly created object. This memory remains allocated throughout the life cycle of the object. When the object is no more referred, the memory allocated to the object is eligible to be back on the heap.


Stack

During method calls, objects are created for method arguments and method variables. These objects are created on stack.

Q)  System.out.println()

à println() is a methd of java.io.printWriter.

à “out” is an instance variable of java.lang.System class.

Q) Transient & volatile

Transient --> The transient modifier applies to variables only, the object are variable will not persist. Transient variables are not serialized.
Volatile --> value will be changed unexpectedly by the other part of the program,

"it tells the compiler a variable   may change asynchronously due to threads"


Q) Access Specifiers & Access modifiers?

Access Specifiers à A.S gives access privileges to outside of application (or) others, they are Public, Protected, Private, Defaults.

Access Modifiers à A.M which gives additional meaning to data, methods and classes, final cannot be modified at any point of time.






Private
Public
Protected
No









modifier

Same class

No

Yes
Yes
Yes

Same package Subclass

No

Yes
Yes
Yes

Same package non-subclass
No

Yes
Yes
Yes

Different package subclass

No

Yes
Yes
No

Different package non-

No

Yes
No
No

subclass






Q) Default Values















long
-2^63 to 2^63 –1

double
0.0d




à 0L








Int
-2^31 to 2^31 –1

float
0.0f




à 0








Short
-2^15 to 2^15 –1

Boolean
False




à 0








Byte
-2^7 to 2^7 –1

char
0 to 2^7 –1 à null character (or)


à 0



‘\u 0000’



Q) Byte code & JIT compiler & JVM & JRE & JDK

à Byte code is a highly optimized set of instructions. JVM is an interpreter for byte code. Translating a java program into byte code helps makes it much easier to run a program in a wide variety of environment.

à JVM is an interpreter for byte code

à JIT (Just In Time) is a part of JVM, it compiles byte code into executable code in real time, will increase the performance of the interpretations.

à   JRE is an implementation of the Java Virtual Machine, which actually executes Java programs.
à JDK is bundle of software that you can use to develop Java based software, Tools provided by JDK is

(i) javac – compiler 
(ii) java – interpretor
(iii) jdb – debugger 
(iv) javap - Disassembles

(v) appletviewer – Applets
(vi) javadoc - documentation generator 
(vii) javah - 'C' header file generator

Q) Wrapper classes

Primitive data types can be converted into objects by using wrapper classes. These are java.lang.package.

Q) Does Java pass method arguments by value or by reference? 
Java passes all arguments by value, not by reference

Q) Arguments & Parameters

While defining method, variable passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.

Q) Public static void main (String [] args)

à We can overLoad the main() method.

à What if the main method is declared as “Private”?

The program compiles properly but at runtime it will give "Main method not public." Message

à What if the static modifier is removed from the signature of the main method? Program compiles. But at runtime throws an error "NoSuchMethodError".
à We can write “static public void” instead of “public static void” but not “public void static”.

à Protected static void main(), static void main(), private static void main() are also valid.

à If I do not provide the String array as the argument to the method? Program compiles but throws a runtime error "NoSuchMethodError".

à If no arguments on the command line, String array of Main method will be empty or null?

It is empty. But not null.

à Variables can have the same name as a method or a class

Q) Can an application have multiple classes having main() method?

A) Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.

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
Refers to instance of class
in the same class

“Super” to invoke the super class
Execute an overridden method in
constructor
the super class
“Inheritance” cannot be inherited
Can be inherited
We can “overload” but we cannot
Can be inherited
“overridden”

Will automatically invoke when an
Method has called explicitly
object is created



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

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.

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 <default>, 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();

}
}

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;     13


Interfaces are useful for?

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




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

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

(i) Ex: - Synchronizing a block of code inside a function: public myFunction (){
synchronized (this) {

}
}

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

(iv) Ex: - public Synchronized void service()

Servlet handle one request at a time in a serialized manner

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 enter 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 sane instance are not.

equals () à method compare the characters in the string object.

StringBuffer sb1 = new StringBuffer("Amit");
StringBuffer sb2= new StringBuffer("Amit");

String s1 = "Amit";
String s2 = "Amit";

String s3 = new String("abcd");
String s4 = new String("abcd");

String ss1 = "Amit";





(sb1==sb2); à F
(s1.equals(s2)); à T


(sb1.equals(sb2)); à F
((s1==s2)); à T


(sb1.equals(ss1)); à F
(s3.equals(s4)); à T




((s3==s4)); à F

String s1
= "abc";



String s2
= new String("abc");



s1 == s2 à F



s1.equals(s2)) à T



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 & URLConnection

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

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

static Class forName(String name)
getClass()
throws ClassNotFoundException

getClassLoader()
getConstructor()
getField()
getDeclaredFields()
getMethods()
getDeclearedMethods()
getInterface()
getSuperClass()

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







Exception






Handling








Q) Diff Exception & Error
Exception and Error both are subclasses of the Throwable class.

ExceptionàException is generated by java runtime system (or) by manually. An exception is a abnormal condition that transfer program execution from a thrower to catcher.

Error àWill stop the program execution, Error is a abnormal system condition we cannot handle these.

Q) Can an exception be rethrown?

A) Yes, an exception can be rethrown.

Q) try, catch, throw, throws

try à This is used to fix up the error, to prevent the program from automatically terminating, try-catch is used to catching an exception that are thrown by the java runtime system.

Throw  à is used to throw an exception explicitly.

Throws à A Throws clause list the type of exceptions that a methods might through.

Q) What happens if an exception is not caught?

A) An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.

Q) What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?

The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination.

Q) Checked & UnChecked Exception :-

Checked exception is some subclass of Exception. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method·

Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

Checked Exceptions
Un checked exception
ClassNotFoundException
ArithmeticException
NoSuchMethodException
ArrayIndexOutOfBoundException
NoSuchFieldException
ClasscastException
InterruptedException
IllegalArgumentException
IllegalAccessException
IllegalMonitorSateException
CloneNotSupportedException
IllegalThreadStateException

IndexOutOfBoundException

NullPointerException

NumberFormatException

StringIndexOutOfBounds

OutOfMemoryError --> Signals that JVM has run out of memory and that the garbage collector is unable to claim any more free memory.

StackOverFlow --> Signals that a stack O.F in the interpreter. 
ArrayIndexOutOfbound --> For accessing an array element by providing an index values <0 or > or equal to the array size.

StringIndexOutOfbound --> For accessing character of a string or string buffer with index values <0 or > or equal to the array size.

Arithmetic Exception --> such as divide by zero.

ArrayStore Exception --> Assignment to an array element of an incompatible types.
ClasscastException --> Invalid casting.

IllegalArgument Exception --> Illegal argument is used to invoke a method. 
Nullpointer Exception --> If attempt to made to use a null object. 
NumberFormat Exception --> Invalid conversition of string to numeric format.
ClassNotfound Exception --> class not found.

Instantion Exception --> Attempt to create an object of an Abstract class or Interface.

NosuchField Exception --> A request field does not exist. 
NosuchMethod Exception --> A request method does not exist.

Q) Methods in Exceptions?
A) getMessage(), toString(), printStackTrace(), getLocalizedMessage(),

Q) What is exception chaining?

A) An exception chain is a list of all the exceptions generated in response to a single root exception. As

each exception is caught and converted to a higher-level exception for rethrowing, it's added to the chain.

This provides a complete record of how an exception is handled The chained exception API was introduced in 1.4. Two methods and two constructors were added to Throwable.

Throwable getCause() Throwable initCause(Throwable) Throwable(String, Throwable) Throwable(Throwable)

The Throwable argument to initCause and the Throwable constructors is the exception that caused the current exception. getCause returns the exception that caused the current exception, and initCause returns the current exception.

Q) Primitive multi tasking

If the threads of different priorities shifting the control depend on the priority i.e.; a thread with higher priority is executed first than the thread with lower priority. This process of shifting control is known as primitive multi tasking.

Q) Http Status Codes

To inform the client of a problem at the server end, you call the “sendError” method. This causes the server to respond with status line, with protocol version and a success or error code.

The first digit of the status code defines the class of response, while the last two digits do not have categories

Numbe
Type
Description
r


1xx
Informational
Requested received, continuing to process
2xx
Success
The action was successfully received, understood, and


accepted
3xx
Redirection
Further action must be taken in order to complete the


request
4xx
Client Error
The request contains bad syntax or cannot be fulfilled
5xx
Server Error
The server failed to fulfil valid request














                                  2Multi Threading


Q) What threads will start when you start the java program? A) Finalizer, Main, Reference Handler, Signal dispatcher.

Q) Thread

Thread is a smallest unit of dispatchable code.

Q) Diff process and threads?

A) Thread is a smallest unit of dispatchable code, Process is a sub program will perform some specific actions.

(I) Process is a heavy weight task and is more cost. (ii) Thread is a lightweight task, which is of low cost.

(iii) A Program can contain more than one thread. (v) A program under execution is called as process.

Q) Sleep(), wait(), notify(), notifyAll(), stop(), suspend(), resume()

sleep        à sleep for a thread until some specific amount of time.

wait à wait for a thread until some specific condition occurs (Or) Tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify().

notify( ) à wakes up the first thread that called wait() on the same object. notifyAll( )à wakes up all the threads that called wait() on the same object, the highest priority thread will run first.
stop( )        à The thread move to dead state.

suspend( ) & resume( ) à To pass and restart the execution of a thread. In case of suspend, thread will be suspended by calling the lock on the object. Resume will restart from where it is suspended.
join( )          à wait for a thread to terminate.

Q) Yield( )

Yield method temporarily stop the callers thread and put at the end of queue to wait for another turn to be executed. It is used to make other threads of the same priority have the chance to run.

à Thread.sleep(milliseconds);

à Thread.sleep(milliseconds, nanoseconds);

Q) Multi Threading

Multithreading is the mechanism in which more than one thread run independent of each other within the process.

Q) Daemon Thread

Daemon thread is one which serves another thread, it has no other role normally a daemon thread carry some background program. When daemon thread remains the program exist.

Q) Thread Priority
          MIN_PRIORITY = 1
NORM_PRIORITY = 5

MAX_PRIORITY = 10

Q) Can I restart a stopped thread?

A) Once a thread is stopped, it cannot be restarted. Keep in mind though that the use of the stop() method of Thread is deprecated and should be avoided.

Q) Thread Priorities

Class A implements Runnable{ Thread t;

Public clicker(int p){

T = new Thread(this) t.setPriority(p);
}

public void run(){
}

public void stop(){
}

public void start(){ t.start();

}
try{

thread.sleep(1000);
}

lo.stop();
hi.stop();

try{
hi.t.join();

lo.t.join();
}

class HiLo{

public static void main(Stirng args[]){ Thread.currentThread().setPriority(Thread.MAX_PRIORITY); Clicker hi = new Clicker(Thread.NORM_PRIORITY+2); Clicker lo = new Clicker(Thread.NORM_PRIORITY-2); Lo.start();

Hi.start();

Q) What is the use of start() function in starting a thread? why we do not use the run() method directly to run the thread?

à Start method tell the JVM that it needs to create a system specific thread. After creating the system resources it passes the runnable object to it to execute the run() method.

à Calling run() method directly has the thread execute in the same as the calling object, not a separate thread of execution.

Q) What are the different levels of locking using ‘Synchronize’ key word? A) Class level, method level, object level, block level

 Q) Which attribute are thread safe?
Objective
Multi Threaded
Single threaded Model

Model






Local variables
Y
Y

Instance variables
N
Y

Class variables
N
N

Request attributes
Y
Y

Session attributes
N
N

Context attributes
N
N








Collections





Frame Work
Q)







Collection
Collection
Legacy

Legacy


classes
Interfaces
classes

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.

Collection Interfaces

Collection à Collection is a group of objects, collection does not allow duplicate elements.

Methods >>
 boolean add(Object obj),
boolean addAll(c), int Size(),
Object[] toArray(),
Boolean isEmpty(),
Object [] toArray(),
void clear().Collection c), 
Iterator iterator(),

boolean remove(Object obj), 
boolean removeAll(Collection)

Exceptions >> UnSupportedPointerException, ClassCastException.

List à List will extend Collection Interface, list stores a sequence of elements that can contain duplicates, elements can be accessed their position in the list using a zero based index, (it can access objects by index).


Methods >>
 void add(int index, Object obj),
 boolean addAll(int index, Collection c),
 Object get(int index), int indexOf(Object obj),
 int lastIndexOf(Object obj),
 ListIterator iterator(),
 Object remove(int index),
 Object removeAll(Collection c),
 Object set(int index, Object obj).

Set à Set will extend Collection Interface, Set cannot contain duplicate elements. Set stored elements in an unordered way. (it can access objects by value).

Sorted Set à Extends Set to handle sorted sets, Sorted Set elements will be in ascending order.

Methods >>
 Object last(),
 Object first(),
 compactor compactor().
 Exceptions >> NullPointerException, ClassCastException,

                          NoSuchElementException.

Map à Map maps unique key to value in a map for every key there is a corresponding value and you will lookup the values using keys. Map cannot contain duplicate “key” and “value”. In map both the “key” & “value are objects.

Methods >>
 Object get(Object k),
Object put(Object k, Object v),
int size(),
remove(Object object),
boolean isEmpty()

Iterator à Iterator makes it easier to traverse through the elements of a collection. It also has an extra feature not present in the older Enumeration interface - the ability to remove elements. This makes it easy to perform a search through a collection, and strip out unwanted entries.

Before accessing a collection through an iterator you must obtain one if the collection classes provide an iterator() method that returns an iterator to the start of the collection. By using iterator object you can access each element in the collection, one element at a time.

Methods >>
 boolean hasNext(),
 object next(),void remove()

Ex:- ArayList arr = new ArrayList(); Arr.add(“c”);

Iterator itr = arr.iterator(); While(itr.hashNext()) {
Object element = itr.next();
}

List Iterator à List Iterator gives the ability to access the collection, either forward/backward direction

Legacy Classes

Dictionary à is an abstract class that represent key/value storage repository and operates much like “Map” once the value is stored you can retrieve it by using key.

     Hash Table à HashTable stores key/value pairs in hash table, HashTable is synchronized when using hash table you have to specify an object that is used as a key, and the value that you want to linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored with the table. Use H.T to store large amount of data, it will search as fast as vector. H.T store the data in sequential order.

Methods>>
 boolean containsKey(Object key),
 boolean containsValue(Object value),
 Object get(Object key),
 Object put(Object key, Object value)

Stack à is a sub class of vector, stack includes all the methods defined by vector and adds several of its own.

Vector à Vector holds any type of objects, it is not fixed length and vector is synchronized. We can store primitive data types as well as objects. Default length of vector is up to 10.

Methods>> 
final void addElement(Object element), 
final int size(), final int capacity(), 
final boolean removeElementAt(int index), 
final void removeAllElements().

Properties à is a subclass of HashTable, it is used to maintain the list of values in which the “key/value” is String.

Legacy Interfaces

Enumeration à Define methods by which you can enumerate the elements in a collection of objects. Enumeration is synchronized.

Methods>> hasMoreElements(),Object nextElement().

Q) Which is the preferred collection class to use for storing database result sets?

A) LinkedList is the best one, benefits include:

1. Retains the original retrieval order. 2. Has quick insertion at the head/tail 3. Doesn't have an internal size limitation like a Vector where when the size is exceeded a new internal structure is created. 4. Permits user-controlled synchronization unlike the pre-Collections Vector which is always synchronized

ResultSet result = stmt.executeQuery("..."); List list = new LinkedList(); while(result.next()) { list.add(result.getString("col"));

}

If there are multiple columns in the result set, you'll have to combine them into their own data structure for each row. Arrays work well for that as you know the size, though a custom class might be best so you can convert the contents to the proper type when extracting from databse, instead of later.

Q) Efficiency of HashTable - If hash table is so fast, why don't we use it for everything?

A) One reason is that in a hash table the relations among keys disappear, so that certain operations (other than search, insertion, and deletion) cannot be easily implemented. For example, it is hard to traverse a hash table according to the order of the key. Another reason is that when no good hash function can be found for a certain application, the time and space cost is even higher than other data structures (array, linked list, or tree).

Hashtable has two parameters that affect its efficiency: its capacity and its load factor. The load factor should be between 0.0 and 1.0. When the number of entries in the hashtable exceeds the product of the load factor and the current capacity, the capacity is increased by calling the rehash method. Larger load factors use memory more efficiently, at the expense of larger expected time per lookup.

If many entries are to be put into a Hashtable, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table.

Q) How does a Hashtable internally maintain the key-value pairs?

A) The Hashtable class uses an internal (private) class named Entry to hold the key-value pairs. All entries of the Hashtable are stored in an array of Entry objects with the hash value of the key serving as the index. If two or more different keys have the same hash value these entries are stored as a linked list under the same index.

Q) Array

Array of fixed length of same data type; we can store primitive data types as well as class objects.

à Arrays are initialized to the default value of their type when they are created, not declared, even if they are local variables

Q) Diff Iterator & Enumeration & List Iterator

Iterator is not synchronized and enumeration is synchronized. Both are interface, Iterator is collection interface that extends from ‘List’ interface. Enumeration is a legacy interface, Enumeration having 2 methods ‘Boolean hasMoreElements()’ & ‘Object NextElement()’. Iterator having 3 methods ‘boolean hasNext()’, ‘object next()’, ‘void remove()’. Iterator also has an extra feature not present in the older Enumeration interface - the ability to remove elements there is one method “void remove()”.

List Iterator

It is an interface, List Iterator extends Iterator to allow bi-directional traversal of a list and modification of the elements. Methods are ‘hasNext()’, ‘ hasPrevious()’.

Q) Diff HashTable & HashMap

à Both provide key/value to access the data. The H.T is one of the collection original collection classes in java. H.P is part of new collection framework.
à H.T is synchronized and H.M is not.

à H.M permits null values in it while H.T does not.

à Iterator in the H.P is fail-safe while the enumerator for the H.T is not.

Q) Converting from a Collection to an array - and back again?

The collection interface define the toArray() method, which returns an array of objects. If you want to convert back to a collection implementation, you could manually traverse each element of the array and add it using the add(Object) method.

// Convert from a collection to an array Object[] array = c.toArray();


                                  30




// Convert back to a collection Collection c2 = new HashSet(); for(int i = 0; i < array.length; i++) {
c2.add(array[i]);

}

Q) How do I look through each element of a HashMap?

A) <select id="swf" name="swf" onChange="showStandardWF()" style="width:175px;">

<option value="">&lt;Select Standard WorkFlow&gt;</option>
<%

hmap =(HashMap)request.getAttribute("stdwf"); if( hmap.size() != 0){

int len = hmap.size(); Set set = hmap.keySet(); Iterator it = set.iterator(); while(it.hasNext())

{

Integer key = (Integer)it.next();
%>

<option
value="<%=key%>"><%=(String)hmap.get(key)%></option>

<%
}

}
%>

</select>

Q) Retrieving data from a collection? public class IteratorDemo
{

public static void main(String args[])
{

Collection c = new ArrayList();

// Add every parameter to our array list
for (int indx = 0; indx < args.length; indx++)

{
c.add(args[indx]);

}

//  Examine only those parameters that start with - Iterator i = c.iterator();

//  PRE : Collection has all parameters

while (i.hasNext())  {
String param = (String) i.next();

// Use the remove method of iterator if (! param.startsWith("-") )
i.remove();
}
//  POST: Collection only has parameters that start with -

//  Demonstrate by dumping collection contents

Iterator i2 = c.iterator(); while (i2.hasNext()) {
System.out.println ("Param : " + i2.next());
}

}
}

Q) How do I sort an array?

A)à Arrays class provides a series of sort() methods for sorting arrays. If the array is an array of primitives (or) an array of a class that implements Comparable then you can just call the method directly:
Arrays.sort(theArray);

àIf, however, it is an array of objects that don't implement the Comparable interface then you need to provide a custom Comparator to help you sort the elements in the array.
Arrays.sort(theArray, theComparator);

No comments:

Post a Comment

Java Packages Interview Question & Answers

All Packages Q) Thread Class Methods: - getName() run() getPriority() Sleep() isA...