Anda di halaman 1dari 12

CORE JAVA INTERVIEW QUESTIONS

1.What is final, finalize() and finally?

o final - declare constant


o finally - handles exception
o finalize - helps in garbage collection, finalize is a protected method in java

2.Why there are no global variables in Java?

Global variables are globally accessible. Java does not support globally accessible variables due to
following reasons:

• The global variables breaks the referential transparency


• Global variables creates collisions in namespace.

3.How to convert String to Number in java program?

The valueOf() function of Integer class is is used to convert string to Number. Here is the
code example:
String numString = "1000";
int id=Integer.valueOf(numString).intValue();

4. What are different types of access modifiers?

Access specifiers are keywords that determine the type of access to the member of a class. These
keywords are for allowing
privileges to parts of a program such as functions and variables. These are:
• Public : accessible to all classes
• Protected : accessible to the classes within the same package and any subclasses.
• Private : accessible only to the class to which they belong
• Default : accessible to the class to which they belong and to subclasses within the same
package

5. What is a static method?

A static variable is associated with the class as a whole rather than with specific instances of a
class. Each object will share a common copy of the static variables i.e. there is only one copy per
class, no matter how many objects are created from it. Class variables or static variables are
declared with the static keyword in a class. These are declared outside a class and stored in static
memory. Class variables are mostly used for constants. Static variables are always called by the
class name. This variable is created when the program starts and gets destroyed when the
programs stops. The scope of the class variable is same an instance variable. Its initial value is
same as instance variable and gets a default value when its not initialized corresponding to the
data type. Similarly, a static method is a method that belongs to the class rather than any object
of the class and doesn't apply to an object or even require that any objects of the class have been
instantiated.
Static methods are implicitly final, because overriding is done based on the type of the object,
and static methods are attached to a class, not an object. A static method in a superclass can be
shadowed by another static method in a subclass, as long as the original method was not
declared final. However, you can't override a static method with a non-static method. In other
words, you can't change a static method into an instance method in a subclass.

Non-static variables take on unique values with each object instance.

1
6. What is the first argument of the String array in main method?

The String array is empty. It does not have any element. This is unlike C/C++ where the first
element by default is the program name. If we do not provide any arguments on the command
line, then the String array of main method will be empty but not null.

7. How can one prove that the array is not null but empty?

Print array.length. It will print 0. That means it is empty. But if it would have been null then it
would have thrown a NullPointerException on attempting to print array.length.

8. Can an application have multiple classes having main method?

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

9. When is static variable loaded? Is it at compile time or runtime? When exactly a


static block is loaded in Java?

Static variable are loaded when class loader brings the class to the JVM. It is not necessary that
an object has to be created. Static variables will be allocated memory space when they have been
loaded. The code in a static block is loaded/executed only once i.e. when the class is first
initialized. A class can have any number of static blocks. Static block is not member of a class,
they do not have a return statement and they cannot be called directly. Cannot contain this or
super. They are primarily used to initialize static fields.

10. How can I swap two variables without using a third variable?

Add two variables and assign the value into First variable. Subtract the Second value with the
result Value. and assign to Second variable. Subtract the Result of First Variable With Result of
Second Variable and Assign to First Variable. Example:

int a=5,b=10;a=a+b; b=a-b; a=a-b;

11. Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this
the OS heap or the heap maintained by the JVM? Why

Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to
those objects are on the STACK.

12. Can a method be static and synchronized?

A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang.
Class instance associated with the object. It is similar to saying:

synchronized(XYZ.class) {

13. Does importing a package imports the sub packages as well? E.g. Does importing
com.bob.* also import com.bob.code.*?

2
No you will have to import the sub packages explicitly. Importing com.bob.* will import classes in
the package bob only. It will not import any class in any of its sub package’s.

14. Explain the usage of Java packages.

A Java package is a naming context for classes and interfaces. A package is used to create a
separate name space for groups of classes and interfaces. Packages are also used to organize
related classes and interfaces into a single API unit and to control accessibility to these classes
and interfaces.
For example: The Java API is grouped into libraries of related classes and interfaces; these
libraries are known as package.

15. What restrictions are placed on method overloading?

Two methods may not have the same name and argument list but different return types.

16. How can a subclass call a method or a constructor defined in a superclass?

A constructor is a member function of a class that is used to create objects of that class, invoked
using the new operator. It has the same name as the class and has no return type. They are only
called once, whereas member functions can be called many times. A method is an ordinary
member function of a class. It has its own name, a return type (which may be void), and is
invoked using the dot operator. Constructor will be automatically invoked when an object is
created whereas method has to be called explicitly.

super.method(); is used to call a super class method from a sub class. To call a constructor of the
super class, we use the super(); statement as the first line of the subclass’s constructor.

17. What is Method Overriding? What restrictions are placed on method overriding?

When a class defines a method using the same name, return type, and argument list as that of a
method in its superclass, the method in the subclass is said to override the method present in the
Superclass. When the method is invoked for an object of the
class, it is the new definition of the method that is called, and not the method definition from
superclass.
Restrictions placed on method overriding
• 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. Methods may be
overridden to be more public, not more private.
• The overriding method may not throw any exceptions that may not be thrown by the overridden
method.

18. Differentiate between a Class and an Object?

The Object class is the highest-level class in the Java class hierarchy. The Class class is used to
represent the classes and interfaces that are loaded by a Java program. The Class class is used to
obtain information about an object's design. A Class is only a definition or prototype of real life
object. Whereas as object is an instance or living representation of real life object. Every object
belongs to a class and every class contains one or more related objects.

19. What is singleton pattern?

This design pattern is used by an application to ensure that at any time there is only one instance
of a class created. You can achieve this by having the private constructor in the class and having
a getter method which returns an object of the class and creates one for the first time if its null.

3
20. What is difference between overloading and overriding?

Method overloading: When 2 or more methods in a class have the same method names with
different arguments, it is said to be method overloading. Overloading does not block inheritance
from the superclass. Overloaded methods must have different method signatures

Method overriding : When a method in a class has the same method name with same arguments
as that of the superclass,
it is said to be method overriding. Overriding blocks inheritance from the superclass. Overridden
methods must have same signature.

Basically overloading and overriding are different aspects of polymorphism.

static/early binding polymorphism: overloading


dynamic/late binding polymorphism: overriding

21. What is the purpose of the System class?

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

22. What is a bean? Where can it be used?

A Bean is a reusable and self-contained software component. Beans created using java take
advantage of all the security and platform independent features of java. Bean can be plugged into
any software application. Bean is a simple class which has set and gets methods. It could be used
within a JSP using JSP tags to use them.

23. What would happen if you say this = null?

It will come up with Error Message

"The left-hand side of an assignment must be a variable".

24. What is the difference between an object and an instance?

An Object May not have a class definition. eg int a[] where a is an array.

An Instance should have a class definition.

eg MyClass my=new MyClass();

my is an instance.

25. What are the other ways to create an object other than creating as new object?

We can create object in different ways;

1. new operator

2. class.forName: Classname obj = Class.forName("Fully Qualified class Name").newInstance();

3. newInstance

4. object.clone

4
26. What is the difference between instance, object, reference and a class?

Class: A class is a user defined data type with set of data members & member functions

Object: An Object is an instance of a class

Reference: A reference is just like a pointer pointing to an object

Instance: This represents the values of data members of a class at a particular time

27. Explain Garbage collection mechanism in Java?

Garbage collection is one of the most important features of Java. The purpose of garbage
collection is to identify and discard objects that are no longer needed by a program so that their
resources can be reclaimed and reused. A Java object is subject to garbage collection when it
becomes unreachable to the program in which it is used. Garbage collection is also called
automatic memory management as JVM automatically removes the unused variables/objects
(value is null) from the memory. 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.
In Java on 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 an
automatic process and can't be forced. There is no guarantee that Garbage collection will start
immediately upon request of System.gc(). Garbage Collector uses Daemon thread.

28. How many methods in the Serializable interface? Which methods of Serializable
interface should I implement?

There is no method in the Serializable interface. It’s an empty interface which does not contain
any methods. The Serializable interface acts as a marker, telling the object serialization tools that
the class is serializable. So we do not implement any methods.

29. What is serialization?

The serialization is a kind of mechanism that makes a class or a bean persistent by having its
properties or fields and state information saved and restored to and from storage. That is, it is a
mechanism with which you can save the state of an object by converting it to a byte stream.

30. What are Transient and Volatile Modifiers

A transient variable is a variable that may not be serialized i.e. the value of the variable can’t be
written to the stream in a Serializable class. If you don't want some field to be serialized, you can
mark that field transient or static. In such a case when the class is retrieved from the
ObjectStream the value of the variable is null.

Volatile modifier applies to variables only and it tells the compiler that the variable modified by
volatile can be changed unexpectedly by other parts of the program.

31. Difference between HashMap and HashTable? Can we make hashmap synchronized?

1. The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and
permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow
nulls).
5
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.

32. What is the difference between set and list?

A Set stores elements in an unordered way and does not contain duplicate elements, whereas a
list stores elements in an ordered way but may contain duplicate elements.

33. What is the Collections API?

The Collections API is a set of classes and interfaces that support operations on collections of
objects.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

34. What is the Map interface?

The Map interface is used associate keys with values.

35. Which implementation of the List interface provides for the fastest insertion of a
new element into the middle of the list?

a. Vector
b. ArrayList
c. LinkedList
d. None of the above

ArrayList and Vector both use an array to store the elements of the list. When an element is
inserted into the middle of the list the elements that follow the insertion point must be shifted to
make room for the new element. The LinkedList is implemented using a doubly linked list; an
insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList
allows for fast insertions and deletions.

36. What are differences between Enumeration, ArrayList, Hashtable and Collections
and Collection?

Enumeration: It is series of elements. It can be use to enumerate through the elements of a


vector, keys or values of a hashtable. You can not remove elements from Enumeration.

ArrayList: It is re-sizable array implementation. Belongs to 'List' group in collection. It permits all
elements, including null. It is not thread -safe.Hashtable: It maps key to value. You can use non-
null value for key or value. It is part of group Map in collection.

Collections: It implements Polymorphic algorithms which operate on collections.

Collection: It is the root interface in the collection hierarchy.

37. What method should the key class of Hashmap override?

The methods to override are equals() and hashCode().

38. What is the difference between throw and throws keywords?

6
The throw keyword denotes a statement that causes an exception to be initiated. It takes the
Exception object to be thrown as an argument. The exception will be caught by an enclosing try-
catch block or propagated further up the calling hierarchy. The throws keyword is a modifier of a
method that denotes that an exception may be thrown by the method. An exception can be
rethrown.

39. What is the base class for Error and Exception?

Throwable

40. What is the difference between the paint() and repaint() methods?

The paint() method supports painting via a Graphics object. The repaint() method is used to
cause paint() to be invoked by the AWT painting thread.

41. Name Container classes.

Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane

42. Is there a separate stack for each thread in Java?

Yes. Every thread maintains its own separate stack, called Runtime Stack but they share the
same memory. Elements of the stack are the method invocations,
called activation records or stack frame. The activation record contains pertinent information
about a method like local variables.

43. Extending Thread class or implementing Runnable Interface. Which is better?

You have two ways to do so. First, making your class "extends" Thread class. The other way is
making your class implement "Runnable" interface. The latter is more advantageous, cause when
you are going for multiple inheritance, then only interface can help. . If you are already inheriting
a different class, then you have to go for Runnable Interface. Otherwise you can extend Thread
class. Also, if you are implementing interface, it means you have to implement all methods in the
interface. Both Thread class and Runnable interface are provided for convenience and use them
as per the requirement. But if you are not extending any class, better extend Thread class as it
will save few lines of coding. Otherwise performance wise, there is no distinguishable difference.
A thread is in the ready state after it has been created and started.

44. When you will synchronize a piece of your code?

When you expect that your shared code will be accessed by different threads and these threads
may change a particular data causing data corruption, then they are placed in a synchronized
construct or a synchronized method.

45. What are Wrapper Classes? Describe the wrapper classes in Java.

Wrapper classes are classes that allow primitive types to be accessed as objects. Wrapper class is
wrapper around a primitive data type.

46. What is the difference between an Interface and an Abstract class?

An abstract class can have instance methods that implement a default behavior. An Interface can
only declare constants and instance methods, but cannot implement default behavior and all
methods are implicitly abstract. An interface has all public members and no implementation. An
abstract class is a class which may have the usual flavors of class members (private, protected,
7
etc.), but has some abstract methods.

47. Describe synchronization in respect to multithreading.

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 to modify a
shared variable while another thread is in the process of using or updating same shared variable.
This usually leads to significant errors.

48. What is an abstract class?

Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is
abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain
static data. Any class with an abstract method is automatically abstract itself, and must be
declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being
instantiated.

49. Does Java provide any construct to find out the size of an object?

No there is not sizeof operator in Java. So there is not direct way to determine the size of an
object directly in Java.

50. Why do we need wrapper classes?

It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes
store objects and not primitive data types. And also the wrapper classes provide many utility
methods also. Because of these reasons we need wrapper classes. And since we create instances
of these classes we can store them in any of the collection classes and pass them around as a
collection. Also we can pass them around as method parameters where a method expects an
object.

51. Is it necessary that each try block must be followed by a catch block?

It is not necessary that each try block must be followed by a catch block. It should be followed by
either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be
declared in the throws clause of the method.

52. What are the steps in the JDBC connection?

While making a JDBC connection we go through the following steps :

Step 1 : Register the database driver by using :

Class.forName(\" driver classs for that specific database\" );

Step 2 : Now create a database connection using :

Connection con = DriverManager.getConnection(url,username,password);

Step 3: Now Create a query using :

Statement stmt = Connection.Statement(\"select * from TABLE NAME\");

8
Step 4 : Exceute the query :

stmt.exceuteUpdate();

53. What modifiers are allowed for methods in an Interface?

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

54. What are some alternatives to inheritance?

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

55. What does it mean that a method or field is "static"?

Static variables and methods are instantiated only once per class. In other words they are class
variables, not instance variables. If you change the value of a static variable in a particular
object, the value of that variable changes for all instances of that class.

Static methods can be referenced with the name of the class 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.

56. What is meant by abstraction?


Abstraction defines the essential characteristics of an object that distinguish it from all other
kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative to the
perspective of the viewer. Its the process of focusing on the essential characteristics of an object.
Abstraction is one of the fundamental elements of the object model.

57. What is meant by Encapsulation?


Encapsulation is the process of compartmentalising the elements of an abtraction that defines
the structure and behaviour. Encapsulation helps to separate the contractual interface of an
abstraction and implementation.

58. What is meant by Inheritance?


Inheritance is a relationship among classes, wherein one class shares the structure or
behaviour defined in another class. This is called Single Inheritance. If a class shares the
structure or behaviour from multiple classes, then it is called Multiple Inheritance. Inheritance
defines "is-a" hierarchy among classes in which one subclass inherits from one or more
generalised superclasses.

59. What is the difference between Enumeration and Iterator interface?


The Enumeration interface allows you to iterate through all the elements of a collection.
Iterating through an Enumeration is similar to iterating through an Iterator. However, there is no
removal support with Enumeration.

60. What is the difference between HashSet and TreeSet?


HashSet Class implements java.util.Set interface to eliminate the duplicate entries and uses
hashing for storage. Hashing is nothing but mapping between a key value and a data item, this
provides efficient searching.

9
The TreeSet Class implements java.util.Set interface provides an ordered set, eliminates duplicate
entries and uses tree for storage.

61. What is the difference between ArrayList and LinkedList?


The ArrayList Class implements java.util.List interface and uses array for storage. An array
storage's are generally faster but we cannot insert and delete entries in middle of the list.To
achieve this kind of addition and deletion requires a new array constructed. You can access any
element at randomly.

The LinkedList Class implements java.util.List interface and uses linked list for storage.A linked
list allow elements to be added, removed from the collection at any location in the container by
ordering the elements.With this implementation you can only access the elements in sequentially.

62. ) What is the difference between a Choice and a List?


A Choice is displayed in a compact form that requires you to pull it down to see the list of
available choices. Only one item may be selected from a Choice. A List may be displayed in such a
way that several List items are visible. A List supports the selection of one or more List items.

63. Which Swing methods are thread-safe?


The only thread-safe methods are repaint(), revalidate(), and invalidate()

64. What class is the top of the AWT event hierarchy?


The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy

65. What is the immediate superclass of the Applet class?


Panel
66. What are the differences between an abstract class and an interface?

An abstract class can have concrete method, which is not allowed in an interface. Abstract class
can have private or protected methods and variables and only public methods and variables are
allowed in interface. We can implement more than one interface , but we can extend only one
abstract class. Interfaces provides loose coupling where as abstract class provides tight coupling.

67. What's the difference between normal methods and constructors? A

Constructors must have the same name of the class and can not have a return type. They are
called only once, while regular methods can be called whenever required. We cannot explicitly
call a constructor.

68. What must be the order of catch blocks when catching more than one exception? A

The sub classes must come first. Otherwise it will give a compile time error.

69. What is the difference between static and non static inner class ? A

A non-static inner class can have an object instances that are associated with instances of the
class's outer class. A static inner class can not have any object instances.

70. Which is the base class for all classes ? A java.lang.Object

71. What is a Dictionary? A

Dictionary is a parent class for any class that maps keys to values. In a dictionary every key is
associated with at most one value.

10
72. Why Java is not fully objective oriented ? A

Due to the use of primitives in java, which are not objects.

73. What is a marker(tag) interface ? A

An interface that not having single method. Eg: Serializable, Cloneable, SingleThreadModel etc. It
is used to just mark java classes that support certain capability.

74. What are the restrictions placed on static method? A

We cannot override static methods. We cannot access any object variables inside static method.
Also this reference also not available in static methods.

75. What is JVM? A

JVM stands for Java Virtual Machine. It is the run time for java programs. All are java programs
are running inside this JVM only. It converts java byte code to OS specific commands. In addition
to governing the execution of an application's byte codes, the virtual machine handles related
tasks such as managing the system's memory, providing security against malicious code, and
managing multiple threads of program execution.

76. What is internationalization? A

Internationalization is the process of designing an application so that it can be adapted to various


languages and regions without changes.

77. What is anonymous class ? A An anonymous class is a type of inner class that don't have any
name.
78. Can we compile a java program without main? A

Yes, we can. In order to compile a java program, we don't require any main method. But to
execute a java program we must have a main in it (unless it is an applet or servlet). Because
main functions is the starting point of java program.

79. What are the restrictions when overriding a method ? A

Overridden methods must have the same name, argument list, and return type (i.e., they must
have the exact signature of the method we are going to override, including return type.) The
overriding method cannot be less visible than the method it overrides( i.e., a public method
cannot be override to private). The overriding method may not throw any exceptions that may
not be thrown by the overridden method.

80. What is coupling? A Coupling is the dependency between different components of a system

81. What is the difference between creating a thread by extending Thread class and by
implementing Runnable interface? Which one should prefer?

When creating a thread by extending the Thread class, it is not mandatory to override the run
method (If we are not overriding the run method , it is useless), because Thread class have
already given a default implementation for run method. But if we are implementing Runnable , it
is mandatory to override the run method. The preferred way to create a thread is by
implementing Runnable interface, because it give loose coupling.

11
82. What is a JVM heap? The heap is the runtime data area from which memory for all class
instances and arrays is allocated. The heap may be of a fixed size or may be expanded. The heap
is created on virtual machine start-up.

83. What is diamond problem? A

The diamond problem is an ambiguity that can occur when a class multiply inherits from two
classes that both descend from a common super class

84. What is sandbox?


A sandbox is a security mechanism for safely running programs. The sandbox typically provides
a tightly-controlled set of resources for guest programs to run in, such as scratch space on disk
and memory.
85. What is the difference between throw and throws clause? A

throw is used to throw an exception manually, where as throws is used in the case of checked
exceptions, to tell the compiler that we haven't handled the exception, so that the exception will
be handled by the calling function.

86. What is a class, member and local variable? A

Variables declared within a method are local variables. Variables declared within the class are
member variables. Variables declared within the class with static modifier are class variables

87. What is the use of assert keyword A

Assert keyword validates certain expressions. It replaces the if block effectively and throws an
AssertionError on failure. The assert keyword should be used only for critical arguments (means
without that the method does nothing).

88. What is composition? A

Holding the reference of the other class within some other class is known as composition.

12

Anda mungkin juga menyukai