Documente Academic
Documente Profesional
Documente Cultură
1
Interview Questions: Core Java
6. Question: I made my class Cloneable but I still get Can’t access protected method
clone. Why?
Answer: Yeah, some of the Java books, in particular "The Java Programming Language", imply
that all you have to do in order to have your class support clone() is implement the Cloneable
interface. Not so. Perhaps that was the intent at some point, but that’s not the way it works
currently. As it stands, you have to implement your own public clone() method, even if it
doesn’t do anything special and just calls super.clone().
Actually
Frist we have to understand the concept of serialization "Serialization is a process in we
writing a state of object to a byte stream".If we want to send our data to another system or in
distributed environment thiss process take place as a form of serialization and
deserialization........
ie our object is converted into byte stream and invoke the method of other machine ...in this
invocation the calling machine serialize it(ie convert it into byte stream) and the recieveing
machine deserialize it....(RMI concept is used in this process)
Serializable: its a intrface and the class that implement this interface can save and rstore
serialization facilities.there is no member define in serializable.it simply use to indicate that
the class has to be serialize......
note :variable that is declare trasient are not saved by
this facilities.......
2
Interview Questions: Core Java
by static method it mean that we can create member that can be used by it self,withod
creating the instance...the best example is main() method.
method declare static can call other static methods they can only access static data..
they cannot refer to super and this any way....
3
Interview Questions: Core Java
to modify a shared object while another thread is in the process of using or updating that
object’s value. This often leads to significant errors.
In Multithreading environment when to thread of equal priority try to access same resources
will lead to deadlock...
we can think monitor as a small box that can hold only one thread...once the thread entered in
the monitor other thread have to wait until that thread exit from the monitor..
note that there in no such class Monitor instead each thread have its own implicit monitor that
is automatically entered when object synchronized method is called. and once the thread enter
inside the synchronized method no other method can call other synchronized method on the
same object....
15. Question: What modifiers may be used with an inner class that is a member of an
outer class?
Answer: A (non-local) inner class may be declared as public, protected, private, static, final, or
abstract.
17. Question: What is the catch or declare rule for method declarations?
Answer: If a checked exception may be thrown within the body of a method, the method must
either catch the exception or declare it in its throws clause.
4
Interview Questions: Core Java
20. Question: How many times may an object’s finalize() method be invoked by the
garbage collector?
Answer: An object’s finalize() method may only be invoked once by the garbage collector.
25. Question: What is the difference between a static and a non-static inner class?
Answer: A non-static inner class may have object instances that are associated with instances
of the class’s outer class. A static inner class does not have any object instances.
26. Question: What is an object’s lock and which object’s have locks?
Answer: An object’s lock is a mechanism that is used by multiple threads to obtain
synchronized access to the object. A thread may execute a synchronized method of an object
only after it has acquired the object’s lock. All objects and classes have locks. A class’s lock is
acquired on the class’s Class object.
5
Interview Questions: Core Java
31. Question: What modifiers can be used with a local inner class?
Answer: A local inner class may be final or abstract.
34. Question: How are this() and super() used with constructors?
Answer: this() is used to invoke a constructor of the same class. super() is used to invoke a
superclass constructor.
35. Question: What are the legal operands of the instanceof operator?
Answer: The left operand is an object reference or null value and the right operand is a class,
interface, or array type.
37. Question: What happens when you add a double value to a String?
Answer: The result is a String object.
40. Question: Can a method be overloaded based on different return type but same
argument type ?
Answer: No, because the methods can be called without using their return type in which case
there is ambiquity for the compiler
6
Interview Questions: Core Java
41. Question: What happens to a static var that is defined within a method of a
class ?
Answer: Can’t do it. You’ll get a compilation error
44. Question: Which is garbage collected first: Normal variables or static variables?
Answer: Normal variables will be collected first. Lets take a simple example:
Class A is having a static variable s which is used by obj1, obj2 and obj3 of Class B. Each
object of class B is having instance variables a and b (normal variables). Lets say if obj1 is not
being in use since long time, then automatically the garbage collector will collect the space
occupied by obj1. It will not destroy the static variable S as it is being used by the other two
objects obj2 and obj3. Therefore only normal variables will be destroyed first.
We can say it in a simple statement that "Variables having less scope will be destroyed first"
7
Interview Questions: Core Java
48. Question: What are the practical benefits, if any, of importing a specific class
rather than an entire package (e.g. import java.net.* versus import
java.net.Socket)?
Answer: It makes no difference in the generated class files since only the classes that are
actually used are referenced by the generated class file. There is another practical benefit to
importing single classes, and this arises when two (or more) packages have classes with the
same name. Take java.util.Timer and javax.swing.Timer, for example. If I import java.util.*
and javax.swing.* and then try to use "Timer", I get an error while compiling (the class name
is ambiguous between both packages). Let’s say what you really wanted was the
javax.swing.Timer class, and the only classes you plan on using in java.util are Collection and
HashMap. In this case, some people will prefer to import java.util.Collection and import
java.util.HashMap instead of importing java.util.*. This will now allow them to use Timer,
Collection, HashMap, and other javax.swing classes without using fully qualified class names
in.
8
Interview Questions: Core Java
compiler checks that you have trapped them, hence checked exceptions.
Runtime exceptions are typically bugs in the program. Errors are severe problems such as out
of memory and sufficiently rare, that you are not required to handle them as they are usually
unrecoverable.
51. Question: What is the exact difference between Abstract classes and Interfaces?
Answer: Interfaces provide a form of multiple inheritance -- any number of interfaces can be
implemented A class can extend only one other class. Interfaces are limited to public methods
and constants with no implementation. Abstract classes can have a partial implementation,
protected parts, static methods, etc.
53. Question: Does the code in finally block get executed if there is an exception and
a return statement in a catch block?
Answer: If an exception occurs and there is a return statement in catch block, the finally block
is still executed. The finally block will not be executed when the System.exit(1) statement is
executed earlier or the system shut down earlier or the memory is used up earlier before the
thread goes to finally block.
For example, a ConnectionPool would be a good place to use a singleton. If clients could
arbitrarily create ConnectionPools without regard to what already exists, you would have a
waste of resources. So you limit the possible number of connection pools to 1 (per JVM), and
you then know that all clients are getting their connections from a single source.
Another example of Singleton use is for Object Factories. Say you have a class called
FooFactory that is responsible for fetching/saving Foo objects to/from a database. You want to
ensure that for each Foo record in the db, there is only one corresponding Foo object floating
around your application. By centralizing all the creation logic in a single class, and making that
class a Singleton, you eliminate the possibility fo duplicate objects.
The code that uses a connection obtained from the connection pool is another matter. If all it
does is do a getData() type operation, there is no harm in having more than one of them.
55. Question: Strings are immutable, How are we able to perform concatination on
String object?
9
Interview Questions: Core Java
Answer: Yes. Strings are immutable. Thats why while concatenating, it always returns a new
string object.
If we take this example :
String s1 = "psn";
s1 = s1.concat("prasad"); // Here you are reassigning the new object to the older reference s1
System.out.println(s1);
String s1 = "psn";
String s2 = s1.concat("prasad");
System.out.println(s1); // will remain same . no change. it prints "psn" only
System.out.println(s2); // as you have assigned the newly created object to s2
56. Question: What are the different ways in which polymorphism can be achieved in
java?
Answer: Polymorphism can be acheived two ways
overloading - static binding/early binding
overriding - dynamic binding/late binding
In case of overloading the method to be called is decided at the compile time based on the
method signature.
In case of overriding the method to be called is decided at run time and NOT at compile time.
This is runtime polymorphism.
57. Question: What’s the difference between constructors and other methods?
Answer: Constructors must have the same name as the class and can not return a value. They
are only called once while regular methods could be called many times.
58. Question: Why do we require public static void main(String args[]) method in
Java programme?
Answer: Following are few reasons why there is public static void main(String args[])
If the main() was not static, you would require an instance of the class in order to execute the
method.
If this is the case, what would create the instance of the class? What if your class did not have
a public constructor?
java Test
would get converted to Test.main() there by invoking the main()
10
Interview Questions: Core Java
Example 1:
class Test {
private String name;
}
This class is tightly encapsulated as you can~t access the member "name".
Example 2:
class Test2 {
private String name;
The standard way to protect the data is to make it private, so that no other class can get
direct access to it, and then write public methods to get the data and set the data. The
method that sets the data should carry out appropriate checks to make sure the incoming data
is valid.
In Example 2 we are validating the incoming data with "test2". If its test2 we are allowing the
data to be set, else we are throwing an exception.
Tight encapsulation will not only protect direct access to data members, but will also prevent
those members from being set to improper values.
60. Question: Can main() of one java program be invoked in another java program~s
main()?
Answer: Yes, This is possible. Have a look at the below code
package corejava;
public class A
{
11
Interview Questions: Core Java
package corejava;
public class B
{
public static void main(String args[])
{
System.out.println("in B");
String str = "one,two";
String[] strArray = str.split(str);
A.main(strArray);
}
}
In short you are initializing an int array in line one and you are creating an int array with
elements in line two.
62. Question: What are the different inner classes available in java? Explain each
inner class with an example.
Answer: There are four types of inner classes in java
1. Member class
2. Static member class
3. Local class
4. Anonymous class
1. Member class
A member class is defined as a member of a class. The member class is instance specific and
has access to any and all methods and members, even the parent~s "this" reference. All
public, protected, default, and private members are visible to instances of member class.
You must provide an instance of the enclosing class when you create a new instance of
member class.
12
Interview Questions: Core Java
If you need to create an instance of member class outside of the scope of the enclosing class,
you need to use an instance of the enclosing class to create the member instance:
or
member classes can be declared as abstract and final. The access specifiers, public, protected,
default and private can be used within the class.
E.g.
public class EnclosingClass {
private static int static_var = 0; // Has got access
public int instance_var = 0; // Has got no access
Because the inner class is static, it can access only the static_var variable, even though it is
private
It cannot access the instance_var variable because it is not static, regardless of the fact that it
is public
13
Interview Questions: Core Java
The fully qualified class name for the inner class is EnclosingClass.StaticInnerClass
i.showName ();
} //End of main
3. Local class
Local classes are declared within a block of code and are visible only within that block, just as
any other method variable. Local classes are good way to maintain Encapsulation.
Local classes, like local variables, cannot be declared public, protected, private, or static.
Local classes cannot have static members.
Local classes can only access final local variables and method arguments of the enclosing
method.
Local inner classes can be declared as abstract and final.
Example
4. Anonymous class
An anonymous class is a local class that has no name. An anonymous class is implicitly final.
14
Interview Questions: Core Java
Anonymous classes cannot be public, protected, private, or static. The syntax for anonymous
inner classes does not allow for any modifiers to be used. An anonymous inner class can
extend a superclass or it can implement an interface.
But not both.
Example
Example
15
Interview Questions: Core Java
Composition:
Composition (called "has-a") is a relationship between classes where one class has a data
member that is an instance of the other class.
class Fruit {
//...
}
class Apple {
private Fruit fruit = new Fruit();
//...
16
Interview Questions: Core Java
}
In the example above, class Apple is related to class Fruit by composition, because Apple has
an instance variable that holds a reference to Fruit object.
In this example, Apple is what I will call front-end class and Fruit is what I will call back-end
class. In a composition relationship, the front-end class holds a reference in one of its instance
variables to a back-end class.
17
Interview Questions: Core Java
Assume that the classes loaded from different jar files have same name but they are treated
as distinct types by JVM
E.g.
Class cla = Class.forName( "com.javagalaxy.util.MyClass" );
MyClass tCla = (MyClass)cla.newInstance( );
tCla.doSomething();
69. Question: What is meant by Virtual function in Java? Does Java supports Virtual
function?
Answer: Java supports Virtual functions, all functions in Java are virtual by default. Virtual
functions or virtual methods are functions or methods that will be redefined in derived classes.
Pure Virtual functions from C++ could be abstract functions without body.
Make your class abstract, define the pure virtual methods you want subclasseses to provide
implementation for
(using the abstract keyword in their definition) and you should be good.
ArrayList used arrays to store its elements and LinkedList used node objects to store its
elements.
ArrayList is faster than LinkedList. Assume a scenario where in both ArrayList and LinkedList
have 5 objects and you are trying to remove 2nd object from these objects, since ArrayList
18
Interview Questions: Core Java
uses arrays its much faster to find the object, delete it and re-arrange the order in the object.
But in LinkedList each object will be linked to its previous and next object, removing the object
at an index will be slower as the object needs to re-arrange the object by linking to previous
and next object in the list (if any)
72. Question: What is marker interface and What is the use of marker interface?
Answer: An interface without any methods is known as marker interface. Examples of marker
interfaces are
1. Serializable
2. EventListener
3. Remote
4. Cloneable
Assume a class X implements Cloneable interface. Now you can call X.clone() in order to clone
this object. If this class doesn’t implement this interface then you will not be able to clone this
class.
The same is for Serializable interface, a class that implements this interface will be serialized
and de-serialized. Classes that require special handling during the serialization and
deserialization process must implement special methods with these exact signatures:
Lets have a look at an example, If object C implemented interfaces A and B, and both A and B
defined a static method F(), then some method invoked C.F(), then which F() would get
invoked?
The one from A() or the one from B()? We don’t know which, and can’t know, so Java doesn’t
let us complicate matters thus.
19
Interview Questions: Core Java
If there’s a problem with garbage collecting classes and if you keep loading new classes, the
VM will run out of space in that memory region, even if there’s plenty of memory available on
the heap. Setting the -Xmx parameter will not help:
this parameter only specifies the size of the total heap and does not affect the size of the
PermGen region.
The JAR file is a Java Archive. The WAR file is a Web Archive. And finally, the EAR file is an
Enterprise Archive.
20