Sunteți pe pagina 1din 20

Interview Questions: Core Java

1. Question: Can there be an abstract class with no abstract methods in it?


Answer: Yes

2. Question: Can an Interface be final?


Answer: No, interface cannot be a final, becz when we do final that means it is not
be overridden whereas we use interface for a multiple inheritance

3. Question: Can an Interface have an inner class?


Answer : Yes
Example:
public interface Sample
{
static int i=0;
void add();
class a1
{
public static void main(String a1[])
{
System.out.println("in interface");
}
}
}
Executtion:
D:\RPrasad\JavaPractice\interface>javac Sample.java
Then it will created two files : Sample.class & Sample$a1.class
We can get the inner class output by : interface>java Sample$a1

4. Question: Can we define private and protected modifiers for variables in


interfaces?
Answer: No

5. Question: Can we overload main method in java?


Answer: Yes. But the main method with String args[] is called when you call the
programme (java Sample) Have a look at this demo.
public class Sample
{
public static void main(String a1[])
{
System.out.println("Main in String[]");
Sample.main(4,5);
}
public static void main(int i,int j)
{
System.out.println("Main in int");
}
}

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

7. Question: What is Externalizable?


Answer: 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)

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

Externalizable: its also an interface,the serialization and desirialization occur


automatically....but some time the programmer recuired to make contoll over this method ,this
can be done by using Externalizable interface,remember that serializable interface define no
method but externalizable define to method that are

void readExternal(ObjectInput inStream)


throws IOException,ClassNotFoundException
//inStream is byte stream from which object is readed

void writeExtrnal(ObjectOutput outStream)


throws IOException
//outStream is byte Stream from which object is written.

8. Question: What modifiers are allowed for methods in an Interface?


Answer: Only public and abstract modifiers are allowed for methods in interfaces.

2
Interview Questions: Core Java

9. Question: What is a local, member and a class variable?


Answer: Variables declared within a method are "local" variables. Variables declared within the
class i.e not within any methods are "member" variables (global variables).
Variables declared within the class i.e not within any methods and are defined as "static" are
class variables

10. Question: What are some alternatives to inheritance?


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

11. Question: What does it mean that a method or field is "static"?


Answer: Static variables and methods are instantiated only once per class. In other words they
are class variables, not instance variables. If you change the value of a static variable in a
particular object, the value of that variable changes for all instances of that class.
Static methods can be referenced with the name of the class rather than the name of a
particular object of the class (though that works too). That’s how library methods like
System.out.println() work. out is a static field in the java.lang.System class.
by static field it means that we are creating global varialble .when the object of its class
declared,no copy of static variable is made.....

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

if we want to intialize static variable we can do it by creating static block,remember static


block is execute frist event before the constructer is call......

12. Question: Diffrence between JRE And JVM AND JDK


Answer: JVM - Java Virtual Machine. This is where all java classes gets executed. JVM converts
byte code to machine understandable code.
JRE - Java Runtime Environment - Contains all core API class files that are needed to execute
a java application
JDK - Java Development Kit - Contains tools to use java, e.g. javac, java, javaw, keytool, etc...
and JRE (See above for description of JRE)

13. Question: What is synchronization and why is it important?


Answer: With respect to multithreading, synchronization is the capability to control the access
of multiple threads to shared resources. Without synchronization, it is possible for one thread

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

To prevent from this condition java provide a efficient mechanism called


"SYNCHRONIZATION"...to prevent this java use old age model of interprocess synchroniztion
called: "monitor".....(by:sir C.A.R.Hoare)

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

14. Question: Is null a keyword?


Answer: The null value is not a keyword.
I think null is considered as keyword in java or at least a known token.
if we use commands like
int null = 0;
we see error like
Syntax error on token "null", invalid VariableDeclaratorId

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.

16. Question: What are wrapped classes?


Answer: Wrapped classes are classes that allow primitive types to be accessed as objects.
Wrapper classes are used so that values can be added to some collection. We can add only
objects to collections.

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.

18. Question: Can an anonymous class be declared as implementing an interface and


extending a class?
Answer: An anonymous class may implement an interface or extend a superclass, but may not
be declared to do both.
what is anonymous class? It is a class which should not contain any name

4
Interview Questions: Core Java

19. Question: What is the purpose of finalization?


Answer: The purpose of finalization is to give an unreachable object the opportunity to
perform any cleanup processing before the object is garbage collected.

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.

21. Question: What is the purpose of the finally clause of a try-catch-finally


statement?
Answer: The finally clause is used to provide the capability to execute code no matter whether
or not an exception is thrown or caught.

22. Question: Can a double value be cast to a byte?


Answer: Yes, a double value can be cast to a byte.

23. Question: Can a Byte object be cast to a double value?


Answer: No, an object cannot be cast to a primitive value.

24. Question: What must a class do to implement an interface?


Answer: It must provide all of the methods in the interface and identify the interface in its
implements clause.

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.

27. Question: When can an object reference be cast to an interface reference?


Answer: An object reference be cast to an interface reference when the object implements the
referenced interface.

28. Question: What classes of exceptions may be caught by a catch clause?


Answer: A catch clause can catch any exception that may be assigned to the Throwable type.
This includes the Error and Exception types.

29. Question: Does a class inherit the constructors of its superclass?


Answer: A class does not inherit constructors from any of its superclasses.

30. Question: What is the purpose of the System class?


Answer: The purpose of the System class is to provide access to system resources.

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.

32. Question: What is the purpose of the File class?


Answer: The File class is used to create objects that provide access to the files and directories
of a local file system.

33. Question: What is casting?


Answer: There are two types of casting, casting between primitive numeric types and casting
between object references. Casting between numeric types is used to convert larger values,
such as double values, to smaller values, such as byte values. Casting between object
references is used to refer to an object by a compatible class, interface, or array type
reference.

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.

36. Question: If an object is garbage collected, can it become reachable again?


Answer: Once an object is garbage collected, it ceases to exist. It can no longer become
reachable again

37. Question: What happens when you add a double value to a String?
Answer: The result is a String object.

38. Question: Whats the difference between notify() and notifyAll()?


Answer: notify() is used to unblock one waiting thread; notifyAll() is used to unblock all of
them. Using notify() is preferable (for efficiency) when only one blocked thread can benefit
from the change (for example, when freeing a buffer back into a pool). notifyAll() is necessary
(for correctness) if multiple threads should resume (for example, when releasing a "writer"
lock on a file might permit all "readers" to resume).

39. Question: Wha is the output from System.out.println("Hello"+null);


Answer: Hellonull

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

42. Question: Describe what happens when an object is created in Java?


Answer: Several things happen in a particular order to ensure the object is constructed
properly:
1. Memory is allocated from heap to hold all instance variables and implementation-specific
data of the object and its superclasses. Implemenation-specific data includes pointers to class
and method data.
2. The instance variables of the objects are initialized to their default values.
3. The constructor for the most derived class is invoked. The first thing a constructor does is
call the consctructor for its superclasses. This process continues until the constrcutor for
java.lang.Object is called, as java.lang.Object is the base class for all objects in java.
4. Before the body of the constructor is executed, all instance variable initializers and
initialization blocks are executed. Then the body of the constructor is executed. Thus, the
constructor for the base class completes first and constructor for the most derived class
completes last.

43. Question: What is the difference between instanceof and isInstance?


Answer: instanceof is used to check to see if an object can be cast into a specified type
without throwing a cast class exception.
isInstance()
Determines if the specified Object is assignment-compatible with the object represented by
this Class. This method is the dynamic equivalent of the Java language instanceof operator.
The method returns true if the specified Object argument is non-null and can be cast to the
reference type represented by this Class object without raising a ClassCastException. It
returns false otherwise.

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"

45. Question: is it necessary to initialize a final variable at the time of declaretion ?


Answer: NO, it’s not necessary.
Many text books say like this but thats not true. Value of a final variable can be instance
specific also, but in this case we have to initialise the variable in all the constructors.
If we want to have a common final value of a variable for all the instances then there are two
ways.
1. Initialise the variable at class level (at the time of declaration) or 2. just declare variable at
class level and initialise it in any one of the instance blocks i.e.

7
Interview Questions: Core Java

A. class A { final int a; {a=5;}}


B. class A { final int a = 5;}

46. Question: What restrictions are placed on method overriding?


Answer: Overridden methods must have the same name, argument list, and return type.
The overriding method may not limit the access of the method it overrides.
The overriding method may not throw any exceptions that may not be thrown by the
overridden method.

47. Question: What are synchronized methods and synchronized statements?


Answer: Synchronized methods are methods that are used to control access to an object. A
thread only executes a synchronized method after it has acquired the lock for the method~s
object or class. Synchronized statements are similar to synchronized methods. A synchronized
statement can only be executed after a thread has acquired the lock for the object or class
referenced in the synchronized statement.

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.

49. Question: What is user defined exception ?


Answer: Apart from the exceptions already defined in Java package libraries, user can define
his own exception classes by extending Exception class.

50. Question: What are Checked and Un-Checked Exceptions? Explain.


Answer: Throwable extends Object (checked)
Exception extends Throwable (checked)
RuntimeException extends Exception (un-checked)
Error extends Throwable (un-checked)
So anything that extends Throwable or Exception (except RuntimeException) will be checked.
Anything that extends Error or RuntimeException will be un-checked
Checked exceptions are problems that arise in correct code and may be due to technical
problems such as IO problems or user mistakes such as opening a socket when the remote
machine does not exist. Because these problems can occur at anytime, say due to network
outage, you must have code that can handle and recover from these. In fact, the Java

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.

52. Question: What is meant by Instance Variables and Class Variables


Answer: instance variables Any item of data that is associated with a particular object. Each
instance of a class has its own copy of the instance variables defined in the class. Also called a
field. class variables A data item associated with a particular class as a whole--not with
particular instances of the class. Class variables are defined in class definitions. Also called a
static field

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.

54. Question: Explain about Singleton Class


Answer: In general, you use a singleton to enforce the notion that there will be only one
instance of a given class. Singletons should be used in situations where creating more than
one of something would be a logical error.

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[])

a. public: The method can be accessed outside the class / package


b. static: You need not have an instance of the class to access the method
c. void: Your application need not return a value, as the JVM launcher would return the value
when it exits
d. main(): This is the entry point for the application

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

59. Question: What is Tight Encapsulation?


Answer: Encapsulation is for member variables in a classes that may not be accessed by any
other classes. Below are few examples

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;

public void setName(String name) {


if(name.equals("test2") {
this.name = name;
}
else {
//throw user exception
}
}
public String getName() {
return 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

public static void main(String args[])


{
System.out.println("in A");
}
}

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

61. Question: int[] array = new int[5];


int[] array1 = {1,2,3,4,5};
Why not new is used in second statement?
Answer: In the first line we are creating an int array with size 5 but in the second line we are
creating an int array with 5 elements in it.

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.

public class EnclosingClass {

12
Interview Questions: Core Java

private int instVar = 1;

public class MemberClass {


public void innerMethod () {
instVar++;
}
}

public MemberClass createMember () {


return this.new MemberClass ();
}
}

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:

EnclosingClass ec = new EnclosingClass ();


EnclosingClass.MemberClass mc = ec.new MemberClass ();

or

EnclosingClass.MemberClass mc = new EnclosingClass ().new MemberClass ();

member classes can be declared as abstract and final. The access specifiers, public, protected,
default and private can be used within the class.

2. Static member class


A static member class is a static member of a class. Like any other static method, a static
member class has access to all static methods of the parent, or top-level, class. These classes
can use instance variables and methods only through an object reference. Only public, final,
and static are permitted as modifier inside a static member class.

E.g.
public class EnclosingClass {
private static int static_var = 0; // Has got access
public int instance_var = 0; // Has got no access

public static class StaticInnerClass {


}
}

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

These classes can be declared as public, abstract and final.

public class Outer {


public String name = "Outer";

public static void main (String argv[]) {


Inner i = new Inner ();

i.showName ();
} //End of main

private static class Inner {


String name = new String ("Inner");
void showName () {
System.out.println (name);
}
} //End of Inner class
}

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

public class AnyClass {


void localClassDemo() { // a function
class LocalClass { // a class inside a function definition
void func() {
System.out.println( “in Local class”);
}
}
LocalClass local = new LocalClass();
local.func() ;
}
}

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

public class SomeGUI extends JFrame


{
protected void buildGUI()
{
button1 = new JButton();
button2 = new JButton();
button1.addActionListener(
new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent e)
{
// do something
}
});
}
}

63. Question: What is the disadvantage of using an inner class?


Answer: Java bytecode has no concept of inner classes, so the compiler translates inner
classes into ordinary classes that are accessible to any code in the same package. An inner
class gets access to the fields of the enclosing outer class-even if these fields are declared
private and the inner class is translated into a separate class. To let this separate class
access the fields of the outer class, the compiler silently changes these fields~ scope from
private to package. As a result, when you use inner classes, you not only have the inner class
exposed, but you also have the compiler silently overruling your decision to make some fields
private.

64. Question: Does java support global variables?


Answer: Though java doesn’t support global variables, you can achieve this by creating
variables public and static.

Example

public class Global {


public static int x = 37;
public static String s = "test";
}

Such members can be accessed by saying:

15
Interview Questions: Core Java

public class test {


public static void main(String args[])
{
Global.x = Global.x + 100;
Global.s = "bbb";
}
}
65. Question: Can an interface have variables defined in it? How do you use them?
Answer: Yes we can have variables defined in an Interface. Have a look at the class below to
know how to use those variables
public interface MyInterface
{
String STR1 = "STR1";
String STR2 = "STR2";
}
public class MyTestClass implements MyInterface
{
public static void main(String args[])
{
System.out.println(STR1);
}
}

66. Question: What is the differences between inheritance and composition?


Answer:
Inheritance:
Inheritance is the ability to derive one class from another; the derived class (also called the
subclass) inherits all of the methods and data members of its superclass.
class Fruit {
//...
}
class Apple extends Fruit {
//...
}
In the above example, class Apple is related to class Fruit by inheritance, because Apple
extends Fruit. In this example Fruit is superclass and Apple is subclass.

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.

67. Question: What is meant by upcasting?


Answer: Upcasting is where a derived object reference is cast to one of its base objects
reference.
class Base
{
public void show()
{
System.out.println("In Base class");
}
}
class Derived extends Base
{
public void show()
{
System.out.println("In Derived class");
}

public static void main(String args[])


{
//upcasting
Base base = new Derived();
base.show();
}
}
When an object is upcast it becomes a base object for the purpose of the cast, therefore any
new fields and methods declared in the derived class are not accessible.

68. Question: What are dynamic class loaders?


Answer: This is a mechanism of loading classes at runtime. They have following
characteristics,
a. lazyloading - load classes only when they are required. This helps in memory management.
b. type safety linkate - Dynamic loading of a class should not require additional run-time
checks in order to guarantee type safety. Adds link-time checks by replacing run-time checks.
They are performed only once.
c. User defined class loaders - Programmers have the control to load classes in their
applications. A user can define a class loader to load classes from remote location.
d. Multiple namespaces - Class loaders provide separate namespaces for different software
components. For example an applet running in a browser loads classes from different jar files.

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.

public abstract class MyClass {


public void concreteInitThing() {
// your code here
}

public abstract void specificImplementation(); //Virtual method


}

public class ConcreteImplementationOfMyClass extends MyClass {


public void specificImplementation() {
// Your code here
}
}
70. Question: How do you uniquely identify one instance of a class among 10
instances of the same class?
Answer: One way would be to check an objects hashCode.

71. Question: What is the difference between ArrayList and LinkedList?


Answer: The difference between ArrayList and LinkedList vary in the way both these objects
implement List interface.

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:

private void writeObject(java.io.ObjectOutputStream out)


throws IOException
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;

73. Question: Why can’t I declare a static method in an interface?


Answer: Because all methods declared in an interface are (implicitly) also "abstract" methods,
by definition, they do not define the (implementation of) the method.

This would cause problems with multiple inheritance.

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.

74. Question: What is PermGen space?


Answer: The memory in the Virtual Machine is divided into a number of regions. One of these
regions is PermGen. It’s an area of memory that is used to (among other things) load class
files. The size of this memory region is fixed, i.e. it does not change when the VM is running.
You can specify the size of this region with a commandline switch: -XX:MaxPermSize .
The default is 64 Mb on the Sun VMs.

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.

JAR files = collection of class files

WAR files = collection of class, JSP, XML files

EAR files = collection of JAR, WAR, and EJBs

The JAR file is a Java Archive. The WAR file is a Web Archive. And finally, the EAR file is an
Enterprise Archive.

20

S-ar putea să vă placă și