Monday, May 26, 2008

Java Interview Questions

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



No



Yes



No



No




Q) Default Values






























long



-2^63 to 2^63 –1 à 0L



double



0.0d



Int



-2^31 to 2^31 –1 à 0



float



0.0f



Short



-2^15 to 2^15 –1 à 0



Boolean



false



Byte



-2^7 to 2^7 –1 à 0



char



0 to 2^7 –1 à null character (or) ‘\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 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.
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

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.



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.



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



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.
A
n interface body may contain constant declarations, abstract method declarations, inner classes and inner interfaces.
All methods of an interface are implicitly Abstract, P
ublic, 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).


 



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 () {
}
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->(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";



String s1 = "abc";
String s2 = new String("abc");

s1 == s2 F
s1.equals(s2))


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

7 comments:

  1. why main() method in java is declared as public?

    ReplyDelete
  2. for learning and searching job in JAVA take help free from www.softwareitjob.com

    ReplyDelete
  3. Because it is Parent Class in Java Code

    ReplyDelete
  4. It is the first method from where execution of code starts. So it must be public otherwise you will end-up with error.

    ReplyDelete
  5. Right, Always JVM starts to execute code from the Main class only

    ReplyDelete
  6. When I am running a Java Process which is multithreaded on a Dual Core CPU on Unix my CPU utilization is of only 1, Can anyone explain why is it so?

    Thanks in Advance

    ReplyDelete
  7. yes it is the most helpful thing for any interview. thank you

    ReplyDelete