Is Java a pure object oriented language?
Java uses primitive data types and hence is not a pure
object oriented language.
What is the difference between a JDK and a JVM?
JDK is Java Development Kit which is for development purpose
and it includes execution environment also. But JVM is purely a run time
environment and hence you will not be able to compile your source files using a
JVM.
What is difference between Path and Classpath?
Path and Classpath are operating system level environment
variales. Path is used define where the system can find the executables(.exe)
files and classpath is used to specify the location .class files.
Does Java support multiple inheritance?
Java doesn't support multiple inheritance.
What are instance variables?
Instance variables are those which are defined at the class
level. Instance variables need not be initialized before using them as they are
automatically initialized to their default values.
Should a main() method be compulsorily declared in all java
classes?
No not required. main() method should be defined only if the
source class is a java application.
Why is the main() method declared static?
main() method is called by the JVM even before the
instantiation of the class hence it is declared as static.
Can a main() method be overloaded?
Yes. You can have any number of main() methods with
different method signature and implementation in the class.
Can a main() method be declared final?
Yes. Any inheriting class will not be able to have it's own
default main() method.
Can a source file contain more than one class declaration?
Yes a single source file can contain any number of Class
declarations but only one of the class can be declared as public.
What is a package?
Package is a collection of related classes and interfaces.
package declaration should be first statement in a java class.
Which package is imported by default?
java.lang package is imported by default even without a
package declaration.
Can a class be declared as protected?
A class can't be declared as protected. only methods can be
declared as protected.
What is the purpose of declaring a variable as final?
A final variable's value can't be changed. final variables
should be initialized before using them.
What is the impact of declaring a method as final?
A method declared as final can't be overridden. A sub-class
can't have the same method signature with a different implementation.
Can you give few examples of final classes defined in Java
API?
java.lang.String, java.lang.Math are final classes.
How is final different from finally and finalize()?
final is a modifier which can be applied to a class or a
method or a variable. final class can't be inherited,final method can't be
overridden and final variable can't be changed.
finally is an exception handling code section which gets
executed whether an exception is raised or not by the try block code segment.
finalize() is a method of Object class which will be
executed by the JVM just before garbage collecting object to give a final
chance for resource releasing activity.
Can a class be declared as static?
We can not declare top level class as static, but only inner
class can be declared static.
public class Test
{
static class InnerClass
{
public static void InnerMethod()
{ System.out.println("Static Inner Class!"); }
}
public static void main(String args[])
{
Test.InnerClass.InnerMethod();
}
}
When will you define a method as static?
When a method needs to be accessed even before the creation
of the object of the class then we should declare the method as static.
I want to print "Hello" even before main() is
executed. How will you acheive that?
Print the statement inside a static block of code. Static
blocks get executed when the class gets loaded into the memory and even before
the creation of an object. Hence it will be executed before the main() method.
And it will be executed only once.
What is an Abstract Class and what is it's purpose?
A Class which doesn't provide complete implementation is
defined as an abstract class. Abstract classes enforce abstraction.
What is use of a abstract variable?
Variables can't be declared as abstract. only classes and
methods can be declared as abstract.
Can you create an object of an abstract class?
Not possible. Abstract classes can't be instantiated.
Can a abstract class be defined without any abstract
methods?
Yes it's possible. This is basically to avoid instance
creation of the class.
Can an Interface implement another Interface?
Intefaces doesn't provide implementation hence a interface
cannot implement another interface.
Can an Interface extend another Interface?
Yes an Interface can inherit another Interface, for that
matter an Interface can extend more than one Interface.
Can a Class extend more than one Class?
Not possible. A Class can extend only one class but can
implement any number of Interfaces.
Can a class be defined inside an Interface?
Yes it's possible.
Can an Interface be defined inside a class?
Yes it's possible.
What is a Marker Interface?
An Interface which doesn't have any declaration inside but
still enforces a mechanism.
What is Externalizable?
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)
What is an abstract method?
An abstract method is a method whose implementation is
deferred to a subclass.
What is a local, member and a class variable?
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" or class variables.
What value does read() return when it has reached the end of
a file?
The read() method returns -1 when it has reached the end of
a file.
What is an object's lock and which object's have locks?
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.
What is casting?
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.
What do you understand by private, protected and public?
These are accessibility modifiers. Private is the most
restrictive, while public is the least restrictive. There is no real difference
between protected and the default type (also known as package protected) within
the context of the same package, however the protected keyword allows
visibility to a derived class in a different package.
Can an anonymous class be declared as implementing an
interface and extending a class?
An anonymous class may implement an interface or extend a
superclass, but may not be declared to do both.
What is the difference between a while statement and a do
while statement?
A while statement checks at the beginning of a loop to see
whether the next loop iteration should occur. A do while statement checks at
the end of a loop to see whether the next iteration of a loop should occur. The
do while statement will always execute the body of a loop at least once.
What are the legal operands of the instanceof operator?
The left operand is an object reference or null value and
the right operand is a class, interface, or array type.
What is the difference between the prefix and postfix forms
of the ++ operator?
The prefix form performs the increment operation and returns
the value of the increment operation. The postfix form returns the current
value all of the expression and then performs the increment operation on that
value.
What restrictions are 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. The overriding method may not throw any exceptions that may not
be thrown by the overridden method.
What is the difference between an if statement and a switch
statement?
The if statement is used to select among two alternatives.
It uses a boolean expression to decide which alternative should be executed.
The switch statement is used to select among multiple alternatives. It uses an
int expression to determine which alternative should be executed.
Can a method be overloaded based on different return type
but same argument type ?
No, because the methods can be called without using their
return type in which case there is ambiquity for the compiler.
What is the difference between method overriding and
overloading?
Overriding is a method with the same name and arguments as
in a parent, whereas overloading is the same method name but different
arguments.
What is the difference between the Boolean & operator
and the && operator?
If an expression involving the Boolean & operator is
evaluated, both operands are evaluated. Then the & operator is applied to
the operand. When an expression involving the && operator is evaluated,
the first operand is evaluated. If the first operand returns a value of true
then the second operand is evaluated. The && operator is then applied
to the first and second operands. If the first operand evaluates to false, the
evaluation of the second operand is skipped.
What is a transient variable?
Transient variable is a variable that may not be serialized.
What is the difference between the >> and >>>
operators?
The >> operator carries the sign bit when shifting
right. The >>> zero-fills bits that have been shifted out.
What is the difference between a constructor and a method?
A constructor is a member function of a class that is used
to create objects of that class. It has the same name as the class itself, has
no return type, and is invoked using the new operator.
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.
What is the purpose of garbage collection in Java, and when
is it used?
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.
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 synchonization, 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.
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, etc.), but has some abstract methods.
Explain different way of using thread?
The thread could be implemented by using runnable interface
or by inheriting from the Thread class. The former is more advantageous, 'cause
when you are going for multiple inheritance, the only interface can help.
What is static in java?
Static means one per class, not one for each object no
matter how many instance of a class might exist. This means that you can use
them without creating an instance of a class.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 nonstatic method. In
other words, you can't change a static method into an instance method in a
subclass.
What are Checked and UnChecked Exception?
A checked exception is some subclass of Exception (or
Exception itself), excluding class RuntimeException and its subclasses. Making
an exception checked forces client programmers to deal with the possibility
that the exception will be thrown.
Example: IOException thrown by java.io.FileInputStream's
read() method.
Unchecked exceptions are RuntimeException and any of its
subclasses. Class Error and its subclasses also are unchecked. With an
unchecked exception, however, the compiler doesn't force client programmers
either to catch the exception or declare it in a throws clause. In fact, client
programmers may not even know that the exception could be thrown.
Example: StringIndexOutOfBoundsException thrown by String's
charAt() method. Checked exceptions must be caught at compile time. Runtime
exceptions do not need to be. Errors often cannot be.
What is Overriding?
When a class defines a method using the same name, return
type, and arguments as a method in its superclass, the method in the class
overrides the method 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. Methods may be overridden to be more public, not more private.
Primitive data types are passed by reference or pass by
value?
Primitive data types are passed by value.
Objects are passed by value or by reference?
Java only supports pass by value. With objects, the object
reference itself is passed by value and so both the original reference and
parameter copy both refer to the same object.
What is serialization?
Serialization is a mechanism by which you can save the state
of an object by converting it to a byte stream.
How do I serialize an object to a file?
The class whose instances are to be serialized should
implement an interface Serializable. Then you pass the instance to the
ObjectOutputStream which is connected to a fileoutputstream. This will save the
object to a file.
What is the common usage of serialization?
Whenever an object is to be sent over the network, objects
need to be serialized. Moreover if the state of an object is to be saved,
objects need to be serilazed.
What is Externalizable interface?
Externalizable is an interface which contains two methods
readExternal and writeExternal. These methods give you a control over the
serialization mechanism.
Thus if your class implements this interface, you can
customize the serialization process by implementing these methods.
What happens to the static fields of a class during
serialization?
There are three exceptions in which serialization doesnot
necessarily read and write to the stream. These are
Serialization ignores static fields, because they are not
part of ay particular state state.
Base class fields are only hendled if the base class itself
is serializable.
What are wrapper classes?
Java provides specialized classes corresponding to each of the
primitive data types. These are called wrapper classes.
They are example: Integer, Character, Double etc.
What are runtime exceptions?
Runtime exceptions are those exceptions that are thrown at
runtime because of either wrong input data or because of wrong business logic
etc. These are not checked by the compiler at compile time.
What is the difference between error and an exception?
An error is an irrecoverable condition occurring at runtime.
Such as OutOfMemory error.
These JVM errors and you can not repair them at runtime.
While exceptions are conditions that occur because of bad input etc. Example:
FileNotFoundException will be thrown if the specified file does not exist. Or
aNullPointerException will take place if you try using a null reference.
In most of the cases it is possible to recover from an
exception (probably by giving user a feedback for entering proper values etc.).
How to create custom exceptions?
Your class should extend class Exception, or some more
specific type thereof.
What are the different ways to handle exceptions?
There are two ways to handle exceptions,
By wrapping the desired code in a try block followed by a
catch block to catch the exceptions. and List the desired exceptions in the throws clause of the
method and let the caller of the method hadle those exceptions.
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.
If I write return at the end of the try block, will the
finally block still execute?
Yes even if you write return as the last statement in the
try block and njo exception occurs, the finally block will execute. The finally
block will execute and then the control return.
If I write System.exit(0); at the end of the try block, will
the finally block still exe
cute?
cute?
No. In this case the finally block will not execute because
when you say System.exit(0); the control immediately goes out of the program,
and thus finally never executes.
What is synchronization and why is it important?
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 object while another thread is in the process of using or
updating that object's value. This often leads to significant errors.
What is the difference between preemptive scheduling and
time slicing?
Under preemptive scheduling, the highest priority task
executes until it enters the waiting or dead states or a higher priority task
comes into existence.
Under time slicing, a task executes for a predefined slice
of time and then reenters the pool of ready tasks. The scheduler then
determines which task should execute next, based on priority and other factors.
What is the purpose of finalization?
The purpose of finalization is to give an unreachable object
the opportunity to perform any cleanup processing before the object is garbage
collected.
How are this() and super() used with constructors?
this() is used to invoke a constructor of the same class.
super() is used to invoke a superclass constructor.
What is daemon thread and which method is used to create the
daemon thread?
Daemon thread is a low priority thread which runs
intermittently in the back ground doing the garbage collection operation for
the java runtime system.setDaemon method is used to create a daemon thread.
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\");
Step 4 : Exceute the query :
stmt.exceuteUpdate();
How does a try statement determine which catch clause should
be used to handle an exception?
When an exception is thrown within the body of a try
statement, the catch clauses of the try statement are examined in the order in
which they appear. The first catch clause that is capable of handling the
exceptionis executed. The remaining catch clauses are ignored.
Is Empty .java file a valid source file?
Yes. An empty .java file is a perfectly valid source file.
What are the different scopes for Java variables?
The scope of a Java variable is determined by the context in
which the variable is declared. Thus a java variable can have one of the three
scopes at any given point in time.
Instance : - These are typical object level variables, they
are initialized to default values at the time of creation of object, and remain
accessible as long as the object accessible.
Local : - These are the variables that are defined within a
method. They remain accessbile only during the course of method excecution.
When the method finishes execution, these variables fall out of scope.
Static: - These are the class level variables. They are
initialized when the class is loaded in JVM for the first time and remain there
as long as the class remains loaded. They are not tied to any particular object
instance.
What is the Collection interface?
The Collection interface provides support for the
implementation of a mathematical bag - an unordered collection of objects that
may contain duplicates.
What is the List interface?
The List interface provides support for ordered collections
of objects.
What is the Set interface?
The Set interface provides methods for accessing the
elements of a finite mathematical set. Sets do not allow duplicate elements.
What is the Map interface?
The Map interface replaces the JDK 1.1 Dictionary class and
is used associate keys with values.
What is the Vector class?
The Vector class provides the capability to implement a
growable array of objects
What is HashMap and Map?
Map is an Interface and Hashmap is the class that implements
Map.
Difference between HashMap and HashTable?
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 doesnt allow).
HashMap does not guarantee that the order of the map will
remain constant over time. HashMap is unsynchronized and Hashtable is
synchronized.
Difference between Vector and ArrayList?
Vector is synchronized whereas arraylist is not.
What is the difference between set and list?
Set stores elements in an unordered way but does not contain
duplicate elements, whereas list stores elements in an ordered way but may
contain duplicate elements.
What is an Iterator interface?
The Iterator interface is used to step through the elements
of a Collection.
Can a for statement loop indefinitely?
Yes, a for statement can loop indefinitely. For example,
consider the following:
for(;;) ;
What is the difference between the Boolean & operator
and the && operator?
If an expression involving the Boolean & operator is
evaluated, both operands are evaluated. Then the &operator is applied to
the operand. When an expression involving the && operator is evaluated,
the first operand is evaluated.
If the first operand returns a value of true then the second
operand is evaluated. The && operator is then applied to the first and
second operands. If the first operand evaluates to false, the evaluation of the
second operand is skipped.
What is the difference between the String and StringBuffer
classes?
String objects are constants. StringBuffer objects are not
constants.
What is the purpose of the System class?
The purpose of the System class is to provide access to
system resources.
What is the purpose of the File class?
The File class is used to create objects that provide access
to the files and directories of a local file system.
What is the difference between the File and RandomAccessFile
classes?
The File class encapsulates the files and directories of the
local file system.
The RandomAccessFile class provides the methods needed to
directly access data contained in any part of a file.
What is mutable object and immutable object?
If a object value is changeable then we can call it as
Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the
value of an object, it is immutable object. (Ex., String, Integer, Float, …)
What is singleton?
It is one of the design pattern. This falls in the
creational pattern of the design pattern. There will be only one instance for
that entire JVM. You can achieve this by having the private constructor in the
class. For eg., public class Singleton { private static final Singleton s = new
Singleton(); private Singleton() { } public static Singleton getInstance() {
return s; } // all non static methods … }
What’s the difference between == and equals method?
equals checks for the content of the string objects while ==
checks for the fact that the two String objects point to same memory location
ie they are same references.
How many different types of JDBC drivers are present?
Discuss them.
There are four JDBC driver types.
Type 1: JDBC-ODBC Bridge plus ODBC Driver:
The first type of JDBC driver is the JDBC-ODBC Bridge. It is
a driver that provides JDBC access to databases through ODBC drivers. The ODBC
driver must be configured on the client for the bridge to work. This driver
type is commonly used for prototyping or when there is no JDBC driver available
for a particular DBMS.
Type 2: Native-API partly-Java Driver:
The Native to API driver converts JDBC commands to
DBMS-specific native calls. This is much like the restriction of Type 1
drivers. The client must have some binary code loaded on its machine. These
drivers do have an advantage over Type 1 drivers because they interface
directly with the database.
Type 3: JDBC-Net Pure Java Driver:
The JDBC-Net drivers are a three-tier solution. This type of
driver translates JDBC calls into a database-independent network protocol that
is sent to a middleware server. This server then translates this
DBMS-independent protocol into a DBMS-specific protocol, which is sent
to a particular database. The results are then routed back
through the middleware server and sent back to the client. This type of
solution makes it possible to implement a pure Java client. It also makes it
possible to swap databases without affecting the client.
Type 4: Native-Protocol Pure Java Driver
These are pure Java drivers that communicate directly with
the vendor’s database. They do this by converting JDBC commands directly into
the database engine’s native protocol. This driver has no additional
translation or middleware layer, which improves performance tremendously.
What’s the difference between the methods sleep() and wait()?
The code sleep(1000); puts thread aside for exactly one
second. The code wait(1000), causes a wait of up to one second. A thread could
stop waiting earlier if it receives the notify() or notifyAll() call. The
method wait() is defined in the class Object and the method sleep() is defined
in the class Thread.
What are Encapsulation, Inheritance and Polymorphism?
Encapsulation is the mechanism that binds together code and
data it manipulates and keeps both safe from outside interference and misuse.
Inheritance is the process by which one object acquires the properties of
another object. Polymorphism is the feature that allows one interface to be
used for general class actions.
What is Composition in Java? Java Composition Example
Composition is the design technique to implement has-a relationship in classes. We can use java inheritance or Object composition for code reuse.
Java composition is achieved by using instance variables that refers to other objects. If the relationship between two classes is has-a then you should use composition rather than inheritance.
Benefit of using composition is that we can control the visibility of other object to client classes and reuse only what we need.
What is the difference between compareTo() vs. equals()?
The 2 main differences are that:
equals will take any Object as a parameter, but compareTo will only take Strings.
equals only tells you whether they're equal or not, but compareTo gives information on how the Strings compare lexicographically.
compareTo() not only applies to Strings but also any other object because compareTo<T> takes a generic argument T. String is one of the classes that has implemented the compareTo() method by implementing the Comparable interface.(compareTo() is a method fo the comparable Interface). So any class is free to implement the Comparable interface.
But compareTo() gives the ordering of objects, used typically in sorting objects in ascending or descending order while equals() will only talk about the equality and say whether they are equal or not.
Equals computes the hashcode. The hashcode of two different strings, although rare, can be the same. But when using compareTo(), it checks the strings character by character. So in this case two string will return true if and only if their actual contents are equal.
A difference is that "foo".equals((String)null) returns false while "foo".compareTo((String)null) == 0 throws a NullPointerException.
So they are not always interchangeable even for Strings.
What is Composition in Java? Java Composition Example
Composition is the design technique to implement has-a relationship in classes. We can use java inheritance or Object composition for code reuse.
Java composition is achieved by using instance variables that refers to other objects. If the relationship between two classes is has-a then you should use composition rather than inheritance.
Benefit of using composition is that we can control the visibility of other object to client classes and reuse only what we need.
What is the difference between compareTo() vs. equals()?
The 2 main differences are that:
equals will take any Object as a parameter, but compareTo will only take Strings.
equals only tells you whether they're equal or not, but compareTo gives information on how the Strings compare lexicographically.
compareTo() not only applies to Strings but also any other object because compareTo<T> takes a generic argument T. String is one of the classes that has implemented the compareTo() method by implementing the Comparable interface.(compareTo() is a method fo the comparable Interface). So any class is free to implement the Comparable interface.
But compareTo() gives the ordering of objects, used typically in sorting objects in ascending or descending order while equals() will only talk about the equality and say whether they are equal or not.
Equals computes the hashcode. The hashcode of two different strings, although rare, can be the same. But when using compareTo(), it checks the strings character by character. So in this case two string will return true if and only if their actual contents are equal.
A difference is that "foo".equals((String)null) returns false while "foo".compareTo((String)null) == 0 throws a NullPointerException.
So they are not always interchangeable even for Strings.